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

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

Introduction

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

Prototype

public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Copies a directory to within another directory preserving the file dates.

Usage

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

@Override
public boolean performFinish() {
    try {//from   w w w . j  av  a2  s. c o m
        EnginePropertiesManager.saveProperties(false);
    } catch (Exception e) {
    }

    if (workspaceMigrationPage != null) {
        File userWorkspace = new File(Engine.USER_WORKSPACE_PATH);

        File eclipseWorkspace = new File(Engine.PROJECTS_PATH);

        ConvertigoPlugin
                .logInfo("The current Eclipse workspace is a pre-6.2.0 CEMS workspace. Migration starting ");

        boolean projectsMoveFailed = false;

        for (File file : eclipseWorkspace.listFiles()) {
            if (!file.getName().equals(".metadata")) {
                try {
                    ConvertigoPlugin.logInfo("Migration in progress: moving " + file.getName() + " ");
                    FileUtils.moveToDirectory(file, userWorkspace, false);
                } catch (IOException e) {
                    projectsMoveFailed = projectsMoveFailed || file.getName().equals("projects");
                    ConvertigoPlugin.logInfo("Migration in progress: failed to move " + file.getName() + " ! ("
                            + e.getMessage() + ")");
                }
            }
        }

        if (!projectsMoveFailed) {
            ConvertigoPlugin.logInfo(
                    "Migration in progress: move move back CEMS projects to the Eclipse workspace ");
            File exMetadata = new File(userWorkspace, "projects/.metadata");
            try {
                FileUtils.copyDirectoryToDirectory(exMetadata, eclipseWorkspace);
                FileUtils.deleteQuietly(exMetadata);
            } catch (IOException e1) {
                ConvertigoPlugin.logInfo(
                        "Migration in progress: failed to merge .metadata ! (" + e1.getMessage() + ")");
            }

            for (File file : new File(userWorkspace, "projects").listFiles()) {
                try {
                    ConvertigoPlugin.logInfo("Migration in progress: moving the file " + file.getName()
                            + " into the Eclipse Workspace ");
                    FileUtils.moveToDirectory(file, eclipseWorkspace, false);
                } catch (IOException e) {
                    ConvertigoPlugin.logInfo("Migration in progress: failed to move " + file.getName() + " ! ("
                            + e.getMessage() + ")");
                }
            }

            ConvertigoPlugin.logInfo("Migration of workspace done !\n" + "Migration of the folder: "
                    + eclipseWorkspace.getAbsolutePath() + "\n" + "Eclipse Workspace with your CEMS projects: "
                    + eclipseWorkspace.getAbsolutePath() + "\n"
                    + "Convertigo Workspace with your CEMS configuration: " + userWorkspace.getAbsolutePath());
        } else {
            ConvertigoPlugin
                    .logInfo("Migration incomplet: cannot move back CEMS projects to the Eclipse workspace !");
        }
    }

    File pscFile = new File(Engine.USER_WORKSPACE_PATH, "studio/psc.txt");
    try {
        FileUtils.writeStringToFile(pscFile,
                //               pscKeyPage.getCertificateKey(), "utf-8");
                pscKeyValidationPage.getCertificateKey(), "utf-8");
    } catch (IOException e) {
        ConvertigoPlugin.logError("Failed to write the PSC file: " + e.getMessage());
    }

    if (!Engine.isStarted) {
        EnginePropertiesManager.unload();
    } else {
        ConvertigoPlugin.configureDeployConfiguration();
    }

    return true;
}

From source file:ai.h2o.servicebuilder.MakePythonWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;//  ww  w  . jav a2 s. c  o  m
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.debug("tmpDir " + tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String mojofile = null;
        String pythonfile = null;
        String predictorClassName = null;
        String pythonenvfile = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) { // pojo file name, use this or a mojo file
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("python")) {
                    pythonfile = "WEB-INF" + File.separator + "python.py";
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(webInfDir, "python.py"));
                }
                if (field.equals("pythonextra")) { // optional extra files for python
                    pythonfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file (optional)
                    mojofile = filename;
                    rawfiles.add(mojofile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
                if (field.equals("envfile")) { // optional conda environment file
                    pythonenvfile = filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.debug("using conda environment file {}", pythonenvfile);
                }
            }
        }
        logger.debug("jar {}  pojo {}  mojo {}  python {}  envfile {}", jarfile, pojofile, mojofile, pythonfile,
                pythonenvfile);
        if ((pojofile == null || jarfile == null) && (mojofile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        if (pojofile != null) {
            // Compile the pojo
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;
        copyExtraFile(servletPath, extraPath, tmpDir, "pyindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-pythonpredict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, "null",
                pythonenvfile == null ? "" : pythonenvfile, srcPath + "ServletUtil-TEMPLATE.java",
                "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictPythonServlet.java", "PredictPythonServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        runCmd(tmpDir,
                Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                        "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                        "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                        "InfoServlet.java", "StatsServlet.java", "PredictPythonServlet.java",
                        "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java"),
                "Compilation of servlet failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done python war creation in {}", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:ai.h2o.servicebuilder.MakeWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;/*from   www.  j a  v a2  s  .c  om*/
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.info("tmpDir {}", tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String prejarfile = null;
        String deepwaterjarfile = null;
        String rawfile = null;
        String predictorClassName = null;
        String transformerClassName = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) { // file fields
                if (field.equals("pojo")) {
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("deepwater")) {
                    deepwaterjarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("prejar")) {
                    prejarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file
                    rawfile = filename;
                    rawfiles.add(rawfile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
            } else { // form text field
                if (field.equals("preclass")) {
                    transformerClassName = i.getString();
                }
            }
        }
        logger.debug("genmodeljar {}  deepwaterjar {}  pojo {}  raw {}", jarfile, deepwaterjarfile, pojofile,
                rawfile);
        if ((pojofile == null || jarfile == null) && (rawfile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        logger.info("prejar {}  preclass {}", prejarfile, transformerClassName);
        if (prejarfile != null && transformerClassName == null
                || prejarfile == null && transformerClassName != null)
            throw new Exception("need both prejar and preclass");

        if (pojofile != null) {
            // Compile the pojo
            String jarfiles = jarfile;
            if (deepwaterjarfile != null)
                jarfiles += ":" + deepwaterjarfile;
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfiles, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;

        if (transformerClassName == null)
            copyExtraFile(servletPath, extraPath, tmpDir, "index.html", "index.html");
        else
            copyExtraFile(servletPath, extraPath, tmpDir, "jarindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-predict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String replaceTransform;
        if (transformerClassName == null)
            replaceTransform = "null";
        else
            replaceTransform = "new " + transformerClassName + "()";

        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, replaceTransform, null,
                srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictServlet.java", "PredictServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PredictBinaryServlet.java", "PredictBinaryServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        List<String> cmd = Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source",
                JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                "PredictServlet.java", "PredictBinaryServlet.java", "InfoServlet.java", "StatsServlet.java",
                "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java");
        runCmd(tmpDir, cmd, "Compilation of extra failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done war creation in {} ms", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed ", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:ch.unibas.fittingwizard.presentation.MoleculeListPage.java

private File copyFilesToMoleculesDir(File selectedDir, File xyzFile) {
    boolean isAlreadyInMoleculeDir = moleculeDir.contains(selectedDir);
    if (!isAlreadyInMoleculeDir) {
        logger.info("Molecule files are not in molecules directory. Copying files to directory.");
        try {//from  ww w . j a v  a  2s.co  m
            FileUtils.copyDirectoryToDirectory(selectedDir, moleculeDir.getDirectory());
            FileUtils.copyFileToDirectory(xyzFile, moleculeDir.getDirectory());
        } catch (IOException e) {
            throw new RuntimeException("Could not copy files to molecule directory.");
        }
    }
    return xyzFile;
}

From source file:it.greenvulcano.util.file.FileManager.java

/**
 * Copy the file/directory to a new one.<br>
 * The filePattern may be a regular expression: in this case, all the filenames
 * matching the pattern will be copied to the target directory.<br>
 * If a file, whose name matches the <code>filePattern</code> pattern, already
 * exists in the same target directory, it will be overwritten.<br>
 *
 * @param sourcePath/*  w  ww .  j  av  a2 s.co m*/
 *            Absolute pathname of the source file/directory.
 * @param targetPath
 *            Absolute pathname of the target file/directory.
 * @param filePattern
 *            A regular expression defining the name of the files to be copied. Used only if
 *            srcPath identify a directory. Null or "" disable file filtering.
 * @throws Exception
 */
public static void cp(String sourcePath, String targetPath, String filePattern) throws Exception {
    File src = new File(sourcePath);
    if (!src.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the source file is NOT absolute: " + sourcePath);
    }
    File target = new File(targetPath);
    if (!target.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the target file is NOT absolute: " + targetPath);
    }

    if (src.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("") || filePattern.equals(".*")) {
            logger.debug(
                    "Copying directory " + src.getAbsolutePath() + " to directory " + target.getAbsolutePath());
            FileUtils.copyDirectory(src, new File(targetPath));
        } else {
            Set<FileProperties> files = ls(sourcePath, filePattern);
            for (FileProperties file : files) {
                logger.debug("Copying file " + file.getName() + " from directory " + src.getAbsolutePath()
                        + " to directory " + target.getAbsolutePath());
                if (file.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(new File(src, file.getName()), target);
                } else {
                    FileUtils.copyFileToDirectory(new File(src, file.getName()), target);
                }
            }
        }
    } else {
        if (target.isDirectory()) {
            logger.debug("Copying file " + src.getAbsolutePath() + " to directory " + target.getAbsolutePath());
            FileUtils.copyFileToDirectory(src, target);
        } else {
            logger.debug("Copying file " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.copyFile(src, target);
        }
    }
}

From source file:com.mortardata.project.EmbeddedMortarProject.java

String syncEmbeddedProjectWithMirror(Git gitMirror, CredentialsProvider cp, String targetBranch,
        String committer) throws GitAPIException, IOException {

    // checkout the target branch
    gitUtil.checkout(gitMirror, targetBranch);

    // clear out the mirror directory contents (except .git and .gitkeep)
    File localBackingGitRepoPath = gitMirror.getRepository().getWorkTree();
    for (File f : FileUtils.listFilesAndDirs(localBackingGitRepoPath,
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".gitkeep")),
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".git")))) {
        if (!f.equals(localBackingGitRepoPath)) {
            logger.debug("Deleting existing mirror file" + f.getAbsolutePath());
            FileUtils.deleteQuietly(f);/*from ww  w .ja v a 2s  .  c  o m*/
        }
    }

    // copy everything from the embedded project
    List<File> manifestFiles = getFilesAndDirsInManifest();
    for (File fileToCopy : manifestFiles) {
        if (!fileToCopy.exists()) {
            logger.warn("Can't find file or directory " + fileToCopy.getCanonicalPath()
                    + " referenced in manifest file.  Ignoring.");
        } else if (fileToCopy.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(fileToCopy, localBackingGitRepoPath);
        } else {
            FileUtils.copyFileToDirectory(fileToCopy, localBackingGitRepoPath);
        }
    }

    // add everything
    logger.debug("git add .");
    gitMirror.add().addFilepattern(".").call();

    // remove missing files (deletes)
    logger.debug("git add -u .");
    gitMirror.add().setUpdate(true).addFilepattern(".").call();

    // commit it
    logger.debug("git commit");
    RevCommit revCommit = gitMirror.commit().setCommitter(committer, committer)
            .setMessage("mortar development snapshot commit").call();
    return ObjectId.toString(revCommit);
}

From source file:com.blackducksoftware.tools.vuln_collector.VCProcessor.java

/**
 * Creates a directory using the project name Parses the name to escape
 * offensive characters./* w w w .  j  a v a2  s.co  m*/
 * 
 * @param reportLocation
 * @param project
 * @return
 * @throws Exception
 */
private File prepareSubDirectory(File reportLocation, String project) throws Exception {
    project = formatProjectPath(project);
    File reportLocationSubDir = new File(reportLocation.toString() + File.separator + project);
    if (!reportLocationSubDir.exists()) {
        boolean dirsMade = reportLocationSubDir.mkdirs();
        if (!dirsMade) {
            throw new Exception("Unable to create report sub-directory for project: " + project);
        }
    }

    // Copy the web resources into this new location
    ClassLoader classLoader = getClass().getClassLoader();
    File webresources = new File(classLoader.getResource(WEB_RESOURCE).getFile());

    if (!webresources.exists()) {
        throw new Exception("Fatal exception, internal web resources are missing!");
    }

    File[] webSubDirs = webresources.listFiles();
    if (webSubDirs.length == 0) {
        throw new Exception(
                "Fatal exception, internal web resources sub directories are missing!  Corrupt archive.");
    }

    boolean readable = webresources.setReadable(true);
    if (!readable) {
        throw new Exception("Fatal. Cannot read internal web resource directory!");
    }

    try {
        for (File webSubDir : webSubDirs) {
            if (webSubDir.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(webSubDir, reportLocationSubDir);
            } else {
                FileUtils.copyFileToDirectory(webSubDir, reportLocationSubDir);
            }
        }
    } catch (IOException ioe) {
        throw new Exception("Error during creation of report directory", ioe);
    }

    return reportLocationSubDir;
}

From source file:de.jwi.jfm.Folder.java

private String copyOrMove(boolean move, String[] selectedIDs, String target)
        throws IOException, OutOfSyncException {
    if ((selectedIDs == null) || (selectedIDs.length == 0)) {
        return "No file selected";
    }//from   w ww  .j  a  va2s  .c o  m

    File f1 = getTargetFile(target);

    if ((null == f1) || (myFile.getCanonicalFile().equals(f1.getCanonicalFile()))) {
        return "illegal target file";
    }

    if ((!f1.isDirectory()) && (selectedIDs.length > 1)) {
        return "target is not a directory";
    }

    StringBuffer sb = new StringBuffer();

    File fx = null;

    for (int i = 0; i < selectedIDs.length; i++) {
        File f = checkAndGet(selectedIDs[i]);

        if (null == f) {
            throw new OutOfSyncException();
        }

        if (!f1.isDirectory()) {
            fx = f1;
        } else {
            fx = new File(f1, f.getName());
        }

        if (move) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, fx, true);
            } else {
                if (!f.renameTo(fx)) {
                    sb.append(f.getName()).append(" ");
                }
            }
        } else {
            try {
                if (f.isDirectory()) {
                    FileUtils.copyDirectoryToDirectory(f, fx);
                } else {
                    FileUtils.copyFile(f, fx, true);
                }
            } catch (IOException e) {
                sb.append(f.getName()).append(" ");
            }
        }
    }

    String s = sb.toString();

    if (!"".equals(s)) {
        String op = move ? "move" : "copy";
        return "failed to " + op + " " + s + " to " + f1.toString();
    }

    return "";
}

From source file:com.stacksync.desktop.Environment.java

public void copyResourcesRecursively(URL originUrl, File destination) throws Exception {
    URLConnection urlConnection = originUrl.openConnection();
    if (urlConnection instanceof JarURLConnection) {
        copyResourcesFromJar((JarURLConnection) urlConnection, destination);
    } else if (urlConnection instanceof FileURLConnection) {
        // I know that this is not so beatiful... I'll try to change in a future...
        if (operatingSystem == OperatingSystem.Mac || operatingSystem == OperatingSystem.Linux) {
            destination = defaultUserConfDir;
        }//w ww .java  2 s  . co  m
        FileUtils.copyDirectoryToDirectory(new File(originUrl.getPath()), destination);
    } else {
        throw new Exception("URLConnection[" + urlConnection.getClass().getSimpleName()
                + "] is not a recognized/implemented connection type.");
    }
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private void moveFiles() {
    try {/*from w  ww  . j  av  a 2s  .c om*/
        context.logInfo("Move files...");
        String projectSourceName = context.getProjectSourceName();
        String projectTargetName = context.getProjectTargetName();
        // Move files *.java from src -> src/main/java
        // Move files *.properties;*.txt;*.jpg -> src/main/resources
        // Move files *.java from test -> src/test/java
        // Move files *.properties;*.txt;*.jpg -> src/test/resources
        // Move files *.* from resources or resource -> src/main/resources
        // Move files from / to / but not .classpath, .project ->
        // src/main/resources
        // Move directory META-INF -> src/main/resources
        String[] extensionsJava = { "java" };
        Iterator<File> fileIterator = FileUtils.iterateFiles(new File(projectSourceName + "/src"),
                extensionsJava, true);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            String nameResultAfterSrc = StringUtils.substringAfterLast(currentFile.getAbsolutePath(), "src\\");
            nameResultAfterSrc = projectTargetName.concat("/src/main/java/").concat(nameResultAfterSrc);
            log.info("Target file: " + nameResultAfterSrc);
            File targetFile = new File(nameResultAfterSrc);
            FileUtils.copyFile(currentFile, targetFile, true);
        }

        // Check whether "resource" or "resources" exist?
        File directoryResources = new File(projectSourceName + "/resource");
        File targetResourcesDir = new File(projectTargetName.concat("/src/main/resources"));
        if (directoryResources.exists()) {
            // Move the files
            FileUtils.copyDirectory(directoryResources, targetResourcesDir);
        }

        directoryResources = new File(projectSourceName + "/resources");
        if (directoryResources.exists()) {
            // Move the files
            FileUtils.copyDirectory(directoryResources, targetResourcesDir);
        }

        // META-INF
        File directoryMetaInf = new File(projectSourceName + "/META-INF");
        if (directoryMetaInf.exists()) {
            FileUtils.copyDirectoryToDirectory(directoryMetaInf, targetResourcesDir);
        }

        // Directory . *.txt, *.doc*, *.png, *.jpg -> src/main/docs
        File targetDocsDir = new File(projectTargetName.concat("/src/main/docs"));
        String[] extensionsRootDir = { "txt", "doc", "docx", "png", "jpg" };
        fileIterator = FileUtils.iterateFiles(new File(projectSourceName), extensionsRootDir, false);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            FileUtils.copyFileToDirectory(currentFile, targetDocsDir);
        }

        // Directory . *.cmd, *.sh -> src/main/bin
        File targetBinDir = new File(projectTargetName.concat("/src/main/bin"));
        String[] extensionsRootBinDir = { "sh", "cmd", "properties" };
        fileIterator = FileUtils.iterateFiles(new File(projectSourceName), extensionsRootBinDir, false);
        for (Iterator<File> iterator = fileIterator; iterator.hasNext();) {
            File currentFile = iterator.next();
            log.info("File to be copied: " + currentFile.getCanonicalPath());
            FileUtils.copyFileToDirectory(currentFile, targetBinDir);
        }
    } catch (IOException e) {
        log.info(e.getStackTrace().toString());
    }
}