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

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

Introduction

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

Prototype

public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException 

Source Link

Document

Copies a filtered directory to a new location preserving the file dates.

Usage

From source file:com.zotoh.maedr.etc.CmdSamples.java

private void create3s(File appdir, File src, String ptr, Properties props) throws Exception {
    File f, t = new File(appdir, SRC);
    String s, lang = props.getProperty("lang");
    File j = new File(t, lang + "/demo/" + ptr);
    j.mkdirs();/*from  www . j a v  a 2 s  .  c  o m*/
    FileUtils.copyDirectory(new File(src, ptr + "/" + lang), j, new NotFileFilter(new SuffixFileFilter(".mf")));
    Iterator<File> it = FileUtils.iterateFiles(j, new SuffixFileFilter("." + lang), null);
    while (it.hasNext()) {
        f = it.next();
        s = StreamUte.readFile(f, "utf-8");
        s = strstr(s, "demo." + ptr + "." + lang, "demo." + ptr);
        StreamUte.writeFile(f, s, "utf-8");
    }
}

From source file:atg.tools.dynunit.test.AtgDustCase.java

/**
 * Every *.properties file copied using this method will have it's scope (if one is available) set to global.
 *
 * @param sourceDirectories//w w  w. j av a2  s  . c  o m
 *         One or more directories containing needed configuration files.
 * @param destinationDirectory
 *         where to copy the above files to. This will also be the
 *         configuration location.
 * @param excludedDirectories
 *         One or more directories not to include during the copy
 *         process. Use this one to speeds up the test cycle
 *         considerably. You can also call it with an empty
 *         {@link String[]} or <code>null</code> if nothing should be
 *         excluded
 *
 * @throws IOException
 *         Whenever some file related error's occur.
 */
protected final void copyConfigurationFiles(@NotNull final String[] sourceDirectories,
        @NotNull final String destinationDirectory, @Nullable final String... excludedDirectories)
        throws IOException {
    logger.entry(sourceDirectories, destinationDirectory, excludedDirectories);
    setConfigurationLocation(destinationDirectory);

    logger.info("Copying configurating files and forcing global scope on all configs.");
    preCopyingOfConfigurationFiles(sourceDirectories, excludedDirectories);
    for (final String sourceDirectory : sourceDirectories) {
        FileUtils.copyDirectory(new File(sourceDirectory), new File(destinationDirectory), new FileFilter() {
            @Override
            public boolean accept(final File file) {
                return ArrayUtils.contains(excludedDirectories, file.getName());
            }
        });
    }
    forceGlobalScopeOnAllConfigs(destinationDirectory);

    if (FileUtil.isDirty()) {
        FileUtil.serialize(GLOBAL_FORCE_SER, FileUtil.getConfigFilesTimestamps());
    }
    logger.exit();
}

From source file:com.eviware.soapui.integration.exporter.ProjectExporter.java

/**
 * Do actual dependency copying and update project's copy dependency path.
 * /* www . jav a2s .  c o  m*/
 * @throws IOException
 */
private boolean copyDependencies() throws IOException {
    boolean result = true;
    projectCopy.setResourceRoot("${projectDir}");
    List<ExternalDependency> dependencies = projectCopy.getExternalDependencies();
    for (ExternalDependency dependency : dependencies) {
        switch (dependency.getType()) {
        case FILE:
            File originalDependency = new File(dependency.getPath());
            if (originalDependency.exists()) {
                File targetDependency = new File(tmpDir, originalDependency.getName());
                FileUtils.copyFile(originalDependency, targetDependency);
                dependency.updatePath(targetDependency.getPath());
            } else {
                SoapUI.log.warn("Do not exists on local file system [" + originalDependency.getPath() + "]");
            }
            break;
        case FOLDER:
            originalDependency = new File(dependency.getPath());
            File targetDependency = new File(tmpDir, originalDependency.getName());
            targetDependency.mkdir();
            FileUtils.copyDirectory(originalDependency, targetDependency, false);
            dependency.updatePath(targetDependency.getPath());
            break;
        default:
            break;
        }
    }

    return result;
}

From source file:com.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

@GET
@Path("packages/prepare")
@Produces(MediaType.TEXT_PLAIN)/*from   w w w.ja va2s .c  o  m*/
public String prepareDynamicPackages(@QueryParam("path") String techWorkspaceDir,
        @QueryParam("options") String options, @QueryParam("techs") String techs) throws IOException {
    if (techWorkspaceDir != null && !techWorkspaceDir.trim().isEmpty()) {
        File packageDir = new File(techWorkspaceDir + "/package");
        if (packageDir.exists() && packageDir.isDirectory()) {
            FileUtils.deleteDirectory(packageDir);
            log.finer("Deleted package directory : " + techWorkspaceDir + "/package");
        }

        if (options != null && !options.trim().isEmpty()) {
            String[] techOptions = options.split(",");
            String codeGenType = techOptions.length >= 1 ? techOptions[0] : null;

            if ("server".equals(codeGenType)) {
                String codeGenSrcDirPath = techWorkspaceDir + "/" + codeGenType + "/src";
                File codeGenSrcDir = new File(codeGenSrcDirPath);

                if (codeGenSrcDir.exists() && codeGenSrcDir.isDirectory()) {
                    String packageSrcDirPath = techWorkspaceDir + "/package/src";
                    File packageSrcDir = new File(packageSrcDirPath);
                    FileUtils.copyDirectory(codeGenSrcDir, packageSrcDir,
                            FileFilterUtils.notFileFilter(new NameFileFilter(
                                    new String[] { "RestApplication.java", "AndroidManifest.xml" })));
                    log.fine("Copied files from " + codeGenSrcDirPath + " to " + packageSrcDirPath);
                } else {
                    log.fine("Swagger code gen source directory doesn't exist : " + codeGenSrcDirPath);
                }
            } else {
                log.fine("Invalid options : " + options);
                return "Invalid options : " + options;
            }
        }

        if (techs != null && !techs.trim().isEmpty()) {
            //Perform actions based on other technologies/micro-services that were selected by the user
            String[] techList = techs.split(",");
            boolean restEnabled = false;
            boolean servletEnabled = false;
            for (String tech : techList) {
                switch (tech) {
                case "rest":
                    restEnabled = true;
                    break;
                case "web":
                    servletEnabled = true;
                    break;
                }
            }
            log.finer("Enabled : REST=" + restEnabled + " : Servlet=" + servletEnabled);

            if (restEnabled) {
                // Swagger and REST are selected. Add Swagger annotations to the REST sample application.
                String restSampleAppPath = getSharedResourceDir()
                        + "appAccelerator/swagger/samples/rest/LibertyRestEndpoint.java";
                File restSampleApp = new File(restSampleAppPath);
                if (restSampleApp.exists()) {
                    String targetRestSampleFile = techWorkspaceDir
                            + "/package/src/main/java/application/rest/LibertyRestEndpoint.java";
                    FileUtils.copyFile(restSampleApp, new File(targetRestSampleFile));
                    log.finer("Successfuly copied " + restSampleAppPath + " to " + targetRestSampleFile);
                } else {
                    log.fine("No swagger annotations were added : " + restSampleApp.getAbsolutePath()
                            + " : exists=" + restSampleApp.exists());
                }
            }

            if (servletEnabled) {
                //Swagger and Servlet are selected. Add swagger.json stub that describes the servlet endpoint to META-INF/stub directory.
                String swaggerStubPath = getSharedResourceDir()
                        + "appAccelerator/swagger/samples/servlet/swagger.json";
                File swaggerStub = new File(swaggerStubPath);
                if (swaggerStub.exists()) {
                    String targetStubPath = techWorkspaceDir
                            + "/package/src/main/webapp/META-INF/stub/swagger.json";
                    FileUtils.copyFile(swaggerStub, new File(targetStubPath));
                    log.finer("Successfuly copied " + swaggerStubPath + " to " + targetStubPath);
                } else {
                    log.fine("Didn't add swagger.json stub : " + swaggerStub.getAbsolutePath() + " : exists="
                            + swaggerStub.exists());
                }
            }
        }
    } else {
        log.fine("Invalid path : " + techWorkspaceDir);
        return "Invalid path";
    }

    return "success";
}

From source file:net.sf.eclipsecs.core.config.CheckConfigurationFactory.java

/**
 * Transfers the internal checkstyle settings and configurations to a new workspace.
 * /*  w ww  .  j  a v a2 s .c  o  m*/
 * @param targetWorkspaceRoot
 *            the target workspace root
 * @throws CheckstylePluginException
 *             if the transfer failed
 */
public static void transferInternalConfiguration(IPath targetWorkspaceRoot) throws CheckstylePluginException {

    IPath targetStateLocation = getTargetStateLocation(targetWorkspaceRoot);

    File targetLocationFile = targetStateLocation.toFile();

    try {

        targetLocationFile.mkdirs();

        FileUtils.copyDirectory(CheckstylePlugin.getDefault().getStateLocation().toFile(), targetLocationFile,
                true);
    } catch (IllegalStateException e) {
        CheckstylePluginException.rethrow(e);
    } catch (IOException e) {
        CheckstylePluginException.rethrow(e);
    }
}

From source file:com.asakusafw.testdriver.compiler.util.DeploymentUtil.java

private static void doCopy(File source, File destination) throws IOException {
    if (source.isFile()) {
        FileUtils.copyFile(source, destination, false);
    } else {//from  w  w  w .ja v a 2  s.  co m
        FileUtils.copyDirectory(source, destination, false);
    }
}

From source file:com.fanniemae.ezpie.actions.Directory.java

protected String copyDirectory() throws IOException {
    if (StringUtilities.isNullOrEmpty(_destinationPath)) {
        throw new PieException(String.format("%s is missing a value for DestinationPath.", _actionName));
    }/*w ww  .  j ava  2s . c o  m*/
    if (FileUtilities.isValidDirectory(_destinationPath)) {
        throw new PieException(String.format("Destination directory (%s) already exists.", _destinationPath));
    }
    _session.addLogMessage("", "Destination Path", _destinationPath);
    _session.addLogMessage("", "Process", "Copy directory");
    FileUtils.copyDirectory(new File(_path), new File(_destinationPath), true);
    return "";
}

From source file:hu.bme.mit.sette.common.tasks.RunnerProjectGenerator.java

/**
 * Writes the runner project out.//from ww w . ja v a 2 s.c o m
 *
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ParseException
 *             If the source code has parser errors.
 * @throws ParserConfigurationException
 *             If a DocumentBuilder cannot be created which satisfies the
 *             configuration requested or when it is not possible to create
 *             a Transformer instance.
 * @throws TransformerException
 *             If an unrecoverable error occurs during the course of the
 *             transformation.
 */
private void writeRunnerProject()
        throws IOException, ParseException, ParserConfigurationException, TransformerException {
    // TODO revise whole method
    // TODO now using JAPA, which does not support Java 7 -> maybe ANTLR
    // supports
    // better

    // create INFO file
    // TODO later maybe use an XML file!!!

    File infoFile = new File(getRunnerProjectSettings().getBaseDirectory(), "SETTE-INFO");

    StringBuilder infoFileData = new StringBuilder();
    infoFileData.append("Tool name: " + getTool().getName()).append('\n');
    infoFileData.append("Tool version: " + getTool().getVersion()).append('\n');
    infoFileData.append("Tool supported Java version: " + getTool().getSupportedJavaVersion()).append('\n');

    // TODO externalise somewhere the date format string
    String generatedAt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    infoFileData.append("Generated at: ").append(generatedAt).append('\n');

    String id = generatedAt + ' ' + getTool().getName() + " (" + getTool().getVersion() + ')';
    infoFileData.append("ID: ").append(id).append('\n');

    FileUtils.write(infoFile, infoFileData);

    // copy snippets
    FileUtils.copyDirectory(getSnippetProjectSettings().getSnippetSourceDirectory(),
            getRunnerProjectSettings().getSnippetSourceDirectory(), false);

    // remove SETTE annotations and imports from file
    Collection<File> filesWritten = FileUtils.listFiles(getRunnerProjectSettings().getSnippetSourceDirectory(),
            null, true);

    mainLoop: for (File file : filesWritten) {
        CompilationUnit compilationUnit = JavaParser.parse(file);

        // remove SETTE annotations
        if (compilationUnit.getTypes() != null) {
            for (TypeDeclaration type : compilationUnit.getTypes()) {
                if (type.getAnnotations() != null) {
                    for (Iterator<AnnotationExpr> iterator = type.getAnnotations().iterator(); iterator
                            .hasNext();) {
                        AnnotationExpr annot = iterator.next();

                        String annotStr = annot.toString().trim();

                        // TODO enhance
                        // if container and has req version and it is java 7
                        // and tool does not support -> remove
                        if (annotStr.startsWith("@SetteSnippetContainer")
                                && annotStr.contains("requiredJavaVersion")
                                && annotStr.contains("JavaVersion.JAVA_7")
                                && !getTool().supportsJavaVersion(JavaVersion.JAVA_7)) {
                            // TODO error handling
                            // remove file
                            System.err.println("Skipping file: " + file + " (required Java version: "
                                    + JavaVersion.JAVA_7 + ")");
                            FileUtils.forceDelete(file);
                            continue mainLoop;

                        }

                        // TODO enhance
                        if (annot.getName().toString().startsWith("Sette")) {
                            iterator.remove();
                        }
                    }
                }

                if (type.getMembers() != null) {
                    for (BodyDeclaration member : type.getMembers()) {
                        if (member.getAnnotations() != null) {
                            for (Iterator<AnnotationExpr> iterator = member.getAnnotations()
                                    .iterator(); iterator.hasNext();) {
                                AnnotationExpr annotation = iterator.next();

                                // TODO enhance
                                if (annotation.getName().toString().startsWith("Sette")) {
                                    iterator.remove();
                                }
                            }
                        }
                    }
                }
            }
        }

        // remove SETTE imports
        if (compilationUnit.getImports() != null) {
            for (Iterator<ImportDeclaration> iterator = compilationUnit.getImports().iterator(); iterator
                    .hasNext();) {
                ImportDeclaration importDeclaration = iterator.next();

                // TODO enhance
                String p1 = "hu.bme.mit.sette.annotations";
                String p2 = "hu.bme.mit.sette.snippets.inputs";
                // TODO enhance
                String p3 = "catg.CATG";
                String p4 = "hu.bme.mit.sette.common.snippets.JavaVersion";

                if (importDeclaration.getName().toString().equals(p3)) {
                    // keep CATG
                } else if (importDeclaration.getName().toString().equals(p4)) {
                    iterator.remove();
                } else if (importDeclaration.getName().toString().startsWith(p1)) {
                    iterator.remove();
                } else if (importDeclaration.getName().toString().startsWith(p2)) {
                    iterator.remove();
                }
            }
        }

        // save edited source code
        FileUtils.write(file, compilationUnit.toString());
    }

    // copy libraries
    if (getSnippetProjectSettings().getLibraryDirectory().exists()) {
        FileUtils.copyDirectory(getSnippetProjectSettings().getLibraryDirectory(),
                getRunnerProjectSettings().getSnippetLibraryDirectory(), false);
    }

    // create project
    this.eclipseProject.save(getRunnerProjectSettings().getBaseDirectory());
}

From source file:com.ephesoft.dcma.gwt.foldermanager.server.FolderManagerServiceImpl.java

@Override
public Boolean copyFiles(List<String> copyFilesList, String currentFolderPath) throws GWTException {
    for (String filePath : copyFilesList) {
        try {/*ww w  . j a  va 2 s.c o m*/
            File srcFile = new File(filePath);
            if (srcFile.exists()) {
                srcFile.getName();
                String fileName = srcFile.getName();
                File copyFile = new File(currentFolderPath + File.separator + fileName);
                if (copyFile.exists()) {
                    if (copyFile.equals(srcFile)) {
                        int counter = 0;
                        while (copyFile.exists()) {
                            String newFileName;
                            if (counter == 0) {
                                newFileName = FolderManagementConstants.COPY_OF + fileName;
                            } else {
                                newFileName = FolderManagementConstants.COPY_OF
                                        + FolderManagementConstants.OPENING_BRACKET + counter
                                        + FolderManagementConstants.CLOSING_BRACKET
                                        + FolderManagementConstants.SPACE + fileName;
                            }
                            counter++;
                            copyFile = new File(currentFolderPath + File.separator + newFileName);
                        }
                    } else {
                        throw new GWTException(
                                FolderManagementMessages.CANNOT_COMPLETE_COPY_PASTE_OPERATION_AS_THE_FILE_FOLDER
                                        + fileName + FolderManagementMessages.ALREADY_EXISTS);
                    }
                }
                if (srcFile.isFile()) {
                    FileUtils.copyFile(srcFile, copyFile, false);
                } else {
                    FileUtils.forceMkdir(copyFile);
                    FileUtils.copyDirectory(srcFile, copyFile, false);
                }
            } else {
                throw new GWTException(
                        FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_COPY_PASTE_OPERATION_FILE_NOT_FOUND
                                + FolderManagementConstants.QUOTES + srcFile.getName()
                                + FolderManagementConstants.QUOTES);
            }
        } catch (IOException e) {
            LOGGER.error(
                    FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_COPY_PASTE_OPERATION_COULD_NOT_COMPLETE_OPERATION
                            + e.getMessage());
            throw new GWTException(
                    FolderManagementMessages.EXCEPTION_OCCURRED_WHILE_COPY_PASTE_OPERATION_COULD_NOT_COMPLETE_OPERATION,
                    e);
        }
    }
    return true;
}

From source file:com.athomas.androidkickstartr.Kickstartr.java

private void copyResDir() throws IOException {
    File androidResDir = fileHelper.getTargetAndroidResDir();
    File sourceResDir = fileHelper.getResDir();

    FileFilter filter = null;//from  w w w . j av  a2 s  .c o  m
    List<IOFileFilter> fileFilters = new ArrayList<IOFileFilter>();

    if (!appDetails.isListNavigation() && !appDetails.isTabNavigation() && appDetails.isSample()) {
        // Exclude arrays.xml from the copy
        IOFileFilter resArraysFilter = FileFilterUtils.nameFileFilter("arrays.xml");
        IOFileFilter fileFilter = FileFilterUtils.notFileFilter(resArraysFilter);
        fileFilters.add(fileFilter);
    }

    if (!appDetails.isViewPager() && appDetails.isSample()) {
        // Exclude fragment_sample.xml from the copy
        IOFileFilter resFragmentSampleFilter = FileFilterUtils.nameFileFilter("fragment_sample.xml");
        IOFileFilter fileFilter = FileFilterUtils.notFileFilter(resFragmentSampleFilter);
        fileFilters.add(fileFilter);
    }

    if (!fileFilters.isEmpty()) {
        filter = FileFilterUtils.and(fileFilters.toArray(new IOFileFilter[fileFilters.size()]));
    }

    FileUtils.copyDirectory(sourceResDir, androidResDir, filter);
}