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.sonatype.security.ldap.persist.validation.LdapConfigurationValidationTest.java

private ExpectedResult runValidation(File ldapXml) throws Exception {
    // copy ldap.xml to conf dir
    File inplaceLdapXml = new File(getConfHomeDir(), "ldap.xml");
    FileUtils.copyFile(ldapXml, inplaceLdapXml);

    LdapConfigurationSource source = this.lookup(LdapConfigurationSource.class);
    try {/*from   ww w . j ava  2s .  c o  m*/
        // Note: This test original also used configuration source, but it does not validate anymore
        // it is done by manager. Hence, validatio code added here below
        final CLdapConfiguration conf = source.load();
        final ValidationResponse vr = lookup(LdapConfigurationValidator.class)
                .validateModel(new ValidationRequest<CLdapConfiguration>(conf));
        if (!vr.isValid()) {
            throw new InvalidConfigurationException(vr);
        }
    } catch (InvalidConfigurationException e) {
        return new ExpectedResult(e.getValidationResponse());
    }

    return new ExpectedResult(0, 0, "No Config Error");

}

From source file:com.splout.db.engine.RedisManager.java

@Override
public void init(File dbFile, Configuration config, List<String> initStatements) throws EngineException {

    File dbFolder = dbFile.getParentFile();

    String redisExecutable = config.getString(REDIS_EXECUTABLE_CONF, null);
    if (redisExecutable == null) {
        throw new EngineException(
                "A Redis executable path should be specified in configuration '" + REDIS_EXECUTABLE_CONF + "'",
                null);/*w w  w  .j a  va2s .co  m*/
    }

    if (!new File(redisExecutable).exists()) {
        throw new EngineException("The specified Redis executable doesn't exist: " + redisExecutable, null);
    }

    int basePort = config.getInt(BASE_PORT_CONF, DEFAULT_BASE_PORT);

    logger.info("Redis executable -> " + redisExecutable + "; base port -> " + basePort);

    File thisServer = new File(dbFolder, "redis-server");
    File thisDataFile = new File(dbFolder, "dump.rdb");
    File actualDataFile = dbFile;
    try {
        Runtime.getRuntime().exec(
                new String[] { "ln", "-s", actualDataFile.getAbsolutePath(), thisDataFile.getAbsolutePath() })
                .waitFor();
        FileUtils.copyFile(new File(redisExecutable), thisServer);
        thisServer.setExecutable(true);

        PortLock portLock = PortUtils.getNextAvailablePort(basePort);
        try {
            logger.info("Using port from port lock: " + portLock.getPort());
            redisServer = new RedisServer(thisServer, portLock.getPort());
            redisServer.start();
            jedis = new Jedis("localhost", portLock.getPort());
        } finally {
            portLock.release();
        }
    } catch (InterruptedException e) {
        throw new EngineException(e);
    } catch (IOException e) {
        throw new EngineException(e);
    }
}

From source file:net.sf.firemox.xml.magic.Oracle2XmlNoRules.java

/**
 * @param oracleFile/*ww  w.j  a  v  a 2  s . com*/
 *          the oracle format text file.
 * @param destinationDir
 *          the directory where built card will be placed.
 * @param recycledDir
 *          the directory where already built card are placed.
 */
public void serialize(File oracleFile, File destinationDir, File recycledDir) {
    if (!oracleFile.exists() || !oracleFile.isFile()) {
        System.err.println("The file '" + oracleFile + "' does not exist");
        System.exit(-1);
        return;
    }

    if (!destinationDir.exists() || !destinationDir.isDirectory()) {
        System.err.println("The destination directory '" + destinationDir + "' does not exist");
        System.exit(-1);
        return;
    }
    final StringBuilder cardText = new StringBuilder();
    int nbCard = 0;
    MToolKit.tbsName = "norules-mtg";
    try {
        final BufferedReader in = new BufferedReader(new FileReader(oracleFile));
        PrintWriter out = null;
        while (nbCard < MAXI) {
            String line = in.readLine();
            if (line == null)
                break;
            String cardName = line.trim();
            if (cardName.length() == 0) {
                continue;
            }

            // a new card starts
            String fileName = MToolKit.getExactKeyName(cardName) + ".xml";
            if (new File(recycledDir, fileName).exists()) {
                if (UPDATE_CARD) {
                    File patchFile = MToolKit.getFile("tbs/norules-mtg/recycled/" + fileName);
                    File tempFile = File.createTempFile(fileName, "temp");
                    FileUtils.copyFile(patchFile, tempFile);
                    final BufferedReader inExist = new BufferedReader(new FileReader(tempFile));
                    final PrintWriter outExist = new PrintWriter(new FileOutputStream(patchFile));
                    String lineExist = null;
                    boolean found = false;
                    while ((lineExist = inExist.readLine()) != null) {
                        if (!found && lineExist.contains("name=\"")) {
                            lineExist = lineExist.substring(0, lineExist.indexOf("name=\"")) + "name=\""
                                    + cardName + lineExist.substring(lineExist.indexOf("\"",
                                            lineExist.indexOf("name=\"") + "name=\"".length() + 2));
                            found = true;
                        }
                        outExist.println(lineExist);
                    }
                    IOUtils.closeQuietly(inExist);
                    IOUtils.closeQuietly(outExist);

                    if (!found) {
                        System.err.println(">> Error patching card '" + cardName + "'");
                        // } else {
                        // patching card
                    }
                }
                skipCard(in);
                continue;
            }

            out = new PrintWriter(new FileOutputStream(new File(destinationDir, fileName)));

            // record the card text
            cardText.setLength(0);
            cardText.append("<!--\n\t");

            line = in.readLine().trim().replaceAll("\\(.*\\)", "").toLowerCase();
            cardText.append('\t').append(line).append("\n");

            while (true) {
                line = in.readLine();
                if (line == null || line.length() == 0)
                    break;
                line = line.replaceAll("--", "");
                cardText.append('\t').append(line).append('\n');
            }

            cardText.append(" -->");
            out.println("<?xml version='1.0'?>");

            out.print("<card xmlns='");
            out.println(IdConst.NAME_SPACE + "'");
            out.print("\txmlns:xsi='");
            out.print(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
            out.println("'");
            out.print("\txsi:schemaLocation='");
            out.println(IdConst.NAME_SPACE + " ../../" + IdConst.TBS_XSD + "'");
            out.println("\tname=\"" + cardName + "\">");
            out.println("<rules-author-comment>riclas</rules-author-comment>\n");
            out.println(cardText.toString());
            out.println("</card>");
            IOUtils.closeQuietly(out);
            nbCard++;
        }
    } catch (FileNotFoundException e) {
        System.err.println("Error openning file '" + oracleFile + "' : " + e);
    } catch (IOException e) {
        System.err.println("IOError reading file '" + oracleFile + "' : " + e);
    }
    System.out.println("Success Parsing : " + nbCard + " card(s)");
}

From source file:com.thoughtworks.go.server.DevelopmentServer.java

private static void copyPluginAssets() throws IOException {
    File classPathRoot = new File(
            DevelopmentServer.class.getProtectionDomain().getCodeSource().getLocation().getPath());
    FileUtils.copyFile(new File("webapp/WEB-INF/rails/webpack/rails-shared/plugin-endpoint.js"),
            new File(classPathRoot, "plugin-endpoint.js"));
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopFileMultiUploadField.java

protected void uploadFiles(File[] files) {
    for (File file : files) {
        try {//from   ww w  . jav a 2  s.  co  m
            fireFileUploadStart(file.getName(), file.length());

            FileInfo fileInfo = fileUploading.createFile();
            UUID tempFileId = fileInfo.getId();
            File tmpFile = fileInfo.getFile();

            FileUtils.copyFile(file, tmpFile);

            filesMap.put(tempFileId, file.getName());

            fireFileUploadFinish(file.getName(), file.length());
        } catch (Exception ex) {
            Messages messages = AppBeans.get(Messages.NAME);
            String uploadError = messages.formatMessage(DesktopFileMultiUploadField.class,
                    "multiupload.uploadError", file.getName());

            TopLevelFrame topLevelFrame = DesktopComponentsHelper.getTopLevelFrame(this);
            topLevelFrame.showNotification(uploadError, Frame.NotificationType.ERROR);

            fireFileUploadError(file.getName(), file.length(), ex);
        }
    }

    fireQueueUploadComplete();
}

From source file:algorithm.ImageImageFrameExpanding.java

/**
 * Attach all payload images to the carrier image.
 * // www.  j av  a 2 s.c om
 * @param carrier
 * @param payloadList
 * @return encapsulated file
 * @throws IOException
 */
private File appendAllPayload(File carrier, List<File> payloadList) throws IOException {
    File outputFile = getOutputFile(carrier);
    FileUtils.copyFile(carrier, outputFile);
    for (File payload : payloadList) {
        append(outputFile, payload);
    }
    return outputFile;
}

From source file:de.thischwa.pmcms.view.context.object.tagtool.LinkTagTool.java

/**
 * Construct the a-tag./*  ww w. j  av  a2s .c o m*/
 */
@Override
public String toString() {
    String hrefString = super.getAttr("href");
    // 1. check, if the base attributes are set
    if (StringUtils.isBlank(hrefString))
        throw new IllegalArgumentException("'href' isn't set!");

    // 2. construct the tag for preview or export
    if (!isExternalLink) {
        VirtualFile vf = new VirtualFile(this.pojoHelper.getSite(), false);
        vf.consructFromTagFromView(hrefString);
        if (isExportView) {
            try {
                File srcFile = vf.getBaseFile();
                File destFile = vf.getExportFile();
                FileUtils.copyFile(srcFile, destFile);
                renderData.addFile(vf);
            } catch (IOException e) {
                logger.error("Error while copy [" + vf.getBaseFile().getPath() + "] to ["
                        + vf.getExportFile().getPath() + "]: " + e.getMessage(), e);
                throw new FatalException("Error while copy [" + vf.getBaseFile().getPath() + "] to ["
                        + vf.getExportFile().getPath() + "]: " + e.getMessage(), e);
            }
            this.setHref(vf.getTagSrcForExport(this.pojoHelper.getLevel()));
        } else
            this.setHref(vf.getTagSrcForPreview());
    }

    isExternalLink = false;
    return super.contructTag();
}

From source file:de.tudarmstadt.ukp.dkpro.core.stanfordnlp.StanfordPosTaggerTrainer.java

@Override
public void initialize(UimaContext aContext) throws ResourceInitializationException {
    super.initialize(aContext);

    try {/*from www . j  a va2  s.  c om*/
        String p = clusterFile.getAbsolutePath();
        if (p.contains("(") || p.contains(")") || p.contains(",")) {
            // The Stanford POS tagger trainer does not suppor these characters in the cluster
            // files path. If we have those, try to copy the clusters somewhere save before
            // training. See: https://github.com/stanfordnlp/CoreNLP/issues/255
            File tempClusterFile = File.createTempFile("dkpro-stanford-pos-trainer", ".cluster");
            FileUtils.copyFile(clusterFile, tempClusterFile);
            clusterFile = tempClusterFile;
            clusterFilesTemporary = true;
        } else {
            clusterFilesTemporary = false;
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:fm.last.commons.test.LastAssertionsTest.java

@Test
public void assertFilesEqualWithSameFileInDifferentFolders() throws IOException {
    File file1 = new File(dataFolder.getFolder(), "file1.txt");
    File file2 = temporaryFolder.newFile("copy.txt");
    FileUtils.copyFile(file1, file2);
    LastAssertions.assertFileEquals(file1, file2);
}

From source file:mx.itesm.imb.EcoreImbEditor.java

/**
 * //from w ww  .  ja va 2  s  .  c om
 * @param ecoreProject
 */
@SuppressWarnings("unchecked")
public static void generateProvidersArtifacts(final File ecoreProject, final File templateProject) {
    File provider;
    File imbProject;
    List<File> imbTypes;
    Iterator<File> files;
    List<String> types;
    String typesPackage;

    // Get imb types
    imbProject = new File(ecoreProject.getParent(), ecoreProject.getName() + ".edit");
    files = FileUtils.iterateFiles(new File(imbProject, "/src/imb"), new String[] { "java" }, true);
    imbTypes = new ArrayList<File>();
    while (files.hasNext()) {
        imbTypes.add(files.next());
    }

    // Get providers files
    files = FileUtils.iterateFiles(imbProject, new IOFileFilter() {

        @Override
        public boolean accept(final File file) {
            return file.getName().endsWith("ItemProvider.java");
        }

        @Override
        public boolean accept(File directory, String file) {
            return file.endsWith("ItemProvider.java");
        }
    }, TrueFileFilter.INSTANCE);

    typesPackage = null;
    types = new ArrayList<String>();
    while (files.hasNext()) {
        try {
            provider = files.next();
            types.add(provider.getName().replace("ItemProvider.java", ""));
            typesPackage = provider.getPath()
                    .substring(provider.getPath().indexOf("src") + "src".length() + 1,
                            provider.getPath().indexOf(provider.getName().replace(".java", "")) - 1)
                    .replace('/', '.');

            EcoreImbEditor.writeEcoreAspect(provider, imbTypes);
            EcoreImbEditor.writeEcoreController(imbProject, templateProject, provider, imbTypes);
            System.out.println("Artifacts for " + provider + " successfully generated");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error generating Artifacts: " + e.getMessage());
        }
    }

    // Configuration properties file
    try {
        FileUtils.copyFile(new File(templateProject, "/templates/configuration-template.properties"),
                new File(imbProject, "/src/mx/itesm/imb/configuration.properties"));
        FileUtils.copyFile(new File(templateProject, "/templates/configuration-template.properties"),
                new File(ecoreProject.getParent(),
                        ecoreProject.getName() + ".editor/src/mx/itesm/imb/configuration.properties"));
    } catch (IOException e) {
        System.out.println("Unable to generate configuration properties file: " + e.getMessage());
    }

    // Selection aspect
    typesPackage = typesPackage.replace(".provider", "");
    EcoreImbEditor.writeSelectionAspect(ecoreProject, typesPackage, types);
}