Example usage for org.apache.commons.io FileUtils cleanDirectory

List of usage examples for org.apache.commons.io FileUtils cleanDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils cleanDirectory.

Prototype

public static void cleanDirectory(File directory) throws IOException 

Source Link

Document

Cleans a directory without deleting it.

Usage

From source file:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java

@Override
public void kill(TopologyLayout topology, String asUser) throws Exception {
    String stormTopologyId = getRuntimeTopologyId(topology, asUser);

    boolean killed = client.killTopology(stormTopologyId, asUser, DEFAULT_WAIT_TIME_SEC);
    if (!killed) {
        throw new Exception("Topology could not be killed " + "successfully.");
    }//from   w w  w  .j  av a2 s  . c  o  m
    File artifactsDir = getArtifactsLocation(topology).toFile();
    if (artifactsDir.exists() && artifactsDir.isDirectory()) {
        LOG.debug("Cleaning up {}", artifactsDir);
        FileUtils.cleanDirectory(artifactsDir);
    }
}

From source file:com.uwsoft.editor.proxy.ResolutionManager.java

public void rePackProjectImages(ResolutionEntryVO resEntry) {
    ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
    TexturePacker.Settings settings = new TexturePacker.Settings();

    settings.flattenPaths = true;/* w ww.ja v a 2  s . co m*/
    //        settings.maxHeight = getMinSquareNum(resEntry.height);
    //        settings.maxWidth = getMinSquareNum(resEntry.height);
    settings.maxHeight = Integer.parseInt(projectManager.getCurrentProjectVO().texturepackerHeight);
    settings.maxWidth = Integer.parseInt(projectManager.getCurrentProjectVO().texturepackerWidth);
    settings.filterMag = Texture.TextureFilter.Linear;
    settings.filterMin = Texture.TextureFilter.Linear;
    settings.duplicatePadding = projectManager.getCurrentProjectVO().texturepackerDuplicate;

    TexturePacker tp = new TexturePacker(settings);

    String sourcePath = projectManager.getCurrentProjectPath() + "/assets/" + resEntry.name + "/images";
    String outputPath = projectManager.getCurrentProjectPath() + "/assets/" + resEntry.name + "/pack";

    FileHandle sourceDir = new FileHandle(sourcePath);
    File outputDir = new File(outputPath);

    try {
        FileUtils.forceMkdir(outputDir);
        FileUtils.cleanDirectory(outputDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (FileHandle entry : sourceDir.list()) {
        String filename = entry.file().getName();
        String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length()).toLowerCase();
        if (extension.equals("png")) {
            tp.addImage(entry.file());
        }
    }

    tp.pack(outputDir, "pack");
}

From source file:com.photon.maven.plugins.android.phase05compile.NdkBuildMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    // Validate the NDK
    final File ndkBuildFile = new File(getAndroidNdk().getNdkBuildPath());
    NativeHelper.validateNDKVersion(ndkBuildFile.getParentFile());

    // This points 
    File nativeLibDirectory = new File(nativeLibrariesOutputDirectory, ndkArchitecture);

    final boolean libsDirectoryExists = nativeLibDirectory.exists();

    File directoryToRemove = nativeLibDirectory;

    if (!libsDirectoryExists) {
        getLog().info("Creating native output directory " + nativeLibDirectory);

        if (nativeLibDirectory.getParentFile().exists()) {
            nativeLibDirectory.mkdir();/*from w  w w  . j  a  v a  2  s  .c  o  m*/
        } else {
            nativeLibDirectory.mkdirs();
            directoryToRemove = nativeLibDirectory.getParentFile();
        }

    }

    final CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();

    executor.setErrorListener(new CommandExecutor.ErrorListener() {
        @Override
        public boolean isError(String error) {

            Pattern pattern = Pattern.compile(buildWarningsRegularExpression);
            Matcher matcher = pattern.matcher(error);

            if (ignoreBuildWarnings && matcher.matches()) {
                return false;
            }
            return true;
        }
    });

    final Set<Artifact> nativeLibraryArtifacts = findNativeLibraryDependencies();
    // If there are any static libraries the code needs to link to, include those in the make file
    final Set<Artifact> resolveNativeLibraryArtifacts = AetherHelper.resolveArtifacts(nativeLibraryArtifacts,
            repoSystem, repoSession, projectRepos);

    try {
        File f = File.createTempFile("android_maven_plugin_makefile", ".mk");
        f.deleteOnExit();

        String makeFile = MakefileHelper.createMakefileFromArtifacts(f.getParentFile(),
                resolveNativeLibraryArtifacts, useHeaderArchives, repoSession, projectRepos, repoSystem);
        IOUtil.copy(makeFile, new FileOutputStream(f));

        // Add the path to the generated makefile
        executor.addEnvironment("ANDROID_MAVEN_PLUGIN_MAKEFILE", f.getAbsolutePath());

        // Only add the LOCAL_STATIC_LIBRARIES
        if (NativeHelper.hasStaticNativeLibraryArtifact(resolveNativeLibraryArtifacts)) {
            executor.addEnvironment("ANDROID_MAVEN_PLUGIN_LOCAL_STATIC_LIBRARIES",
                    MakefileHelper.createStaticLibraryList(resolveNativeLibraryArtifacts, true));
        }
        if (NativeHelper.hasSharedNativeLibraryArtifact(resolveNativeLibraryArtifacts)) {
            executor.addEnvironment("ANDROID_MAVEN_PLUGIN_LOCAL_SHARED_LIBRARIES",
                    MakefileHelper.createStaticLibraryList(resolveNativeLibraryArtifacts, false));
        }

    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    File localCIncludesFile = null;
    //
    try {
        localCIncludesFile = File.createTempFile("android_maven_plugin_makefile_captures", ".tmp");
        localCIncludesFile.deleteOnExit();
        executor.addEnvironment("ANDROID_MAVEN_PLUGIN_LOCAL_C_INCLUDES_FILE",
                localCIncludesFile.getAbsolutePath());
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage());
    }

    // Add any defined system properties
    if (systemProperties != null && !systemProperties.isEmpty()) {
        for (Map.Entry<String, String> entry : systemProperties.entrySet()) {
            executor.addEnvironment(entry.getKey(), entry.getValue());
        }
    }

    executor.setLogger(this.getLog());
    final List<String> commands = new ArrayList<String>();

    commands.add("-C");
    if (ndkBuildDirectory == null) {
        ndkBuildDirectory = project.getBasedir().getAbsolutePath();
    }
    commands.add(ndkBuildDirectory);

    if (ndkBuildAdditionalCommandline != null) {
        String[] additionalCommands = ndkBuildAdditionalCommandline.split(" ");
        for (final String command : additionalCommands) {
            commands.add(command);
        }
    }

    // If a build target is specified, tag that onto the command line as the
    // very last of the parameters
    if (target != null) {
        commands.add(target);
    } else {
        commands.add(project.getArtifactId());
    }

    final String ndkBuildPath = resolveNdkBuildExecutable();
    getLog().info(ndkBuildPath + " " + commands.toString());

    try {
        executor.executeCommand(ndkBuildPath, commands, project.getBasedir(), true);
    } catch (ExecutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    // Cleanup libs/armeabi directory if needed - this implies moving any native artifacts into target/libs
    if (clearNativeArtifacts) {

        final File destinationDirectory = new File(ndkOutputDirectory.getAbsolutePath(), "/" + ndkArchitecture);

        try {
            if (!libsDirectoryExists) {
                FileUtils.moveDirectory(nativeLibDirectory, destinationDirectory);
            } else {
                FileUtils.copyDirectory(nativeLibDirectory, destinationDirectory);
                FileUtils.cleanDirectory(nativeLibDirectory);
            }

            nativeLibDirectory = destinationDirectory;

        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    if (!libsDirectoryExists) {
        getLog().info("Cleaning up native library output directory after build");
        getLog().debug("Removing directory: " + directoryToRemove);
        if (!directoryToRemove.delete()) {
            getLog().warn("Could not remove directory, marking as delete on exit");
            directoryToRemove.deleteOnExit();
        }
    }

    // Attempt to attach the native library if the project is defined as a "pure" native Android library
    // (packaging is 'so' or 'a') or if the plugin has been configured to attach the native library to the build
    if ("so".equals(project.getPackaging()) || "a".equals(project.getPackaging()) || attachNativeArtifacts) {

        File[] files = nativeLibDirectory.listFiles(new FilenameFilter() {
            public boolean accept(final File dir, final String name) {
                if ("a".equals(project.getPackaging())) {
                    return name.startsWith("lib" + (target != null ? target : project.getArtifactId()))
                            && name.endsWith(".a");
                } else {
                    return name.startsWith("lib" + (target != null ? target : project.getArtifactId()))
                            && name.endsWith(".so");
                }
            }
        });

        // slight limitation at this stage - we only handle a single .so artifact
        if (files == null || files.length != 1) {
            getLog().warn("Error while detecting native compile artifacts: "
                    + (files == null || files.length == 0 ? "None found" : "Found more than 1 artifact"));
            if (files != null && files.length > 1) {
                getLog().error("Currently, only a single, final native library is supported by the build");
                throw new MojoExecutionException(
                        "Currently, only a single, final native library is supported by the build");
            } else {
                getLog().error(
                        "No native compiled library found, did the native compile complete successfully?");
                throw new MojoExecutionException(
                        "No native compiled library found, did the native compile complete successfully?");
            }
        } else {
            getLog().debug("Adding native compile artifact: " + files[0]);
            final String artifactType = resolveArtifactType(files[0]);
            projectHelper.attachArtifact(this.project, artifactType,
                    (ndkClassifier != null ? ndkClassifier : ndkArchitecture), files[0]);
        }

    }

    // Process conditionally any of the headers to include into the header archive file
    processHeaderFileIncludes(localCIncludesFile);

}

From source file:com.o2d.pkayjava.editor.proxy.ResolutionManager.java

public void rePackProjectImages(ResolutionEntryVO resEntry) {
    ProjectManager projectManager = facade.retrieveProxy(ProjectManager.NAME);
    TexturePacker.Settings settings = new TexturePacker.Settings();

    settings.flattenPaths = true;/*from   w  w w.j a v a 2  s.c o m*/
    //        settings.maxHeight = getMinSquareNum(resEntry.height);
    //        settings.maxWidth = getMinSquareNum(resEntry.height);
    settings.maxHeight = Integer.parseInt(projectManager.getCurrentProjectVO().texturepackerHeight);
    settings.maxWidth = Integer.parseInt(projectManager.getCurrentProjectVO().texturepackerWidth);
    settings.filterMag = Texture.TextureFilter.Linear;
    settings.filterMin = Texture.TextureFilter.Linear;

    TexturePacker tp = new TexturePacker(settings);

    String sourcePath = projectManager.getCurrentWorkingPath() + "/"
            + projectManager.getCurrentProjectVO().projectName + "/assets/" + resEntry.name + "/images";
    String outputPath = projectManager.getCurrentWorkingPath() + "/"
            + projectManager.getCurrentProjectVO().projectName + "/assets/" + resEntry.name + "/pack";

    FileHandle sourceDir = new FileHandle(sourcePath);
    File outputDir = new File(outputPath);

    try {
        FileUtils.forceMkdir(outputDir);
        FileUtils.cleanDirectory(outputDir);
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (FileHandle entry : sourceDir.list()) {
        String filename = entry.file().getName();
        String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length()).toLowerCase();
        if (extension.equals("png")) {
            tp.addImage(entry.file());
        }
    }

    tp.pack(outputDir, "pack");
}

From source file:fr.gael.dhus.service.SystemService.java

/**
* Performs Solr restoration.//from w  w  w. ja v a 2  s.c  o  m
*
* @param properties properties containing arguments to execute the restoration.
*/
private static void restoreSolr4Index(Properties properties) throws IOException, SolrServerException {
    String solr_home = properties.getProperty("dhus.solr.home");
    String core_name = properties.getProperty("dhus.solr.core.name");
    final String name = properties.getProperty("dhus.solr.backup.name");
    final String location = properties.getProperty("dhus.solr.backup.location");

    if (solr_home == null || core_name == null || name == null || location == null)
        throw new UnsupportedOperationException();

    System.setProperty("solr.solr.home", solr_home);
    File index_path = new File(location, "snapshot." + name);
    File target_path = Paths.get(solr_home, core_name, "data", name).toFile();

    if (!index_path.exists())
        throw new UnsupportedOperationException("solr source to restore not found (" + index_path + ").");
    if (!target_path.exists())
        throw new UnsupportedOperationException("solr restore path not found (" + target_path + ").");

    FileUtils.cleanDirectory(target_path);
    FileUtils.copyDirectory(index_path, target_path);

    logger.info("SolR indexes restored.");
}

From source file:com.fsck.k9.helper.Utility.java

public static void clearTemporaryAttachmentsCache(Context context) {
    File cacheDir = context.getCacheDir();
    File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY);
    if (tempAttachmentsDirectory.exists()) {
        try {// w ww . j av  a 2 s  .  co m
            FileUtils.cleanDirectory(tempAttachmentsDirectory);
        } catch (IOException e) {
            Timber.e(e, "Error occurred while cleaning temporary directory for resized attachments");
        }
    }
}

From source file:com.alibaba.jstorm.daemon.nimbus.ServiceHandler.java

@Override
public void restart(String name, String jsonConf)
        throws TException, NotAliveException, InvalidTopologyException, TopologyAssignException {
    LOG.info("Begin to restart " + name + ", new configuration:" + jsonConf);

    // 1. get topologyId
    StormClusterState stormClusterState = data.getStormClusterState();
    String topologyId;/*from   ww w  .j  av a  2s .c o  m*/
    try {
        topologyId = Cluster.get_topology_id(stormClusterState, name);
    } catch (Exception e2) {
        topologyId = null;
    }
    if (topologyId == null) {
        LOG.info("No topology of " + name);
        throw new NotAliveException("No topology of " + name);
    }

    // Restart the topology: Deactivate -> Kill -> Submit
    // 2. Deactivate
    deactivate(name);
    JStormUtils.sleepMs(5000);
    LOG.info("Deactivate " + name);

    // 3. backup old jar/configuration/topology
    StormTopology topology;
    Map topologyConf;
    String topologyCodeLocation = null;
    try {
        topology = StormConfig.read_nimbus_topology_code(conf, topologyId);
        topologyConf = StormConfig.read_nimbus_topology_conf(conf, topologyId);
        if (jsonConf != null) {
            Map<Object, Object> newConf = (Map<Object, Object>) JStormUtils.from_json(jsonConf);
            topologyConf.putAll(newConf);
        }

        // Copy storm files back to stormdist dir from the tmp dir
        String oldDistDir = StormConfig.masterStormdistRoot(conf, topologyId);
        String parent = StormConfig.masterInbox(conf);
        topologyCodeLocation = parent + PathUtils.SEPERATOR + topologyId;
        FileUtils.forceMkdir(new File(topologyCodeLocation));
        FileUtils.cleanDirectory(new File(topologyCodeLocation));
        File stormDistDir = new File(oldDistDir);
        stormDistDir.setLastModified(System.currentTimeMillis());
        FileUtils.copyDirectory(stormDistDir, new File(topologyCodeLocation));

        LOG.info("Successfully read old jar/conf/topology " + name);
    } catch (Exception e) {
        LOG.error("Failed to read old jar/conf/topology", e);
        if (topologyCodeLocation != null) {
            try {
                PathUtils.rmr(topologyCodeLocation);
            } catch (IOException ignored) {
            }
        }
        throw new TException("Failed to read old jar/conf/topology ");

    }

    // 4. Kill
    // directly use remove command to kill, more stable than issue kill cmd
    RemoveTransitionCallback killCb = new RemoveTransitionCallback(data, topologyId);
    killCb.execute(new Object[0]);
    LOG.info("Successfully kill the topology " + name);

    // send metric events
    TopologyMetricsRunnable.KillTopologyEvent killEvent = new TopologyMetricsRunnable.KillTopologyEvent();
    killEvent.clusterName = this.data.getClusterName();
    killEvent.topologyId = topologyId;
    killEvent.timestamp = System.currentTimeMillis();
    this.data.getMetricRunnable().pushEvent(killEvent);

    Remove removeEvent = new Remove();
    removeEvent.topologyId = topologyId;
    this.data.getMetricRunnable().pushEvent(removeEvent);

    // 5. submit
    try {
        submitTopology(name, topologyCodeLocation, JStormUtils.to_json(topologyConf), topology);
    } catch (AlreadyAliveException e) {
        LOG.info("Failed to kill the topology" + name);
        throw new TException("Failed to kill the topology" + name);
    } finally {
        try {
            PathUtils.rmr(topologyCodeLocation);
        } catch (IOException ignored) {
        }
    }

}

From source file:edu.duke.cabig.c3pr.webservice.integration.C3PREmbeddedTomcatTestBase.java

/**
 * @throws RuntimeException//from  w w  w  . j  a v  a  2  s.com
 */
private void initCatalinaHome() throws RuntimeException {
    String catalinaHomeEnv = System.getenv(CATALINA_HOME);
    if (StringUtils.isBlank(catalinaHomeEnv)) {
        throw new RuntimeException("CATALINA_HOME is not set by the Ant script.");
    }

    catalinaHome = new File(catalinaHomeEnv);
    if (!catalinaHome.exists() || !catalinaHome.isDirectory()
            || (catalinaHome.list().length > 0 && !isCatalinaHomeSafe())) {
        catalinaHome = null;
        throw new RuntimeException("CATALINA_HOME must point to an existent and empty directory.");
    }
    try {
        FileUtils.cleanDirectory(catalinaHome);
    } catch (IOException e) {
    }
}

From source file:com.uwsoft.editor.controlles.ResolutionManager.java

public void resizeImagesTmpDirToResolution(String packName, File sourceFolder, ResolutionEntryVO resolution,
        File targetFolder) {/*w  w w.j  a  v a  2s. c  o m*/
    float ratio = ResolutionManager.getResolutionRatio(resolution,
            dataManager.getCurrentProjectInfoVO().originalResolution);

    if (targetFolder.exists()) {
        try {
            FileUtils.cleanDirectory(targetFolder);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // now pack
    TexturePacker.Settings settings = new TexturePacker.Settings();

    settings.flattenPaths = true;
    settings.maxHeight = getMinSquareNum(resolution.height);
    settings.maxWidth = getMinSquareNum(resolution.height);
    settings.filterMag = Texture.TextureFilter.Linear;
    settings.filterMin = Texture.TextureFilter.Linear;

    TexturePacker tp = new TexturePacker(settings);
    for (final File fileEntry : sourceFolder.listFiles()) {
        if (!fileEntry.isDirectory()) {
            BufferedImage bufferedImage = ResolutionManager.imageResize(fileEntry, ratio);
            tp.addImage(bufferedImage, FilenameUtils.removeExtension(fileEntry.getName()));
        }
    }

    tp.pack(targetFolder, packName);
}

From source file:com.gemstone.gemfire.management.internal.configuration.SharedConfigurationEndToEndDUnitTest.java

private void shutdownAll() throws IOException {
    VM locatorAndMgr = Host.getHost(0).getVM(3);
    locatorAndMgr.invoke(new SerializableCallable() {
        /**//from w w w  .  j a va 2  s.  c o  m
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public Object call() throws Exception {
            GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
            ShutdownAllRequest.send(cache.getDistributedSystem().getDistributionManager(), -1);
            return null;
        }
    });

    locatorAndMgr.invoke(SharedConfigurationDUnitTest.locatorCleanup);
    //Clean up the directories
    if (!serverNames.isEmpty()) {
        for (String serverName : serverNames) {
            final File serverDir = new File(serverName);
            FileUtils.cleanDirectory(serverDir);
            FileUtils.deleteDirectory(serverDir);
        }
    }
    serverNames.clear();
    serverNames = null;
}