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.artifactory.logging.version.LoggingVersion.java

/**
 * Creates a backup of the existing logback configuration file and proceeds to save post-conversion content
 *
 * @param result Conversion result/*  w  w w.  j a  v a  2  s.c  o m*/
 * @param etcDir directory to which to save the conversion result
 */
public void backupAndSaveLogback(String result, File etcDir) throws IOException {
    File logbackConfigFile = new File(etcDir, ArtifactoryHome.LOGBACK_CONFIG_FILE_NAME);
    if (logbackConfigFile.exists()) {
        File originalBackup = new File(etcDir, "logback.original.xml");
        if (originalBackup.exists()) {
            FileUtils.deleteQuietly(originalBackup);
        }
        FileUtils.moveFile(logbackConfigFile, originalBackup);
    }

    FileUtils.writeStringToFile(logbackConfigFile, result, "utf-8");
}

From source file:org.artifactory.repo.service.DeployServiceImpl.java

private File extractArchive(BasicStatusHolder status, File archive) throws Exception {
    String archiveName = archive.getName();
    String fixedArchiveName = new String(archiveName.getBytes(Charsets.UTF_8.name()), Charsets.UTF_8);
    File fixedArchive = new File(archive.getParentFile(), fixedArchiveName);
    try {/*from   w  w  w.  ja va2s .c o m*/
        if (!fixedArchive.exists()) {
            FileUtils.moveFile(archive, fixedArchive);
        }
    } catch (IOException e) {
        throw new Exception("Could not encode archive name to UTF-8.", e);
    }
    File extractFolder = new File(ContextHelper.get().getArtifactoryHome().getTempUploadDir(),
            fixedArchive.getName() + "_extracted_" + System.currentTimeMillis());
    if (extractFolder.exists()) {
        //Clean up any existing folder
        try {
            FileUtils.deleteDirectory(extractFolder);
        } catch (IOException e) {
            status.error("Could not delete existing extracted archive folder: "
                    + extractFolder.getAbsolutePath() + ".", e, log);
            return null;
        }
    }
    try {
        FileUtils.forceMkdir(extractFolder);
    } catch (IOException e) {
        log.error("Could not created the extracted archive folder: " + extractFolder.getAbsolutePath() + ".",
                log);
        return null;
    }

    try {
        ZipUtils.extract(fixedArchive, extractFolder);
    } catch (Exception e) {
        FileUtils.deleteQuietly(extractFolder);
        if (e.getMessage() == null) {
            String errorMessage;
            if (e instanceof IllegalArgumentException) {
                errorMessage = "Please make sure the textual values in the archive are encoded in UTF-8.";
            } else {
                errorMessage = "Please ensure the integrity of the selected archive";
            }
            throw new Exception(errorMessage, e);
        }
        throw e;
    }
    return extractFolder;
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

/**
 * Renames the master key file, effectively disabling encryption.
 *//*from   ww w .  j a  va 2s  . c  o  m*/
public static void removeMasterKeyFile() {
    File keyFile = getMasterKeyFile();
    if (!keyFile.exists()) {
        throw new RuntimeException(
                "Cannot remove master key file if it does not exists at " + keyFile.getAbsolutePath());
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmsssSSS");
    File renamed = new File(
            keyFile + "." + new Random().nextInt((10000 - 1) + 1) + "." + format.format(new Date()));

    try {
        FileUtils.moveFile(keyFile, renamed);
    } catch (IOException e) {
        throw new RuntimeException("Could not rename master key file at " + keyFile.getAbsolutePath() + " to "
                + renamed.getAbsolutePath(), e);
    }
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

private void createArchive(ExportSettings settings, MutableStatusHolder status, String timestamp,
        File workingExportDir) {//from  ww  w  .  j a  v  a  2  s . com
    status.status("Creating archive...", log);

    File tempArchiveFile = new File(settings.getBaseDir(), timestamp + ".tmp.zip");
    try {
        ZipUtils.archive(workingExportDir, tempArchiveFile, true);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create system export archive.", e);
    }
    //Delete the temp export dir
    try {
        FileUtils.deleteDirectory(workingExportDir);
    } catch (IOException e) {
        log.warn("Failed to delete temp export directory.", e);
    }

    // From now on use only java.io.File for the file actions!

    //Delete any exiting final archive
    File archive = new File(settings.getBaseDir(), timestamp + ".zip");
    if (archive.exists()) {
        boolean deleted = archive.delete();
        if (!deleted) {
            status.warn("Failed to delete existing final export archive.", log);
        }
    }
    //Rename the archive file
    try {
        FileUtils.moveFile(tempArchiveFile, archive);
    } catch (IOException e) {
        status.error(String.format("Failed to move '%s' to '%s'.", tempArchiveFile.getAbsolutePath(),
                archive.getAbsolutePath()), e, log);
    } finally {
        settings.setOutputFile(archive.getAbsoluteFile());
    }
}

From source file:org.b3log.solo.service.ImportService.java

/**
 * Imports markdowns files as articles. See <a href="https://hacpai.com/article/1498490209748">Solo ? Hexo/Jekyll ?</a> for
 * more details./*w  w  w. j  a  v a2 s  . c  o m*/
 */
public void importMarkdowns() {
    new Thread(() -> {
        final ServletContext servletContext = SoloServletListener.getServletContext();
        final String markdownsPath = servletContext.getRealPath("markdowns");
        LOGGER.debug("Import directory [" + markdownsPath + "]");

        JSONObject admin;
        try {
            admin = userQueryService.getAdmin();
        } catch (final Exception e) {
            return;
        }

        if (null == admin) { // Not init yet
            return;
        }

        final String adminId = admin.optString(Keys.OBJECT_ID);

        int succCnt = 0, failCnt = 0;
        final Set<String> failSet = new TreeSet<>();
        final Collection<File> mds = FileUtils.listFiles(new File(markdownsPath), new String[] { "md" }, true);
        if (null == mds || mds.isEmpty()) {
            return;
        }

        for (final File md : mds) {
            final String fileName = md.getName();
            if (StringUtils.equalsIgnoreCase(fileName, "README.md")) {
                continue;
            }

            try {
                final String fileContent = FileUtils.readFileToString(md, "UTF-8");
                final JSONObject article = parseArticle(fileName, fileContent);
                article.put(Article.ARTICLE_AUTHOR_ID, adminId);

                final JSONObject request = new JSONObject();
                request.put(Article.ARTICLE, article);

                final String id = articleMgmtService.addArticle(request);
                FileUtils.moveFile(md, new File(md.getPath() + "." + id));
                LOGGER.info("Imported article [" + article.optString(Article.ARTICLE_TITLE) + "]");
                succCnt++;
            } catch (final Exception e) {
                LOGGER.log(Level.ERROR, "Import file [" + fileName + "] failed", e);

                failCnt++;
                failSet.add(fileName);
            }
        }

        if (0 == succCnt && 0 == failCnt) {
            return;
        }

        final StringBuilder logBuilder = new StringBuilder();
        logBuilder.append("[").append(succCnt).append("] imported, [").append(failCnt).append("] failed");
        if (failCnt > 0) {
            logBuilder.append(": ").append(Strings.LINE_SEPARATOR);

            for (final String fail : failSet) {
                logBuilder.append("    ").append(fail).append(Strings.LINE_SEPARATOR);
            }
        } else {
            logBuilder.append(" :p");
        }
        LOGGER.info(logBuilder.toString());
    }).start();
}

From source file:org.ballerinalang.stdlib.internal.file.MoveTo.java

@Override
public void execute(Context context) {
    BMap<String, BValue> sourcePathStruct = (BMap<String, BValue>) context.getRefArgument(0);
    Path sourcePath = (Path) sourcePathStruct.getNativeData(Constants.PATH_DEFINITION_NAME);

    BMap<String, BValue> targetPathStruct = (BMap<String, BValue>) context.getRefArgument(1);
    Path targetPath = (Path) targetPathStruct.getNativeData(Constants.PATH_DEFINITION_NAME);

    File source = new File(sourcePath.toString());
    File target = new File(targetPath.toString());
    try {//from w ww .  ja  va2  s  . c  o m
        if (source.isDirectory()) {
            FileUtils.moveDirectory(source, target);
        } else {
            FileUtils.moveFile(source, target);
        }
    } catch (IOException ex) {
        String msg = "IO error occurred while moving file/directory from: \'" + sourcePath + "\' to: \'"
                + targetPath + "\'. " + ex.getMessage();
        log.error(msg, ex);
        context.setReturnValues(BLangVMErrors.createError(context, msg));
    }
}

From source file:org.benetech.secureapp.generator.BuildingApkController.java

static private File renameApk(File apkCreated, AppConfiguration config) throws IOException {
    File finalFile = new File(apkCreated.getParent(), config.getApkName());
    FileUtils.moveFile(apkCreated, finalFile);
    return finalFile;
}

From source file:org.broadleafcommerce.cms.file.service.StaticAssetStorageServiceImpl.java

protected void createLocalFileFromInputStream(InputStream is, File baseLocalFile) throws IOException {
    FileOutputStream tos = null;//from  w ww. ja v  a2  s  .  co  m
    FileWorkArea workArea = null;
    try {
        if (!baseLocalFile.getParentFile().exists()) {
            boolean directoriesCreated = false;
            if (!baseLocalFile.getParentFile().exists()) {
                directoriesCreated = baseLocalFile.getParentFile().mkdirs();
                if (!directoriesCreated) {
                    // There is a chance that another VM created the directories.   If not, we may not have 
                    // proper permissions and this is an error we need to report.
                    if (!baseLocalFile.getParentFile().exists()) {
                        throw new RuntimeException("Unable to create middle directories for file: "
                                + baseLocalFile.getAbsolutePath());
                    }
                }
            }
        }

        workArea = broadleafFileService.initializeWorkArea();
        File tmpFile = new File(FilenameUtils.concat(workArea.getFilePathLocation(), baseLocalFile.getName()));

        tos = new FileOutputStream(tmpFile);

        IOUtils.copy(is, tos);

        // close the input/output streams before trying to move files around
        is.close();
        tos.close();

        // Adding protection against this file already existing / being written by another thread.
        // Adding locks would be useless here since another VM could be executing the code. 
        if (!baseLocalFile.exists()) {
            try {
                FileUtils.moveFile(tmpFile, baseLocalFile);
            } catch (FileExistsException e) {
                // No problem
                if (LOG.isDebugEnabled()) {
                    LOG.debug("File exists error moving file " + tmpFile.getAbsolutePath(), e);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(tos);

        if (workArea != null) {
            broadleafFileService.closeWorkArea(workArea);
        }
    }
}

From source file:org.broadleafcommerce.common.file.service.FileSystemFileServiceProvider.java

@Override
public List<String> addOrUpdateResourcesForPaths(FileWorkArea workArea, List<File> files,
        boolean removeFilesFromWorkArea) {
    List<String> result = new ArrayList<String>();
    for (File srcFile : files) {
        if (!srcFile.getAbsolutePath().startsWith(workArea.getFilePathLocation())) {
            throw new FileServiceException("Attempt to update file " + srcFile.getAbsolutePath()
                    + " that is not in the passed in WorkArea " + workArea.getFilePathLocation());
        }/*from  www  . ja v  a  2s .c  om*/

        String fileName = srcFile.getAbsolutePath().substring(workArea.getFilePathLocation().length());

        // before building the resource name, convert the file path to a url-like path
        String url = FilenameUtils.separatorsToUnix(fileName);
        String resourceName = buildResourceName(url);
        String destinationFilePath = FilenameUtils
                .normalize(getBaseDirectory(false) + File.separator + resourceName);
        File destFile = new File(destinationFilePath);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        try {
            if (removeFilesFromWorkArea) {
                if (destFile.exists()) {
                    FileUtils.deleteQuietly(destFile);
                }
                FileUtils.moveFile(srcFile, destFile);
            } else {
                FileUtils.copyFile(srcFile, destFile);
            }
            result.add(fileName);
        } catch (IOException ioe) {
            throw new FileServiceException("Error copying resource named " + fileName + " from workArea "
                    + workArea.getFilePathLocation() + " to " + resourceName, ioe);
        }
    }
    return result;
}

From source file:org.carrot2.workbench.core.ui.actions.ExportImageAction.java

@Override
public void run() {
    File tempFile = null;/*  w  w w. j  a  va2  s  .  c  o m*/
    OutputStream os = null;
    try {
        tempFile = File.createTempFile("capture", "png");
        os = new FileOutputStream(tempFile);
        this.imageStreamProvider.save(os);
        CloseableUtils.close(os);

        final Path path = openSavePNG(
                new Path("clusters-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".png"));

        if (path != null) {
            FileUtils.moveFile(tempFile, path.toFile());
        }
    } catch (IOException e) {
        CloseableUtils.close(os);
        if (tempFile != null)
            tempFile.delete();
    } finally {
        CloseableUtils.close(os);
    }
}