Example usage for java.io File renameTo

List of usage examples for java.io File renameTo

Introduction

In this page you can find the example usage for java.io File renameTo.

Prototype

public boolean renameTo(File dest) 

Source Link

Document

Renames the file denoted by this abstract pathname.

Usage

From source file:com.fluidops.iwb.api.solution.ZipFileBasedSolutionService.java

@Override
@SuppressWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "Rename result ignored on purpose.")
protected InstallationResult doInstall(File solutionZip, SolutionInfo solutionInfo) {
    if (solutionZip == null || !solutionZip.isFile())
        throw new IllegalStateException("File not found: " + solutionZip);

    try {/*from  w w  w .  jav a  2 s .com*/
        File unzippedRoot = File.createTempFile(getClass().getName(), "");
        try {
            delete(unzippedRoot);
            mkdirs(unzippedRoot);
            ZipUtil.unzip(solutionZip, unzippedRoot);
            InstallationResult solutionContext = solutionHandler.install(solutionInfo, unzippedRoot);
            if (solutionContext.getInstallationStatus().isSuccess())
                solutionZip.renameTo(new File(solutionZip.getParentFile(),
                        solutionZip.getName() + "." + DateTimeUtil.getDate("yyyyMMdd-HHmmss")));
            return solutionContext;
        } finally {
            GenUtil.deleteRec(unzippedRoot);
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.visural.stereotyped.ui.service.StereotypeServiceImpl.java

public void archive(UUID id) {
    int next = getNextFreeBackup(id);
    String path = getStereotypesPath() + "/" + id.toString() + STEREOTYPE_EXT;
    File in = new File(path);
    if (in.exists()) {
        in.renameTo(new File(path + "." + next));
    }/*from ww w  .  ja  v a 2  s  .  c o m*/
    __cacheData().invalidateCache(MethodCall.get(StereotypeServiceImpl.class, "read", id));
}

From source file:com.weibo.wesync.notify.xml.XMLProperties.java

/**
 * Creates a new XMLPropertiesTest object.
 *
 * @param file the file that properties should be read from and written to.
 * @throws IOException if an error occurs loading the properties.
 *//* ww  w  . j  a v a 2s.com*/
public XMLProperties(File file) throws IOException {
    this.file = file;
    if (!file.exists()) {
        // Attempt to recover from this error case by seeing if the
        // tmp file exists. It's possible that the rename of the
        // tmp file failed the last time Jive was running,
        // but that it exists now.
        File tempFile;
        tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
        if (tempFile.exists()) {
            tempFile.renameTo(file);
        }
        // There isn't a possible way to recover from the file not
        // being there, so throw an error.
        else {
            throw new FileNotFoundException("XML properties file does not exist: " + file.getName());
        }
    }
    // Check read and write privs.
    if (!file.canRead()) {
        throw new IOException("XML properties file must be readable: " + file.getName());
    }
    if (!file.canWrite()) {
        throw new IOException("XML properties file must be writable: " + file.getName());
    }

    FileReader reader = new FileReader(file);
    buildDoc(reader);
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

/**
 * ??//from  ww  w. j  a v  a2 s .c o m
 */
private void fuckNotDefinedRes_clearAddRes(File apkFile) throws IOException, ShakaException {
    if (notDefinedRes.size() <= 0) {
        return;
    }

    File tempFile = File.createTempFile(apkFile.getName(), null);
    tempFile.delete();
    tempFile.deleteOnExit();
    boolean renameOk = apkFile.renameTo(tempFile);
    if (!renameOk) {
        throw new ShakaException(
                "could not rename the file " + apkFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    try (ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
            ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(apkFile))) {
        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean toBeDeleted = false;
            for (String f : notDefinedRes) {
                if (f.equals(name)) {
                    toBeDeleted = true;
                    LogHelper.warning("Delete temp res : " + f);
                    break;
                }
            }
            if (!toBeDeleted) {
                // Add ZIP entry to output stream.
                zout.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                IOUtils.copy(zin, zout);
            }
            entry = zin.getNextEntry();
        }
    }

    tempFile.delete();
    notDefinedRes.clear();
}

From source file:com.geewhiz.pacify.filter.PacifyVelocityFilter.java

@Override
public LinkedHashSet<Defect> filter(PFile pFile, Map<String, String> propertyValues) {
    LinkedHashSet<Defect> defects = new LinkedHashSet<Defect>();

    if (!BEGIN_TOKEN.equals(pFile.getBeginToken())) {
        defects.add(new WrongTokenDefinedDefect(pFile, "If you use the PacifyVelocityFilter class, only \""
                + BEGIN_TOKEN + "\" is allowed as start token."));
    }//from  w w  w .  j  a v  a 2 s . c o m

    if (!END_TOKEN.equals(pFile.getEndToken())) {
        defects.add(new WrongTokenDefinedDefect(pFile, "If you use the PacifyVelocityFilter class, only \""
                + END_TOKEN + "\" is allowed as end token."));
    }

    if (!defects.isEmpty()) {
        return defects;
    }

    File fileToFilter = pFile.getFile();
    File tmpFile = FileUtils.createEmptyFileWithSamePermissions(fileToFilter);

    Template template = getTemplate(fileToFilter, pFile.getEncoding());
    Context context = getContext(propertyValues, fileToFilter);

    try {
        FileWriterWithEncoding fw = new FileWriterWithEncoding(tmpFile, pFile.getEncoding());
        template.merge(context, fw);
        fw.close();
        if (!fileToFilter.delete()) {
            throw new RuntimeException("Couldn't delete file [" + fileToFilter.getPath() + "]... Aborting!");
        }
        if (!tmpFile.renameTo(fileToFilter)) {
            throw new RuntimeException("Couldn't rename filtered file from [" + tmpFile.getPath() + "] to ["
                    + fileToFilter.getPath() + "]... Aborting!");
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return defects;
}

From source file:com.zimbra.cs.store.file.BlobConsistencyUtil.java

private void checkMailbox(int mboxId, SoapProvisioning prov) throws ServiceException {
    XMLElement request = new XMLElement(AdminConstants.CHECK_BLOB_CONSISTENCY_REQUEST);
    for (short volumeId : volumeIds) {
        request.addElement(AdminConstants.E_VOLUME).addAttribute(AdminConstants.A_ID, volumeId);
    }//from ww  w . j  a v  a 2 s . c  o m
    request.addElement(AdminConstants.E_MAILBOX).addAttribute(AdminConstants.A_ID, mboxId);
    request.addAttribute(AdminConstants.A_CHECK_SIZE, !skipSizeCheck);
    request.addAttribute(AdminConstants.A_REPORT_USED_BLOBS, outputUsedBlobs || usedBlobWriter != null);

    Element response = prov.invoke(request);
    for (Element mboxEl : response.listElements(AdminConstants.E_MAILBOX)) {
        // Print results.
        BlobConsistencyChecker.Results results = new BlobConsistencyChecker.Results(mboxEl);
        for (BlobInfo blob : results.missingBlobs.values()) {
            System.out.format("Mailbox %d, item %d, rev %d, %s: blob not found.\n", results.mboxId, blob.itemId,
                    blob.modContent, locatorText(blob));
        }
        for (BlobInfo blob : results.incorrectSize.values()) {
            System.out.format(
                    "Mailbox %d, item %d, rev %d, %s: incorrect data size.  Expected %d, was %d.  File size is %d.\n",
                    results.mboxId, blob.itemId, blob.modContent, locatorText(blob), blob.dbSize,
                    blob.fileDataSize, blob.fileSize);
        }
        for (BlobInfo blob : results.unexpectedBlobs.values()) {
            System.out.format("Mailbox %d, %s: unexpected blob.  File size is %d.\n", results.mboxId,
                    locatorText(blob), blob.fileSize);
            if (unexpectedBlobWriter != null) {
                unexpectedBlobWriter.println(blob.path);
            }
        }
        for (BlobInfo blob : results.incorrectModContent.values()) {
            System.out.format("Mailbox %d, item %d, rev %d, %s: file has incorrect revision.\n", results.mboxId,
                    blob.itemId, blob.modContent, locatorText(blob));
        }
        for (BlobInfo blob : results.usedBlobs.values()) {
            if (outputUsedBlobs) {
                System.out.format("Used blob: Mailbox %d, item %d, rev %d, %s.\n", results.mboxId, blob.itemId,
                        blob.version, locatorText(blob));
            }
            if (usedBlobWriter != null) {
                usedBlobWriter.println(blob.path);
            }
        }

        // Fix inconsistencies.
        if (missingBlobDeleteItem && results.missingBlobs.size() > 0) {
            exportAndDelete(prov, results);
        }
        if (incorrectRevisionRenameFile) {
            for (BlobInfo blob : results.incorrectModContent.values()) {
                File file = new File(blob.path);
                File dir = file.getParentFile();
                if (dir != null) {
                    File newFile = new File(dir, FileBlobStore.getFilename(blob.itemId, blob.modContent));
                    System.out.format("Renaming %s to %s.\n", file.getAbsolutePath(),
                            newFile.getAbsolutePath());
                    if (!file.renameTo(newFile)) {
                        System.err.format("Unable to rename %s to %s.\n", file.getAbsolutePath(),
                                newFile.getAbsolutePath());
                    }
                } else {
                    System.err.format("Could not determine parent directory of %s.\n", file.getAbsolutePath());
                }
            }
        }
    }
}

From source file:com.email.SendEmail.java

/**
 * Sends a single email and uses account based off of the section that the
 * email comes from after email is sent the attachments are gathered
 * together and collated into a single PDF file and a history entry is
 * created based off of that entry/*  w ww. ja  v a  2s. c  o m*/
 *
 * @param eml EmailOutModel
 */
public static void sendEmails(EmailOutModel eml) {
    SystemEmailModel account = null;

    String section = eml.getSection();
    if (eml.getSection().equalsIgnoreCase("Hearings") && (eml.getCaseType().equalsIgnoreCase("MED")
            || eml.getCaseType().equalsIgnoreCase("REP") || eml.getCaseType().equalsIgnoreCase("ULP"))) {
        section = eml.getCaseType();
    }

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(section)) {
            account = acc;
            break;
        }
    }

    //Account Exists?
    if (account != null) {
        //Case Location
        String casePath = (eml.getCaseType().equals("CSC") || eml.getCaseType().equals("ORG"))
                ? FileService.getCaseFolderORGCSCLocation(eml)
                : FileService.getCaseFolderLocation(eml);

        //Attachment List
        boolean allFilesExists = true;
        List<EmailOutAttachmentModel> attachmentList = EmailOutAttachment.getAttachmentsByEmail(eml.getId());

        for (EmailOutAttachmentModel attach : attachmentList) {
            File attachment = new File(casePath + attach.getFileName());
            boolean exists = attachment.exists();
            if (exists == false) {
                allFilesExists = false;
                SECExceptionsModel item = new SECExceptionsModel();
                item.setClassName("SendEmail");
                item.setMethodName("sendEmails");
                item.setExceptionType("FileMissing");
                item.setExceptionDescription("Can't Send Email, File Missing for EmailID: " + eml.getId()
                        + System.lineSeparator() + "EmailSubject: " + eml.getSubject() + System.lineSeparator()
                        + "File: " + attachment);

                ExceptionHandler.HandleNoException(item);

                break;
            } else {
                if ("docx".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))
                        || "doc".equalsIgnoreCase(FilenameUtils.getExtension(attach.getFileName()))) {
                    if (!attachment.renameTo(attachment)) {
                        allFilesExists = false;
                        SECExceptionsModel item = new SECExceptionsModel();
                        item.setClassName("SendEmail");
                        item.setMethodName("sendEmails");
                        item.setExceptionType("File In Use");
                        item.setExceptionDescription("Can't Send Email, File In Use for EmailID: " + eml.getId()
                                + System.lineSeparator() + "EmailSubject: " + eml.getSubject()
                                + System.lineSeparator() + "File: " + attachment);

                        ExceptionHandler.HandleNoException(item);
                        break;
                    }
                }
            }
        }

        if (allFilesExists) {
            //Set up Initial Merge Utility
            PDFMergerUtility ut = new PDFMergerUtility();

            //List ConversionPDFs To Delete Later
            List<String> tempPDFList = new ArrayList<>();

            //create email message body
            Date emailSentTime = new Date();
            String emailPDFname = EmailBodyToPDF.createEmailOutBody(eml, attachmentList, emailSentTime);

            //Add Email Body To PDF Merge
            try {
                ut.addSource(casePath + emailPDFname);
                tempPDFList.add(casePath + emailPDFname);
            } catch (FileNotFoundException ex) {
                ExceptionHandler.Handle(ex);
            }

            //Get parts
            String FromAddress = account.getEmailAddress();
            String[] TOAddressess = ((eml.getTo() == null) ? "".split(";") : eml.getTo().split(";"));
            String[] CCAddressess = ((eml.getCc() == null) ? "".split(";") : eml.getCc().split(";"));
            String[] BCCAddressess = ((eml.getBcc() == null) ? "".split(";") : eml.getBcc().split(";"));
            String emailSubject = eml.getSubject();
            String emailBody = eml.getBody();

            //Set Email Parts
            Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
            Properties properties = EmailProperties.setEmailOutProperties(account);
            Session session = Session.getInstance(properties, auth);
            MimeMessage smessage = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            //Add Parts to Email Message
            try {
                smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
                for (String To : TOAddressess) {
                    if (EmailValidator.getInstance().isValid(To)) {
                        smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                    }
                }
                for (String CC : CCAddressess) {
                    if (EmailValidator.getInstance().isValid(CC)) {
                        smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(CC));
                    }
                }
                for (String BCC : BCCAddressess) {
                    if (EmailValidator.getInstance().isValid(BCC)) {
                        smessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                    }
                }
                smessage.setSubject(emailSubject);

                MimeBodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(emailBody, "text/plain");
                multipart.addBodyPart(messageBodyPart);

                //get attachments
                for (EmailOutAttachmentModel attachment : attachmentList) {
                    String fileName = attachment.getFileName();
                    String extension = FilenameUtils.getExtension(fileName);

                    //Convert attachments to PDF
                    //If Image
                    if (FileService.isImageFormat(fileName)) {
                        fileName = ImageToPDF.createPDFFromImageNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Word Doc
                    } else if (extension.equals("docx") || extension.equals("doc")) {
                        fileName = WordToPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If Text File
                    } else if ("txt".equals(extension)) {
                        fileName = TXTtoPDF.createPDFNoDelete(casePath, fileName);

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                            tempPDFList.add(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }

                        //If PDF
                    } else if (FilenameUtils.getExtension(fileName).equals("pdf")) {

                        //Add Attachment To PDF Merge
                        try {
                            ut.addSource(casePath + fileName);
                        } catch (FileNotFoundException ex) {
                            ExceptionHandler.Handle(ex);
                        }
                    }

                    DataSource source = new FileDataSource(casePath + fileName);
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(fileName);
                    multipart.addBodyPart(messageBodyPart);
                }
                smessage.setContent(multipart);

                //Send Message
                if (Global.isOkToSendEmail()) {
                    Transport.send(smessage);
                } else {
                    Audit.addAuditEntry("Email Not Actually Sent: " + eml.getId() + " - " + emailSubject);
                }

                //DocumentFileName
                String savedDoc = (String.valueOf(new Date().getTime()) + "_" + eml.getSubject())
                        .replaceAll("[:\\\\/*?|<>]", "_") + ".pdf";

                //Set Merge File Destination
                ut.setDestinationFileName(casePath + savedDoc);

                //Try to Merge
                try {
                    ut.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
                } catch (IOException ex) {
                    ExceptionHandler.Handle(ex);
                }

                //Add emailBody Activity
                addEmailActivity(eml, savedDoc, emailSentTime);

                //Copy to related case folders
                if (section.equals("MED")) {
                    List<RelatedCaseModel> relatedMedList = RelatedCase.getRelatedCases(eml);
                    if (relatedMedList.size() > 0) {
                        for (RelatedCaseModel related : relatedMedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                } else {
                    //This is blanket and should grab all related cases. (UNTESTED outside of CMDS)
                    List<EmailOutRelatedCaseModel> relatedList = EmailOutRelatedCase.getRelatedCases(eml);
                    if (relatedList.size() > 0) {
                        for (EmailOutRelatedCaseModel related : relatedList) {

                            //Copy finalized document to proper folder
                            File srcFile = new File(casePath + savedDoc);

                            File destPath = new File((section.equals("CSC") || section.equals("ORG"))
                                    ? FileService.getCaseFolderORGCSCLocation(related)
                                    : FileService.getCaseFolderLocationEmailOutRelatedCase(related));
                            destPath.mkdirs();

                            try {
                                FileUtils.copyFileToDirectory(srcFile, destPath);
                            } catch (IOException ex) {
                                Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
                            }

                            //Add Related Case Activity Entry
                            addEmailOutActivityRelatedCase(eml, related, savedDoc, emailSentTime);
                        }
                    }
                }

                //Clean SQL entries
                EmailOut.deleteEmailEntry(eml.getId());
                EmailOutAttachment.deleteAttachmentsForEmail(eml.getId());
                EmailOutRelatedCase.deleteEmailOutRelatedForEmail(eml.getId());

                //Clean up temp PDFs
                for (String tempPDF : tempPDFList) {
                    new File(tempPDF).delete();
                }

            } catch (AddressException ex) {
                ExceptionHandler.Handle(ex);
            } catch (MessagingException ex) {
                ExceptionHandler.Handle(ex);
            }
        }
    }
}

From source file:com.l2jfree.gameserver.cache.CrestCache.java

public void convertOldPedgeFiles() {
    File dir = new File(Config.DATAPACK_ROOT, "data/crests/");

    File[] files = dir.listFiles(new OldPledgeFilter());

    if (files == null)
        files = new File[0];

    for (File file : files) {
        int clanId = Integer.parseInt(file.getName().substring(7, file.getName().length() - 4));

        _log.info("Found old crest file \"" + file.getName() + "\" for clanId " + clanId);

        int newId = IdFactory.getInstance().getNextId();

        L2Clan clan = ClanTable.getInstance().getClan(clanId);

        if (clan != null) {
            removeOldPledgeCrest(clan.getCrestId());

            file.renameTo(new File(Config.DATAPACK_ROOT, "data/crests/Crest_" + newId + ".bmp"));
            _log.info("Renamed Clan crest to new format: Crest_" + newId + ".bmp");

            Connection con = null;

            try {
                con = L2DatabaseFactory.getInstance().getConnection(con);
                PreparedStatement statement = con
                        .prepareStatement("UPDATE clan_data SET crest_id = ? WHERE clan_id = ?");
                statement.setInt(1, newId);
                statement.setInt(2, clan.getClanId());
                statement.executeUpdate();
                statement.close();//from  ww w .  j  av a2s .com
            } catch (SQLException e) {
                _log.warn("Could not update the crest id:", e);
            } finally {
                L2DatabaseFactory.close(con);
            }

            clan.setCrestId(newId);
            clan.setHasCrest(true);
        } else {
            _log.info("Clan Id: " + clanId + " does not exist in table.. deleting.");
            file.delete();
        }
    }
}

From source file:me.neatmonster.spacertk.actions.PluginActions.java

/**
 * Disables a plugin/*from  w  w w. j a  va2  s .  c om*/
 * @param pluginName Plugin to disable
 * @return If successful
 */
@Action(aliases = { "disable", "pluginDisable" })
public boolean disable(final String pluginName) {
    final File pluginFile = pluginsManager.getPluginFile(pluginName);
    if (pluginFile == null)
        return false;
    final boolean wasRunning = RemoteToolkit.isRunning();
    if (wasRunning)
        RemoteToolkit.hold();
    while (RemoteToolkit.isRunning())
        try {
            Thread.sleep(1000);
        } catch (final InterruptedException e) {
            e.printStackTrace();
        }
    final boolean result = pluginFile.renameTo(new File(pluginFile.getPath() + ".DISABLED"));
    if (wasRunning)
        RemoteToolkit.unhold();
    return result;
}