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

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

Introduction

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

Prototype

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

Source Link

Document

Moves a file.

Usage

From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_6.java

private void upgradeHeaderVersion(String basename) throws IOException {
    InputStream headerStream;/*  w  w  w  .ja v a2s  .  co m*/
    try {
        headerStream = new GZIPInputStream(new RepositionableInputStream(basename + ".header"));
    } catch (IOException e) {
        // try not compressed for compatibility with 1.4-:
        LOG.trace("falling back to legacy 1.4- uncompressed header.");

        headerStream = new FileInputStream(basename + ".header");
    }
    // accept very large header messages, since these may contain query identifiers:
    final CodedInputStream codedInput = CodedInputStream.newInstance(headerStream);
    codedInput.setSizeLimit(Integer.MAX_VALUE);
    final Alignments.AlignmentHeader header = Alignments.AlignmentHeader.parseFrom(codedInput);

    Alignments.AlignmentHeader.Builder upgradedHeader = Alignments.AlignmentHeader.newBuilder(header);
    upgradedHeader.setVersion(VersionUtils.getImplementationVersion(UpgradeTo1_9_6.class));
    FileUtils.moveFile(new File(basename + ".header"),
            new File(makeBackFilename(basename + ".header", ".bak")));
    GZIPOutputStream headerOutput = new GZIPOutputStream(new FileOutputStream(basename + ".header"));
    try {
        upgradedHeader.build().writeTo(headerOutput);
    } finally {
        headerOutput.close();
    }
}

From source file:com.linkedin.pinot.controller.api.restlet.resources.LLCSegmentCommit.java

boolean uploadSegment(final String instanceId, final String segmentNameStr) {
    // 1/ Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory();

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    final RestletFileUpload upload = new RestletFileUpload(factory);
    final List<FileItem> items;

    try {//w w  w  .j av a2 s. c  o m
        // The following statement blocks until the entire segment is read into memory.
        items = upload.parseRequest(getRequest());

        boolean found = false;
        File dataFile = null;

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
            final FileItem fi = it.next();
            if (fi.getFieldName() != null && fi.getFieldName().equals(segmentNameStr)) {
                found = true;
                dataFile = new File(tempDir, segmentNameStr);
                fi.write(dataFile);
            }
        }

        if (!found) {
            LOGGER.error("Segment not included in request. Instance {}, segment {}", instanceId,
                    segmentNameStr);
            return false;
        }
        // We will not check for quota here. Instead, committed segments will count towards the quota of a
        // table
        LLCSegmentName segmentName = new LLCSegmentName(segmentNameStr);
        final String rawTableName = segmentName.getTableName();
        final File tableDir = new File(baseDataDir, rawTableName);
        final File segmentFile = new File(tableDir, segmentNameStr);

        synchronized (_pinotHelixResourceManager) {
            if (segmentFile.exists()) {
                LOGGER.warn("Segment file {} exists. Replacing with upload from {}", segmentNameStr,
                        instanceId);
                FileUtils.deleteQuietly(segmentFile);
            }
            FileUtils.moveFile(dataFile, segmentFile);
        }

        return true;
    } catch (Exception e) {
        LOGGER.error("File upload exception from instance {} for segment {}", instanceId, segmentNameStr, e);
    }
    return false;
}

From source file:com.massabot.codesender.utils.SettingsFactory.java

/**
 * Convert legacy property file to JSON, move files from top level setting directory to UGS
 * settings directory.//  www.  j  a  v a 2s .  c om
 */
private static void migrateOldSettings() {
    File newSettingsDir = getSettingsDirectory();
    File oldSettingDir = newSettingsDir.getParentFile();
    File oldPropertyFile = new File(oldSettingDir, PROPERTIES_FILENAME);
    File oldJsonFile = new File(oldSettingDir, JSON_FILENAME);

    // Convert property file in old location to json file in new location.
    if (oldPropertyFile.exists()) {
        try {
            Settings out = new Settings();
            // logger.log(Level.INFO, "{0}: {1}", new
            // Object[]{Localization.getString("settings.log.location"), settingsFile});
            logger.log(Level.INFO, "Log location: {0}", oldPropertyFile.getAbsolutePath());
            Properties properties = new Properties();
            properties.load(new FileInputStream(oldPropertyFile));
            out.setLastOpenedFilename(properties.getProperty("last.dir", System.getProperty(USER_HOME)));
            out.setPort(properties.getProperty("port", ""));
            out.setPortRate(properties.getProperty("port.rate", "9600"));
            out.setManualModeEnabled(Boolean.valueOf(properties.getProperty("manualMode.enabled", FALSE)));
            out.setManualModeStepSize(Double.valueOf(properties.getProperty("manualMode.stepsize", "1")));
            out.setScrollWindowEnabled(Boolean.valueOf(properties.getProperty("scrollWindow.enabled", "true")));
            out.setVerboseOutputEnabled(
                    Boolean.valueOf(properties.getProperty("verboseOutput.enabled", FALSE)));
            out.setFirmwareVersion(properties.getProperty("firmwareVersion", "GRBL"));
            out.setSingleStepMode(Boolean.valueOf(properties.getProperty("singleStepMode", FALSE)));
            out.setStatusUpdatesEnabled(
                    Boolean.valueOf(properties.getProperty("statusUpdatesEnabled", "true")));
            out.setStatusUpdateRate(Integer.valueOf(properties.getProperty("statusUpdateRate", "200")));
            out.setDisplayStateColor(Boolean.valueOf(properties.getProperty("displayStateColor", "true")));
            out.updateMacro(1, null, null, properties.getProperty("customGcode1", "G0 X0 Y0;"));
            out.updateMacro(2, null, null, properties.getProperty("customGcode2", "G0 G91 X10;G0 G91 Y10;"));
            out.updateMacro(3, null, null, properties.getProperty("customGcode3", ""));
            out.updateMacro(4, null, null, properties.getProperty("customGcode4", ""));
            out.updateMacro(5, null, null, properties.getProperty("customGcode5", ""));
            out.setLanguage(properties.getProperty("language", "en_US"));
            saveSettings(out);

            // Delete the old settings file if it exists.
            oldPropertyFile.delete();
        } catch (IOException ex) {
            Logger.getLogger(SettingsFactory.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // Move old json file from old location to new location.
    else if (oldJsonFile.exists()) {
        try {
            // If the new file doesn't exist, move the old one.
            if (!getSettingsFile().exists()) {
                FileUtils.moveFile(oldJsonFile, getSettingsFile());
            }
            // Delete the old settings file if it exists.
            oldJsonFile.delete();
        } catch (IOException ex) {
            Logger.getLogger(SettingsFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfigurator.java

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);/*  w ww  . j  a  va  2 s  . c o  m*/
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

            // If this is the manifest, skip it.
            if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                continue;
            }

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:ca.brood.softlogger.dataoutput.CSVOutputModule.java

private void updateFilename() throws Exception {
    String theFileName;// w ww  . j  a  v a  2s. co m
    String oldFileName;
    Calendar cal = Calendar.getInstance();
    theFileName = csvSubdirectory + "/" + String.format("%1$tY%1$tm%1$td-%1$tH.%1$tM.%1$tS", cal) + "-"
            + m_OutputDevice.getDescription() + ".csv";

    try {
        if (!csvSubdirectory.equals(".")) {
            File csvDir = new File(csvSubdirectory);
            if (!csvDir.isDirectory()) {
                csvDir.mkdirs();
            }
        }
    } catch (Exception e) {
        log.error("Error - couldn't create the CSV destination directory: " + csvSubdirectory, e);
        throw e;
    }

    if (writer == null) {
        writer = new CSVFileWriter(theFileName);

        //Move all CSV files from csvSubdirectory to completedFileDirectory
        if (completedFileDirectory.length() > 0) {
            String[] extensions = new String[1];
            extensions[0] = "csv";
            File csvDir = new File(csvSubdirectory);
            File completedDir = new File(completedFileDirectory);

            try {
                Iterator<File> fileIter = FileUtils.iterateFiles(csvDir, extensions, false);

                while (fileIter.hasNext()) {
                    FileUtils.moveFileToDirectory(fileIter.next(), completedDir, true);
                }
            } catch (Exception e) {
                log.error("Couldn't move existing CSV files on startup.", e);
            }
        }

    } else {
        oldFileName = writer.getFilename();
        writer.setFilename(theFileName);

        if (!oldFileName.equalsIgnoreCase(theFileName)) {
            //File name has changed, move the old file if required
            try {
                if (completedFileDirectory.length() > 0) {
                    File completedDir = new File(completedFileDirectory);
                    if (!completedDir.isDirectory()) {
                        completedDir.mkdirs();
                    }
                    File oldFile = new File(oldFileName);
                    if (oldFile.exists()) {
                        String movedFileName = completedFileDirectory + "/" + oldFile.getName();
                        File movedFile = new File(movedFileName);

                        log.debug("Moving " + oldFileName + " to " + movedFileName);

                        FileUtils.moveFile(oldFile, movedFile);
                    }
                }
            } catch (Exception e) {
                log.error("Couldn't move the completed CSV file", e);
            }
        }
    }
}

From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_8_2.java

private void upgradeHeaderVersion(String basename) throws IOException {
    InputStream headerStream;// w  w  w. java2s. co  m
    try {
        headerStream = new GZIPInputStream(new FileInputStream(basename + ".header"));
    } catch (IOException e) {
        // try not compressed for compatibility with 1.4-:
        LOG.trace("falling back to legacy 1.4- uncompressed header.");

        headerStream = new FileInputStream(basename + ".header");
    }
    // accept very large header messages, since these may contain query identifiers:
    final CodedInputStream codedInput = CodedInputStream.newInstance(headerStream);
    codedInput.setSizeLimit(Integer.MAX_VALUE);
    final Alignments.AlignmentHeader header = Alignments.AlignmentHeader.parseFrom(codedInput);

    Alignments.AlignmentHeader.Builder upgradedHeader = Alignments.AlignmentHeader.newBuilder(header);
    upgradedHeader.setVersion(VersionUtils.getImplementationVersion(UpgradeTo1_9_8_2.class));
    FileUtils.moveFile(new File(basename + ".header"),
            new File(makeBackFilename(basename + ".header", ".bak")));
    GZIPOutputStream headerOutput = new GZIPOutputStream(new FileOutputStream(basename + ".header"));
    try {
        upgradedHeader.build().writeTo(headerOutput);
    } finally {
        headerOutput.close();
    }
}

From source file:it.greenvulcano.util.file.FileManager.java

/**
 * Move a file/directory on the local file system.<br>
 *
 * @param oldPath//  www . java 2  s.  c  om
 *            Absolute pathname of the file/directory to be renamed
 * @param newPath
 *            Absolute pathname of the new file/directory
 * @param filePattern
 *            A regular expression defining the name of the files to be copied. Used only if
 *            srcPath identify a directory. Null or "" disable file filtering.
 * @throws Exception
 */
public static void mv(String oldPath, String newPath, String filePattern) throws Exception {
    File src = new File(oldPath);
    if (!src.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the source is NOT absolute: " + oldPath);
    }
    File target = new File(newPath);
    if (!target.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the destination is NOT absolute: " + newPath);
    }
    if (target.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            FileUtils.deleteQuietly(target);
        }
    }
    if (src.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            logger.debug("Moving directory " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveDirectory(src, target);
        } else {
            Set<FileProperties> files = ls(oldPath, filePattern);
            for (FileProperties file : files) {
                logger.debug("Moving file " + file.getName() + " from directory " + src.getAbsolutePath()
                        + " to directory " + target.getAbsolutePath());
                File finalTarget = new File(target, file.getName());
                FileUtils.deleteQuietly(finalTarget);
                if (file.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(new File(src, file.getName()), finalTarget, true);
                } else {
                    FileUtils.moveFileToDirectory(new File(src, file.getName()), target, true);
                }
            }
        }
    } else {
        if (target.isDirectory()) {
            File finalTarget = new File(target, src.getName());
            FileUtils.deleteQuietly(finalTarget);
            logger.debug("Moving file " + src.getAbsolutePath() + " to directory " + target.getAbsolutePath());
            FileUtils.moveFileToDirectory(src, target, true);
        } else {
            logger.debug("Moving file " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveFile(src, target);
        }
    }
}

From source file:de.ingrid.interfaces.csw.config.CommunicationProvider.java

/**
 * Write the given communication Configuration to the disc. To keep the time
 * for modifying the actual configuration file as short as possible, the
 * method writes the configuration into a temporary file first and then
 * renames this file to the original configuration file name. Note: Since
 * renaming a file is not atomic in Windows, if the target file exists
 * already (we need to delete and then rename), this method is synchronized.
 * /*from www  . j  a va2  s. co m*/
 * @param configuration
 *            Configuration instance
 * @throws IOException
 */
public synchronized void write(Communication configuration) throws IOException {

    // make sure the configuration is loaded
    this.getConfiguration();

    // serialize the Configuration instance to xml
    XStream xstream = new XStream();
    this.setXStreamAliases(xstream);
    String xml = xstream.toXML(configuration);

    // write the configuration to a temporary file first
    File tmpFile = File.createTempFile("communication", null);
    BufferedWriter output = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(tmpFile.getAbsolutePath()), "UTF8"));
    try {
        output.write(xml);
        output.close();
        output = null;
    } finally {
        if (output != null) {
            output.close();
        }
    }

    // move the temporary file to the configuration file
    this.configurationFile.delete();
    FileUtils.moveFile(tmpFile, this.configurationFile);
}

From source file:io.hops.hopsworks.ca.api.certs.CertSigningService.java

private CsrDTO signCSR(String hostId, String commandId, String csr, boolean rotation, CertificateType certType)
        throws HopsSecurityException {
    try {//from   w  ww . j  a v  a  2  s. com
        // If there is a certificate already for that host, rename it to .TO_BE_REVOKED.COMMAND_ID
        // When AgentResource has received a successful response for the key rotation, revoke and delete it
        if (rotation) {
            File certFile = Paths.get(settings.getIntermediateCaDir(), "certs",
                    hostId + CertificatesMgmService.CERTIFICATE_SUFFIX).toFile();
            if (certFile.exists()) {
                File destination = Paths
                        .get(settings.getIntermediateCaDir(), "certs",
                                hostId + serviceCertificateRotationTimer.getToBeRevokedSuffix(commandId))
                        .toFile();
                try {
                    FileUtils.moveFile(certFile, destination);
                } catch (FileExistsException ex) {
                    FileUtils.deleteQuietly(destination);
                    FileUtils.moveFile(certFile, destination);
                }
            }
        }
        String agentCert = opensslOperations.signCertificateRequest(csr, certType);
        File caCertFile = Paths.get(settings.getIntermediateCaDir(), "certs", "ca-chain.cert.pem").toFile();
        String caCert = Files.toString(caCertFile, Charset.defaultCharset());
        return new CsrDTO(caCert, agentCert, settings.getHadoopVersionedDir());
    } catch (IOException ex) {
        throw new HopsSecurityException(RESTCodes.SecurityErrorCode.CSR_ERROR, Level.SEVERE, "host: " + hostId,
                ex.getMessage(), ex);
    }
}

From source file:de.bitinsomnia.webdav.server.MiltonFileResource.java

@Override
public void moveTo(CollectionResource rDest, String name)
        throws ConflictException, NotAuthorizedException, BadRequestException {
    LOGGER.debug("Moving {} to {}/{}", this.file, rDest.getName(), name);

    File copyFilePath = new File(resourceFactory.getRootFolder(), rDest.getName());
    File copyFile = new File(copyFilePath, name);

    try {/* ww w.  ja  v  a2 s .co m*/
        FileUtils.moveFile(this.file, copyFile);
    } catch (IOException e) {
        LOGGER.error("Error moving file {} to {}/{}", this.file, rDest, name, e);
        throw new RuntimeIoException(e);
    }
}