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:de.mpg.imeji.presentation.servlet.DigilibServlet.java

/**
 * Copy a file from a location to another on the fileSystem
 * /*from   w w  w . j  a  v  a2 s . com*/
 * @param from
 * @param to
 */
private void copyFile(String from, String to) {
    try {
        FileUtils.copyFileToDirectory(new File(from), new File(to));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:acoli.controller.Controller.java

/**
 *
 * @param request/*  w  ww  . j  av a  2 s.  c  o m*/
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws FileNotFoundException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileNotFoundException {

    // Get servlet context.
    ServletContext servletContext = this.getServletConfig().getServletContext();
    String path = servletContext.getRealPath("/");
    //System.out.println(path);
    // Previously used way to obtain servlet context doesn't work.
    //ServletContext context = request.getServletContext();
    //String path = context.getRealPath("/");
    //System.out.println("ServletContext.getRealPath():" + path + "<--");

    String forward = "";
    // Get a map of the request parameters
    @SuppressWarnings("unchecked")
    Map parameters = request.getParameterMap();

    if (parameters.containsKey("grammar")) {
        HttpSession session = request.getSession(false);
        String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //System.out.println("Uploaded file to analyze: " + absoluteUnzippedGrammarDir);

        // User-selected port.
        String javaport = (String) request.getParameter("javaport");

        System.out.println("User selected port: " + javaport);
        String traleport = String.valueOf((Integer.parseInt(javaport) - 1000));

        // Check if these ports are already in use
        // if so, kill the grammar in the corresponding directory and start a new one.
        if (portAvailable(Integer.parseInt(javaport)) && portAvailable(Integer.parseInt(traleport))) {
            System.out.println("Both javaport/traleport: " + javaport + "/" + traleport + " available!");
        } else {
            // Java port not free.
            if (!portAvailable(Integer.parseInt(javaport))) {
                System.out.println("Port: " + javaport + " not available!");
                // Get the grammar directory that is running on this port and kill it.
                if (portToGrammarFolderMappings.containsKey(javaport)) {
                    String grammarDirToKill = portToGrammarFolderMappings.get(javaport);
                    // Stop grammar.
                    runBashScript(path, "./single_grammar_stop.sh", grammarDirToKill, "");

                } else {
                    killProcessID(path, "./free_java_port.sh", javaport);
                }
            }
            // Trale port not free.
            if (!portAvailable(Integer.parseInt(traleport))) {
                killProcessID(path, "./free_sicstus_port.sh", traleport);
            }
        }
        // Generate port-specific files
        // which will be redirected by the script later.
        PrintWriter w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "javaserverport.txt"));
        w.write(javaport);
        w.flush();
        w.close();

        w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "traleserverstart.pl"));
        w.write("trale_server_start(" + traleport + ").\n"); // 1000 port ids less than the java id.
        w.flush();
        w.close();

        // Copy wtx.pl and tokenization.pl into the grammar directory.
        File tokenizationFile = new File(path + "/resources/servertrale_files/tokenization.pl");
        File wtxFile = new File(path + "/resources/servertrale_files/wtx.pl");

        //System.out.println("tokenizationFile: " + tokenizationFile.getAbsolutePath());
        //System.out.println("wtxFile: " + wtxFile.getAbsolutePath());
        File destinationDir = new File(absoluteUnzippedGrammarDir + "/");
        //System.out.println("destinationDir: " + absoluteUnzippedGrammarDir);
        FileUtils.copyFileToDirectory(tokenizationFile, destinationDir);
        FileUtils.copyFileToDirectory(wtxFile, destinationDir);

        // Start grammar.
        // Check webtrale version from user selection.
        String labelVersion = (String) request.getParameter("webtraleVersion");
        System.out.println("User selected label version: " + labelVersion);

        switch (labelVersion) {
        case "webtralePS94":
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_labels.jar");
            break;
        case "webtraleAprilLabels":
            // April labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_aprillabels.jar");
            break;
        case "webtraleMayLabels":
            // May labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_maylabels.jar");
            break;
        case "webtraleJuneLabels":
            // June labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_junelabels.jar");
            break;
        default:
            // Standard labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_nolabels.jar");
            break;
        }

        portToGrammarFolderMappings.put(javaport, absoluteUnzippedGrammarDir);
        session.setAttribute("javaport", javaport);
        System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n");

        forward = GRAMMAR_JSP;
    } else if (parameters.containsKey("run")) {
        forward = RUN_JSP;
    } else if (parameters.containsKey("admin")) {
        System.out.println("Accessing grammar admin.");
        // Check which ports are still non-available.
        TreeMap<String, String> tmpMap = new TreeMap<>();
        for (String aJavaPort : portToGrammarFolderMappings.keySet()) {
            if (!portAvailable(Integer.parseInt(aJavaPort))) {
                tmpMap.put(aJavaPort, portToGrammarFolderMappings.get(aJavaPort));
            }
        }

        portToGrammarFolderMappings.clear();
        portToGrammarFolderMappings = tmpMap;
        System.out
                .println("Used ports and grammar directories in admin: " + portToGrammarFolderMappings + "\n");

        // only testing.
        //portToGrammarFolderMappings.put("7001", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/BEBFECC89/posval");
        //portToGrammarFolderMappings.put("7002", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/B02CA6BAA/4_Semantics_Raising");

        // Save all used ports and directories in this session attribute.
        HttpSession session = request.getSession(false);
        String portToGrammarFolderMappingsString = portToGrammarFolderMappings.toString().substring(1,
                portToGrammarFolderMappings.toString().length() - 1);
        session.setAttribute("runningGrammars", portToGrammarFolderMappingsString.split("\\, "));

        forward = ADMIN_JSP;

    } // Upload (START PAGE)
    else {

        //            HttpSession session = request.getSession(false);
        //            String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //            if (absoluteUnzippedGrammarDir != null) {
        //                // Stop grammar.
        //                runBashScript(path, "./single_grammar_stop.sh", absoluteUnzippedGrammarDir);
        //                // Remove this java port from the list of occupied ports.
        //                TreeMap<String, String> tmpMap = new TreeMap<>();
        //                for(String aJavaPort : portToGrammarFolderMappings.keySet()) {
        //                    String aGrammarDir = portToGrammarFolderMappings.get(aJavaPort);
        //                    if(aGrammarDir.equals(absoluteUnzippedGrammarDir)) {
        //                        // Java port should be removed. So ignore it.
        //                    }
        //                    else {
        //                        tmpMap.put(aJavaPort, absoluteUnzippedGrammarDir);
        //                    }
        //                }
        //                portToGrammarFolderMappings.clear();
        //                portToGrammarFolderMappings = tmpMap;
        //                System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n\n");
        //                
        //            } else {
        //                System.out.println("No grammar to kill.");
        //            }
        forward = UPLOAD_JSP;
    }

    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}

From source file:edu.pitt.dbmi.facebase.hd.FileManager.java

/** copies files to mounted truecrypt volume
 * Assumes all Instruction objects and their associated Files are in order.
 * Assumes suitably large truecrypt volume is mounted and writable and can hold all of the data. 
 * Double-checks that data will fit onto volume (although this fact has also been established elsewhere by now).
 * This method will block for a very long time if large amounts of data are being copied. 
 * //from w  ww  .  j ava  2  s .  c  o m
 * @return true if copy effort succeeded
 */
public boolean copyFilesToVolume(ArrayList<Instructions> alival) {
    log.debug("FileManager.copyFilesToVolume() called.");
    long totalSize = 0;
    HashMap<File, String> hmfs = new HashMap<File, String>();
    for (Instructions i : alival) {
        hmfs.put(i.getFile(), i.getRelativePathToFileInArchive());
        totalSize += i.getFile().length();
    }
    long volSize = 0;
    File trueCryptVolFile = new File(this.getTrueCryptPath());
    volSize = trueCryptVolFile.length();
    if (totalSize > volSize) {
    } else {
    }
    try {
        for (File f : hmfs.keySet()) {
            File tcvpPlusRptfia = new File(trueCryptVolumePath + hmfs.get(f));
            File parentDir = new File(tcvpPlusRptfia.getParent());
            if (f.isFile()) {
                if (parentDir.isDirectory()) {
                } else {
                    parentDir.mkdirs();
                    if (parentDir.isDirectory()) {
                    }
                }
                log.debug("About to copy with FileUtils.copyFileToDirectory() using two args, FILE, DIR:");
                log.debug(f + " " + parentDir);
                FileUtils.copyFileToDirectory(f, parentDir);
            }
        }
    } catch (IOException ioe) {
        String errorString = "FileManager caught an ioe in copyFilesToVolume()" + ioe.toString();
        String logString = ioe.getMessage();
        edu.pitt.dbmi.facebase.hd.HumanDataController.addError(errorString, logString);
        log.error(errorString, ioe);
        return false;
    }
    //Uncomment these next 2 lines to simulate errors
    //edu.pitt.dbmi.facebase.hd.HumanDataController.addError("BADSTUFFmessage","BADSTUFFlog");
    //log.error("FileManager caught an ioe in copyFilesToVolume()BADSTUFF", new IOException());
    return true;
}

From source file:com.commander4j.sys.JHostList.java

public boolean checkUpdatedHosts() {
    boolean result = false;

    if (Common.updateMODE.equals("AUTOMATIC")) {

        Double currentHostVersion = Double.valueOf(Common.hostVersion);
        logger.debug("Current Host File Version = " + String.valueOf(currentHostVersion));

        String hostUpdatePath = Common.hostUpdatePath;
        if (hostUpdatePath.equals("") == true) {

            logger.debug("No hosts file update location specified, checking application update url.");

            hostUpdatePath = Common.updateURL;
            if (hostUpdatePath.equals("") == true) {
                logger.debug("No application update location specified. Hosts update will not occur.");
            } else {

                hostUpdatePath = StringUtils.removeIgnoreCase(hostUpdatePath, "file:");

                int windowsDriveLetter = hostUpdatePath.indexOf(":");
                if (windowsDriveLetter > 0) {
                    hostUpdatePath = StringUtils.substring(hostUpdatePath, windowsDriveLetter - 1);
                }/*w  w w . j  ava  2 s  .  c  o m*/

                hostUpdatePath = JUtility.formatPath(hostUpdatePath);
                hostUpdatePath = StringUtils.replaceIgnoreCase(hostUpdatePath, "updates.xml", "hosts.xml");
                logger.debug("Using application update url to check for updated hosts.");
            }
        }

        Common.hostUpdatePath = hostUpdatePath;

        // See if updatedHosts location specified
        if (hostUpdatePath.equals("") == false) {
            logger.debug("Updated Host Path = [" + hostUpdatePath + "]");
            if (Files.exists(Paths.get(hostUpdatePath))) {
                logger.debug("Updated Host Path = [" + hostUpdatePath + "] found.");

                Double updatedHostVersion = JXMLHost.checkHostVersion(hostUpdatePath);
                logger.debug("Updated Host File Version = " + String.valueOf(updatedHostVersion));

                if (updatedHostVersion > currentHostVersion) {
                    logger.debug("Copying Updated Host File [" + hostUpdatePath + "]");
                    try {
                        File destDir = new File(System.getProperty("user.dir") + File.separator + "xml"
                                + File.separator + "hosts");
                        File srcFile = new File(hostUpdatePath);
                        FileUtils.copyFileToDirectory(srcFile, destDir);
                        result = true;
                    } catch (Exception e) {
                        logger.debug("Error Copying Updated Host File :" + e.getMessage());
                    }
                } else {
                    logger.debug("Current hosts file is up to date " + currentHostVersion.toString());
                }
            } else {
                logger.debug("Updated Host Path = " + hostUpdatePath + " not found.");
            }
        }
    }

    return result;
}

From source file:com.github.hadoop.maven.plugin.pack.PackMojo.java

/**
 * Create the hadoop deploy artifacts/*from  w w  w. j  a  v  a  2 s.co  m*/
 * 
 * @throws IOException
 * @return File that contains the root of jar file to be packed.
 * @throws InvalidDependencyVersionException
 * @throws ArtifactNotFoundException
 * @throws ArtifactResolutionException
 */
private File createHadoopDeployArtifacts() throws IOException {
    FileUtils.deleteDirectory(outputDirectory);
    final File rootDir = new File(outputDirectory.getAbsolutePath() + File.separator + "root");
    FileUtils.forceMkdir(rootDir);

    final File jarlibdir = new File(rootDir.getAbsolutePath() + File.separator + "lib");
    FileUtils.forceMkdir(jarlibdir);

    final File classesdir = new File(project.getBuild().getDirectory() + File.separator + "classes");
    FileUtils.copyDirectory(classesdir, rootDir);
    final Set<Artifact> filteredArtifacts = this.filterArtifacts(this.artifacts);
    getLog().info("");
    getLog().info("Dependencies of this project independent of hadoop classpath " + filteredArtifacts);
    getLog().info("");
    for (final Artifact artifact : filteredArtifacts) {
        FileUtils.copyFileToDirectory(artifact.getFile(), jarlibdir);
    }
    return rootDir;
}

From source file:com.opoopress.maven.plugins.theme.PackageMojo.java

private File createArchive() throws MojoExecutionException {
    File outputFile = getOutputFile(buildDirectory, finalName, getClassifier());

    File classesDirectory = getClassesDirectory();
    File classesJarFile = getClassesJarFile(buildDirectory, finalName, getClassesClassifier());

    //must copy all dependencies to 'target/plugins' directory
    File targetPluginsDir = new File(buildDirectory, "plugins");

    try {//from w  w  w  .ja va  2 s.c om
        zipArchiver.setDestFile(outputFile);
        zipArchiver.setForced(forceCreation);

        zipArchiver.addDirectory(basedir, getIncludes(), getExcludes());
        //            zipArchiver.addDirectory(basedir, buildIncludes(basedir), null);

        //classes jar
        if (classesDirectory.exists() && classesJarFile.exists()) {
            targetPluginsDir.mkdirs();
            FileUtils.copyFileToDirectory(classesJarFile, targetPluginsDir);
        } else {
            getLog().warn("No theme classes add to theme package.");
        }

        //archive classes jar file and all dependencies
        if (targetPluginsDir.exists() && targetPluginsDir.list().length > 0) {
            zipArchiver.addDirectory(buildDirectory, new String[] { "plugins/**" }, null);
        }

        zipArchiver.createArchive();

    } catch (Exception e) {
        throw new MojoExecutionException("Error assembling OpooPress theme package", e);
    }

    /*
    MavenArchiver archiver = new MavenArchiver();
            
    archiver.setArchiver(jarArchiver);
            
    archiver.setOutputFile(outputFile);
            
    archive.setForced(forceCreation);
    archive.setAddMavenDescriptor(false);
    //        archive.setManifest(null);
            
    try {
    archiver.getArchiver().addDirectory(basedir, getIncludes(), getExcludes());
            
    //classes jar
    if (classesDirectory.exists() && classesJarFile.exists()) {
        targetPluginsDir.mkdirs();
        FileUtils.copyFileToDirectory(classesJarFile, targetPluginsDir);
    } else {
        getLog().warn("No theme classes add to theme package.");
    }
            
    //archive classes jar file and all dependencies
    if (targetPluginsDir.exists() && targetPluginsDir.list().length > 0) {
        archiver.getArchiver().addDirectory(buildDirectory, new String[]{"plugins/**"}, null);
    }
            
    archiver.createArchive(project, archive);
    } catch (Exception e) {
    throw new MojoExecutionException("Error assembling OpooPress theme package", e);
    }*/

    return outputFile;
}

From source file:com.zotoh.maedr.etc.CmdAppOps.java

private String bundleWebApp(String target, String outdir) throws Exception {
    File cfg = new File(getCwd(), CFG);
    JSONObject dev, devs, root;//from w  ww .  ja v  a 2 s .  c o  m
    InputStream inp = null;

    try {
        root = JSONUte.read(inp = readStream(new File(cfg, APPCONF)));
        devs = root.optJSONObject(CFGKEY_DEVICES);
    } finally {
        close(inp);
    }

    String json, xml, proc = "", key, type, jetty = "";
    int cnt = 0;
    for (Iterator<?> it = devs.keys(); it.hasNext();) {
        key = nsb(it.next());
        dev = devs.optJSONObject(key);
        type = dev.optString(CFGKEY_TYPE);
        if (dev.has(DEV_STATUS) && dev.optBoolean(DEV_STATUS) == false) {
            continue;
        }
        if (!"jetty".equals(type)) {
            continue;
        }
        proc = dev.optString("processor");
        jetty = key;
        ++cnt;
    }
    if (cnt > 1) {
        throw new Exception("Too many Jetty device(s)");
    }
    if (cnt == 0) {
        throw new Exception("No Jetty device defined");
    }
    dev = (JSONObject) devs.remove(jetty);
    xml = toWebXML(dev);
    dev = new JSONObject();
    dev.put(CFGKEY_TYPE, DT_WEB_SERVLET);
    dev.put("port", "0");
    dev.put("host", "");
    if (!isEmpty(proc)) {
        dev.put("processor", proc);
    }
    devs.put(WEBSERVLET_DEVID, dev);
    json = JSONUte.asString(root);

    File fo = new File(outdir, "webapps");
    fo.mkdirs();
    File t = new File(fo, TMP);
    t.mkdirs();
    new File(fo, REALM).mkdirs();
    new File(fo, DB).mkdirs();
    File c = new File(fo, CFG);
    c.mkdirs();
    new File(fo, LOGS).mkdirs();

    FileUtils.copyFileToDirectory(new File(cfg, APPPROPS), c);
    writeFile(new File(c, APPCONF), json, "utf-8");
    writeFile(new File(t, "web.xml"), xml, "utf-8");

    return target;
}

From source file:it.drwolf.ridire.utility.CorpusPackager.java

private void processLine(String fileLine) throws IOException {
    this.strTokenizer.setIgnoreEmptyTokens(false);
    this.strTokenizer.reset(fileLine);
    String[] tokens = this.strTokenizer.getTokenArray();
    if (tokens.length == 5) {
        Integer words = Integer.parseInt(tokens[0].trim());
        String jobName = tokens[1].trim();
        FileFilter fileFilter = new RegexFileFilter(jobName.replaceAll("_", "[_ ]"));
        String jobsDir = "/home/drwolf/heritrix-3.1.1-SNAPSHOT/jobs/";
        File[] jobsDirs = new File(jobsDir).listFiles(fileFilter);
        File jobDirFile = null;//from  w  w w .  ja v a2s. com
        if (jobsDirs.length > 0) {
            jobDirFile = jobsDirs[0];
        } else {
            System.out.println(jobName + "\tnot found.");
            return;
        }
        String fileDigest = tokens[2].trim();
        if (words < this.minValue || words >= this.maxValue) {
            System.out.println(jobName + "\t" + fileDigest + "\t skipped: out of range.");
            return;
        }
        String functional = tokens[3].trim();
        String semantic = tokens[4].trim();
        String dirname = functional.trim();
        if (dirname.trim().length() < 1) {
            dirname = semantic.trim();
        }
        if (dirname.trim().length() < 1) {
            dirname = "other";
        }
        File destDir = new File(this.dirName + System.getProperty("file.separator") + dirname);
        File f = new File(jobDirFile.getAbsolutePath() + "/arcs/resources/" + fileDigest + ".txt");
        if (!f.exists() || !f.canRead()) {
            f = new File("/home/drwolf/heritrix-3.1.1-SNAPSHOT/jobs/completed-" + jobName + "/arcs/resources/"
                    + fileDigest + ".txt");
            if (!f.exists() || !f.canRead()) {
                System.out.println(jobName + "\t" + fileDigest + "\tnot found.");
                return;
            }
        }
        FileUtils.copyFileToDirectory(f, destDir);
    }
}

From source file:fm.last.commons.io.LastFileUtilsTest.java

@Test
public void testMoveFileToDirectorySafely() throws IOException {
    // first copy file from data folder to temp folder so it can be moved safely
    File originalFile = dataFolder.getFile("3805bytes.log");
    FileUtils.copyFileToDirectory(originalFile, tempFolder.getRoot());
    File inputFile = new File(tempFolder.getRoot(), originalFile.getName());
    assertTrue(inputFile.getAbsolutePath() + " not found", inputFile.exists());

    // now do the actual moving
    File newDir = tempFolder.newFolder("FileUtilsTest");
    assertTrue(newDir.exists());// w  ww .  j a va  2  s  .  c o  m
    // copy file over to newdir, not creating it if it doesn't exist
    LastFileUtils.moveFileToDirectorySafely(inputFile, newDir, false);
    assertFalse(inputFile.getAbsolutePath() + " exists", inputFile.exists());
    File movedFile = new File(newDir, inputFile.getName());
    assertTrue(movedFile.getAbsolutePath() + " doesn't exist", movedFile.exists());
    assertEquals(FileUtils.readFileToString(originalFile), FileUtils.readFileToString(movedFile));
}

From source file:com.photon.phresco.service.util.DependencyUtils.java

public static void copyFilesTo(File[] files, File destPath) throws IOException {
    if (isDebugEnabled) {
        LOGGER.debug("DependencyUtils.copyFilesTo:Entry");
        LOGGER.info("DependencyUtils.copyFilesTo", "destPath=\"" + destPath + "\"");
    }/*from w ww  . ja va2 s.com*/
    if (files == null || destPath == null) {
        //nothing to copy
        return;
    }
    for (File file : files) {
        if (file.isDirectory()) {
            FileUtils.copyDirectory(file, destPath);
        } else {
            FileUtils.copyFileToDirectory(file, destPath);
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("DependencyUtils.copyFilesTo:Exit");
    }

}