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:com.sap.prd.mobile.ios.mios.UpdateVersionInPListTaskTest.java

@Before
public void setup() throws IOException {

    infoPlist = tmpFolder.newFile(infoPListMaster.getName());
    FileUtils.copyFile(infoPListMaster, infoPlist);
}

From source file:action.BannerAction.java

public String create() throws Exception {
    String filePath = request.getSession().getServletContext().getRealPath("/")
            .concat("public\\upload\\banner");
    Random rand = new Random();
    int n = rand.nextInt(99999) + 1;
    File fileToCreate = new File(filePath, n + "_" + this.getUploadFileName());
    FileUtils.copyFile(this.getUpload(), fileToCreate);
    banner = new Banner();
    this.getBanner().setUrl(n + "_" + this.getUploadFileName());
    boolean insert = controller.insert(this.getBanner());

    if (insert == true) {
        list = controller.getAll();/*from  w ww .j a v a  2 s  . c o  m*/
        ServletActionContext.getRequest().getSession().setAttribute("list", list);
        this.addActionMessage("Upload banner success!");
        return SUCCESS;
    } else {
        this.addActionError("Have some error, please try again!");
        return INPUT;
    }
}

From source file:net.sourceforge.atunes.utils.TempFolder.java

@Override
public File addFile(final File srcFile) {
    File destFile = new File(StringUtils.getString(this.osManager.getTempFolder(),
            this.osManager.getFileSeparator(), srcFile.getAbsolutePath().hashCode()));
    try {//from ww  w . j  a  v a2  s . co m
        FileUtils.copyFile(srcFile, destFile);
    } catch (IOException e) {
        return null;
    }
    return destFile;
}

From source file:hu.bme.mit.sette.tools.jpet.JPetGenerator.java

@Override
protected void afterWriteRunnerProject(EclipseProject pEclipseProject) throws IOException, SetteException {
    File buildXml = new File(getRunnerProjectSettings().getBaseDirectory(), "build.xml");
    FileUtils.copyFile(getTool().getDefaultBuildXml(), buildXml);
}

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

/**
 * Appends the passed files (in list order) to the destination.
 * //from   w  w w  . j a  v  a2s . c o m
 * @param destination Destination file.
 * @param files List of files to be appended to the destination file.
 * @throws IOException If an error occurs appending the files.
 */
public static void appendFiles(File destination, List<File> files) throws IOException {
    FileUtils.copyFile(files.get(0), destination);
    FileOutputStream fos = new FileOutputStream(destination, true);
    for (int i = 1; i < files.size(); i++) {
        FileInputStream fis = new FileInputStream(files.get(i));
        IOUtils.copy(fis, fos);
        IOUtils.closeQuietly(fis);
    }
    IOUtils.closeQuietly(fos);
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*  w  ww .  j a va 2 s  .  c  o  m*/
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:functionaltests2.SchedulerCommandLine.java

/**
 * Start a Scheduler and Resource Manager.
 *///from www .  j  a v  a2s  .co m
public static void startSchedulerCmdLine(boolean restart, File proactiveConf) throws Exception {

    File schedHome = new File(System.getProperty("pa.scheduler.home")).getCanonicalFile();
    File rmHome = new File(System.getProperty("pa.rm.home")).getCanonicalFile();
    if (proactiveConf != null) {
        FileUtils.copyFile(proactiveConf,
                new File(schedHome, "config" + fs + "proactive" + fs + "ProActiveConfiguration.xml"));
    }

    System.out.println(schedHome);

    p = null;
    ProcessBuilder pb = new ProcessBuilder();
    if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.unix)) {
        pb.directory(new File(schedHome + fs + "bin" + fs + "unix"));
        pb.command("/bin/bash", restart ? "scheduler-start" : "scheduler-start-clean",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    } else {

        pb.directory(new File(schedHome + fs + "bin" + fs + "windows"));

        pb.command("cmd.exe", "/c", restart ? "scheduler-start.bat" : "scheduler-start-clean.bat",
                "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999");
        pb.environment().put("SchedulerTStarter", "SchedulerTStarter");
        p = pb.start();

    }

    IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[SchedulerTStarter]",
            System.out);
    Thread t1 = new Thread(lt1, "SchedulerTStarter");
    t1.setDaemon(true);
    t1.start();

    // waiting the initialization
    RMAuthentication rmAuth = RMConnection.waitAndJoin("pnp://localhost:9999");

    System.out.println("RM successfully joined.");

    SchedulerConnection.waitAndJoin("pnp://localhost:9999");
    System.out.println("Scheduler successfully joined.");

}

From source file:au.org.ala.delta.intkey.model.StartupUtils.java

/**
 * Save a copy of a dataset that was opened from a remote location
 * //from ww w  . j  a v a 2  s .c  o m
 * @param context
 *            Intkey context
 * @param saveDir
 *            Directory in which to save a copy of the dataset
 * @return A copy of the JNLP-style dataset startup file to use to open the
 *         saved copy of the dataset.
 * @throws IOException
 *             If saving to disk failed.
 */
public static File saveRemoteDataset(IntkeyContext context, File saveDir) throws IOException {
    StartupFileData startupFileData = context.getStartupFileData();
    File datasetZip = startupFileData.getDataFileLocalCopy();

    // Copy the zipped dataset as downloaded from the web
    // FileUtils.copyFileToDirectory(datasetZip, saveDir);

    // Copy the zipped dataset as downloaded from the web
    // Use utility method to avoid overwriting existing files with the same
    // name
    File copyZipFile = Utils.getSaveFileForDirectory(saveDir, datasetZip.getName());
    FileUtils.copyFile(datasetZip, copyZipFile);

    // Write a new .ink file
    // Use utility method to avoid overwriting existing files with the same
    // name
    File newInkFile = Utils.getSaveFileForDirectory(saveDir,
            FilenameUtils.getName(startupFileData.getInkFileLocation().getFile()));

    FileWriter fw = new FileWriter(newInkFile);
    BufferedWriter bufFW = new BufferedWriter(fw);

    bufFW.append(INIT_FILE_INK_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(newInkFile.toURI().toURL().toString());
    bufFW.append("\n");

    bufFW.append(INIT_FILE_DATA_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(copyZipFile.toURI().toURL().toString());
    bufFW.append("\n");

    bufFW.append(INIT_FILE_INITIALIZATION_FILE_KEYWORD);
    bufFW.append("=");
    bufFW.append(startupFileData.getInitializationFileLocation());
    bufFW.append("\n");

    String imagePath = startupFileData.getImagePath();
    if (imagePath != null) {
        bufFW.append(INIT_FILE_IMAGE_PATH_KEYWORD);
        bufFW.append("=");
        bufFW.append(imagePath);
        bufFW.append("\n");
    }

    String infoPath = startupFileData.getInfoPath();
    if (infoPath != null) {
        bufFW.append(INIT_FILE_INFO_PATH_KEYWORD);
        bufFW.append("=");
        bufFW.append(infoPath);
        bufFW.append("\n");
    }

    bufFW.flush();
    bufFW.close();

    return newInkFile;
}

From source file:mesclasses.handlers.PropertiesCache.java

public void load() throws IOException {
    FileConfigurationManager conf = FileConfigurationManager.getInstance();
    File confFile = new File(conf.getPropertiesDir() + FileConfigurationManager.SEP + DEFAULT_PROPERTIES_FILE);
    if (!confFile.exists()) {
        LOG.debug("Aucun fichier de properties trouv, on va voir si il en existe un dans l'ancien path");
        File oldFile = new File("savedData/properties/mesclasses.properties");
        if (oldFile.exists()) {
            LOG.debug("Fichier de properties trouv  l'ancienne location, on le copie");
            FileUtils.copyFile(oldFile, confFile);
        } else {//  w  w w. j av  a  2 s.  c  o m
            LOG.debug("Cration d'un nouveau fichier de properties");
            confFile.createNewFile();
        }
    }

    load(confFile);

}

From source file:biz.gabrys.lesscss.extended.compiler.storage.DataStorageImpl.java

/**
 * {@inheritDoc}// w  ww .ja v  a 2 s .co m
 * @throws DataStorageException if an I/O error occurred.
 * @since 1.0
 */
public void put(final String fileName, final File file) {
    synchronized (mutex) {
        final File cache = getFilePreparedForPut(fileName);
        try {
            FileUtils.copyFile(file, cache);
        } catch (final IOException e) {
            throw new DataStorageException(e);
        }
    }
}