Java Code Examples for org.apache.commons.io.FileUtils#forceMkdirParent()

The following examples show how to use org.apache.commons.io.FileUtils#forceMkdirParent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: XUnitGenerator.java    From maestro-java with Apache License 2.0 6 votes vote down vote up
/**
 * Generate the xUnit file
 * @param test the test case
 * @param results the results as returned by the peers
 * @param duration the test duration
 */
public static void generate(final Test test, List<? extends MaestroNote> results, long duration) {
    String xUnitDir = System.getenv("TEST_XUNIT_DIR");
    if (xUnitDir == null) {
        logger.info("Skipping xunit file generation because TEST_XUNIT_DIR environment is not set");

        return;
    }

    File file = new File(xUnitDir, generateName(test) + ".xml");

    try {
        FileUtils.forceMkdirParent(file);

        TestSuites testSuites = convertToTestSuites(test, results, duration);

        XunitWriter xunitWriter = new XunitWriter();

        xunitWriter.saveToXML(file, testSuites);

    } catch (IOException e) {
        logger.error("Failed to generate the xunit file: {}", e.getMessage());
    }
}
 
Example 2
Source File: AnalyticsPluginAssetsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void onPluginMetadataLoad_shouldKnowPluginStaticAssetsPath() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);
    String shaHashOfZipAndPluginScript = "cfbb9309faf81a2b61277abc3b5c31486797d62b24ddfd83a2f871fc56d61ea2";
    assertEquals(Paths.get("assets", "plugins", PLUGIN_ID, shaHashOfZipAndPluginScript).toString(), assetsService.assetPathFor(PLUGIN_ID));
}
 
Example 3
Source File: AnalyticsPluginAssetsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void onPluginMetadataLoad_shouldUpdateThePluginInfoWithAssetsPath() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);
    GoPluginDescriptor goPluginDescriptor = GoPluginDescriptor.builder().id(PLUGIN_ID).build();
    AnalyticsPluginInfo analyticsPluginInfo = new AnalyticsPluginInfo(goPluginDescriptor, null, null, null);

    metadataStore.setPluginInfo(analyticsPluginInfo);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertThat(analyticsPluginInfo.getStaticAssetsPath(), is(assetsService.assetPathFor(PLUGIN_ID)));
}
 
Example 4
Source File: AnalyticsPluginAssetsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void onPluginMetadataLoad_shouldCachePluginStaticAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(testDataZipArchive());

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertFalse(dirtyPath.toFile().exists());
    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(Paths.get(railsRoot.getAbsolutePath(), "public", assetsService.assetPathFor(PLUGIN_ID), "test.txt").toFile().exists());
}
 
Example 5
Source File: AnalyticsPluginAssetsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void onPluginMetadataLoad_shouldClearExistingCacheAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path dirtyPath = Paths.get(pluginDirPath.toString(), "dirty.txt");
    FileUtils.forceMkdirParent(dirtyPath.toFile());
    Files.write(dirtyPath, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(dirtyPath.toFile().exists());

    addAnalyticsPluginInfoToStore(PLUGIN_ID);
    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);
    when(extension.getStaticAssets(PLUGIN_ID)).thenReturn(null);

    assetsService.onPluginMetadataCreate(PLUGIN_ID);

    assertFalse(dirtyPath.toFile().exists());
    assertFalse(pluginDirPath.toFile().exists());
}
 
Example 6
Source File: AnalyticsPluginAssetsServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void onPluginMetadataUnLoad_shouldClearExistingCacheAssets() throws Exception {
    railsRoot = temporaryFolder.newFolder();
    Path pluginDirPath = Paths.get(railsRoot.getAbsolutePath(), "public", "assets", "plugins", PLUGIN_ID);

    Path path = Paths.get(pluginDirPath.toString(), "foo.txt");
    FileUtils.forceMkdirParent(path.toFile());
    Files.write(path, "hello".getBytes());

    assertTrue(pluginDirPath.toFile().exists());
    assertTrue(path.toFile().exists());

    when(servletContext.getInitParameter("rails.root")).thenReturn("rails-root");
    when(servletContext.getRealPath("rails-root")).thenReturn(railsRoot.getAbsolutePath());
    when(extension.canHandlePlugin(PLUGIN_ID)).thenReturn(true);

    assetsService.onPluginMetadataRemove(PLUGIN_ID);

    assertFalse(path.toFile().exists());
    assertFalse(pluginDirPath.toFile().exists());
}
 
Example 7
Source File: NodeUpdateImportsTest.java    From flow with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    tmpRoot = temporaryFolder.getRoot();

    frontendDirectory = new File(tmpRoot, DEFAULT_FRONTEND_DIR);
    nodeModulesPath = new File(tmpRoot, NODE_MODULES);
    generatedPath = new File(tmpRoot, DEFAULT_GENERATED_DIR);
    importsFile = new File(generatedPath, IMPORTS_NAME);
    importsDefinitionFile = new File(generatedPath, IMPORTS_D_TS_NAME);
    fallBackImportsFile = new File(generatedPath,
            FrontendUtils.FALLBACK_IMPORTS_NAME);
    File webpackDir = temporaryFolder.newFolder();
    tokenFile = new File(webpackDir, "config/flow-build-info.json");
    FileUtils.forceMkdirParent(tokenFile);
    tokenFile.createNewFile();

    assertTrue(nodeModulesPath.mkdirs());
    createExpectedImports(frontendDirectory, nodeModulesPath);
    assertTrue(new File(nodeModulesPath,
            FLOW_NPM_PACKAGE_NAME + "ExampleConnector.js").exists());

    new File(frontendDirectory, "extra-javascript.js").createNewFile();
    new File(frontendDirectory, "extra-css.css").createNewFile();
}
 
Example 8
Source File: NodeUpdateTestUtil.java    From flow with Apache License 2.0 6 votes vote down vote up
public static void createStubWebpackServer(String readyString,
        int milliSecondsToRun, String baseDir) throws IOException {
    File serverFile = new File(baseDir, WEBPACK_SERVER);
    FileUtils.forceMkdirParent(serverFile);

    serverFile.createNewFile();
    serverFile.setExecutable(true);
    FileUtils.write(serverFile,
            ("#!/usr/bin/env node\n" + "const fs = require('fs');\n"
                    + "const args = String(process.argv);\n"
                    + "fs.writeFileSync('" + WEBPACK_TEST_OUT_FILE
                    + "', args);\n" + "console.log(args + '\\n[wps]: "
                    + readyString + ".');\n" + "setTimeout(() => {}, "
                    + milliSecondsToRun + ");\n"),
            "UTF-8");
}
 
Example 9
Source File: AbstractTaskClientGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws ExecutionFailedException {
    if (!shouldGenerate()) {
        return;
    }
    File generatedFile = getGeneratedFile();
    try {
        String fileContent = getFileContent();
        log().info("writing file '{}'", generatedFile);

        FileUtils.forceMkdirParent(generatedFile);
        FileUtils.writeStringToFile(generatedFile, fileContent, UTF_8);
    } catch (IOException exception) {
        String errorMessage = String.format("Error writing '%s'", generatedFile);
        throw new ExecutionFailedException(errorMessage, exception);
    }
}
 
Example 10
Source File: TaskRunNpmInstall.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the local hash to node_modules.
 * <p>
 * This is for handling updated package to the code repository by another
 * developer as then the hash is updated and we may just be missing one
 * module.
 */
private void updateLocalHash() {
    try {
        final JsonObject vaadin = packageUpdater.getPackageJson()
                .getObject(VAADIN_DEP_KEY);
        if (vaadin == null) {
            packageUpdater.log().warn("No vaadin object in package.json");
            return;
        }
        final String hash = vaadin.getString(HASH_KEY);

        final JsonObject localHash = Json.createObject();
        localHash.put(HASH_KEY, hash);

        final File localHashFile = getLocalHashFile();
        FileUtils.forceMkdirParent(localHashFile);
        String content = stringify(localHash, 2) + "\n";
        FileUtils.writeStringToFile(localHashFile, content, UTF_8.name());

    } catch (IOException e) {
        packageUpdater.log().warn("Failed to update node_modules hash.", e);
    }
}
 
Example 11
Source File: UIUtil.java    From rest-client with Apache License 2.0 6 votes vote down vote up
/**
* 
* @Title: saveFile 
* @Description: Save HTTP history to file  
* @param  
* @return void
* @throws
 */
public static void saveFile()
{
    File fhist = new File(RESTConst.HTTP_HIST_JSON);
    try
    {
        if (!fhist.exists())
        {
            FileUtils.forceMkdirParent(fhist);
            fhist.createNewFile();
        }
    }
    catch(IOException ie)
    {
        log.error("Failed to create new file.", ie);
        return;
    }

    List<HttpHist> histLst = new ArrayList<HttpHist>(RESTCache.getHists().values());
    HttpHists hists = new HttpHists(histLst);
    RESTUtil.toJsonFile(fhist, hists);
}
 
Example 12
Source File: TaskRunNpmInstallTest.java    From flow with Apache License 2.0 5 votes vote down vote up
public void writeLocalHash(String hash) throws IOException {
    final JsonObject localHash = Json.createObject();
    localHash.put(HASH_KEY, hash);

    final File localHashFile = new File(getNodeUpdater().nodeModulesFolder,
            ".vaadin/vaadin.json");
    FileUtils.forceMkdirParent(localHashFile);
    getNodeUpdater().writePackageFile(localHash, localHashFile);
}
 
Example 13
Source File: NodeUpdateTestUtil.java    From flow with Apache License 2.0 5 votes vote down vote up
public static void createStubNode(boolean stubNode, boolean stubNpm,
        boolean stubPnpm, String baseDir) throws IOException {

    if (stubNpm) {
        File npmCli = new File(baseDir,
                "node/node_modules/npm/bin/npm-cli.js");
        FileUtils.forceMkdirParent(npmCli);
        FileUtils.writeStringToFile(npmCli,
                "process.argv.includes('--version') && console.log('5.6.0');",
                StandardCharsets.UTF_8);
    }
    if (stubPnpm) {
        File ppmCli = new File(baseDir, "node_modules/pnpm/bin/pnpm.js");
        FileUtils.forceMkdirParent(ppmCli);
        FileUtils.writeStringToFile(ppmCli,
                "process.argv.includes('--version') && console.log('4.5.0');",
                StandardCharsets.UTF_8);
        new File(baseDir, "node_modules/.modules.yaml").createNewFile();
    }
    if (stubNode) {
        File node = new File(baseDir,
                FrontendUtils.isWindows() ? "node/node.exe" : "node/node");
        node.createNewFile();
        node.setExecutable(true);
        if (FrontendUtils.isWindows()) {
            // Commented out until a node.exe is created that is not flagged
            // by Windows defender.
            // FileUtils.copyFile(new File(
            // getClassFinder().getClass().getClassLoader().getResource("test_node.exe").getFile()
            // ), node);
        } else {
            FileUtils.write(node,
                    "#!/bin/sh\n[ \"$1\" = -v ] && echo 8.0.0 || sleep 1\n",
                    "UTF-8");
        }
    }
}
 
Example 14
Source File: LockDevDepVersionsMojo.java    From flow with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    File targetFile = new File(generatedDependenciesFolder,
            generatedDependencies);
    try {
        FileUtils.forceMkdirParent(targetFile);
    } catch (IOException exception) {
        throw new MojoExecutionException(
                "Can't make directories for the generated file", exception);
    }

    String content = listDevDependencies();

    JsonObject result = Json.createObject();
    JsonObject object = Json.parse(content);
    collectDeps(result, object);

    readVersionsFromPackageJson(result);

    try {
        FileUtils.write(targetFile, stringify(result, 2) + "\n",
                StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new MojoFailureException(
                "Couldn't write dependencies into the target file", e);
    }
}
 
Example 15
Source File: NodeUpdater.java    From flow with Apache License 2.0 5 votes vote down vote up
String writePackageFile(JsonObject json, File packageFile)
        throws IOException {
    log().info("writing file {}.", packageFile.getAbsolutePath());
    FileUtils.forceMkdirParent(packageFile);
    String content = stringify(json, 2) + "\n";
    FileUtils.writeStringToFile(packageFile, content, UTF_8.name());
    return content;
}
 
Example 16
Source File: FileTools.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public static void unzip(File fileZip,File dest) throws IOException 
{
	
	if(!dest.isDirectory())
		throw new IOException(dest + " is not a directory");
	
	try(ZipFile zipFile = new ZipFile(fileZip)){
		Enumeration<? extends ZipEntry> entries = zipFile.entries();
		while (entries.hasMoreElements()) 
		{
			ZipEntry zipEntry = entries.nextElement();
        	File f = new File(dest, zipEntry.getName());
        	
        	if(zipEntry.isDirectory())
        	{
        		FileUtils.forceMkdir(f);
        	}
        	else
        	{
        		FileUtils.forceMkdirParent(f);
        		FileUtils.touch(f);
        	}
        	
        	
	       	try(FileOutputStream fos = new FileOutputStream(f))
	       	{
	       		IOUtils.write(zipFile.getInputStream(zipEntry).readAllBytes(), fos);
	       	}
	         
	    }
	}
}
 
Example 17
Source File: DeployController.java    From reposilite with Apache License 2.0 5 votes vote down vote up
public Result<Context, String> deploy(Context context) {
    if (!configuration.isDeployEnabled()) {
        return Result.error("Artifact deployment is disabled");
    }

    Result<Session, String> authResult = this.authenticator.authDefault(context);

    if (authResult.containsError()) {
        return Result.error(authResult.getError());
    }

    File file = repositoryService.getFile(context.req.getRequestURI());
    File metadataFile = new File(file.getParentFile(), "maven-metadata.xml");
    metadataService.clearMetadata(metadataFile);

    if (file.getName().contains("maven-metadata")) {
        return Result.ok(context.result("Success"));
    }

    try {
        FileUtils.forceMkdirParent(file);
        Files.copy(Objects.requireNonNull(context.req.getInputStream()), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        return Result.ok(context.result("Success"));
    } catch (IOException e) {
        reposilite.throwException(context.req.getRequestURI(), e);
        return Result.error("Failed to upload artifact");
    }
}
 
Example 18
Source File: HeadlessDriverUtils.java    From headless-chrome with MIT License 5 votes vote down vote up
public static void takeFullScreenshot(WebDriver webDriver, File pngFile, By... highlights)
        throws IOException {
    final PageSnapshot pageSnapshot = Shutterbug.shootPage(webDriver, BOTH_DIRECTIONS);
    if (ArrayUtils.isNotEmpty(highlights)) {
        Arrays.stream(highlights)
                .map(webDriver::findElements)
                .flatMap(Collection::stream)
                .forEach(pageSnapshot::highlight);
    }
    FileUtils.forceMkdirParent(pngFile);
    pageSnapshot.withName(pngFile.getName());
    pageSnapshot.save(pngFile.getParent());
    FileUtils.deleteQuietly(pngFile);
    FileUtils.moveFile(new File(pngFile.getPath() + ".png"), pngFile);
}
 
Example 19
Source File: JarUtil.java    From gocd with Apache License 2.0 5 votes vote down vote up
private static File extractJarEntry(JarFile jarFile, JarEntry jarEntry, File targetFile) {
    LOG.debug("Extracting {}!/{} -> {}", jarFile, jarEntry, targetFile);
    try (InputStream inputStream = jarFile.getInputStream(jarEntry)) {
        FileUtils.forceMkdirParent(targetFile);
        Files.copy(inputStream, targetFile.toPath());
        return targetFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 20
Source File: InstallManagerService.java    From fdroidclient with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Check if any OBB files are available, and if so, download and install them. This
 * also deletes any obsolete OBB files, per the spec, since there can be only one
 * "main" and one "patch" OBB installed at a time.
 *
 * @see <a href="https://developer.android.com/google/play/expansion-files.html">APK Expansion Files</a>
 */
private void getObb(final String canonicalUrl, String obbUrlString,
                    final File obbDestFile, final String hash, final long repoId) {
    if (obbDestFile == null || obbDestFile.exists() || TextUtils.isEmpty(obbUrlString)) {
        return;
    }
    final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!running) {
                localBroadcastManager.unregisterReceiver(this);
                return;
            }
            String action = intent.getAction();
            if (Downloader.ACTION_STARTED.equals(action)) {
                Utils.debugLog(TAG, action + " " + intent);
            } else if (Downloader.ACTION_PROGRESS.equals(action)) {

                long bytesRead = intent.getLongExtra(Downloader.EXTRA_BYTES_READ, 0);
                long totalBytes = intent.getLongExtra(Downloader.EXTRA_TOTAL_BYTES, 0);
                appUpdateStatusManager.updateApkProgress(canonicalUrl, totalBytes, bytesRead);
            } else if (Downloader.ACTION_COMPLETE.equals(action)) {
                localBroadcastManager.unregisterReceiver(this);
                File localFile = new File(intent.getStringExtra(Downloader.EXTRA_DOWNLOAD_PATH));
                Uri localApkUri = Uri.fromFile(localFile);
                Utils.debugLog(TAG, "OBB download completed " + intent.getDataString()
                        + " to " + localApkUri);

                try {
                    if (Hasher.isFileMatchingHash(localFile, hash, "sha256")) {
                        Utils.debugLog(TAG, "Installing OBB " + localFile + " to " + obbDestFile);
                        FileUtils.forceMkdirParent(obbDestFile);
                        FileUtils.copyFile(localFile, obbDestFile);
                        FileFilter filter = new WildcardFileFilter(
                                obbDestFile.getName().substring(0, 4) + "*.obb");
                        for (File f : obbDestFile.getParentFile().listFiles(filter)) {
                            if (!f.equals(obbDestFile)) {
                                Utils.debugLog(TAG, "Deleting obsolete OBB " + f);
                                FileUtils.deleteQuietly(f);
                            }
                        }
                    } else {
                        Utils.debugLog(TAG, localFile + " deleted, did not match hash: " + hash);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    FileUtils.deleteQuietly(localFile);
                }
            } else if (Downloader.ACTION_INTERRUPTED.equals(action)) {
                localBroadcastManager.unregisterReceiver(this);
            } else if (Downloader.ACTION_CONNECTION_FAILED.equals(action)) {
                DownloaderService.queueUsingDifferentMirror(context, repoId, canonicalUrl);
            } else {
                throw new RuntimeException("intent action not handled!");
            }
        }
    };
    DownloaderService.queueUsingRandomMirror(this, repoId, obbUrlString);
    localBroadcastManager.registerReceiver(downloadReceiver,
            DownloaderService.getIntentFilter(obbUrlString));
}