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

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

Introduction

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

Prototype

public static void copyFileToDirectory(File srcFile, File destDir) throws IOException 

Source Link

Document

Copies a file to a directory preserving the file date.

Usage

From source file:org.liberty.android.fantastischmemo.converter.Mnemosyne2CardsExporter.java

@Override
public void convert(String src, String dest) throws Exception {
    // Make the tmp directory tmp/[src file name]/
    String srcFilename = FilenameUtils.getName(src);

    // This the file name for cards without extension
    String deckName = FilenameUtils.removeExtension(srcFilename);

    File tmpDirectory = new File(AMEnv.DEFAULT_TMP_PATH + deckName);

    FileUtils.deleteDirectory(tmpDirectory);
    FileUtils.forceMkdir(tmpDirectory);/*from ww w  .j a  v a  2s .co m*/

    try {
        // Example content of cards
        // $ ls
        // METADATA  cards.xml  musicnotes

        // Make sure the XML file exists.
        File xmlFile = new File(tmpDirectory + "/cards.xml");

        // Before opening dest. Try to backup and delete the dest db.
        amFileUtil.deleteFileWithBackup(dest);
        createXMLFile(src, xmlFile);

        File metadataFile = new File(tmpDirectory + "/METADATA");
        createMetadata(deckName, metadataFile);

        // The last step is to see if there are images to export.
        File imageDir = new File(AMEnv.DEFAULT_IMAGE_PATH + srcFilename);
        if (imageDir.exists() && imageDir.isDirectory()) {
            // Copy all the images to the tmp directory
            Collection<File> imageFiles = FileUtils.listFiles(imageDir,
                    new SuffixFileFilter(new String[] { "jpg", "png", "bmp", "jpeg" }, IOCase.INSENSITIVE),
                    DirectoryFileFilter.DIRECTORY);

            for (File f : imageFiles) {
                FileUtils.copyFileToDirectory(f, tmpDirectory);
            }
        }

        // Now create the cards file:
        AMZipUtils.zipDirectory(tmpDirectory, "", new File(dest));

    } finally {
        FileUtils.deleteDirectory(tmpDirectory);
    }
}

From source file:org.liberty.android.fantastischmemo.converter.Mnemosyne2CardsImporter.java

@Override
public void convert(String src, String dest) throws Exception {
    // Make the tmp directory tmp/[src file name]/
    String srcFilename = FilenameUtils.getName(src);
    File tmpDirectory = new File(AMEnv.DEFAULT_TMP_PATH + srcFilename);

    FileUtils.deleteDirectory(tmpDirectory);
    FileUtils.forceMkdir(tmpDirectory);//from ww  w .  j a v a2 s  . c  om

    AnyMemoDBOpenHelper helper = null;
    try {
        // First unzip the file since cards is just a zip archive
        // Example content of cards
        // $ ls
        // METADATA  cards.xml  musicnotes
        AMZipUtils.unZipFile(new File(src), tmpDirectory);

        // Make sure the XML file exists.
        File xmlFile = new File(tmpDirectory + "/cards.xml");
        if (!xmlFile.exists()) {
            throw new Exception("Could not find the cards.xml after extracting " + src);
        }

        List<Card> cardList = xmlToCards(xmlFile);

        if (!new File(dest).exists()) {
            amFileUtil.createDbFileWithDefaultSettings(new File(dest));
        }
        helper = AnyMemoDBOpenHelperManager.getHelper(dest);
        CardDao cardDao = helper.getCardDao();
        cardDao.createCards(cardList);

        // The last step is to see if there are images to import.
        Collection<File> imageFiles = FileUtils.listFiles(tmpDirectory,
                new SuffixFileFilter(new String[] { "jpg", "png", "bmp" }, IOCase.INSENSITIVE),
                DirectoryFileFilter.DIRECTORY);
        if (!imageFiles.isEmpty()) {
            String destDbName = FilenameUtils.getName(dest);
            File imageDir = new File(AMEnv.DEFAULT_IMAGE_PATH + destDbName);
            FileUtils.forceMkdir(imageDir);
            for (File imageFile : imageFiles) {
                FileUtils.copyFileToDirectory(imageFile, imageDir);
            }
        }
    } finally {
        if (helper != null) {
            AnyMemoDBOpenHelperManager.releaseHelper(helper);
        }
        FileUtils.deleteDirectory(tmpDirectory);
    }

}

From source file:org.lorislab.maven.jboss.server.DeploymentMojo.java

/**
 * The deploy the file to the server./*from www . j  a va  2 s.c  o  m*/
 *
 * @throws MojoExecutionException
 * @throws MojoFailureException
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    File targetDir = getTargetDir();

    if (exploded) {
        try {
            getLog().info("Deploy the directory: " + targetDirName + " to the server: "
                    + targetDir.getAbsolutePath());

            File target = new File(targetDir, targetDirName);

            FileUtils.deleteDirectory(target);

            // create target directory
            if (!target.exists()) {
                target.mkdir();
            }

            // copy directory
            FileUtils.copyDirectory(deployDir, target);

            // redeploy the application
            FileUtils.touch(new File(targetDir, targetDirName + ".dodeploy"));
            getLog().info("Exploded deployed finished!");
        } catch (IOException ex) {
            throw new MojoExecutionException("Error to copy the deploy final " + deployFile.getAbsolutePath(),
                    ex);
        }
    } else {
        try {
            getLog().info("Deploy the file: " + deployFile.getAbsolutePath() + " to the server: "
                    + targetDir.getAbsolutePath());
            FileUtils.copyFileToDirectory(deployFile, targetDir);
            getLog().info("Deployed finished!");
        } catch (IOException ex) {
            throw new MojoExecutionException("Error to copy the deploy final " + deployFile.getAbsolutePath(),
                    ex);
        }
    }
}

From source file:org.lpe.common.util.system.LpeSystemUtils.java

/**
 * Extracts files from a directory in the classpath to a temp directory and
 * returns the File instance of the destination directory.
 * //  w  ww  .j  a v a  2  s  .  com
 * @param srcDirName
 *            a directory name in the classpath
 * @param destName
 *            the name of the destination folder in the temp folder
 * @param fileType
 *            a string describing the file types, if a log message is needed
 * @param timeStamp
 *            if <code>true</code>, it will add a time stamp to the name of
 *            the target directory (recommended)
 * @param classloader
 *            classloader to use
 * 
 * @return the name of the target directory
 * 
 * @throws IOException
 *             ...
 * @throws URISyntaxException
 *             ...
 */
public static String extractFilesFromClasspath(String srcDirName, String destName, String fileType,
        ClassLoader classloader, boolean timeStamp) throws IOException, URISyntaxException {

    if (timeStamp) {
        // remove dots and colons from timestamp as they are not allowed for
        // windows directory names
        String clearedTimeStamp = (LpeStringUtils.getTimeStamp() + "-" + Thread.currentThread().getId())
                .replace('.', '_');

        clearedTimeStamp = clearedTimeStamp.replace(':', '_');
        clearedTimeStamp = clearedTimeStamp.replace(' ', '_');

        destName = destName + "_" + clearedTimeStamp;
    }
    final String targetDirName = LpeFileUtils.concatFileName(getSystemTempDir(), destName);

    // create a temp lib directory
    File targetDirFile = new File(targetDirName);
    if (!targetDirFile.exists()) {
        boolean ok = targetDirFile.mkdir();
        if (!ok) {
            logger.warn("Could not create directory {}", targetDirFile.getAbsolutePath());
        }
    }

    logger.debug("Copying {} to {}.", fileType, targetDirName);

    Enumeration<URL> urls = classloader.getResources(srcDirName); // getSystemResources(srcDirName);

    if (urls.hasMoreElements()) {
        logger.debug("There are some urls for resource '{}' provided by the classloader.", srcDirName);
    } else {
        logger.debug("There are no urls for resource '{}' provided by the classloader.", srcDirName);
    }

    while (urls.hasMoreElements()) {

        final URL url = urls.nextElement();

        if (fileType != null && fileType.trim().length() > 0) {
            logger.debug("Loading {} from {}...", fileType, url);
        }

        Iterator<File> libs = null;
        String unpackedJarDir = null;
        if (url.getProtocol().equals("bundleresource")) {
            continue;
        } else if (url.getProtocol().equals("jar")) {
            try {
                unpackedJarDir = LpeFileUtils.concatFileName(targetDirName, "temp");

                extractJARtoTemp(url, srcDirName, unpackedJarDir);

                final String unpackedNativeDir = LpeFileUtils.concatFileName(unpackedJarDir, srcDirName);
                final File unpackedNativeDirFile = new File(unpackedNativeDir);
                libs = FileUtils.iterateFiles(unpackedNativeDirFile, null, false);
            } catch (IllegalArgumentException iae) {
                // ignore
                LOGGER.warn("Jar not found, could not extract jar. {}", iae);

            }
        } else {
            // File nativeLibDir = new
            // File(url.toString().replaceAll("\\\\", "/"));
            File nativeLibDir = new File(url.toURI());
            libs = FileUtils.iterateFiles(nativeLibDir, null, false);
        }

        while (libs != null && libs.hasNext()) {
            final File libFile = libs.next();
            logger.debug("Copying resouce file {}...", libFile.getName());
            FileUtils.copyFileToDirectory(libFile, targetDirFile);
        }

        // clean up temp dir
        if (unpackedJarDir != null) {
            File dirToRemove = new File(unpackedJarDir);
            if (dirToRemove.isDirectory() && dirToRemove.exists()) {
                LpeFileUtils.removeDir(unpackedJarDir);
            }
        }

    }

    return targetDirName;
}

From source file:org.m2latex.mojo.TexFileUtilsImpl.java

private void copyFilesToDirectory(File[] files, File targetDirectory) throws MojoExecutionException {
    for (int i = 0; i < files.length; i++) {
        try {//from  www .jav  a2  s .  co m
            FileUtils.copyFileToDirectory(files[i], targetDirectory);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Error copying file " + files[i] + " to directory " + targetDirectory, e);
        }
    }
}

From source file:org.m2latex.mojo.TexFileUtilsImpl.java

private void copyFileToDirectory(File file, File targetDir) throws IOException {
    log.info("Copying " + file.getName() + " to " + targetDir);
    FileUtils.copyFileToDirectory(file, targetDir);
}

From source file:org.metaeffekt.dcc.commons.execution.ExecutionStateHandlerTest.java

@Test
public void alreadySuccessfullyExecuted() throws IOException {
    final File stateDir = DccUtils.workStateBaseDir(solutionDir);

    FileUtils.copyFileToDirectory(
            new File(new File(new File(targetDir, DccConstants.CONFIG_SUB_DIRECTORY), "unit1"),
                    "start.properties"),
            new File(stateDir, "unit1"));
    FileUtils.copyFileToDirectory(//ww w.  j  a v  a2  s  .com
            new File(new File(new File(targetDir, DccConstants.CONFIG_SUB_DIRECTORY), "unit2"),
                    "start.properties"),
            new File(stateDir, "unit2"));

    executionStateHandler = new ExecutionStateHandler(targetDir, solutionDir);

    InputStream consolidatedState = executionStateHandler.consolidateState(deploymentId);
    executionStateHandler.updateConsolidatedState(consolidatedState, host, deploymentId);

    assertTrue("unit1.start should have been executed", executionStateHandler
            .alreadySuccessfullyExecuted(Id.createUnitId("unit1"), Commands.START, host, deploymentId));
    assertTrue("unit2.start should have been executed", executionStateHandler
            .alreadySuccessfullyExecuted(Id.createUnitId("unit2"), Commands.START, host, deploymentId));
    assertFalse("unit3.start should NOT have been executed", executionStateHandler
            .alreadySuccessfullyExecuted(Id.createUnitId("unit3"), Commands.START, host, deploymentId));
    assertFalse("unit4.stop should NOT have been executed", executionStateHandler
            .alreadySuccessfullyExecuted(Id.createUnitId("unit4"), Commands.STOP, host, deploymentId));
}

From source file:org.metaeffekt.dcc.commons.execution.ExecutionStateHandlerTest.java

@Test
public void handleStart() throws IOException {
    executionStateHandler = new ExecutionStateHandler(emptyTargetDir, solutionDir);

    final File executedProperties = new File(new File(targetDir, "template1"), "stop.properties");
    final File toExecuteProperties = new File(new File(targetDir, "template1"), "start.properties");
    File unit6Source = executionStateHandler.getCacheLocation(host, deploymentId);
    File unit6Target = new File(unit6Source, "unit6");

    FileUtils.copyFileToDirectory(executedProperties, unit6Target);

    executionStateHandler = new ExecutionStateHandler(targetDir, solutionDir);

    final Id<UnitId> unitId = Id.createUnitId("unit6");
    assertTrue("unit6.stop should have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.STOP, host, deploymentId));
    assertFalse("unit6.start should not have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.START, host, deploymentId));

    executionStateHandler.persistStateAfterSuccessfulExecution(unitId, Commands.START, toExecuteProperties);
    executionStateHandler.updateConsolidatedState(executionStateHandler.consolidateState(deploymentId), host,
            deploymentId);/*from w  w  w  .  j  av a  2  s .  c o  m*/

    assertFalse("unit6.stop state should have been cleared",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.STOP, host, deploymentId));
    assertTrue("unit6.start should have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.START, host, deploymentId));
}

From source file:org.metaeffekt.dcc.commons.execution.ExecutionStateHandlerTest.java

@Test
public void handleStop() throws IOException {
    executionStateHandler = new ExecutionStateHandler(emptyTargetDir, solutionDir);

    final File executedProperties = new File(new File(targetDir, "template2"), "start.properties");
    final File toExecuteProperties = new File(new File(targetDir, "template2"), "stop.properties");
    FileUtils.copyFileToDirectory(executedProperties,
            new File(executionStateHandler.getCacheLocation(host, deploymentId), "unit5"));

    executionStateHandler = new ExecutionStateHandler(targetDir, solutionDir);

    final Id<UnitId> unitId = Id.createUnitId("unit5");
    assertTrue("unit5.start should have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.START, host, deploymentId));
    assertFalse("unit5.stop should not have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.STOP, host, deploymentId));

    executionStateHandler.persistStateAfterSuccessfulExecution(unitId, Commands.STOP, toExecuteProperties);
    executionStateHandler.updateConsolidatedState(executionStateHandler.consolidateState(deploymentId), host,
            deploymentId);/* w  ww. j  ava 2  s  .  c  o m*/

    assertFalse("unit5.start state should have been cleared",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.START, host, deploymentId));
    assertTrue("unit5.stop should have been executed",
            executionStateHandler.alreadySuccessfullyExecuted(unitId, Commands.STOP, host, deploymentId));
}

From source file:org.mifos.framework.ApplicationInitializer.java

private void copyResources(ServletContext sc) throws IOException {
    URL protocol = ETLReportDWHelper.class.getClassLoader().getResource("sql/release-upgrades.txt");
    ConfigurationLocator configurationLocator = new ConfigurationLocator();
    String configPath = configurationLocator.getConfigurationDirectory();
    try {//  w w w .  jav  a 2  s  .  c o  m
        if (protocol.getProtocol().equals("jar")) {
            String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL";
            String destinationDirectoryForJar = configPath + "/ETL/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
            String pathFromJar = "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
            String pathFromJobs = "/WEB-INF/MifosDataWarehouseETL/";
            if (File.separatorChar == '\\') {
                destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\");
                destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\");
            }
            File directory = new File(destinationDirectoryForJobs);
            directory.mkdirs();
            FileUtils.cleanDirectory(directory);
            File jarDest = new File(destinationDirectoryForJar);
            URL fullPath = sc.getResource(pathFromJar);
            File f = new File(sc.getResource(pathFromJobs).toString().replace("file:", ""));
            for (File fileEntry : f.listFiles()) {
                FileUtils.copyFileToDirectory(fileEntry, directory);
                logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
            }
            FileUtils.copyURLToFile(fullPath, jarDest);
            logger.info("Copy file: " + fullPath + " to: " + directory);
        }
    } catch (NullPointerException e) {
        String destinationDirectoryForJobs = configPath + "/ETL/MifosDataWarehouseETL";
        String destinationDirectoryForJar = configPath + "/ETL/";
        String pathFromJar = sc.getRealPath("/") + "/WEB-INF/mifos-etl-plugin-1.0-SNAPSHOT.one-jar.jar";
        String pathFromJobs = sc.getRealPath("/") + "/WEB-INF/MifosDataWarehouseETL/";
        if (File.separatorChar == '\\') {
            destinationDirectoryForJobs = destinationDirectoryForJobs.replaceAll("/", "\\\\");
            destinationDirectoryForJar = destinationDirectoryForJar.replaceAll("/", "\\\\");
        }
        File directory = new File(destinationDirectoryForJobs);
        directory.mkdirs();
        FileUtils.cleanDirectory(directory);
        logger.info(System.getProperty("user.dir"));
        File jarDest = new File(destinationDirectoryForJar);
        URL fullPath = sc.getResource(pathFromJar);
        File f = new File(pathFromJobs);
        for (File fileEntry : f.listFiles()) {
            FileUtils.copyFileToDirectory(fileEntry, directory);
            logger.info("Copy file: " + fileEntry.getName() + " to: " + directory);
        }
        FileUtils.copyFileToDirectory(new File(pathFromJar), jarDest);
        logger.info("Copy file: " + fullPath + " to: " + directory);
    }
}