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:com.fota.firmMgt.controller.FirmUpdateCTR.java

/**
 *  ?/* www  .  j av  a 2 s .c om*/
 * @param vo
 * @param model
 * @return
 */
@RequestMapping(value = "/add")
@ResponseBody
public ModelAndView add(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("firmUpdateVO") FirmUpdateVO vo, ModelMap model) throws Exception {
    if (PropUtil.getPropValue("onm.mode").equals("P")) {
        Runtime.getRuntime()
                .exec("sudo mount -t nfs 10.220.250.11:/vol/vol2/c-dms-pd1-w01 /home/jboss/firmware");
        logger.warn("Firmware Modify - File Upload Start... "
                + "( Mount On : sudo mount -t nfs 10.220.250.11:/vol/vol2/c-dms-pd1-w01 /home/jboss/firmware )");
        // ?? ?  ?  2~3     sleep 3 
        Thread.sleep(3000);
    }

    Date now = new Date();
    logger.info("File update start : " + now.toString());

    //    ? ?
    File temp_folder = new File(DEFAULT_PATH);
    if (!temp_folder.exists() || !temp_folder.isDirectory()) {
        temp_folder.mkdirs();
    }

    // ?? : 500M
    int maxfilesize = 500 * 1024 * 1024;
    MultipartRequest multi = null;
    File upfile = null;

    try {
        //  ?
        multi = new MultipartRequest(request, DEFAULT_PATH, maxfilesize, "utf-8");
        upfile = new File(DEFAULT_PATH + multi.getFilesystemName("file"));

        vo.setFileName(VoV.valid(upfile.getName(), 200, 8));
        vo.setFileSize(Integer.parseInt(String.valueOf(upfile.length())));

        //vo.setBizTypeId(VoV.valid(multi.getParameter("bizTypeId"), 30, 4));
        //vo.setSvcId(VoV.valid(multi.getParameter("svcId"), 30, 4));
        //vo.setMakerId(VoV.valid(multi.getParameter("makerId"), 30, 4));
        vo.setDevModelId(VoV.valid(multi.getParameter("devModelId"), 30, 4));
        vo.setFotaType(VoV.valid(multi.getParameter("fotaType"), 50));
        if (!vo.getFotaType().equals("") && !vo.getFotaType().equals("PUSH")
                && !vo.getFotaType().equals("POLLING") && !vo.getFotaType().equals("PUSHPOLLING"))
            throw new Exception();

        vo.setFirmwareId(VoV.valid(multi.getParameter("firmwareId"), 30, 4));
        //vo.setFirmwareDesc(VoV.valid(multi.getParameter("firmwareDesc"), 1000, 9));
        vo.setFirmwareVer(VoV.valid(multi.getParameter("firmwareVer"), 100, 4));
        vo.setFirmwareMakerVer(VoV.valid(multi.getParameter("firmwareMakerVer"), 100, 8));
        vo.setVerMemo(VoV.valid(multi.getParameter("verMemo"), 1000, 9));

        //   ? ?
        String path = DEFAULT_PATH + vo.getDevModelId() + "/";
        File pysicalfolder = new File(path);
        if (!pysicalfolder.exists() || !pysicalfolder.isDirectory()) {
            pysicalfolder.mkdirs();
        }
        vo.setFilePath(VoV.valid(path, 200));

        //  ???
        File destFile = new File(path + upfile.getName());
        if (destFile.exists()) {
            destFile.delete();
        }
        FileUtils.moveFile(upfile, destFile);

        //CRC, '0' 
        vo.setCrc("0");
        vo.setCretNm(((UserLoginVO) request.getSession().getAttribute("userInfo")).getUserNm());

    } catch (Exception e) { //  ?? 
        // ??? ? ? 
        if (upfile != null && upfile.exists()) {
            upfile.delete();
        }

        String errorMSG = e.getMessage();
        if (errorMSG.indexOf("exceeds") != 0) {
            model.addAttribute("error", "?? 500MB ?.");
        }

        logger.info("File update error : " + errorMSG);
        response.setStatus(500);
        return new ModelAndView(ajaxMainView, model);
    }

    mySVC.add(vo);

    now = new Date();
    logger.info("File update end : " + now.toString());

    //      Runtime.getRuntime().exec("sudo umount /home/jboss/firmware");
    //      logger.warn("Firmware Modify - File Upload end... "
    //            + "( Mount Off : sudo umount /home/jboss/firmware )");

    return new ModelAndView(ajaxMainView, model);
}

From source file:edu.umn.msi.tropix.common.io.FileUtilsImpl.java

public void moveFile(final File sourceFile, final File destFile) {
    try {/*from  ww w  .j  av  a2 s .com*/
        FileUtils.moveFile(sourceFile, destFile);
    } catch (final IOException e) {
        throw new IORuntimeException(e);
    }
}

From source file:com.ettrema.zsync.IntegrationTests.java

/**
 * Reads the ZSync upload data that was saved to uploadFile, constructs an UploadReader
 * to assemble the new file, and saves (and returns) the assembled file as fileName
 * // www. j a  va  2  s.c om
 * @param uploadFile A file containing the data from an upload
 * @param fileName The pathname String (with file name included)
 * @return The assembled File
 * @throws IOException
 * @throws ParseException
 */
private File readSavedUpload(File uploadFile, String fileName, File serverFile)
        throws IOException, ParseException {

    InputStream uploadIn = new FileInputStream(uploadFile);
    UploadReader um = new UploadReader(serverFile, uploadIn);

    File assembledFile = new File(fileName);
    if (assembledFile.exists()) {
        if (!assembledFile.delete()) {
            throw new RuntimeException(
                    "Couldnt delete previous assembled file: " + assembledFile.getAbsolutePath());
        }
    }
    long tm = System.currentTimeMillis();
    File tempAssembled = um.assemble();
    tm = System.currentTimeMillis() - tm;
    System.out.println("Assembled file in: " + tm + "ms");
    FileUtils.moveFile(tempAssembled, assembledFile);

    uploadIn.close();
    System.out.println("Assesmbled to: " + assembledFile.getAbsolutePath());
    return assembledFile;

}

From source file:com.abiquo.am.services.filesystem.TemplateFileSystem.java

public static void copyFileToTemplatePath(final String packagePath, final File file) {
    // Transfer the upload content into the repository file system
    final String filePath = packagePath + file.getName();

    File f = new File(filePath);
    // TODO check do not exist and can be created

    try {//from ww  w .  ja v a 2  s  .  c  om
        FileUtils.moveFile(file, f);
    } catch (IOException e) {
        throw new AMException(AMError.DISK_FILE_MOVE, packagePath, e);

    }
}

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

/**
 * Write the given 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  ww w.  j  a  v a 2s .  c o m
 * @param configuration
 *            Configuration instance
 * @throws IOException
 */
public synchronized void write(Configuration 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("config", 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:net.ftb.util.FTBFileUtils.java

public static void move(File oldFile, File newFile) {
    try {/*from  w w w .j  a v a 2 s.  c  om*/
        if (oldFile.exists() && !newFile.exists()) {
            FileUtils.moveFile(oldFile, newFile);
        }
    } catch (IOException e) {
        Logger.logWarn("Exception occurred while moving " + oldFile.toString() + " : " + e.getMessage());
    }
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

private void encryptZipFolder(String returnPath) throws IOException {
    boolean enableEncryption = Boolean.parseBoolean(PdiConfig.getProperty(Constants.DOWNLOAD_ZIP_ENCRYPTION));

    if (enableEncryption) {
        String tFileName = returnPath.concat("_temp.zip");
        LOGGER.info("Deleted un-zipped folder {}", tFileName);

        File tFile = new File(tFileName);
        String srcFile = returnPath.concat(ZIP);
        FileUtils.moveFile(new File(srcFile), tFile);
        AESEncrypter encrypter = new AESEncrypter();
        encrypter.encrypt(tFileName, srcFile);
        if (!tFile.delete()) {
            LOGGER.error("ERROR in delelting zip folder path" + tFileName);
        }/*from   w  w w .  j  a  va  2 s. com*/
        LOGGER.info("Encrypted folder {}", srcFile);
    }
}

From source file:com.seleniumtests.ut.reporter.TestTestStep.java

/**
 * Check we get all files from a step and its sub steps
 * @throws IOException/*from  ww  w  . j ava 2s  . c  o  m*/
 */
@Test(groups = { "ut" })
public void testListAllAttachments() throws IOException {
    TestStep step = new TestStep("step1", null, new ArrayList<>());

    // create screenshot for main step
    ScreenShot screenshot1 = new ScreenShot();

    File tmpImgFile = File.createTempFile("img", ".png");
    File tmpImgFile2 = Paths.get(tmpImgFile.getParent(), "screenshots", tmpImgFile.getName()).toFile();
    FileUtils.moveFile(tmpImgFile, tmpImgFile2);
    File tmpHtmlFile = File.createTempFile("html", ".html");
    File tmpHtmlFile2 = Paths.get(tmpHtmlFile.getParent(), "htmls", tmpHtmlFile.getName()).toFile();
    FileUtils.moveFile(tmpHtmlFile, tmpHtmlFile2);

    screenshot1.setOutputDirectory(tmpImgFile.getParent());
    screenshot1.setLocation("http://mysite.com");
    screenshot1.setTitle("mysite");
    screenshot1.setImagePath("screenshots/" + tmpImgFile2.getName());
    screenshot1.setHtmlSourcePath("htmls/" + tmpHtmlFile2.getName());
    step.addSnapshot(new Snapshot(screenshot1), 0, null);

    TestStep subStep = new TestStep("subStep", null, new ArrayList<>());

    // create screenshot for sub step
    ScreenShot screenshot2 = new ScreenShot();

    File tmpImgFile3 = File.createTempFile("img", ".png");
    File tmpImgFile4 = Paths.get(tmpImgFile3.getParent(), "screenshots", tmpImgFile3.getName()).toFile();
    FileUtils.moveFile(tmpImgFile3, tmpImgFile4);

    screenshot2.setOutputDirectory(tmpImgFile3.getParent());
    screenshot2.setLocation("http://mysite.com");
    screenshot2.setTitle("mysite");
    screenshot2.setImagePath("screenshots/" + tmpImgFile4.getName());
    subStep.addSnapshot(new Snapshot(screenshot2), 0, null);

    subStep.addAction(new TestAction("action1", true, new ArrayList<>()));
    step.addAction(new TestAction("action2", false, new ArrayList<>()));
    step.addAction(subStep);

    List<File> attachments = step.getAllAttachments();
    Assert.assertEquals(attachments.size(), 3);
    Assert.assertEquals(attachments.get(0).getName(), "N-A_0-1_step1-" + tmpHtmlFile2.getName());
    Assert.assertEquals(attachments.get(1).getName(), "N-A_0-1_step1-" + tmpImgFile2.getName());
    Assert.assertEquals(attachments.get(2).getName(), "N-A_0-1_subStep-" + tmpImgFile4.getName());
}

From source file:com.blackducksoftware.integration.hub.cli.CLIDownloadService.java

private void updateJreSecurity(final IntLogger logger, CLILocation cliLocation,
        CIEnvironmentVariables ciEnvironmentVariables) throws IOException {
    final String cacertsFilename = "cacerts";
    if (ciEnvironmentVariables.containsKey(CIEnvironmentVariables.BDS_CACERTS_OVERRIDE)) {
        final File securityDirectory = cliLocation.getJreSecurityDirectory();
        if (securityDirectory == null) {
            // the cli might not have the jre included
            return;
        }/*www.jav  a  2  s.c o m*/
        final String customCacertsPath = ciEnvironmentVariables
                .getValue(CIEnvironmentVariables.BDS_CACERTS_OVERRIDE);
        final File customCacerts = new File(customCacertsPath);

        final File cacerts = new File(securityDirectory, cacertsFilename);
        final File cacertsBackup = new File(securityDirectory, cacertsFilename + System.currentTimeMillis());

        try {
            FileUtils.moveFile(cacerts, cacertsBackup);
            FileUtils.copyFile(customCacerts, cacerts);
        } catch (final IOException e) {
            logger.error("Could not copy the custom cacerts file from: " + customCacertsPath + " to: "
                    + cacerts.getAbsolutePath() + " msg: " + e.getMessage());
            throw e;
        }
    }
}

From source file:com.fota.firmMgt.controller.FirmRegiCTR.java

/**
 *  ?// w  ww  .java 2 s  .  co  m
 * @param vo
 * @param model
 * @return
 */
@RequestMapping(value = "/regi")
@ResponseBody
public ModelAndView regi(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute("firmUpdateVO") FirmUpdateVO vo, ModelMap model) throws Exception {
    if (PropUtil.getPropValue("onm.mode").equals("P")) {
        Runtime.getRuntime()
                .exec("sudo mount -t nfs 10.220.250.11:/vol/vol2/c-dms-pd1-w01 /home/jboss/firmware");
        logger.warn("Firmware Regist - File Upload Start... "
                + "( Mount On : sudo mount -t nfs 10.220.250.11:/vol/vol2/c-dms-pd1-w01 /home/jboss/firmware )");

        // ?? ?  ?  2~3     sleep 3 
        Thread.sleep(3000);
    }

    Date now = new Date();
    logger.info("File update start : " + now.toString());

    //    ? ?
    File temp_folder = new File(DEFAULT_PATH);
    if (!temp_folder.exists() || !temp_folder.isDirectory()) {
        temp_folder.mkdirs();
    }

    // ?? : 500M
    int maxfilesize = 500 * 1024 * 1024;
    MultipartRequest multi = null;
    File upfile = null;

    try {
        //  ?
        multi = new MultipartRequest(request, DEFAULT_PATH, maxfilesize, "utf-8");
        upfile = new File(DEFAULT_PATH + multi.getFilesystemName("file"));

        vo.setFileName(VoV.valid(upfile.getName(), 200, 8));
        //         2015-10-07
        //         vo.setFileSize(String.valueOf(upfile.length()));
        vo.setFileSize(Integer.parseInt(String.valueOf(upfile.length())));

        vo.setBizTypeId(VoV.valid(multi.getParameter("bizTypeId"), 30));
        vo.setSvcId(VoV.valid(multi.getParameter("svcId"), 30, 4));
        vo.setMakerId(VoV.valid(multi.getParameter("makerId"), 30, 4));
        vo.setDevModelId(VoV.valid(multi.getParameter("devModelId"), 30, 4));
        vo.setFotaType(VoV.valid(multi.getParameter("fotaType"), 50));
        if (!vo.getFotaType().equals("") && !vo.getFotaType().equals("PUSH")
                && !vo.getFotaType().equals("POLLING") && !vo.getFotaType().equals("PUSHPOLLING"))
            throw new Exception();

        //vo.setFirmwareId(VoV.valid(multi.getParameter("firmwareId"), 30, 4));
        //vo.setFirmwareDesc(VoV.valid(multi.getParameter("firmwareDesc"), 1000, 9));
        vo.setFirmwareVer(VoV.valid(multi.getParameter("firmwareVer"), 100, 4));
        vo.setFirmwareMakerVer(VoV.valid(multi.getParameter("firmwareMakerVer"), 100, 8));
        vo.setVerMemo(VoV.valid(multi.getParameter("verMemo"), 1000, 9));

        //   ? ?
        String path = DEFAULT_PATH + vo.getDevModelId() + "/";
        File pysicalfolder = new File(path);
        if (!pysicalfolder.exists() || !pysicalfolder.isDirectory()) {
            pysicalfolder.mkdirs();
        }
        vo.setFilePath(VoV.valid(path, 200));

        //  ???
        File destFile = new File(path + upfile.getName());
        if (destFile.exists()) {
            destFile.delete();
        }
        FileUtils.moveFile(upfile, destFile);

        //CRC, '0' 
        vo.setCrc("0");
        vo.setCretNm(((UserLoginVO) request.getSession().getAttribute("userInfo")).getUserNm());

    } catch (Exception e) { //  ?? 
        // ??? ? ? 
        if (upfile != null && upfile.exists()) {
            upfile.delete();
        }

        String errorMSG = e.getMessage();
        if (errorMSG.indexOf("exceeds") != 0) {
            model.addAttribute("error", "?? 500MB ?.");
        }

        logger.info("File update error : " + errorMSG);
        response.setStatus(500);
        return new ModelAndView(ajaxMainView, model);
    }

    mySVC.regi(vo);

    now = new Date();
    logger.info("File update end : " + now.toString());

    //      Runtime.getRuntime().exec("sudo umount /home/jboss/firmware");
    //      logger.warn("Firmware Regist - File Upload end... "
    //            + "( Mount Off : sudo umount /home/jboss/firmware )");

    return new ModelAndView(ajaxMainView, model);
}