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:org.apache.hive.beeline.util.QFileClient.java

public void cleanup() {
    if (beeLine != null) {
        beeLine.runCommands(new String[] { "!quit" });
    }//from w ww.  j  av  a2  s.  c  om
    if (beelineOutputStream != null) {
        beelineOutputStream.close();
    }
    if (hasErrors) {
        String oldFileName = outputDirectory + "/" + qFileName + ".raw";
        String newFileName = oldFileName + ".error";
        try {
            FileUtils.moveFile(new File(oldFileName), new File(newFileName));
        } catch (IOException e) {
            System.out.println("Failed to move '" + oldFileName + "' to '" + newFileName);
        }
    }
}

From source file:org.apache.james.mailbox.maildir.mail.MaildirMessageMapper.java

/**
 * @see org.apache.james.mailbox.store.mail.MessageMapper#updateFlags(org.apache.james.mailbox.store.mail.model.Mailbox,
 *      javax.mail.Flags, boolean, boolean,
 *      org.apache.james.mailbox.model.MessageRange)
 *///from  w  w  w  .  j  a va 2  s  . c o  m
@Override
public Iterator<UpdatedFlags> updateFlags(Mailbox mailbox, FlagsUpdateCalculator flagsUpdateCalculator,
        MessageRange set) throws MailboxException {
    final List<UpdatedFlags> updatedFlags = new ArrayList<UpdatedFlags>();
    final MaildirFolder folder = maildirStore.createMaildirFolder(mailbox);

    Iterator<MailboxMessage> it = findInMailbox(mailbox, set, FetchType.Metadata, -1);
    while (it.hasNext()) {
        final MailboxMessage member = it.next();
        Flags originalFlags = member.createFlags();
        member.setFlags(flagsUpdateCalculator.buildNewFlags(originalFlags));
        Flags newFlags = member.createFlags();

        try {
            MaildirMessageName messageName = folder.getMessageNameByUid(mailboxSession, member.getUid());
            if (messageName != null) {
                File messageFile = messageName.getFile();
                // System.out.println("save existing " + message +
                // " as " + messageFile.getName());
                messageName.setFlags(member.createFlags());
                // this automatically moves messages from new to cur if
                // needed
                String newMessageName = messageName.getFullName();

                File newMessageFile;

                // See MAILBOX-57
                if (newFlags.contains(Flag.RECENT)) {
                    // message is recent so save it in the new folder
                    newMessageFile = new File(folder.getNewFolder(), newMessageName);
                } else {
                    newMessageFile = new File(folder.getCurFolder(), newMessageName);
                }
                long modSeq;
                // if the flags don't have change we should not try to move
                // the file
                if (newMessageFile.equals(messageFile) == false) {
                    FileUtils.moveFile(messageFile, newMessageFile);
                    modSeq = newMessageFile.lastModified();

                } else {
                    modSeq = messageFile.lastModified();
                }
                member.setModSeq(modSeq);

                updatedFlags.add(new UpdatedFlags(member.getUid(), modSeq, originalFlags, newFlags));

                long uid = member.getUid();
                folder.update(mailboxSession, uid, newMessageName);
            }
        } catch (IOException e) {
            throw new MailboxException("Failure while save MailboxMessage " + member + " in Mailbox " + mailbox,
                    e);
        }

    }
    return updatedFlags.iterator();

}

From source file:org.apache.james.mailbox.maildir.mail.MaildirMessageMapper.java

/**
 * @see org.apache.james.mailbox.store.mail.AbstractMessageMapper#save(org.apache.james.mailbox.store.mail.model.Mailbox,
 *      MailboxMessage)//from w  ww  .  j ava2s  .  c  o  m
 */
@Override
protected MessageMetaData save(Mailbox mailbox, MailboxMessage message) throws MailboxException {
    MaildirFolder folder = maildirStore.createMaildirFolder(mailbox);
    long uid = 0;
    // a new message
    // save file to "tmp" folder
    File tmpFolder = folder.getTmpFolder();
    // The only case in which we could get problems with clashing names
    // is if the system clock
    // has been set backwards, then the server is restarted with the
    // same pid, delivers the same
    // number of messages since its start in the exact same millisecond
    // as done before and the
    // random number generator returns the same number.
    // In order to prevent this case we would need to check ALL files in
    // all folders and compare
    // them to this message name. We rather let this happen once in a
    // billion years...
    MaildirMessageName messageName = MaildirMessageName.createUniqueName(folder,
            message.getFullContentOctets());
    File messageFile = new File(tmpFolder, messageName.getFullName());
    FileOutputStream fos = null;
    InputStream input = null;
    try {
        if (!messageFile.createNewFile())
            throw new IOException("Could not create file " + messageFile);
        fos = new FileOutputStream(messageFile);
        input = message.getFullContent();
        byte[] b = new byte[BUF_SIZE];
        int len = 0;
        while ((len = input.read(b)) != -1)
            fos.write(b, 0, len);
    } catch (IOException ioe) {
        throw new MailboxException("Failure while save MailboxMessage " + message + " in Mailbox " + mailbox,
                ioe);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        }
    }
    File newMessageFile = null;
    // delivered via SMTP, goes to ./new without flags
    if (message.isRecent()) {
        messageName.setFlags(message.createFlags());
        newMessageFile = new File(folder.getNewFolder(), messageName.getFullName());
        // System.out.println("save new recent " + message + " as " +
        // newMessageFile.getName());
    }
    // appended via IMAP (might already have flags etc, goes to ./cur
    // directly)
    else {
        messageName.setFlags(message.createFlags());
        newMessageFile = new File(folder.getCurFolder(), messageName.getFullName());
        // System.out.println("save new not recent " + message + " as "
        // + newMessageFile.getName());
    }
    try {
        FileUtils.moveFile(messageFile, newMessageFile);
    } catch (IOException e) {
        // TODO: Try copy and delete
        throw new MailboxException("Failure while save MailboxMessage " + message + " in Mailbox " + mailbox,
                e);
    }
    try {
        uid = folder.appendMessage(mailboxSession, newMessageFile.getName());
        message.setUid(uid);
        message.setModSeq(newMessageFile.lastModified());
        return new SimpleMessageMetaData(message);
    } catch (MailboxException e) {
        throw new MailboxException("Failure while save MailboxMessage " + message + " in Mailbox " + mailbox,
                e);
    }

}

From source file:org.apache.karaf.cave.server.storage.CaveRepositoryImpl.java

/**
 * Upload an artifact from the given URL.
 *
 * @param url the URL of the artifact.//from  w w  w.  jav  a 2 s . c  om
 * @throws Exception in case of upload failure.
 */
public void upload(URL url) throws Exception {
    LOGGER.debug("Upload new artifact from {}", url);
    String artifactName = "artifact-" + System.currentTimeMillis();
    File temp = new File(new File(this.getLocation()), artifactName);
    FileUtils.copyURLToFile(url, temp);
    // update the repository.xml
    ResourceImpl resource = (ResourceImpl) new DataModelHelperImpl().createResource(temp.toURI().toURL());
    if (resource == null) {
        temp.delete();
        LOGGER.warn("The {} artifact source is not a valid OSGi bundle", url);
        throw new IllegalArgumentException(
                "The " + url.toString() + " artifact source is not a valid OSGi bundle");
    }
    File destination = new File(new File(this.getLocation()),
            resource.getSymbolicName() + "-" + resource.getVersion() + ".jar");
    if (destination.exists()) {
        temp.delete();
        LOGGER.warn("The {} artifact is already present in the Cave repository", url);
        throw new IllegalArgumentException(
                "The " + url.toString() + " artifact is already present in the Cave repository");
    }
    FileUtils.moveFile(temp, destination);
    resource = (ResourceImpl) new DataModelHelperImpl().createResource(destination.toURI().toURL());
    this.addResource(resource);
    this.generateRepositoryXml();
}

From source file:org.apache.kylin.tool.AbstractInfoExtractor.java

@Override
protected void execute(OptionsHelper optionsHelper) throws Exception {
    String exportDest = optionsHelper.getOptionValue(options.getOption("destDir"));
    boolean shouldCompress = optionsHelper.hasOption(OPTION_COMPRESS)
            ? Boolean.valueOf(optionsHelper.getOptionValue(OPTION_COMPRESS))
            : true;//from  w  ww .ja  va  2s.  c  o m
    boolean isSubmodule = optionsHelper.hasOption(OPTION_SUBMODULE)
            ? Boolean.valueOf(optionsHelper.getOptionValue(OPTION_SUBMODULE))
            : false;

    if (StringUtils.isEmpty(exportDest)) {
        throw new RuntimeException("destDir is not set, exit directly without extracting");
    }
    if (!exportDest.endsWith("/")) {
        exportDest = exportDest + "/";
    }

    // create new folder to contain the output
    String packageName = packageType.toLowerCase() + "_"
            + new SimpleDateFormat("YYYY_MM_dd_HH_mm_ss").format(new Date());
    if (!isSubmodule && new File(exportDest).exists()) {
        exportDest = exportDest + packageName + "/";
    }

    exportDir = new File(exportDest);
    FileUtils.forceMkdir(exportDir);

    if (!isSubmodule) {
        dumpBasicDiagInfo();
    }

    executeExtract(optionsHelper, exportDir);

    // compress to zip package
    if (shouldCompress) {
        File tempZipFile = File.createTempFile(packageType + "_", ".zip");
        ZipFileUtils.compressZipFile(exportDir.getAbsolutePath(), tempZipFile.getAbsolutePath());
        FileUtils.cleanDirectory(exportDir);

        File zipFile = new File(exportDir, packageName + ".zip");
        FileUtils.moveFile(tempZipFile, zipFile);
        exportDest = zipFile.getAbsolutePath();
        exportDir = new File(exportDest);
    }

    if (!isSubmodule) {
        StringBuffer output = new StringBuffer();
        output.append("\n========================================");
        output.append("\nDump " + packageType + " package locates at: \n" + exportDir.getAbsolutePath());
        output.append("\n========================================");
        logger.info(output.toString());
        System.out.println(output.toString());
    }
}

From source file:org.apache.openmeetings.test.selenium.SeleniumUtils.java

public static void makeScreenShot(String testName, Exception e, WebDriver driver) {
    try {/*  w  ww  .  j a  v a  2 s  .c  o  m*/
        DateFormat df = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss");
        String fileName = e.getMessage().replace(" ", "_");
        fileName = fileName.replaceAll("(\r\n|\n)", "");
        fileName = fileName.replaceAll("/", "");

        if (fileName.length() > 100) {
            fileName = fileName.substring(0, 100);
        }

        fileName = fileName + "_" + df.format(new Date()) + ".png";
        File screenShotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        String path = "." + File.separatorChar + "build" + File.separatorChar + "screenshots"
                + File.separatorChar + testName;

        File screenshotFolder = new File(path);
        if (!screenshotFolder.exists()) {
            screenshotFolder.mkdirs();
        }

        System.out.println("screenshot copy from: " + screenShotFile.getAbsolutePath());
        System.out.println("Length Filename: " + fileName.length() + " - Writing screenshot to: " + path
                + File.separatorChar + fileName);

        FileUtils.moveFile(screenShotFile, new File(path + File.separatorChar + fileName));
    } catch (Exception err) {
        log.error("Error", err);
    }

}

From source file:org.apache.pig.test.TestPigStorage.java

@Test
public void testIncompleteDataWithPigSchema() throws Exception {
    File parent = new File(datadir, "incomplete_data_with_pig_schema_1");
    parent.deleteOnExit();/*  w  w  w  . java2s  . c  o m*/
    parent.mkdirs();
    File tmpInput = File.createTempFile("tmp", "tmp");
    tmpInput.deleteOnExit();
    File outFile = new File(parent, "out");
    pig.registerQuery("a = load '" + Util.encodeEscape(tmpInput.getAbsolutePath())
            + "' as (x:int, y:chararray, z:chararray);");
    pig.store("a", outFile.getAbsolutePath(), "PigStorage('\\t', '-schema')");
    File schemaFile = new File(outFile, ".pig_schema");

    parent = new File(datadir, "incomplete_data_with_pig_schema_2");
    parent.deleteOnExit();
    File inputDir = new File(parent, "input");
    inputDir.mkdirs();
    File inputSchemaFile = new File(inputDir, ".pig_schema");
    FileUtils.moveFile(schemaFile, inputSchemaFile);
    File inputFile = new File(inputDir, "data");
    Util.writeToFile(inputFile, new String[] { "1" });
    pig.registerQuery("a = load '" + Util.encodeEscape(inputDir.getAbsolutePath()) + "';");
    Iterator<Tuple> it = pig.openIterator("a");
    assertTrue(it.hasNext());
    assertEquals(tuple(1, null, null), it.next());
    assertFalse(it.hasNext());

    // Now, test with prune
    pig.registerQuery(
            "a = load '" + Util.encodeEscape(inputDir.getAbsolutePath()) + "'; b = foreach a generate y, z;");
    it = pig.openIterator("b");
    assertTrue(it.hasNext());
    assertEquals(tuple(null, null), it.next());
    assertFalse(it.hasNext());
}

From source file:org.apache.solr.AnalysisAfterCoreReloadTest.java

private void overwriteStopwords(String stopwords) throws IOException {
    try (SolrCore core = h.getCoreContainer().getCore(collection)) {
        String configDir = core.getResourceLoader().getConfigDir();
        FileUtils.moveFile(new File(configDir, "stopwords.txt"), new File(configDir, "stopwords.txt.bak"));
        File file = new File(configDir, "stopwords.txt");
        FileUtils.writeStringToFile(file, stopwords, "UTF-8");

    }/* ww w.j a  v  a 2s  . c  o m*/
}

From source file:org.apache.solr.AnalysisAfterCoreReloadTest.java

@Override
public void tearDown() throws Exception {
    String configDir;/*  w  w w . j  a va2 s  .c  o m*/
    try (SolrCore core = h.getCoreContainer().getCore(collection)) {
        configDir = core.getResourceLoader().getConfigDir();
    }
    super.tearDown();
    if (new File(configDir, "stopwords.txt.bak").exists()) {
        FileUtils.deleteQuietly(new File(configDir, "stopwords.txt"));
        FileUtils.moveFile(new File(configDir, "stopwords.txt.bak"), new File(configDir, "stopwords.txt"));
    }
}

From source file:org.apache.solr.schema.TestManagedSchema.java

public void testUpgradeThenRestartNonManagedAfterPuttingBackNonManagedSchema() throws Exception {
    assertSchemaResource(collection, "managed-schema");
    deleteCore();// w  ww.  j ava  2 s  .c om
    File nonManagedSchemaFile = new File(tmpConfDir, "schema-minimal.xml");
    assertFalse(nonManagedSchemaFile.exists());
    File upgradedOriginalSchemaFile = new File(tmpConfDir, "schema-minimal.xml.bak");
    assertTrue(upgradedOriginalSchemaFile.exists());

    // After upgrade to managed schema, downgrading to non-managed should work after putting back the non-managed schema.
    FileUtils.moveFile(upgradedOriginalSchemaFile, nonManagedSchemaFile);
    initCore("solrconfig-basic.xml", "schema-minimal.xml", tmpSolrHome.getPath());
    assertSchemaResource(collection, "schema-minimal.xml");
}