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.domainmath.gui.update.UpdateFrame.java

/**
 * Move files to src dir.//  w ww  .ja v  a  2  s. c o m
 * @param file_list
 * @param srcDir 
 */
private void moveFile(File[] file_list, File srcDir) {
    for (File file : file_list) {

        // copy folders.
        if (file.isDirectory()) {
            try {
                FileUtils.copyDirectoryToDirectory(file, srcDir);
                FileUtils.deleteDirectory(file);
            } catch (IOException ex) {

            }
        } else if (file.isFile()) {
            try {
                FileUtils.copyFileToDirectory(file, srcDir);
                FileUtils.forceDelete(file);
            } catch (IOException ex) {

            }
        }
    }
}

From source file:org.dspace.app.itemimport.ItemImportServiceImpl.java

/**
 * /*w w w . j a va 2s . c  om*/
 * Given a local file or public URL to a zip file that has the Simple Archive Format, this method imports the contents to DSpace
 * @param filepath The filepath to local file or the public URL of the zip file
 * @param owningCollection The owning collection the items will belong to
 * @param otherCollections The collections the created items will be inserted to, apart from the owning one
 * @param resumeDir In case of a resume request, the directory that containsthe old mapfile and data 
 * @param inputType The input type of the data (bibtex, csv, etc.), in case of local file
 * @param context The context
 * @param template whether to use template item
 * @throws Exception if error
 */
@Override
public void processUIImport(String filepath, Collection owningCollection, String[] otherCollections,
        String resumeDir, String inputType, Context context, final boolean template) throws Exception {
    final EPerson oldEPerson = context.getCurrentUser();
    final String[] theOtherCollections = otherCollections;
    final Collection theOwningCollection = owningCollection;
    final String theFilePath = filepath;
    final String theInputType = inputType;
    final String theResumeDir = resumeDir;
    final boolean useTemplateItem = template;

    Thread go = new Thread() {
        @Override
        public void run() {
            Context context = null;

            String importDir = null;
            EPerson eperson = null;

            try {

                // create a new dspace context
                context = new Context();
                eperson = ePersonService.find(context, oldEPerson.getID());
                context.setCurrentUser(eperson);
                context.turnOffAuthorisationSystem();

                boolean isResume = theResumeDir != null;

                List<Collection> collectionList = new ArrayList<>();
                if (theOtherCollections != null) {
                    for (String colID : theOtherCollections) {
                        UUID colId = UUID.fromString(colID);
                        if (!theOwningCollection.getID().equals(colId)) {
                            Collection col = collectionService.find(context, colId);
                            if (col != null) {
                                collectionList.add(col);
                            }
                        }
                    }
                }

                importDir = ConfigurationManager.getProperty("org.dspace.app.batchitemimport.work.dir")
                        + File.separator + "batchuploads" + File.separator + context.getCurrentUser().getID()
                        + File.separator
                        + (isResume ? theResumeDir : (new GregorianCalendar()).getTimeInMillis());
                File importDirFile = new File(importDir);
                if (!importDirFile.exists()) {
                    boolean success = importDirFile.mkdirs();
                    if (!success) {
                        log.info("Cannot create batch import directory!");
                        throw new Exception("Cannot create batch import directory!");
                    }
                }

                String dataPath = null;
                String dataDir = null;

                if (theInputType.equals("saf")) { //In case of Simple Archive Format import (from remote url)
                    dataPath = importDirFile + File.separator + "data.zip";
                    dataDir = importDirFile + File.separator + "data_unzipped2" + File.separator;
                } else if (theInputType.equals("safupload")) { //In case of Simple Archive Format import (from upload file)
                    FileUtils.copyFileToDirectory(new File(theFilePath), importDirFile);
                    dataPath = importDirFile + File.separator + (new File(theFilePath)).getName();
                    dataDir = importDirFile + File.separator + "data_unzipped2" + File.separator;
                } else { // For all other imports
                    dataPath = importDirFile + File.separator + (new File(theFilePath)).getName();
                    dataDir = importDirFile + File.separator + "data" + File.separator;
                }

                //Clear these files, if a resume
                if (isResume) {
                    if (!theInputType.equals("safupload")) {
                        (new File(dataPath)).delete();
                    }
                    (new File(importDirFile + File.separator + "error.txt")).delete();
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    FileDeleteStrategy.FORCE.delete(
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                }

                //In case of Simple Archive Format import we need an extra effort to download the zip file and unzip it
                String sourcePath = null;
                if (theInputType.equals("saf")) {
                    OutputStream os = new FileOutputStream(dataPath);

                    byte[] b = new byte[2048];
                    int length;

                    InputStream is = new URL(theFilePath).openStream();
                    while ((length = is.read(b)) != -1) {
                        os.write(b, 0, length);
                    }

                    is.close();
                    os.close();

                    sourcePath = unzip(new File(dataPath), dataDir);

                    //Move files to the required folder
                    FileUtils.moveDirectory(new File(sourcePath),
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    dataDir = importDirFile + File.separator + "data_unzipped" + File.separator;
                } else if (theInputType.equals("safupload")) {
                    sourcePath = unzip(new File(dataPath), dataDir);
                    //Move files to the required folder
                    FileUtils.moveDirectory(new File(sourcePath),
                            new File(importDirFile + File.separator + "data_unzipped" + File.separator));
                    FileDeleteStrategy.FORCE.delete(new File(dataDir));
                    dataDir = importDirFile + File.separator + "data_unzipped" + File.separator;
                }

                //Create mapfile path
                String mapFilePath = importDirFile + File.separator + "mapfile";

                List<Collection> finalCollections = null;
                if (theOwningCollection != null) {
                    finalCollections = new ArrayList<>();
                    finalCollections.add(theOwningCollection);
                    finalCollections.addAll(collectionList);
                }

                setResume(isResume);

                if (theInputType.equals("saf") || theInputType.equals("safupload")) { //In case of Simple Archive Format import
                    addItems(context, finalCollections, dataDir, mapFilePath, template);
                } else { // For all other imports (via BTE)
                    addBTEItems(context, finalCollections, theFilePath, mapFilePath, useTemplateItem,
                            theInputType, dataDir);
                }

                // email message letting user know the file is ready for
                // download
                emailSuccessMessage(context, eperson, mapFilePath);

                context.complete();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                String exceptionString = ExceptionUtils.getStackTrace(e);

                try {
                    File importDirFile = new File(importDir + File.separator + "error.txt");
                    PrintWriter errorWriter = new PrintWriter(importDirFile);
                    errorWriter.print(exceptionString);
                    errorWriter.close();

                    emailErrorMessage(eperson, exceptionString);
                    throw new Exception(e.getMessage());
                } catch (Exception e2) {
                    // wont throw here
                }
            }

            finally {
                // Make sure the database connection gets closed in all conditions.
                try {
                    context.complete();
                } catch (SQLException sqle) {
                    context.abort();
                }
            }
        }

    };

    go.isDaemon();
    go.start();

}

From source file:org.duracloud.common.util.IOUtil.java

public static void copyFileToDirectory(File file, File dir) {
    try {//from www  .  j  av a2s.  c o m
        FileUtils.copyFileToDirectory(file, dir);
    } catch (IOException e) {
        throw new DuraCloudRuntimeException(e);
    }
}

From source file:org.ebayopensource.turmeric.eclipse.test.util.FunctionalTestHelper.java

@SuppressWarnings("unchecked")
public static void copyServiceConsumerFile(String consumerPrjName, String serviceName, String srcFolder)
        throws Exception {

    // final String baseConsumerFilename = "Base"
    // + StringUtils.capitalize(serviceName) + "Consumer.java";

    final String copyConsDir = WsdlUtilTest.getPluginOSPath(SoaTestConstants.PLUGIN_ID,
            "test-data/" + srcFolder);
    Assert.assertNotNull(copyConsDir);/*  w  w w . j  ava  2  s  . c  om*/

    final String srcConsumerFile = copyConsDir.concat("/" + "Consumer.java");

    System.out.println("The srcConsumerFile that is being copied is " + srcConsumerFile);
    IProject consPrj = WorkspaceUtil.getProject(consumerPrjName);

    /*
     * NameFileFilter fileFilter = new NameFileFilter(baseConsumerFilename);
     * 
     * Collection<File> files = FileUtils.listFiles(consPrj.getLocation()
     * .toFile(), fileFilter, TrueFileFilter.INSTANCE);
     * 
     * Assert.assertNotNull(files); Assert.assertTrue(files.size() > 0);
     * 
     * File curBaseConsFile = null; for (Iterator iterator =
     * files.iterator(); iterator.hasNext();) { File file = (File)
     * iterator.next(); if (file.getAbsolutePath().indexOf("src") > 0 ) {
     * curBaseConsFile = file; }
     * System.out.println("The file in collection is " +
     * file.getAbsolutePath()); }
     * 
     * // File curBaseConsFile = files.iterator().next();
     * 
     * IPath baseConsDir = new Path(curBaseConsFile.getAbsolutePath())
     * .removeLastSegments(1);
     * 
     * System.out.println("The directory that consumer file is copied into is "
     * + baseConsDir.toOSString()); try { FileUtils.copyFileToDirectory(new
     * File(srcConsumerFile), baseConsDir.toFile(), false); } catch
     * (IOException e) { e.printStackTrace();
     * Assert.fail("Copying Consumer file to the Base Consumer Dir failed" +
     * baseConsDir.toOSString()); }
     * 
     * WorkspaceUtil.refresh(consPrj);
     * consPrj.build(IncrementalProjectBuilder.INCREMENTAL_BUILD,
     * ProgressUtil .getDefaultMonitor(null));
     */
    IPath srcDir = new Path(consPrj.getLocation().toString().concat("/" + "src"));
    try {
        FileUtils.copyFileToDirectory(new File(srcConsumerFile), srcDir.toFile());
    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail("Copying Consumer file to the Src Dir failed" + srcDir.toOSString());
    }
    WorkspaceUtil.refresh(consPrj);
    consPrj.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, ProgressUtil.getDefaultMonitor(null));
}

From source file:org.ebayopensource.turmeric.frameworkjars.ui.CopyLibraryDialog.java

@Override
protected void okPressed() {
    if (metadata == null)
        return;/*w  ww  .  jav a2 s .  co m*/
    final String destination = this.destinationText.getText();
    final IRunnableWithProgress runnable = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            monitor.beginTask("Copying jars for library ->" + metadata + "...", IProgressMonitor.UNKNOWN);
            try {
                monitor.internalWorked(20);
                IMavenEclipseApi api = MavenApiPlugin.getDefault().getMavenEclipseApi();

                File destDir = new File(destination);
                if (destDir.exists() == false)
                    destDir.mkdir();
                else {
                    try {
                        FileUtils.cleanDirectory(destDir);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                monitor.internalWorked(20);
                try {
                    for (Artifact artifact : api.resolveArtifactAsClasspath(metadata)) {
                        File artifactFile = artifact.getFile();
                        if (artifactFile.getName().endsWith(".pom")) {
                            System.out.println("bad");
                        }
                        monitor.setTaskName("Copying from " + artifactFile + " to " + destDir);
                        FileUtils.copyFileToDirectory(artifact.getFile(), destDir);
                        monitor.internalWorked(20);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                throw new InvocationTargetException(e);
            } finally {
                monitor.done();
            }
        }
    };

    final IProgressService service = PlatformUI.getWorkbench().getProgressService();
    try {
        service.run(false, false, runnable);
    } catch (Exception e) {
        ErrorDialog.openError(getShell(), "Error Occurred", "error occurred while copying library->" + metadata,
                new Status(IStatus.ERROR, "org.ebayopensource.turmeric", e.getLocalizedMessage(), e));
        e.printStackTrace();
    }

    super.okPressed();
}

From source file:org.eclipse.jdt.ls.core.internal.managers.AbstractInvisibleProjectBasedTest.java

protected void addLibs(java.nio.file.Path projectPath) throws Exception {
    java.nio.file.Path libPath = Files
            .createDirectories(projectPath.resolve(InvisibleProjectBuildSupport.LIB_FOLDER));
    File libFile = libPath.toFile();
    FileUtils.copyFileToDirectory(new File(getSourceProjectDirectory(), "eclipse/source-attachment/foo.jar"),
            libFile);//from w w w.  j av a2s . co  m
    FileUtils.copyFileToDirectory(
            new File(getSourceProjectDirectory(), "eclipse/source-attachment/foo-sources.jar"), libFile);
}

From source file:org.eclipse.jdt.ls.core.internal.managers.EclipseBuildSupportTest.java

@Test
public void testUpdateJar() throws Exception {
    importProjects("eclipse/updatejar");
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("updatejar");
    assertIsJavaProject(project);/*from   ww w . ja v  a 2s .com*/
    List<IMarker> errors = ResourceUtils.getErrorMarkers(project);
    assertEquals("Unexpected errors " + ResourceUtils.toString(errors), 2, errors.size());
    File projectFile = project.getLocation().toFile();
    File validFooJar = new File(projectFile, "foo.jar");
    File destLib = new File(projectFile, "lib");
    FileUtils.copyFileToDirectory(validFooJar, destLib);
    File newJar = new File(destLib, "foo.jar");
    projectsManager.fileChanged(newJar.toPath().toUri().toString(), CHANGE_TYPE.CREATED);
    waitForBackgroundJobs();
    errors = ResourceUtils.getErrorMarkers(project);
    assertEquals("Unexpected errors " + ResourceUtils.toString(errors), 0, errors.size());

}

From source file:org.eclipse.thym.core.plugin.actions.CopyFileAction.java

@Override
public void install() throws CoreException {
    try {//from  w ww. j a v  a2s .  c o  m
        if (source.isDirectory()) {
            FileUtils.copyDirectory(source, target);
        }
        //source is a file
        else if (target.exists()) {
            if (target.isDirectory()) {
                FileUtils.copyFileToDirectory(source, target);
            } else {
                FileUtils.copyFile(source, target);
            }
        } else if (FilenameUtils.getExtension(target.toString()).isEmpty()) {// it is likely a directory
            FileUtils.copyFileToDirectory(source, target);
        } else {
            FileUtils.copyFile(source, target);
        }

    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                "Error copying " + source + " to " + target, e));
    }
}

From source file:org.eclipse.thym.ui.wizard.export.NativeBinaryExportOperation.java

@Override
protected void execute(IProgressMonitor monitor)
        throws CoreException, InvocationTargetException, InterruptedException {
    SubMonitor sm = SubMonitor.convert(monitor);
    sm.setWorkRemaining(delegates.size() * 10);
    for (AbstractNativeBinaryBuildDelegate delegate : delegates) {
        if (monitor.isCanceled()) {
            break;
        }/*from  w  w w  . ja v  a2 s. c  om*/
        delegate.setRelease(true);
        delegate.buildNow(sm.newChild(10));
        try {
            File buildArtifact = delegate.getBuildArtifact();
            File destinationFile = new File(destinationDir, buildArtifact.getName());
            if (destinationFile.exists()) {
                String callback = overwriteQuery.queryOverwrite(destinationFile.toString());
                if (IOverwriteQuery.NO.equals(callback)) {
                    continue;
                }
                if (IOverwriteQuery.CANCEL.equals(callback)) {
                    break;
                }
            }
            File artifact = delegate.getBuildArtifact();
            if (artifact.isDirectory()) {
                FileUtils.copyDirectoryToDirectory(artifact, destinationDir);
            } else {
                FileUtils.copyFileToDirectory(artifact, destinationDir);
            }
            sm.done();
        } catch (IOException e) {
            HybridCore.log(IStatus.ERROR, "Error on NativeBinaryExportOperation", e);
        }
    }
    monitor.done();
}

From source file:org.eurocarbdb.action.hplc.digestUpload.java

public String execute() throws Exception {

    if (submitAction.equals("Upload") && digest_id > 0) {

        File tar = new File("/tmp/digest" + profile_id + digest_id + ".txt");

        FileUtils.copyFileToDirectory(file, targetDir);
        FileUtils.copyFile(file, tar);//  ww w.ja v  a2  s  .c o  m

        //File tarx = new File ("/tmp/digested" + digest_id + ".txt");
        //File tarx = new File ("/tmp/digested" + profile_id + digest_id + ".txt");
        //FileUtils.copyFile(tar, tarx); 

        /*        boolean success = (new File("/tmp/digest_file.txt")).delete();
                if (!success) {
                // Deletion failed
                }
        */

        return SUCCESS;
    }

    else {
        return INPUT;
    }

}