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:com.bbc.remarc.util.ResourceManager.java

private static void createDocumentsFromFileMap(HashMap<String, List<File>> fileMap,
        HashMap<String, ResourceType> typeMap, File properties, String resourcesDir) {

    DB db = MongoClient.getDB();//from w  w w  .  j ava2s .  c o m

    Properties documentProps = processPropertiesFile(properties);
    if (documentProps == null) {
        log.error("could not create properties file. Abort directory.");
        return;
    }

    String theme = documentProps.getProperty("theme");
    String decade = documentProps.getProperty("decade");
    if (theme == null && decade == null) {
        log.error("ERROR! Properties file contained neither THEME nor DECADE. Abort directory.");
        return;
    }

    // now we process each key (document) in the hashmap, copying the
    // resources (file array) into the correct folder
    Set<String> keys = fileMap.keySet();
    for (String key : keys) {

        log.debug("processing [" + key + "]");

        // create document with id, theme and decade
        BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start();
        documentBuilder.add("id", key);
        documentBuilder.add("theme", theme);
        documentBuilder.add("decade", decade);

        // based upon the documentType, we can determine all our urls and
        // storage variables
        ResourceType documentType = typeMap.get(key);

        File fileDestDirectory = null;

        // Get the relative base URL from an Environment variable if it has been set
        String relativefileBaseUrl = System.getenv(Configuration.ENV_BASE_URL);
        if (relativefileBaseUrl == null || "".equals(relativefileBaseUrl)) {
            relativefileBaseUrl = Configuration.DEFAULT_RELATIVE_BASE_URL;
        } else {
            relativefileBaseUrl += Configuration.CONTENT_DIR;
        }

        String mongoCollection = "";

        switch (documentType) {
        case IMAGE:
            mongoCollection = "images";
            fileDestDirectory = new File(resourcesDir + Configuration.IMAGE_DIR_NAME);
            relativefileBaseUrl += Configuration.IMAGE_DIR;
            break;
        case AUDIO:
            mongoCollection = "audio";
            fileDestDirectory = new File(resourcesDir + Configuration.AUDIO_DIR_NAME);
            relativefileBaseUrl += Configuration.AUDIO_DIR;
            break;
        case VIDEO:
            mongoCollection = "video";
            fileDestDirectory = new File(resourcesDir + Configuration.VIDEO_DIR_NAME);
            relativefileBaseUrl += Configuration.VIDEO_DIR;
            break;
        default:
            break;
        }

        List<File> files = fileMap.get(key);
        for (File resource : files) {

            log.debug("--- processing [" + resource.getName() + "]");

            String resourceLocation = relativefileBaseUrl + resource.getName();
            String extension = FilenameUtils.getExtension(resource.getName());

            ResourceType fileType = getTypeFromExtension(extension);

            // now determine the value to store the resource under in MongoDB, different if an image or metadata
            String urlKey;
            switch (fileType) {
            case IMAGE:
                urlKey = "imageUrl";
                break;
            case INFORMATION:
                urlKey = "metadata";
                break;
            default:
                urlKey = (extension + "ContentUrl");
                break;
            }

            // If the file is a metadata file, we want to read from it, otherwise we just add the location to the db
            if (fileType == ResourceType.INFORMATION) {
                String metadata = processMetadata(resource.getPath());
                documentBuilder.add(urlKey, metadata);
            } else {
                documentBuilder.add(urlKey, resourceLocation);
            }

        }

        // insert the document into the database
        try {
            DBObject obj = documentBuilder.get();

            log.debug("writing document to collection (" + mongoCollection + "): " + obj);

            db.requestStart();
            DBCollection collection = db.getCollection(mongoCollection);
            collection.insert(documentBuilder.get());

        } finally {
            db.requestDone();
        }

        // write all the resource files to the correct directory
        log.debug("copying resources into " + fileDestDirectory.getPath());

        for (File resource : files) {

            // We don't want to copy the metadata into the directory, so remove it here
            String extension = FilenameUtils.getExtension(resource.getName());
            ResourceType fileType = getTypeFromExtension(extension);

            if (fileType != ResourceType.INFORMATION) {
                try {
                    FileUtils.copyFileToDirectory(resource, fileDestDirectory);
                } catch (IOException e) {
                    log.error("ERROR! Couldn't copy resource to directory: " + e);
                }
            }
        }

    }
}

From source file:es.urjc.mctwp.image.management.ImageCollectionManager.java

/**
 * This is the same function as above, but it copies all content
 * from a directory instead of an image/*from   ww w.ja v a  2 s.  c  o  m*/
 * 
 * @param directory
 * @param source
 * @throws IOException
 */
private void copyToDirectory(File directory, File source) throws IOException {

    if (source.isFile()) {
        FileUtils.copyFileToDirectory(source, directory);
    } else if (source.isDirectory()) {

        //Create temp directory where put all file content of Image
        File tmpDir = new File(FilenameUtils.concat(directory.getAbsolutePath(), source.getName()));
        if (!tmpDir.exists())
            tmpDir.mkdir();

        if (source.listFiles() != null)
            for (File file : source.listFiles())
                copyToDirectory(tmpDir, file);
    }
}

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

private void moveFiles() {
    try {//from w ww .  j  a v a  2  s . c  o m
        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());
    }
}

From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.AbstractUnitTest.java

@Before
public final void startKRBServer() throws Exception {
    FileUtils.deleteDirectory(new File("testtmp"));
    FileUtils.forceMkdir(new File("testtmp/tgtcc/"));
    FileUtils.forceMkdir(new File("testtmp/keytab/"));

    String loginconf = FileUtils/*w w w .j a v  a 2  s .  c  o m*/
            .readFileToString(getAbsoluteFilePathFromClassPath("login.conf_template").toFile());

    // @formatter:on
    loginconf = loginconf.replace("${debug}", String.valueOf(debugAll))
            .replace("${initiator.principal}", "spock/admin@CCK.COM")
            .replace("${initiator.ticketcache}", new File("testtmp/tgtcc/spock.cc").toURI().toString())
            .replace("${keytab}", new File("testtmp/keytab/es_server.keytab").toURI().toString());
    // @formatter:off

    final File loginconfFile = new File("testtmp/jaas/login.conf");
    FileUtils.write(new File("testtmp/jaas/login.conf"), loginconf);
    PropertyUtil.setSystemProperty(KrbConstants.JAAS_LOGIN_CONF_PROP, loginconfFile.getAbsolutePath(), true);

    embeddedKrbServer.start(new File("testtmp/simplekdc/"));

    FileUtils.copyFileToDirectory(new File("testtmp/simplekdc/krb5.conf"),
            new File("testtmp/config/data/simplekdc/"));
}

From source file:com.aliyun.odps.local.common.WareHouse.java

/**
 * copy table schema to destination directory
 *//*from   w  w  w  . j a  va2  s .c  om*/
public boolean copyTableSchema(String projectName, String tableName, File destDir, int limitDownloadRecordCount,
        char inputColumnSeperator) throws IOException, OdpsException {
    if (StringUtils.isBlank(projectName) || StringUtils.isBlank(tableName) || destDir == null) {
        return false;
    }
    TableInfo tableInfo = TableInfo.builder().projectName(projectName).tableName(tableName).build();

    LOG.info("Start to copy table schema: " + tableInfo + "-->" + destDir.getAbsolutePath());

    if (!existsTable(projectName, tableName)) {
        DownloadUtils.downloadTableSchemeAndData(getOdps(), tableInfo, limitDownloadRecordCount,
                inputColumnSeperator);
    }

    File tableDir = getTableDir(projectName, tableName);
    File schemaFile = new File(tableDir, Constants.SCHEMA_FILE);
    if (!schemaFile.exists()) {
        throw new FileNotFoundException(
                "Schema file of table " + projectName + "." + tableName + " not exists in warehouse.");
    }

    if (!destDir.exists()) {
        destDir.mkdirs();
    }

    FileUtils.copyFileToDirectory(schemaFile, destDir);
    LOG.info("Finished copy table schema: " + tableInfo + "-->" + destDir.getAbsolutePath());
    return true;
}

From source file:Forms.frm_Penghuni.java

public boolean salinFoto() {
    try {//from w w w .  java 2  s  . c om
        String path = new File(".").getCanonicalPath();
        FileUtils.copyFileToDirectory(file, new File(path + "/image"));
        FileUtils.copyFileToDirectory(file1, new File(path + "/image"));

    } catch (IOException ex) {

        //            Logger.getLogger(frm_detail_penghuni.class.getName()).log(Level.SEVERE, null, ex);

    }
    return true;
}

From source file:gov.nasa.ensemble.common.ui.FileSystemExportWizardPage.java

public boolean finish() {
    File destination = new File(getDestinationValue());
    if (!ensureDirectoryExists(destination)) {
        MessageDialog.openError(getContainer().getShell(), "Error",
                "Error validating destination directory: " + getDestinationValue());
        return false;
    }/*w  w w. j  a v a  2 s. c om*/
    List<File> failedToCopy = null;
    List<IOException> errors = null;
    for (File file : getFilesToCopy()) {
        try {
            FileUtils.copyFileToDirectory(file, destination);
        } catch (IOException io) {
            // keep track of which files failed to copy
            if (failedToCopy == null) {
                failedToCopy = new ArrayList<File>();
                errors = new ArrayList<IOException>();
            }
            failedToCopy.add(file);
            if (errors != null)
                errors.add(io);

            Logger.getLogger(getClass()).error(io);
        }
    }

    // check whether all the copies were successful
    // if any were not, then pop of an informative error
    if (failedToCopy != null) {
        final StringBuilder b = new StringBuilder();
        for (int i = 0; i < failedToCopy.size(); i++)
            if (errors != null) {
                b.append("\t").append(failedToCopy.get(i).getName()).append(" : ")
                        .append(errors.get(i).getMessage()).append("\n\n");
            }
        MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error Retrieving Files",
                "The following files were not successfully retrieved:\n\n" + b.toString());
        return false;
    }

    return true;
}

From source file:com.asakusafw.testdriver.JobflowExecutor.java

private void deployApplication(JobflowInfo info) throws IOException {
    LOG.debug("Deploying application library: {}", info.getPackageFile()); //$NON-NLS-1$
    File jobflowDest = context.getJobflowPackageLocation(info.getJobflow().getBatchId());
    FileUtils.copyFileToDirectory(info.getPackageFile(), jobflowDest);

    File dependenciesDest = context.getLibrariesPackageLocation(info.getJobflow().getBatchId());
    if (dependenciesDest.exists()) {
        LOG.debug("Cleaning up dependency libraries: {}", dependenciesDest); //$NON-NLS-1$
        FileUtils.deleteDirectory(dependenciesDest);
    }//from   w w  w.ja  v  a 2  s .c  o  m

    File dependencies = context.getLibrariesPath();
    if (dependencies.exists()) {
        LOG.debug("Deplogying dependency libraries: {} -> {}", dependencies, dependenciesDest); //$NON-NLS-1$
        if (dependenciesDest.mkdirs() == false && dependenciesDest.isDirectory() == false) {
            LOG.warn(MessageFormat.format("???????: {0}",
                    dependenciesDest.getAbsolutePath()));
        }
        for (File file : dependencies.listFiles()) {
            if (file.isFile() == false) {
                continue;
            }
            LOG.debug("Copying a library: {} -> {}", file, dependenciesDest); //$NON-NLS-1$
            FileUtils.copyFileToDirectory(file, dependenciesDest);
        }
    }
}

From source file:edu.ur.file.db.FileSystemManager.java

/**
 * Copy the file to the specified directory.
 * /*  w  w w. j a va2  s .  c o  m*/
 * @param file the file to copy
 * @param directory to copy the file to
 * 
 * @return true if the file is copied.
 */
static boolean copyFileToDirectory(File file, File directory) {
    try {
        FileUtils.copyFileToDirectory(file, directory);
    } catch (IOException io) {
        throw new RuntimeException("Trying to copy file " + file.getAbsolutePath() + " to directory "
                + directory.getAbsolutePath(), io);
    }

    return true;
}

From source file:me.neatmonster.spacertk.actions.ServerActions.java

/**
 * Rollover's the log/*from ww w .  ja  va 2  s .co m*/
 * @return If successful
 */
@Action(aliases = { "rollOverLog", "rollOver" })
public boolean rollOver() {
    File oldLog = null;
    for (File file : new File(".").listFiles()) {
        if (file.getName().contains("server") && file.getPath().endsWith("log")) {
            oldLog = file;
        }
    }
    if (oldLog == null) {
        return false;
    }
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm");
    final File newLog = new File("server_" + format.format(new Date()) + ".log");
    try {
        if (!newLog.exists())
            newLog.createNewFile();
        FileUtils.writeStringToFile(newLog, FileUtils.readFileToString(oldLog));
        FileUtils.write(oldLog, "");

        if (SpaceRTK.getInstance().backupLogs) {
            FileUtils.copyFileToDirectory(oldLog, new File(SpaceRTK.getInstance().backupDirName));
        }
        oldLog.delete();
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return true;
}