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:de.uzk.hki.da.fs.UtilitiesTest.java

/**
 * test written for a bugfix in compareFolders. The bug was that folders on some locations
 * got listings of contained files that differed in their order. Though the compared folders
 * were equal, compareFolders returned false
 *
 * @throws IOException Signals that an I/O exception has occurred.
 *///from w  w  w.  java  2s  .c om
@Test
public void copyToTmpAndCompare() throws IOException {
    FileUtils.copyDirectoryToDirectory(new File("src/test/resources/fs/folderComparison/folder1"),
            new File("/tmp/"));

    assertTrue(FolderUtils.compareFolders(new File("src/test/resources/fs/folderComparison/folder1"),
            new File("/tmp/folder1")));
}

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

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File tmp = null;/* w  ww .jav a  2s  .  c o m*/
    try {
        //create temp directory
        tmp = createTempDirectory("compilePojo");
        logger.info("tmp dir {}", tmp);

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        List<String> pojofiles = new ArrayList<String>();
        String jarfile = null;
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) {
                if (field.equals("pojo")) {
                    pojofiles.add(filename);
                }
                if (field.equals("jar")) {
                    jarfile = filename;
                }
                FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmp, filename));
            }
        }
        if (pojofiles.isEmpty() || jarfile == null)
            throw new Exception("need pojofile(s) and jarfile");

        //  create output directory
        File out = new File(tmp.getPath(), "out");
        boolean mkDirResult = out.mkdir();
        if (!mkDirResult)
            throw new Exception("Can't create output directory (out)");

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

        copyExtraFile(servletPath, "extra" + File.separator, tmp, "H2OPredictor.java", "H2OPredictor.java");
        FileUtils.copyDirectoryToDirectory(
                new File(servletPath, "extra" + File.separator + "WEB-INF" + File.separator + "lib"), tmp);
        copyExtraFile(servletPath, "extra" + File.separator, new File(out, "META-INF"), "MANIFEST.txt",
                "MANIFEST.txt");

        // Compile the pojo(s)
        for (String pojofile : pojofiles) {
            runCmd(tmp,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfile + ":lib/*", "-d", "out",
                            pojofile, "H2OPredictor.java"),
                    "Compilation of pojo failed: " + pojofile);
        }

        // create jar result file
        runCmd(out, Arrays.asList("jar", "xf", tmp + File.separator + jarfile),
                "jar extraction of h2o-genmodel failed");

        runCmd(out,
                Arrays.asList("jar", "xf", tmp + File.separator + "lib" + File.separator + "gson-2.6.2.jar"),
                "jar extraction of gson failed");

        runCmd(out, Arrays.asList("jar", "cfm", tmp + File.separator + "result.jar",
                "META-INF" + File.separator + "MANIFEST.txt", "."), "jar creation failed");

        byte[] resjar = IOUtils.toByteArray(new FileInputStream(tmp + File.separator + "result.jar"));
        if (resjar == null)
            throw new Exception("Can't create jar of compiler output");

        logger.info("jar created, size {}", resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = pojofiles.get(0).replace(".java", "");
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".jar");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        logger.error("post failed", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        try {
            if (tmp != null && tmp.exists())
                FileUtils.deleteDirectory(tmp);
        } catch (IOException e) {
            logger.error("Can't delete tmp directory");
        }
    }
}

From source file:de.uzk.hki.da.cb.UpdateMetadataActionTests.java

@Before
public void setUp() throws IOException {
    PreservationSystem pSystem = new PreservationSystem();
    pSystem.setUrisFile("http://data.danrw.de/file");
    pSystem.setLicenseValidationTestCSNFlag(C.PRESERVATIONSYS_LICENSE_VALIDATION_YES);

    action = new UpdateMetadataAction();
    node = new Node();
    node.setWorkingResource("vm3");
    node.setWorkAreaRootPath(Path.make(workAreaPath));
    action.setLocalNode(node);/* w  w  w.  ja v a2s .c om*/
    action.setPSystem(pSystem);
    action.setPresMode(true);

    obj = TESTHelper.setUpObject("23", workAreaPath);

    action.setTestContractors(new HashSet<String>() {
        {
            this.add(obj.getContractor().getShort_name());
        }
    });
    WorkArea wa = new WorkArea(node, obj);
    action.setWorkArea(wa);

    FileUtils.copyDirectoryToDirectory(new File("src/main/xslt"), new File("conf/"));
}

From source file:ch.bender.evacuate.RunnerTest.java

/**
 * This method is executed just before each test method
 * /*w  ww  . ja  v  a2 s. c om*/
 * @throws Throwable
 *         On any problem (test method will not be executed)
 */
@Before
public void setUp() throws Throwable {
    myLog.debug("entering");
    try {
        if (Files.exists(Testconstants.ROOT_DIR)) {
            Helper.deleteDirRecursive(Testconstants.ROOT_DIR);
        }

        /*
         * Preparing the test sandbox in current directory:
         * 
         * testsandbox
         *   +- orig
         *      +- sub1
         *         +- fileSub12.txt
         *   +- backup
         *      +- sub1
         *         +- fileSub1.txt
         *         +- fileSub12.txt
         *      +- sub2
         *         +- sub2sub1
         *            +- fileSub2Sub1.txt
         *         +- fileSub2.txt
         *      +- file1.txt
         *   +- evacuate
         *       <empty>
         */
        Files.createDirectory(Testconstants.ROOT_DIR);

        myOrigDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "orig");
        myOrigDirSub1 = Testconstants.createNewFolder(myOrigDir, "sub1");
        myOrigDirSub2 = Testconstants.createNewFolder(myOrigDir, "sub2");
        myOrigDirSub2Sub1 = Testconstants.createNewFolder(myOrigDirSub2, "sub2sub1");

        myOrigFile1 = Testconstants.createNewFile(myOrigDir, "file1.txt");
        myOrigFileSub1 = Testconstants.createNewFile(myOrigDirSub1, "fileSub1.txt");
        myOrigFileSub12 = Testconstants.createNewFile(myOrigDirSub1, "fileSub12.txt");
        myOrigFileSub2 = Testconstants.createNewFile(myOrigDirSub2, "fileSub2.txt");
        myOrigFileSub2Sub1 = Testconstants.createNewFile(myOrigDirSub2Sub1, "fileSub2Sub1.txt");

        myBackupDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "backup");
        FileUtils.copyFileToDirectory(myOrigFile1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub1.toFile(), myBackupDir.toFile());
        FileUtils.copyDirectoryToDirectory(myOrigDirSub2.toFile(), myBackupDir.toFile());

        myEvacuateDir = Testconstants.createNewFolder(Testconstants.ROOT_DIR, "evacuate");

        // delete some objects from orig dir:
        Helper.deleteDirRecursive(myOrigDirSub2);
        Files.delete(myOrigFile1);
        Files.delete(myOrigFileSub1);

        myDryRun = false;
        myMove = false;
        myOrigDirStr = myOrigDir.toString();
        myBackupDirStr = myBackupDir.toString();
        myEvacuateDirStr = myEvacuateDir.toString();

    } catch (Throwable t) {
        myLog.error("Throwable caught in setup", t);
        throw t;
    }
}

From source file:com.photon.phresco.plugins.WordPressPackage.java

private boolean build() throws MojoExecutionException {
    boolean isBuildSuccess = true;
    try {//from w  w  w  .  ja va  2  s . co m
        configure();
        File[] listSourceFiles = srcDir.listFiles();
        for (File childFile : listSourceFiles) {
            if (childFile.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(childFile, targetDir);
            } else {
                FileUtils.copyFileToDirectory(childFile, targetDir);
            }
        }
        createPackage();

    } catch (IOException e) {
        isBuildSuccess = false;
        getLog().error(e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
    return isBuildSuccess;
}

From source file:com.xebialabs.deployit.maven.packager.ManifestPackager.java

public void addDeployableArtifact(DeployableArtifactItem item) {
    if ("Dar".equals(item.getType()))
        return;//from   w ww .j  a v  a2  s  .  c  om

    if ("Pom".equals(item.getType()))
        return;

    final Map<String, Attributes> entries = manifest.getEntries();
    final Attributes attributes = new Attributes();
    final String type = item.getType();
    final File location = new File(item.getLocation());

    attributes.putValue("CI-Type", type);
    if (item.hasName())
        attributes.putValue("CI-Name", item.getName());

    String darLocation = (item.getDarLocation() == null ? type : item.getDarLocation());

    if (item.isFolder()) {
        entries.put(darLocation, attributes);
    } else {
        if (location.isAbsolute())
            entries.put(darLocation + "/" + location.getName(), attributes);
        else
            entries.put(darLocation + "/" + item.getLocation(), attributes);
    }

    final File targetDir = new File(targetDirectory, darLocation);
    if (generateManifestOnly) {
        System.out.println("Skip copying artifact " + item.getName() + " to " + targetDir);
        return;
    }
    targetDir.mkdirs();

    File locationTargetDirs;
    //do not create missing directories is there are no parents or if the file is absolute
    if (location.isAbsolute() || location.getParent() == null) {
        locationTargetDirs = targetDir;
    } else {
        locationTargetDirs = new File(targetDir, location.getParent());
        locationTargetDirs.mkdirs();
    }

    try {
        if (location.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(location, locationTargetDirs);
        } else {
            FileUtils.copyFileToDirectory(location, locationTargetDirs);
        }
    } catch (IOException e) {
        throw new RuntimeException("Fail to copy of " + location + " to " + targetDir, e);

    }

}

From source file:com.bibisco.test.AllTests.java

@BeforeClass
public static void cleanProjectsDirectory() throws IOException, ConfigurationException, InterruptedException {

    FileUtils.copyFile(new File(mStrTestBibiscoDBFilePath), new File(mStrDBFilePath));
    FileUtils.cleanDirectory(new File(BIBISCO_INTERNAL_PROJECTS_DIR));
    FileUtils.copyDirectoryToDirectory(new File(mStrTestProjectDBFilePath),
            new File(BIBISCO_INTERNAL_PROJECTS_DIR));
    FileUtils.copyDirectoryToDirectory(new File(mStrTestProject2DBFilePath),
            new File(BIBISCO_INTERNAL_PROJECTS_DIR));
    FileUtils.copyDirectoryToDirectory(new File(mStrTestProject3DBFilePath),
            new File(BIBISCO_INTERNAL_PROJECTS_DIR));
}

From source file:com.bibisco.test.AllTests.java

public static void cleanTestProjectDB() throws IOException {
    FileUtils.copyFile(new File(mStrTestBibiscoDBFilePath), new File(mStrDBFilePath));
    FileUtils.copyDirectoryToDirectory(new File(mStrTestProjectDBFilePath),
            new File(BIBISCO_INTERNAL_PROJECTS_DIR));
}

From source file:gov.nih.nci.restgen.util.GeneratorUtil.java

public static void copyDir(String srcFolderStr, String destFolderStr, List<String> excludes)
        throws IOException {
    File srcFolder = new File(srcFolderStr);
    File destFolder = new File(destFolderStr);

    if (srcFolder.isDirectory()) {

        // if directory not exists, create it
        if (!destFolder.exists()) {
            destFolder.mkdir();//from  ww  w  .  j a  va2s  .c o  m
            //System.out.println("Directory copied from " + srcFolder + "  to " + destFolder);
        }
        FileUtils.copyDirectoryToDirectory(srcFolder, destFolder);
        if (excludes != null && excludes.size() > 0) {
            for (String fileName : excludes) {
                File deleteFile = new File(destFolder + File.separator + fileName);
                FileUtils.deleteQuietly(deleteFile);
            }
        }
    }
}

From source file:com.linkedin.pinot.core.segment.store.SegmentLocalFSDirectoryTest.java

@Test
public void testDirectorySize() throws IOException {
    // this test verifies that the segment size is returned correctly even if v3/ subdir
    // does not exist. We have not good way to test all the conditions since the
    // format converters are higher level modules that can not be used in this package
    // So, we do what we can do best....HACK HACK HACK
    File sizeTestDirectory = null;
    try {/*from ww  w. j a  va  2  s  . c om*/
        sizeTestDirectory = new File(SegmentLocalFSDirectoryTest.class.getName() + "-size_test");
        if (sizeTestDirectory.exists()) {
            FileUtils.deleteQuietly(sizeTestDirectory);
        }
        FileUtils.copyDirectoryToDirectory(segmentDirectory.getPath().toFile(), sizeTestDirectory);
        SegmentDirectory sizeSegment = SegmentLocalFSDirectory.createFromLocalFS(sizeTestDirectory, metadata,
                ReadMode.mmap);
        Assert.assertEquals(sizeSegment.getDiskSizeBytes(), segmentDirectory.getDiskSizeBytes());

        Assert.assertFalse(
                SegmentDirectoryPaths.segmentDirectoryFor(sizeTestDirectory, SegmentVersion.v3).exists());
        File v3SizeDir = new File(sizeTestDirectory, SegmentDirectoryPaths.V3_SUBDIRECTORY_NAME);
        // the destination is not exactly v3 but does not matter
        FileUtils.copyDirectoryToDirectory(segmentDirectory.getPath().toFile(), v3SizeDir);
        SegmentDirectory sizeV3Segment = SegmentDirectory.createFromLocalFS(v3SizeDir, metadata, ReadMode.mmap);
        Assert.assertEquals(sizeSegment.getDiskSizeBytes(), sizeV3Segment.getDiskSizeBytes());

        // now drop v3
        FileUtils.deleteQuietly(v3SizeDir);
        v3SizeDir.mkdirs();
        // sizes still match because we get the size from the parent...
        Assert.assertEquals(sizeSegment.getDiskSizeBytes(), sizeV3Segment.getDiskSizeBytes());
    } finally {
        if (sizeTestDirectory != null) {
            FileUtils.deleteQuietly(sizeTestDirectory);
        }
    }
}