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.hpe.application.automation.bamboo.tasks.RunFromFileSystemTask.java

private void prepareHtmlArtifact(ResultInfoItem resultItem, final TaskContext taskContext, BuildLogger logger) {
    File contentDir = resultItem.getSourceDir();
    if (contentDir == null || !contentDir.isDirectory()) {
        return;//from   ww w.j a v  a2s .  co  m
    }
    File destPath = new File(TestResultHelper.getOutputFilePath(taskContext), resultItem.getTestName());
    if (!destPath.exists() && !destPath.isDirectory()) {
        destPath.mkdirs();
    }

    try {
        FileUtils.copyDirectoryToDirectory(contentDir, destPath);
    } catch (Exception e) {
        logger.addBuildLogEntry(e.getMessage());
        return;
    }

    String content = "<!DOCTYPE html>\n" + "<html>\n" + "    <head>\n" + "        <title>Test</title>\n"
            + "        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n"
            + "        <script type=\"text/javascript\">\n" + "        function codeAddress() {\n"
            + "          var currentUrl = window.location.toString();\n" + "         var replaceString = '"
            + contentDir.getName() + "/" + RESULT_HTML_REPORT_FILE_NAME + "';\n"
            + "          currentUrl = currentUrl.replace('" + HTML_REPORT_FILE_NAME + "', replaceString);\n"
            + "           window.location = currentUrl;\n" + "        }\n"
            + "        window.onload = codeAddress;\n" + "        </script>\n" + "    </head>\n"
            + "    <body>\n" + "   \n" + "    </body>\n" + "</html>";

    try {
        FileUtils.writeStringToFile(new File(destPath, HTML_REPORT_FILE_NAME), content);
    } catch (IOException e) {
    }
}

From source file:com.docd.purefm.utils.PFMFileUtils.java

public static void copyDirectoryToDirectory(@NonNull final GenericFile source,
        @NonNull final GenericFile target, final boolean useCommandLine) throws IOException {
    if (useCommandLine) {
        if (!source.exists()) {
            throw new FileNotFoundException("Source '" + source + "' does not exist");
        }//from   w w  w  .  j  ava  2s . c  o  m
        if (!source.isDirectory()) {
            throw new IOException("Source '" + source + "' exists but is not a directory");
        }
        if (source.getCanonicalPath().equals(target.getCanonicalPath())) {
            throw new IOException("Source '" + source + "' and destination '" + target + "' are the same");
        }
        if (!target.exists()) {
            throw new FileNotFoundException("Target dir does not exist");
        }
        if (!target.isDirectory()) {
            throw new IOException("Target is not a directory");
        }
        final boolean result = CommandLine.execute(new CommandCopyRecursively(source, target));
        if (!result) {
            throw new IOException("Copying failed");
        }
    } else {
        FileUtils.copyDirectoryToDirectory(source.toFile(), target.toFile());
    }
}

From source file:com.aliyun.odps.mapred.unittest.MRUnitTest.java

private void processResources(JobConf job, UTContext context) throws IOException {

    RuntimeContext ctx = context.getRuntimeContext();

    // process files
    Map<String, byte[]> fileResources = context.getFileResources();
    for (Map.Entry<String, byte[]> entry : fileResources.entrySet()) {
        LOG.info("process file resource: " + entry.getKey());
        File resFile = new File(ctx.getResourceDir(), entry.getKey());
        FileUtils.writeByteArrayToFile(resFile, entry.getValue());
    }/*  w  w  w .j  a  v a2  s .c om*/

    // process archives
    Map<String, File> archiveResources = context.getArchiveResources();
    for (Map.Entry<String, File> entry : archiveResources.entrySet()) {
        LOG.info("process archive resource: " + entry.getKey());
        File resDecompressedDir = new File(ctx.getResourceDir(), entry.getKey() + "_decompressed");
        File resFile = new File(ctx.getResourceDir(), entry.getKey());
        File path = entry.getValue();
        if (path.isFile()) {
            FileUtils.copyFile(path, resFile);
            ArchiveUtils.unArchive(resFile, resDecompressedDir);
        } else {
            resFile.createNewFile();
            FileUtils.copyDirectoryToDirectory(path, resDecompressedDir);
        }
    }

    // process tables
    Map<String, List<Record>> tableResources = context.getTableResources();
    Map<String, TableMeta> tableMetas = context.getTableMetas();
    for (Map.Entry<String, List<Record>> entry : tableResources.entrySet()) {
        LOG.info("process table resource: " + entry.getKey());
        File resDir = new File(ctx.getResourceDir(), entry.getKey());
        writeRecords(resDir, entry.getValue(), tableMetas.get(entry.getKey()));
    }

    context.clearResources();
}

From source file:aurelienribon.gdxsetupui.ProjectSetup.java

/**
 * Everything is moved to the right location.
 * @throws IOException/*from   w ww . j ava  2s  .co m*/
 */
public void copy() throws IOException {
    File src = new File(tmpDst, cfg.projectName + cfg.suffixCommon);
    File dst = new File(cfg.destinationPath);
    FileUtils.copyDirectoryToDirectory(src, dst);

    if (cfg.isDesktopIncluded) {
        src = new File(tmpDst, cfg.projectName + cfg.suffixDesktop);
        FileUtils.copyDirectoryToDirectory(src, dst);
    }

    if (cfg.isAndroidIncluded) {
        src = new File(tmpDst, cfg.projectName + cfg.suffixAndroid);
        FileUtils.copyDirectoryToDirectory(src, dst);
    }

    if (cfg.isHtmlIncluded) {
        src = new File(tmpDst, cfg.projectName + cfg.suffixHtml);
        FileUtils.copyDirectoryToDirectory(src, dst);
    }

    if (cfg.isIosIncluded) {
        src = new File(tmpDst, cfg.projectName + cfg.suffixIos);
        FileUtils.copyDirectoryToDirectory(src, dst);
    }
}

From source file:de.tilman.synctool.SyncTool.java

/**
 * Conducts the specified operation for the file.
 * /*from ww w . j av a2 s . co m*/
 * @param file the file to be processed
 * @param directory the target directory
 * @param operation the operation to be executed
 */
private void syncFileToDirectory(File file, File directory, Operation operation) {

    try {
        if (operation == Operation.NONE) {
            if (!silent)
                log.info("No operation for " + file);
            return;
        } else if (operation == Operation.COPY) {
            if (file.isDirectory()) {
                log.info("Copying directory " + file);
                if (!dryRun)
                    FileUtils.copyDirectoryToDirectory(file, directory);
                dirsCopied++;
            } else {
                log.info("Copying file " + file);
                if (!dryRun)
                    FileUtils.copyFileToDirectory(file, directory);
                filesCopied++;
            }
            return;
        } else if (operation == Operation.DELETE) {
            if (file.isDirectory()) {
                log.info("Deleting directory " + file);
                if (!dryRun)
                    FileUtils.deleteDirectory(file);
                dirsDeleted++;
            } else {
                log.info("Deleting file " + file);
                if (!dryRun)
                    file.delete();
                filesDeleted++;
            }
            return;
        }
    } catch (IOException ioe) {
        log.fatal(ioe.getMessage(), ioe);
        System.exit(-8);
    }
}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 *  ./*from w  ww.java  2s. c  o m*/
 *
 * @param srcDir ?  .
 * @param destDir   .
 * @see FileUtils#copyDirectoryToDirectory(File, File)
 */
public static void copyDirectoryToDirectory(final String srcDir, final String destDir) {
    processIO(new IOCallback<Object>() {
        public Object doInProcessIO() throws IOException, NullPointerException {
            FileUtils.copyDirectoryToDirectory(new File(srcDir), new File(destDir));
            return null;
        }
    });
}

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

private String pasteClipboard(HttpSession session) throws OutOfSyncException, IOException {
    ClipBoardContent clipBoardContent = (ClipBoardContent) session.getAttribute("clipBoardContent");
    if (clipBoardContent == null) {
        return "nothing in clipboard";
    }//w w  w.  j  a  v  a2s . c  o m

    for (int i = 0; i < clipBoardContent.selectedfiles.length; i++) {
        File f = clipBoardContent.selectedfiles[i];
        File f1 = f.getParentFile();

        if (myFile.getCanonicalFile().equals(f1.getCanonicalFile())) {
            return "same folder";
        }
    }

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

        if (clipBoardContent.contentType == ClipBoardContent.COPY_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(f, myFile);
            } else {
                FileUtils.copyFileToDirectory(f, myFile, true);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            if (f.isDirectory()) {
                FileUtils.moveDirectoryToDirectory(f, myFile, false);
            } else {
                FileUtils.moveFileToDirectory(f, myFile, false);
            }
        }
        if (clipBoardContent.contentType == ClipBoardContent.CUT_CONTENT) {
            session.removeAttribute("clipBoardContent");
        }
    }

    return "";
}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

public boolean finishTempCachePreparation(FileInfo fileInfo) {

    /* Decompress the file */
    decompressFile(getTempCacheCompressedFilePath(fileInfo),
            GriffinCompression.getByName(fileInfo.getCompression()));

    /* Verification */
    String fileHash = computeMD5(getTempCacheFilePath(fileInfo)).get();
    if (!fileInfo.getHash().equals(fileHash)) {
        logger.warn(String.format("File verification for downloaded file failed %s",
                fileInfo.toString().replaceAll(System.getProperty("line.separator"), " ")));
        logger.debug(String.format("Expected hash: %s actual hash: %s", fileInfo.getHash(), fileHash));
        if (logger.isDebugEnabled()) {
            try {
                /* Store file for forensics */
                String tempDir = FilenameUtils.concat(getTempCacheDirectory(), fileInfo.getFilename());
                FileUtils.copyDirectoryToDirectory(new File(tempDir), new File(getForensicCacheDirectory()));
            } catch (IOException e) {
                // Ignore
            }//  ww w.  j  a  v a  2 s  .c o  m
        }
        return false;
    }
    return true;
}

From source file:edu.isi.wings.portal.controllers.RunController.java

public String publishRun(String runid) {
    HashMap<String, String> retmap = new HashMap<String, String>();
    ExecutionMonitorAPI monitor = config.getDomainExecutionMonitor();
    RuntimePlan plan = monitor.getRunDetails(runid);
    if (plan.getRuntimeInfo().getStatus() != Status.SUCCESS) {
        retmap.put("error", "Can only publish successfully completed runs");
    } else {/* w  w w .j a  v  a 2 s  .  co  m*/
        try {
            Mapper opmm = new Mapper();

            Publisher publisher = config.getPublisher();

            String tstoreurl = publisher.getTstoreUrl();
            String puburl = publisher.getUrl();
            String upurl = publisher.getUploadServer().getUrl();

            opmm.setPublishExportPrefix(puburl);

            String rname = runid.substring(runid.indexOf('#') + 1);
            String runurl = opmm.getRunUrl(rname);

            String tid = plan.getOriginalTemplateID();
            String tmpname = tid.substring(tid.indexOf('#') + 1);
            String tmd5 = getTemplateMD5(plan.getOriginalTemplateID());
            String tname = tmpname + "-" + tmd5;
            String turl = opmm.getTemplateUrl(tname);

            // Check if run already published
            if (graphExists(tstoreurl, runurl)) {
                retmap.put("url", runurl);
                retmap.put("error", "Run already published");
                return json.toJson(retmap);
            }

            // Fetch expanded template (to get data binding ids)
            TemplateCreationAPI tc = TemplateFactory.getCreationAPI(props);
            Template xtpl = tc.getTemplate(plan.getExpandedTemplateID());
            HashMap<String, String> varBindings = new HashMap<String, String>();
            for (Variable var : xtpl.getVariables()) {
                varBindings.put(var.getID(), var.getBinding().getID());
            }

            // Create a temporary directory to upload/move
            File _tmpdir = File.createTempFile("temp", "");
            File tempdir = new File(_tmpdir.getParent() + "/" + rname);
            FileUtils.deleteQuietly(tempdir);
            if (!_tmpdir.delete() || !tempdir.mkdirs())
                throw new Exception("Cannot create temp directory");

            File datadir = new File(tempdir.getAbsolutePath() + "/data");
            File codedir = new File(tempdir.getAbsolutePath() + "/code");
            File dcontdir = new File(tempdir.getAbsolutePath() + "/ont/data");
            File acontdir = new File(tempdir.getAbsolutePath() + "/ont/components");
            File wflowdir = new File(tempdir.getAbsolutePath() + "/ont/workflows");
            File execsdir = new File(tempdir.getAbsolutePath() + "/ont/executions");

            datadir.mkdirs();
            codedir.mkdirs();
            dcontdir.mkdirs();
            acontdir.mkdirs();
            wflowdir.mkdirs();
            execsdir.mkdirs();

            String tupurl = upurl + "/" + tempdir.getName();
            String dataurl = tupurl + "/data";
            String codeurl = tupurl + "/code";
            String dconturl = tupurl + "/ont/data";
            String aconturl = tupurl + "/ont/components";
            String wflowurl = tupurl + "/ont/workflows";
            String execsurl = tupurl + "/ont/executions";

            Properties props = config.getProperties();
            String dclib = props.getProperty("lib.domain.data.url");
            String dcont = props.getProperty("ont.domain.data.url");
            String aclib = props.getProperty("lib.concrete.url");
            String acabs = props.getProperty("lib.abstract.url");
            String wfpfx = props.getProperty("domain.workflows.dir.url");
            String expfx = props.getProperty("domain.executions.dir.url");

            String cdir = props.getProperty("lib.domain.code.storage");
            String ddir = props.getProperty("lib.domain.data.storage");

            // Get files to upload && modify "Locations" to point to uploaded urls
            HashSet<ExecutionFile> uploadFiles = new HashSet<ExecutionFile>();
            HashSet<ExecutionCode> uploadCodes = new HashSet<ExecutionCode>();

            for (ExecutionStep step : plan.getPlan().getAllExecutionSteps()) {
                for (ExecutionFile file : step.getInputFiles())
                    uploadFiles.add(file);
                for (ExecutionFile file : step.getOutputFiles())
                    uploadFiles.add(file);
                uploadCodes.add(step.getCodeBinding());
            }

            for (ExecutionFile file : uploadFiles) {
                File copyfile = new File(file.getLocation());

                // Only upload files below a threshold file size
                long maxsize = publisher.getUploadServer().getMaxUploadSize();
                if (copyfile.length() > 0 && (maxsize == 0 || copyfile.length() < maxsize)) {
                    // Copy over file to temp directory
                    FileUtils.copyFileToDirectory(copyfile, datadir);

                    // Change file path in plan to the web accessible one 
                    file.setLocation(file.getLocation().replace(ddir, dataurl));
                } else {
                    String bindingid = varBindings.get(file.getID());
                    file.setLocation(config.getServerUrl() + this.dataUrl + "/fetch?data_id="
                            + URLEncoder.encode(bindingid, "UTF-8"));
                }
            }
            for (ExecutionCode code : uploadCodes) {
                File copydir = null;
                if (code.getCodeDirectory() != null) {
                    copydir = new File(code.getCodeDirectory());
                    // Change path in plan to the web accessible one
                    code.setCodeDirectory(code.getCodeDirectory().replace(cdir, codeurl));
                } else {
                    File f = new File(code.getLocation());
                    copydir = f.getParentFile();
                }
                // Copy over directory to temp directory
                FileUtils.copyDirectoryToDirectory(copydir, codedir);

                // Change path in plan to the web accessible one
                code.setLocation(code.getLocation().replace(cdir, codeurl));
            }

            String dcontdata = IOUtils.toString(new URL(dcont));
            dcontdata = dcontdata.replace(dcont, dconturl + "/ontology.owl");
            FileUtils.write(new File(dcontdir.getAbsolutePath() + "/ontology.owl"), dcontdata);

            String dclibdata = IOUtils.toString(new URL(dclib));
            dclibdata = dclibdata.replace(dcont, dconturl + "/ontology.owl");
            dclibdata = dclibdata.replace(dclib, dconturl + "/library.owl");
            dclibdata = dclibdata.replace(ddir, dataurl);
            FileUtils.write(new File(dcontdir.getAbsolutePath() + "/library.owl"), dclibdata);

            String aclibdata = IOUtils.toString(new URL(aclib));
            aclibdata = aclibdata.replace(dcont, aconturl + "/ontology.owl");
            aclibdata = aclibdata.replace(aclib, aconturl + "/library.owl");
            aclibdata = aclibdata.replace(cdir, codeurl);
            FileUtils.write(new File(acontdir.getAbsolutePath() + "/library.owl"), aclibdata);

            String acabsdata = IOUtils.toString(new URL(acabs));
            acabsdata = acabsdata.replace(dcont, dconturl + "/ontology.owl");
            acabsdata = acabsdata.replace(aclib, aconturl + "/library.owl");
            acabsdata = acabsdata.replace(acabs, aconturl + "/abstract.owl");
            FileUtils.write(new File(acontdir.getAbsolutePath() + "/abstract.owl"), acabsdata);

            File planfile = new File(execsdir.getAbsolutePath() + "/" + plan.getPlan().getName() + ".owl");
            String plandata = plan.getPlan().serialize();
            plandata = plandata.replace("\"" + wfpfx, "\"" + wflowurl);
            plandata = plandata.replace("\"" + expfx, "\"" + execsurl);
            plandata = plandata.replace(dclib, dconturl + "/library.owl");
            plandata = plandata.replace(dcont, dconturl + "/ontology.owl");
            plandata = plandata.replace(aclib, aconturl + "/library.owl");
            plandata = plandata.replace(acabs, aconturl + "/abstract.owl");
            FileUtils.write(planfile, plandata);

            String rplanurl = execsurl + "/" + plan.getName() + ".owl";
            File rplanfile = new File(execsdir.getAbsolutePath() + "/" + plan.getName() + ".owl");
            String rplandata = IOUtils.toString(new URL(runid));
            rplandata = rplandata.replace(wfpfx, wflowurl);
            rplandata = rplandata.replace(expfx, execsurl);
            rplandata = rplandata.replace(tmpname + ".owl", tname + ".owl");
            rplandata = rplandata.replace("#" + tmpname + "\"", "#" + tname + "\"");
            rplandata = rplandata.replace(dclib, dconturl + "/library.owl");
            rplandata = rplandata.replace(dcont, dconturl + "/ontology.owl");
            rplandata = rplandata.replace(aclib, aconturl + "/library.owl");
            rplandata = rplandata.replace(acabs, aconturl + "/abstract.owl");
            FileUtils.write(rplanfile, rplandata);

            URL otplurl = new URL(plan.getOriginalTemplateID());
            String otmplurl = wflowurl + "/" + otplurl.getRef() + ".owl";
            File otplfile = new File(wflowdir.getAbsolutePath() + "/" + otplurl.getRef() + ".owl");
            String otpldata = IOUtils.toString(otplurl);
            otpldata = otpldata.replace(wfpfx, wflowurl);
            otpldata = otpldata.replace(expfx, execsurl);
            otpldata = otpldata.replace(dclib, dconturl + "/library.owl");
            otpldata = otpldata.replace(dcont, dconturl + "/ontology.owl");
            otpldata = otpldata.replace(aclib, aconturl + "/library.owl");
            otpldata = otpldata.replace(acabs, aconturl + "/abstract.owl");
            FileUtils.write(otplfile, otpldata);

            URL xtplurl = new URL(plan.getExpandedTemplateID());
            File xtplfile = new File(execsdir.getAbsolutePath() + "/" + xtplurl.getRef() + ".owl");
            String xtpldata = IOUtils.toString(xtplurl);
            xtpldata = xtpldata.replace(wfpfx, wflowurl);
            xtpldata = xtpldata.replace(expfx, execsurl);
            xtpldata = xtpldata.replace(dclib, dconturl + "/library.owl");
            xtpldata = xtpldata.replace(dcont, dconturl + "/ontology.owl");
            xtpldata = xtpldata.replace(aclib, aconturl + "/library.owl");
            xtpldata = xtpldata.replace(acabs, aconturl + "/abstract.owl");
            FileUtils.write(xtplfile, xtpldata);

            // TODO: Change base url to an opmw.url + "/resource/WorkflowTemplate/ ??

            uploadDirectory(publisher.getUploadServer(), tempdir);
            FileUtils.deleteQuietly(tempdir);

            // Convert results into prov and opmw
            File opmwfile = File.createTempFile("opmw-", ".owl");
            File provfile = File.createTempFile("prov-", ".owl");
            File tmplfile = File.createTempFile("tmpl-", ".owl");

            String liburl = props.getProperty("lib.domain.execution.url");
            runurl = opmm.transformWINGSResultsToOPMW(rplanurl, liburl, "RDF/XML", opmwfile.getAbsolutePath(),
                    provfile.getAbsolutePath(), rname);

            turl = opmm.transformWINGSElaboratedTemplateToOPMW(otmplurl, "RDF/XML", tmplfile.getAbsolutePath(),
                    tname);

            // Publish run opmw data
            publishFile(tstoreurl, runurl, opmwfile.getAbsolutePath());

            // Publish provenance data to the default graph
            publishFile(tstoreurl, "default", provfile.getAbsolutePath());

            // Publish template if it doesn't already exist
            if (!graphExists(tstoreurl, turl))
                publishFile(tstoreurl, turl, tmplfile.getAbsolutePath());

            opmwfile.delete();
            provfile.delete();
            tmplfile.delete();

            retmap.put("url", runurl);

        } catch (Exception e) {
            e.printStackTrace();
            retmap.put("error", e.getMessage());
        }
    }
    return json.toJson(retmap);
}

From source file:de.uzk.hki.da.sb.Cli.java

/**
 * Copies the files listed in a file list to a single directory
 * /*  www . ja va  2  s  .c  o  m*/
 * @param fileListFile The file list file
 * @return The path to the directory containing the files
 */
private String copySipContentToFolder(File fileListFile) {

    CliProgressManager progressManager = new CliProgressManager();

    String tempFolderName = getTempFolderName();

    String fileList = "";
    try {
        fileList = Utilities.readFile(fileListFile);
    } catch (Exception e) {
        logger.log("ERROR: Failed to read file " + fileListFile.getAbsolutePath(), e);
        System.out.println("Die Datei " + fileListFile.getAbsolutePath() + " konnte nicht gelesen werden.");
        return "";
    }

    fileList = fileList.replace("\r", "");
    if (!fileList.endsWith("\n"))
        fileList += "\n";

    long files = 0;
    for (int i = 0; i < fileList.length(); i++) {
        if (fileList.charAt(i) == '\n')
            files++;
    }
    progressManager.setTotalSize(files);

    File tempDirectory = new File(tempFolderName + File.separator + sipFactory.getName());
    tempDirectory.mkdirs();

    while (true) {
        int index = fileList.indexOf('\n');

        if (index >= 0) {
            String filepath = fileList.substring(0, index);
            fileList = fileList.substring(index + 1);

            File file = new File(filepath);
            if (!file.exists()) {
                logger.log("ERROR: File " + file.getAbsolutePath() + " is referenced in filelist, "
                        + "but does not exist");
                System.out.println("\nDie in der Dateiliste angegebene Datei " + file.getAbsolutePath()
                        + " existiert nicht.");
                FileUtils.deleteQuietly(tempDirectory);
                return "";
            }

            try {
                if (file.isDirectory())
                    FileUtils.copyDirectoryToDirectory(file, tempDirectory);
                else
                    FileUtils.copyFileToDirectory(file, tempDirectory);
                progressManager.copyFilesFromListProgress();
            } catch (IOException e) {
                logger.log("ERROR: Failed to copy file " + file.getAbsolutePath() + " to folder "
                        + tempDirectory.getAbsolutePath(), e);
                System.out.println("\nDie in der Dateiliste angegebene Datei " + file.getAbsolutePath()
                        + " konnte nicht kopiert werden.");
                FileUtils.deleteQuietly(tempDirectory);
                return "";
            }
        } else
            break;
    }

    return (tempDirectory.getAbsolutePath());
}