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.jahia.utils.maven.plugin.DeployMojo.java

/**
 * Copy JAR file to jahia webapp, tries to hotswap classes
 * @throws Exception//from  w  w  w.  j a va2  s .c  om
 */
private void deployJarProject() {
    Artifact artifact = project.getArtifact();
    try {
        artifactResolver.resolve(artifact, project.getRemoteArtifactRepositories(), localRepository);
        File libDir = new File(new File(getWebappDeploymentDir(), "WEB-INF"), "lib");
        getLog().info("Deploying jar file " + artifact.getFile().getName() + " to " + libDir);
        File deployedJar = new File(libDir, artifact.getFile().getName());
        boolean needHotSwap = deployedJar.exists();
        FileUtils.copyFileToDirectory(artifact.getFile(), libDir);
        if (needHotSwap) {
            hotSwap(deployedJar);
        }
    } catch (Exception e) {
        getLog().error("Error while deploying JAR project", e);
    }
}

From source file:org.jajuk.util.UpgradeManager.java

/**
 * For Jajuk < 1.9: bootstrap file is now in XML format
 * <br>/*  ww  w  . ja va 2 s . c  o  m*/
 * If it exists and contains data in 1.7 or 1.8 format, it convert it to new XML
 * format (to handle backslashes properly, old format just drop them)
 * <br>
 * This method doesn't yet validate provided workspace paths but only the bootstrap file
 * structure itself.
 */
public static void upgradeBootstrapFile() {
    try {
        String KEY_TEST = "test";
        String KEY_FINAL = "final";
        File bootstrapOld = new File(SessionService.getBootstrapPath(Const.FILE_BOOTSTRAP_OLD));
        File bootstrapOldOldHome = new File(System.getProperty("user.home") + "/" + Const.FILE_BOOTSTRAP_OLD);
        File bootstrapNew = new File(SessionService.getBootstrapPath());
        // Fix for #1473 : move the bootstrap file if required (See #1473)
        if (UtilSystem.isUnderWindows() && !bootstrapOld.equals(bootstrapOldOldHome) && !bootstrapOld.exists()
                && bootstrapOldOldHome.exists()) {
            try {
                FileUtils.copyFileToDirectory(bootstrapOldOldHome, new File(UtilSystem.getUserHome()));
                UtilSystem.deleteFile(bootstrapOldOldHome);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (bootstrapOld.exists() && !bootstrapNew.exists()) {
            Properties prop = null;
            // Try to load a bootstrap file using plain text old format
            prop = new Properties();
            FileInputStream fis = new FileInputStream(
                    SessionService.getBootstrapPath(Const.FILE_BOOTSTRAP_OLD));
            prop.load(fis);
            fis.close();
            // If it exists and contains pre-1.7 bootstrap format (a single line with a raw path),
            // convert it to 1.7 format first
            if (prop.size() == 1) {
                // We get something like <... path ...> = <nothing>
                String path = (String) prop.keys().nextElement();
                // we use this path for both test and final workspace
                prop.clear();
                prop.put(KEY_TEST, path);
                prop.put(KEY_FINAL, path);
            }
            // Make sure to populate both test and final release
            if (!prop.containsKey(KEY_TEST)) {
                prop.put(KEY_TEST, UtilSystem.getUserHome());
            }
            if (!prop.containsKey(KEY_FINAL)) {
                prop.put(KEY_FINAL, UtilSystem.getUserHome());
            }
            // Write down the new bootstrap file
            SessionService.commitBootstrapFile(prop);
            // Delete old bootstrap file
            bootstrapOld.delete();
        }
    } catch (Exception e) {
        // Do not throw any exception from here. display raw stack trace, Logs facilities 
        // are not yet available.
        e.printStackTrace();
    }
}

From source file:org.jajuk.util.UtilSystem.java

/**
 * Copy a file to given directory./*  w  w w .  j a v  a 2 s . c  om*/
 * 
 * @param file : file to copy
 * @param directory : destination directory
 * 
 * @return destination file
 * 
 * @throws JajukException the jajuk exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void copyToDir(final File file, final File directory) throws JajukException, IOException {
    Log.debug("Copying: {{" + file.getAbsolutePath() + "}}  to : " + directory.getAbsolutePath());
    if (!file.exists() || !file.canRead()) {
        throw new JajukException(9, file.getAbsolutePath(), null);
    }
    FileUtils.copyFileToDirectory(file, directory);
}

From source file:org.jasig.resource.aggr.ResourcesAggregatorImplTest.java

@Test
public void testIncludeOverlay() throws Exception {
    String tempPath = getTestOutputRoot() + "/skin-test-incl-overlay";

    File outputDirectory = new File(tempPath);
    outputDirectory.mkdirs();//from  ww  w .ja  v  a 2 s . c o m
    Assert.assertTrue(outputDirectory.exists());

    FileUtils.copyFileToDirectory(new ClassPathResource("skin-test-incl-overlay/overlay/overlay.css").getFile(),
            outputDirectory);
    FileUtils.copyFileToDirectory(new ClassPathResource("skin-test-incl-overlay/overlay/overlay.js").getFile(),
            outputDirectory);

    File skinXml = new ClassPathResource("skin-test-incl-overlay/skin.xml").getFile();
    Assert.assertTrue(skinXml.exists());

    ResourcesAggregatorImpl impl = new ResourcesAggregatorImpl();
    impl.aggregate(new AggregationRequest().setResourcesXml(skinXml).setOutputBaseDirectory(outputDirectory)
            .addAdditionalSourceDirectory(outputDirectory));

    Diff d = new Diff(new FileReader(new ClassPathResource("skin-test-incl-overlay/skin.aggr.xml").getFile()),
            new FileReader(new File(outputDirectory, "skin.aggr.xml")));
    assertTrue(d.toString(), d.similar());
}

From source file:org.jboss.arquillian.android.drone.impl.AndroidDroneArchiveDeployer.java

/**
 * Copies file to directory//  ww  w .  j av a  2 s  . c  o  m
 *
 * @param src source file
 * @param dest destination directory
 */
private void copyFileToDirectory(File src, File dest) {
    try {
        FileUtils.copyFileToDirectory(src, dest);
    } catch (IOException ex) {
        throw new RuntimeException("Unable to copy " + src.getAbsolutePath() + " to " + dest.getAbsolutePath());
    }
}

From source file:org.jboss.loom.actions.ModuleCreationAction.java

@Override
public void perform() throws MigrationException {
    // Create a module.
    try {//from www.j av  a2  s. co m
        // Copy jar file
        File dir = getModuleDir();
        FileUtils.copyFileToDirectory(this.jarFile, dir);
        //File dest = new File(dir, this.jarFile.getName());
        //FileUtils.copyFile( jarFile, dest );

        // XML doc
        File moduleXmlFile = new File(dir, MODULE_XML_FNAME);
        if (moduleXmlFile.exists() && this.ifExists != Configuration.IfExists.OVERWRITE)
            throw new ActionException(this, MODULE_XML_FNAME + " already exists: " + moduleXmlFile.getPath());

        //Document doc = AS7ModuleUtils.createModuleXML( moduleName, jarFile.getName(), deps );
        //XmlUtils.transformDocToFile( doc, moduleXmlFile );
        AS7ModuleUtils.createModuleXML_FreeMarker(new ModuleXmlInfo(moduleName, jarFile.getName(), deps),
                moduleXmlFile);

        // Backup
        this.moduleDir = dir;
    } catch (IOException ex) {
        throw new ActionException(this, "Copying failed: " + ex.getMessage(), ex);
    } catch (Exception ex) {
        throw new ActionException(this, "Creation of " + MODULE_XML_FNAME + " failed: " + ex.getMessage(), ex);
    }

    setState(State.DONE);
}

From source file:org.jboss.tools.aerogear.hybrid.ui.wizard.export.NativeBinaryExportOperation.java

@Override
protected void execute(IProgressMonitor monitor)
        throws CoreException, InvocationTargetException, InterruptedException {
    monitor.beginTask("Build native binaries", delegates.size() * 2);
    for (AbstractNativeBinaryBuildDelegate delegate : delegates) {
        if (monitor.isCanceled()) {
            break;
        }/*from   w  w  w. ja v  a2  s . c om*/
        SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
        subMonitor.setTaskName("Building " + delegate.getProject().getName());
        delegate.setRelease(true);
        delegate.buildNow(subMonitor);
        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);
            }
            monitor.worked(1);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    monitor.done();

}

From source file:org.jboss.tools.foundation.core.properties.internal.VersionProviderTest.java

@Test
public void testLoadCachedProperties() throws Exception {

    File buildDir = new File("bin");
    if (!buildDir.exists() || !buildDir.isDirectory()) {
        buildDir = new File("target");
    }/*  w  ww .j a  v  a2 s.  co  m*/

    File targetDir = new File(buildDir, "remotelocation");
    FileUtils.deleteDirectory(targetDir);
    targetDir.mkdirs();

    FileUtils.copyFileToDirectory(new File("data/jbosstools-versions.properties"), targetDir);
    File remoteFile = new File(targetDir, "jbosstools-versions.properties");
    assertTrue(remoteFile.exists());

    URI propertiesURI = remoteFile.toURI();
    Properties props = VersionPropertiesProvider.loadProperties(propertiesURI, monitor);
    assertNotNull(props);
    assertTrue(props.size() > 0);

    remoteFile.delete();
    assertFalse(remoteFile.exists());

    Properties cache = VersionPropertiesProvider.loadProperties(propertiesURI, monitor);
    assertNotNull(cache);
    assertEquals(props, cache);

}

From source file:org.jboss.tools.tycho.sitegenerator.GenerateDirectoryXmlMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (!PackagingType.TYPE_ECLIPSE_REPOSITORY.equals(this.project.getPackaging())) {
        return;/*from  ww  w.ja va 2 s  . co  m*/
    }
    if (!this.outputDirectory.exists()) {
        this.outputDirectory.mkdirs();
    }
    File repositoryPluginsFolder = new File(project.getBuild().getDirectory(), "repository/plugins");
    File discoveryPluginsFolder = new File(this.outputDirectory, "plugins");
    StringBuilder directoryXml = new StringBuilder();
    directoryXml.append("<?xml version='1.0' encoding='UTF-8'?>\n");
    directoryXml.append("<directory xmlns='http://www.eclipse.org/mylyn/discovery/directory/'>\n");
    for (File plugin : repositoryPluginsFolder.listFiles()) {
        directoryXml.append("  <entry url='plugins/");
        directoryXml.append(plugin.getName());
        directoryXml.append("' permitCategories='true'/>");
        directoryXml.append('\n');
        try {
            FileUtils.copyFileToDirectory(plugin, discoveryPluginsFolder);
        } catch (Exception ex) {
            throw new MojoFailureException(ex.getMessage(), ex);
        }
    }
    directoryXml.append("</directory>");

    if (this.discoveryFileName == null) {
        this.discoveryFileName = this.project.getArtifactId() + ".xml";
    }
    try {
        FileUtils.writeStringToFile(new File(this.outputDirectory, this.discoveryFileName),
                directoryXml.toString());
    } catch (Exception ex) {
        throw new MojoFailureException(ex.getMessage(), ex);
    }
}

From source file:org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScriptTest.java

@Test
public void testUpdatedClasspath() throws Exception {
    r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
    GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy();
    gmas.add(Jenkins.READ, "devel");
    for (Permission p : Item.PERMISSIONS.getPermissions()) {
        gmas.add(p, "devel");
    }//  w  w w  .j av a  2  s  .  c  o  m
    r.jenkins.setAuthorizationStrategy(gmas);

    // Copy jar files to temporary directory, then overwrite them with updated jar files.
    File tmpDir = tmpFolderRule.newFolder();

    for (File jarfile : getAllJarFiles()) {
        FileUtils.copyFileToDirectory(jarfile, tmpDir);
    }

    List<ClasspathEntry> classpath = new ArrayList<ClasspathEntry>();
    for (File jarfile : tmpDir.listFiles()) {
        classpath.add(new ClasspathEntry(jarfile.getAbsolutePath()));
    }

    String SCRIPT_TO_RUN = "\"Script is run\";";

    // approve script
    {
        FreeStyleProject p = r.createFreeStyleProject();
        p.getPublishersList().add(new TestGroovyRecorder(new SecureGroovyScript(SCRIPT_TO_RUN, false)));

        Set<ScriptApproval.PendingScript> pss = ScriptApproval.get().getPendingScripts();
        assertNotEquals(0, pss.size());
        for (ScriptApproval.PendingScript ps : pss) {
            ScriptApproval.get().approveScript(ps.getHash());
        }
    }

    // Success without classpaths
    {
        FreeStyleProject p = r.createFreeStyleProject();
        p.getPublishersList().add(new TestGroovyRecorder(new SecureGroovyScript(SCRIPT_TO_RUN, false)));

        r.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
    }

    FreeStyleProject p = r.createFreeStyleProject();
    p.getPublishersList().add(new TestGroovyRecorder(new SecureGroovyScript(SCRIPT_TO_RUN, false, classpath)));

    // Fail as the classpath is not approved.
    r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());

    // Approve classpath.
    {
        List<ScriptApproval.PendingClasspathEntry> pcps = ScriptApproval.get().getPendingClasspathEntries();
        assertNotEquals(0, pcps.size());
        for (ScriptApproval.PendingClasspathEntry pcp : pcps) {
            ScriptApproval.get().approveClasspathEntry(pcp.getHash());
        }
    }

    // Success as approved.
    r.assertBuildStatusSuccess(p.scheduleBuild2(0));

    // overwrite jar files.
    for (File jarfile : getAllUpdatedJarFiles()) {
        FileUtils.copyFileToDirectory(jarfile, tmpDir);
    }

    // Fail as the updated jar files are not approved.
    r.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());

    // Approve classpath.
    {
        List<ScriptApproval.PendingClasspathEntry> pcps = ScriptApproval.get().getPendingClasspathEntries();
        assertNotEquals(0, pcps.size());
        for (ScriptApproval.PendingClasspathEntry pcp : pcps) {
            ScriptApproval.get().approveClasspathEntry(pcp.getHash());
        }
    }

    // Success as approved.
    r.assertBuildStatusSuccess(p.scheduleBuild2(0));
}