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

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

Introduction

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

Prototype

public static void copyFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Copies a file to a new location preserving the file date.

Usage

From source file:io.wcm.devops.conga.plugins.aem.postprocessor.ContentPackageOsgiConfigPostProcessorTest.java

@Test
public void testPostProcess() throws Exception {
    // prepare provisioning file
    File target = new File("target/" + ContentPackageOsgiConfigPostProcessor.NAME + "-test");
    if (target.exists()) {
        FileUtils.deleteDirectory(target);
    }//  w w w.ja v a2  s.com
    File contentPackageFile = new File(target, "test.txt");
    FileUtils.copyFile(new File(getClass().getResource("/provisioning/provisioning.txt").toURI()),
            contentPackageFile);

    // post-process
    FileContext fileContext = new FileContext().file(contentPackageFile).charset(StandardCharsets.UTF_8);
    PluginContextOptions pluginContextOptions = new PluginContextOptions()
            .pluginManager(new PluginManagerImpl())
            .logger(LoggerFactory.getLogger(ProvisioningOsgiConfigPostProcessor.class));
    PostProcessorContext context = new PostProcessorContext().pluginContextOptions(pluginContextOptions)
            .options(PACKAGE_OPTIONS);

    assertTrue(underTest.accepts(fileContext, context));
    underTest.apply(fileContext, context);

    // validate
    assertFalse(contentPackageFile.exists());

    File zipFile = new File(target, "test.zip");
    assertTrue(zipFile.exists());

    try (InputStream is = new ByteArrayInputStream(
            getDataFromZip(zipFile, "jcr_root/apps/test/config/my.pid.config"))) {

        // check for initial comment line
        is.mark(256);
        final int firstChar = is.read();
        if (firstChar == '#') {
            int b;
            while ((b = is.read()) != '\n') {
                if (b == -1) {
                    throw new IOException("Unable to read configuration.");
                }
            }
        } else {
            is.reset();
        }

        Dictionary<?, ?> config = ConfigurationHandler.read(is);
        assertEquals("value1", config.get("stringProperty"));
        assertArrayEquals(new String[] { "v1", "v2", "v3" }, (String[]) config.get("stringArrayProperty"));
        assertEquals(true, config.get("booleanProperty"));
        assertEquals(999999999999L, config.get("longProperty"));
    }

    assertTrue(ZipUtil.containsEntry(zipFile, "jcr_root/apps/test/config/my.factory-my.pid.config"));
    assertTrue(ZipUtil.containsEntry(zipFile, "jcr_root/apps/test/config.mode1/my.factory-my.pid2.config"));
    assertTrue(ZipUtil.containsEntry(zipFile, "jcr_root/apps/test/config.mode2/my.pid2.config"));

    Document filterXml = getXmlFromZip(zipFile, "META-INF/vault/filter.xml");
    assertXpathEvaluatesTo("/apps/test/config", "/workspaceFilter/filter[1]/@root", filterXml);

    Document propsXml = getXmlFromZip(zipFile, "META-INF/vault/properties.xml");
    assertXpathEvaluatesTo("myGroup", "/properties/entry[@key='group']", propsXml);
    assertXpathEvaluatesTo("myName", "/properties/entry[@key='name']", propsXml);
    assertXpathEvaluatesTo("myDesc\n---\nSample comment in provisioning.txt",
            "/properties/entry[@key='description']", propsXml);
    assertXpathEvaluatesTo("1.5", "/properties/entry[@key='version']", propsXml);
}

From source file:com.orange.ocara.model.export.docx.DocxWriter.java

/**
 * To zip a directory.// w w  w  .  j av a 2 s.c om
 *
 * @param rootPath  root path
 * @param directory directory
 * @param zos       ZipOutputStream
 * @throws IOException
 */
private void zipDirectory(String rootPath, File directory, ZipOutputStream zos) throws IOException {
    //get a listing of the directory content
    File[] files = directory.listFiles();

    //loop through dirList, and zip the files
    for (File file : files) {
        if (file.isDirectory()) {
            zipDirectory(rootPath, file, zos);
            continue;
        }

        String filePath = FilenameUtils.normalize(file.getPath(), true);
        String fileName = StringUtils.difference(rootPath, filePath);

        fileName = fileName.replaceAll("\\[_\\]", "_").replaceAll("\\[.\\]", ".");

        //create a FileInputStream on top of file
        ZipEntry anEntry = new ZipEntry(fileName);
        zos.putNextEntry(anEntry);

        FileUtils.copyFile(file, zos);
    }
}

From source file:de.uni_hildesheim.sse.ant.versionReplacement.BinaryVersionTask.java

@Override
public void execute() throws BuildException {
    if (null == version || version.isEmpty()) {
        throw new BuildException("No version specified.");
    }// w  ww.  j  ava 2  s .com
    if (null == sourceFolder) {
        throw new BuildException("No source folder specified.");
    }
    if (!sourceFolder.exists()) {
        sourceFolder.mkdirs();
    }
    if (!sourceFolder.isDirectory()) {
        throw new BuildException("Source folder not is a directory.");
    }
    if (null == destinationFolder) {
        throw new BuildException("No destination folder specified.");
    }
    if (!destinationFolder.exists()) {
        destinationFolder.mkdirs();
    }
    if (!destinationFolder.isDirectory()) {
        throw new BuildException("Destination folder not is a directory.");
    }

    File[] files = sourceFolder.listFiles();
    for (File f : files) {
        String name = f.getName();
        boolean rename = true;
        if (null != prefix && prefix.length() > 0) {
            rename = name.startsWith(prefix);
        }
        if (rename) {
            int pos = name.lastIndexOf('_');
            name = name.substring(0, pos + 1) + version;
        }
        try {
            File target = new File(destinationFolder, name);
            FileUtils.copyFile(f, target);
            log("Copied to " + target);
        } catch (IOException e) {
            throw new BuildException(e);
        }

    }
}

From source file:com.microsoft.applicationinsights.agent.internal.config.XmlAgentConfigurationBuilderTest.java

private AgentConfiguration testConfiguration(String testFileName) throws IOException {
    File folder = null;//from  www .  j av a 2s  . co  m
    try {
        folder = createFolder();
        ClassLoader classLoader = getClass().getClassLoader();
        URL testFileUrl = classLoader.getResource(testFileName);
        File sourceFile = new File(testFileUrl.toURI());
        File destinationFile = new File(folder, TEMP_CONF_FILE);
        FileUtils.copyFile(sourceFile, destinationFile);
        return new XmlAgentConfigurationBuilder().parseConfigurationFile(folder.toString());
    } catch (java.net.URISyntaxException e) {
        return null;
    } finally {
        cleanFolder(folder);
    }
}

From source file:eu.cloud4soa.soa.git.GitProxyTest.java

@Before
public void before() throws Exception {

    MockitoAnnotations.initMocks(this);

    if (originalAuthFile == null)
        originalAuthFile = gitservices.AUTHORIZED_KEYS_FILE;
    if (originalGitFile == null)
        originalGitFile = gitservices.PROXY_GIT_FILE;

    this.authTempFile = File.createTempFile("authorizedKeys", ".txt");
    FileUtils.copyFile(new File(originalAuthFile), this.authTempFile);
    gitservices.AUTHORIZED_KEYS_FILE = this.authTempFile.getAbsolutePath();

    this.gitTempFile = File.createTempFile("git", ".txt");
    FileUtils.copyFile(new File(originalGitFile), this.gitTempFile);
    gitservices.PROXY_GIT_FILE = this.gitTempFile.getAbsolutePath();

}

From source file:com.gs.obevo.db.scenariotests.OnboardingDeployTest.java

@Test
public void onboardingTest() throws Exception {
    final File srcDir = new File("./src/test/resources/scenariotests/onboardingDeploy");
    final File destDir = new File("./target/scenariotests/onboardingDeploy");
    FileUtils.deleteQuietly(destDir);/*  w  ww. ja  v a 2 s . co  m*/

    FileUtils.copyDirectory(srcDir, destDir);

    LOG.info("Part 1 - do the deployment w/ onboarding mode");
    DbDeployerAppContext deployContext = DbEnvironmentFactory.getInstance()
            .readOneFromSourcePath(destDir.getAbsolutePath(), "test").buildAppContext();

    try {
        deployContext.setupEnvInfra().cleanEnvironment().deploy(new MainDeployerArgs().onboardingMode(true));
    } catch (RuntimeException exc) {
        exc.printStackTrace();
        // ignoring
    }

    // Verify that the exception files have been created properly
    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_A.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_B.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_C.ddl").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_WITH_ERROR.ddl").exists());
    assertTrue(new File(destDir, "SCHEMA1/view/exceptions/VIEW_WITH_ERROR.sql").exists());
    assertTrue(new File(destDir, "SCHEMA1/view/dependentOnExceptions/VIEW_DEPENDING_ON_BAD_VIEW.sql").exists());

    LOG.info("Part 2 - rerun the deploy and ensure the data remains as is");
    deployContext = DbEnvironmentFactory.getInstance().readOneFromSourcePath(destDir.getAbsolutePath(), "test")
            .buildAppContext();

    try {
        deployContext.deploy(new MainDeployerArgs().onboardingMode(true));
    } catch (RuntimeException exc) {
        exc.printStackTrace();
        // ignoring
    }

    // Same assertions as before should hold
    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_A.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_B.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_C.ddl").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_WITH_ERROR.ddl").exists());
    assertTrue(new File(destDir, "SCHEMA1/view/exceptions/VIEW_WITH_ERROR.sql").exists());
    assertTrue(new File(destDir, "SCHEMA1/view/dependentOnExceptions/VIEW_DEPENDING_ON_BAD_VIEW.sql").exists());

    LOG.info("Part 3 - fix the view and verify that it is moved back to the regular folder");
    FileUtils.copyFile(new File(srcDir, "VIEW_WITH_ERROR.corrected.sql"),
            new File(destDir, "SCHEMA1/view/exceptions/VIEW_WITH_ERROR.sql"));

    deployContext = DbEnvironmentFactory.getInstance().readOneFromSourcePath(destDir.getAbsolutePath(), "test")
            .buildAppContext();

    try {
        deployContext.deploy(new MainDeployerArgs().onboardingMode(true));
    } catch (RuntimeException exc) {
        exc.printStackTrace();
        // ignoring
    }

    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_A.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/staticdata/exceptions/TABLE_B.csv").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_C.ddl").exists());
    assertTrue(new File(destDir, "SCHEMA1/table/exceptions/TABLE_WITH_ERROR.ddl").exists());
    // These two have changed from above
    assertTrue(new File(destDir, "SCHEMA1/view/VIEW_WITH_ERROR.sql").exists());
    assertTrue(new File(destDir, "SCHEMA1/view/VIEW_DEPENDING_ON_BAD_VIEW.sql").exists());
}

From source file:edu.kit.dama.util.release.GenerateSourceRelease.java

public static void copySources(File source, File destination, final ReleaseConfiguration config)
        throws IOException {
    for (String folder : config.getInputDirectories()) {
        File input = new File(source, folder);
        if (!input.exists()) {
            //warn
            continue;
        }/*from   ww  w  .ja v  a  2  s  .  c o m*/
        new File(destination, folder).mkdirs();
        FileUtils.copyDirectory(input, new File(destination, folder), new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                //check folders to ignore
                for (String folder : config.getDirectoriesToIgnore()) {
                    if (pathname.isDirectory() && folder.equals(pathname.getName())) {
                        return false;
                    }
                }

                //check files to ignore
                for (String file : config.getFilesToIgnore()) {
                    if (pathname.isFile() && new WildcardFileFilter(file).accept(pathname)) {
                        return false;
                    }
                }

                return true;
            }
        });
    }

    for (String file : config.getFilesToRemove()) {
        FileUtils.deleteQuietly(new File(destination, file));
    }

    for (String file : config.getInputFiles()) {
        File input = new File(source, file);
        if (input.exists()) {
            FileUtils.copyFile(new File(source, file), new File(destination, file));
        } else {
            //warn
        }
    }
}

From source file:ch.tatool.app.export.FileDataExporter.java

/**
 * Exports the module data to a file//from w w  w. jav  a 2 s.c  om
 */
public String exportData(Component parentFrame, Module module, int fromSessionIndex,
        DataExporterError exporterError) {

    String filename = "";

    // get path
    String path = getPath();

    if (path == null) {
        // ask the user where he wants to export the data to
        filename = getStorageDirectory(parentFrame);
    } else {
        Date d = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
        String account = removeSpecialCharacters(module.getUserAccount().getName());
        String moduleName = removeSpecialCharacters(module.getName());

        if (relativeToHome) {
            filename = System.getProperty("user.home") + System.getProperty("file.separator") + path
                    + System.getProperty("file.separator") + moduleName + "_" + account + "_"
                    + dateformat.format(d) + ".csv";
        } else {
            filename = path + System.getProperty("file.separator") + moduleName + "_" + account + "_"
                    + dateformat.format(d) + ".csv";
        }

    }

    // create a new csv exporter

    CSVTrialDataExport csvExport = new CSVTrialDataExport(dataService);

    // change CSV separator for English language to comma
    if (dataService.getMessages().getLocale().getLanguage().equals("en")) {
        csvExport.setCSVParameters(',');
    } else {
        csvExport.setCSVParameters(';');
    }

    File tmpFile = csvExport.exportData(module, fromSessionIndex);

    if (filename == null) {
        exporterError.setErrorType(DataExporterError.GENERAL_CANCEL);
        return "The export has been cancelled.";
    }

    // copy/move the file to the destination
    try {
        File moduleDataFile = new File(filename);
        FileUtils.copyFile(tmpFile, moduleDataFile);
        tmpFile.delete();
    } catch (IOException ioe) {
        logger.error("Unable to move exported file to destination", ioe);
        exporterError.setErrorType(DataExporterError.FILE_GENERAL);
        exporterError.setErrorReason(ioe.getMessage());
        return "Export failed.\n" + ioe.getMessage();
    }
    return null;
}

From source file:de.uzk.hki.da.cb.ScanActionTests.java

/**
 * Sets the up before class.//w  w w.j a v a2s .c  o m
 * @throws IOException 
 */
@Before
public void setUp() throws IOException {

    j.setRep_name(REPNAME);

    DAFile premis = new DAFile(REPNAME + "a", "premis.xml");
    DAFile file = new DAFile(REPNAME + "a", TIFF_TESTFILE);
    file.setFormatPUID(TIF_PUID);
    List<DAFile> files = new ArrayList<DAFile>();
    files.add(file);
    files.add(premis);
    o.getLatestPackage().getFiles().addAll(files);

    Set<Node> nodes = new HashSet<Node>();
    nodes.add(n);
    ConversionRoutine toPng = new ConversionRoutine("TOPNG", "de.uzk.hki.da.cb.CLIConversionStrategy",
            "cp input output", "bmp");
    ConversionPolicy policy = new ConversionPolicy(TIF_PUID, toPng);
    List<ConversionPolicy> policies = new ArrayList<ConversionPolicy>();
    List<ConversionPolicy> noPolicies = new ArrayList<ConversionPolicy>();
    policies.add(policy);

    PreservationSystem pSystem = mock(PreservationSystem.class);

    when(pSystem.getApplicablePolicies((DAFile) anyObject(), (Boolean) anyObject())).thenReturn(policies)
            .thenReturn(noPolicies);
    when(pSystem.getAdmin()).thenReturn(o.getContractor()); // quick fix
    action.setDistributedConversionAdapter(mock(DistributedConversionAdapter.class));
    action.setPSystem(pSystem);
    n.setWorkAreaRootPath(workAreaRootPath);

    FileUtils.copyFile(Path.makeFile(workAreaRootPath, "premis.xml_MIGRATION_NOTIFY"), premisFile);
}

From source file:de.uzk.hki.da.pkg.CopyUtility.java

/**
 * Copies a file to a target folder//ww  w.jav  a2 s  . co m
 * 
 * @param source The source file
 * @param destination The target file
 * @return false if the SIP creation process was aborted during the copy process, otherwise true
 * @throws IOException
 * @throws IllegalArgumentException
 */
private boolean copy(File source, File destination) throws IOException, IllegalArgumentException {

    if (sipBuildingProcess.isAborted())
        return false;

    if (source.isDirectory()) {

        if (!(source.getName().equals("thumbs")) && !(source.getName().equals("thumbnails"))) {

            if (!destination.exists()) {
                destination.mkdir();
            }

            String files[] = source.list();

            for (String file : files) {
                File srcFile = new File(source, file);
                File destFile = new File(destination, file);

                if (!copy(srcFile, destFile))
                    return false;
            }
            destination.setLastModified(source.lastModified());
        }

    } else {

        if (!source.getName().equals(".DS_Store") && (source.length() != 0)
                && checkFileExtension(source.getName())) {
            FileUtils.copyFile(source, destination);
        }

        if (progressManager != null)
            progressManager.copyProgress(jobId, FileUtils.sizeOf(source));
    }

    return true;
}