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.opennms.upgrade.implementations.JmxRrdMigratorOffline.java

/**
 * Fixes a JMX graph template file.//from   www.  j av a  2 s  .  co  m
 *
 * @param jmxTemplateFile the JMX template file
 * @throws OnmsUpgradeException the OpenNMS upgrade exception
 */
private void fixJmxGraphTemplateFile(File jmxTemplateFile) throws OnmsUpgradeException {
    try {
        log("Updating JMX graph templates on %s\n", jmxTemplateFile);
        zipFile(jmxTemplateFile);
        backupFiles.add(new File(jmxTemplateFile.getAbsolutePath() + ZIP_EXT));
        File outputFile = new File(jmxTemplateFile.getCanonicalFile() + ".temp");
        FileWriter w = new FileWriter(outputFile);
        Pattern defRegex = Pattern.compile("DEF:.+:(.+\\..+):");
        Pattern colRegex = Pattern.compile("\\.columns=(.+)$");
        Pattern incRegex = Pattern.compile("^include.directory=(.+)$");
        List<File> externalFiles = new ArrayList<File>();
        boolean override = false;
        LineIterator it = FileUtils.lineIterator(jmxTemplateFile);
        while (it.hasNext()) {
            String line = it.next();
            Matcher m = incRegex.matcher(line);
            if (m.find()) {
                File includeDirectory = new File(jmxTemplateFile.getParentFile(), m.group(1));
                if (includeDirectory.isDirectory()) {
                    FilenameFilter propertyFilesFilter = new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return (name.endsWith(".properties"));
                        }
                    };
                    for (File file : includeDirectory.listFiles(propertyFilesFilter)) {
                        externalFiles.add(file);
                    }
                }
            }
            m = colRegex.matcher(line);
            if (m.find()) {
                String[] badColumns = m.group(1).split(",(\\s)?");
                for (String badDs : badColumns) {
                    String fixedDs = getFixedDsName(badDs);
                    if (fixedDs.equals(badDs)) {
                        continue;
                    }
                    if (badMetrics.contains(badDs)) {
                        override = true;
                        log("  Replacing bad data source %s with %s on %s\n", badDs, fixedDs, line);
                        line = line.replaceAll(badDs, fixedDs);
                    } else {
                        log("  Warning: a bad data source not related with JMX has been found: %s (this won't be updated)\n",
                                badDs);
                    }
                }
            }
            m = defRegex.matcher(line);
            if (m.find()) {
                String badDs = m.group(1);
                if (badMetrics.contains(badDs)) {
                    override = true;
                    String fixedDs = getFixedDsName(badDs);
                    log("  Replacing bad data source %s with %s on %s\n", badDs, fixedDs, line);
                    line = line.replaceAll(badDs, fixedDs);
                } else {
                    log("  Warning: a bad data source not related with JMX has been found: %s (this won't be updated)\n",
                            badDs);
                }
            }
            w.write(line + "\n");
        }
        LineIterator.closeQuietly(it);
        w.close();
        if (override) {
            FileUtils.deleteQuietly(jmxTemplateFile);
            FileUtils.moveFile(outputFile, jmxTemplateFile);
        } else {
            FileUtils.deleteQuietly(outputFile);
        }
        if (!externalFiles.isEmpty()) {
            for (File configFile : externalFiles) {
                fixJmxGraphTemplateFile(configFile);
            }
        }
    } catch (Exception e) {
        throw new OnmsUpgradeException("Can't fix " + jmxTemplateFile + " because " + e.getMessage(), e);
    }
}

From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java

/**
 * Process single files.// w w w  .j a  v  a 2 s  .  c  o  m
 *
 * @param resourceDir the resource directory
 * @param isRrdtool the is RRDtool enabled
 * @throws Exception the exception
 */
private void processSingleFiles(File resourceDir, boolean isRrdtool) throws Exception {
    // META
    final String metaExt = ".meta";
    File[] metaFiles = getFiles(resourceDir, metaExt);
    if (metaFiles == null) {
        log("Warning: there are no %s files on %s\n", metaExt, resourceDir);
    } else {
        for (final File metaFile : metaFiles) {
            log("Processing META %s\n", metaFile);
            String dsName = metaFile.getName().replaceFirst(metaExt, "");
            String newName = getFixedDsName(dsName);
            if (!dsName.equals(newName)) {
                Properties meta = new Properties();
                Properties newMeta = new Properties();
                try (FileReader fr = new FileReader(metaFile);) {
                    meta.load(fr);
                    for (Object k : meta.keySet()) {
                        String key = (String) k;
                        String newKey = key.replaceAll(dsName, newName);
                        newMeta.put(newKey, newName);
                    }
                    File newFile = new File(metaFile.getParentFile(), newName + metaExt);
                    log("Re-creating META into %s\n", newFile);
                    try (FileWriter fw = new FileWriter(newFile);) {
                        newMeta.store(fw, null);
                    }
                    if (!metaFile.equals(newFile)) {
                        if (!metaFile.delete()) {
                            LOG.warn("Could not delete file {}", metaFile.getPath());
                        }
                    }
                }
            }
        }
    }
    // JRBs
    final String rrdExt = getRrdExtension();
    File[] jrbFiles = getFiles(resourceDir, rrdExt);
    if (jrbFiles == null) {
        log("Warning: there are no %s files on %s\n", rrdExt, resourceDir);
    } else {
        for (final File jrbFile : jrbFiles) {
            log("Processing %s %s\n", rrdExt.toUpperCase(), jrbFile);
            String dsName = jrbFile.getName().replaceFirst(rrdExt, "");
            String newName = getFixedDsName(dsName);
            File newFile = new File(jrbFile.getParentFile(), newName + rrdExt);
            if (!dsName.equals(newName)) {
                try {
                    log("Renaming %s to %s\n", rrdExt.toUpperCase(), newFile);
                    FileUtils.moveFile(jrbFile, newFile);
                } catch (Exception e) {
                    log("Warning: Can't move file because: %s", e.getMessage());
                    continue;
                }
            }
            if (!isRrdtool) { // Only the JRBs may contain invalid DS inside
                updateJrb(newFile);
            }
        }
    }
}

From source file:org.opennms.upgrade.implementations.JmxRrdMigratorOffline.java

/**
 * Process group files.// w  ww.j  av  a 2 s.  c o m
 *
 * @param resourceDir the resource directory
 * @param isRrdtool the is RRDtool enabled
 * @throws Exception the exception
 */
private void processGroupFiles(File resourceDir, boolean isRrdtool) throws Exception {
    // DS
    File dsFile = new File(resourceDir, "ds.properties");
    log("Processing DS %s\n", dsFile);
    if (dsFile.exists()) {
        Properties dsProperties = new Properties();
        Properties newDsProperties = new Properties();
        try (FileReader fr = new FileReader(dsFile);) {
            dsProperties.load(fr);
            for (Object key : dsProperties.keySet()) {
                String oldName = (String) key;
                String newName = getFixedDsName(oldName);
                String oldFile = dsProperties.getProperty(oldName);
                String newFile = getFixedFileName(oldFile);
                newDsProperties.put(newName, newFile);
            }
            try (FileWriter fw = new FileWriter(dsFile);) {
                newDsProperties.store(new FileWriter(dsFile), null);
            }
        }
    }
    // META
    final String metaExt = ".meta";
    File[] metaFiles = getFiles(resourceDir, metaExt);
    if (metaFiles == null) {
        log("Warning: there are no %s files on %s\n", metaExt, resourceDir);
    } else {
        for (final File metaFile : metaFiles) {
            log("Processing META %s\n", metaFile);
            Properties meta = new Properties();
            Properties newMeta = new Properties();
            try (FileReader fr = new FileReader(metaFile);) {
                meta.load(fr);
                for (Object k : meta.keySet()) {
                    String key = (String) k;
                    String dsName = meta.getProperty(key);
                    String newName = getFixedDsName(dsName);
                    String newKey = key.replaceAll(dsName, newName);
                    newMeta.put(newKey, newName);
                }
                File newFile = new File(metaFile.getParentFile(),
                        getFixedFileName(metaFile.getName().replaceFirst(metaExt, "")) + metaExt);
                log("Recreating META into %s\n", newFile);
                try (FileWriter fw = new FileWriter(newFile);) {
                    newMeta.store(fw, null);
                }
                if (!metaFile.equals(newFile)) {
                    if (!metaFile.delete()) {
                        LOG.warn("Could not delete file: {}", metaFile.getPath());
                    }
                }
            }
        }
    }
    // JRBs
    final String rrdExt = getRrdExtension();
    File[] jrbFiles = getFiles(resourceDir, rrdExt);
    if (jrbFiles == null) {
        log("Warning: there are no %s files on %s\n", rrdExt, resourceDir);
    } else {
        for (final File jrbFile : jrbFiles) {
            log("Processing %s %s\n", rrdExt.toUpperCase(), jrbFile);
            File newFile = new File(jrbFile.getParentFile(),
                    getFixedFileName(jrbFile.getName().replaceFirst(rrdExt, "")) + rrdExt);
            if (!jrbFile.equals(newFile)) {
                try {
                    log("Renaming %s to %s\n", rrdExt.toUpperCase(), newFile);
                    FileUtils.moveFile(jrbFile, newFile);
                } catch (Exception e) {
                    log("Warning: Can't move file because: %s", e.getMessage());
                    continue;
                }
            }
            if (!isRrdtool) { // Only the JRBs may contain invalid DS inside
                updateJrb(newFile);
            }
        }
    }
}

From source file:org.opennms.upgrade.implementations.SnmpInterfaceRrdMigratorOnline.java

/**
 * Merge RRDs.//from  w ww.j a  va  2s. c o m
 *
 * @param source the source RRD
 * @param dest the destination RRD
 * @throws Exception the exception
 */
protected void mergeRrd(File source, File dest) throws Exception {
    log("  merging RRD %s into %s\n", source, dest);
    RRDv3 rrdSrc = RrdConvertUtils.dumpRrd(source);
    RRDv3 rrdDst = RrdConvertUtils.dumpRrd(dest);
    if (rrdSrc == null || rrdDst == null) {
        log("  Warning: can't load RRDs (ingoring merge).\n");
        return;
    }
    rrdDst.merge(rrdSrc);
    final File outputFile = new File(dest.getCanonicalPath() + ".merged");
    RrdConvertUtils.restoreRrd(rrdDst, outputFile);
    if (dest.exists()) {
        FileUtils.deleteQuietly(dest);
    }
    FileUtils.moveFile(outputFile, dest);
}

From source file:org.opennms.upgrade.implementations.SnmpInterfaceRrdMigratorOnline.java

/**
 * Merge JRBs.//from  ww  w. j  a v a 2  s .  com
 *
 * @param source the source JRB
 * @param dest the destination JRB
 * @throws Exception the exception
 */
protected void mergeJrb(File source, File dest) throws Exception {
    log("  merging JRB %s into %s\n", source, dest);
    RRDv1 rrdSrc = RrdConvertUtils.dumpJrb(source);
    RRDv1 rrdDst = RrdConvertUtils.dumpJrb(dest);
    if (rrdSrc == null || rrdDst == null) {
        log("  Warning: can't load JRBs (ingoring merge).\n");
        return;
    }
    rrdDst.merge(rrdSrc);
    final File outputFile = new File(dest.getCanonicalPath() + ".merged");
    RrdConvertUtils.restoreJrb(rrdDst, outputFile);
    if (dest.exists()) {
        FileUtils.deleteQuietly(dest);
    }
    FileUtils.moveFile(outputFile, dest);
}

From source file:org.polymap.service.fs.providers.fs.FsContentProvider.java

public void moveTo(IContentNode src, IPath dest, String newName) throws BadRequestException, IOException {
    FsFolder destFolder = (FsFolder) getSite().getFolder(dest);
    File destFile = new File(destFolder.getDir(), newName);

    // file//w w  w.j a v a  2 s .  c o m
    if (src instanceof FsFile) {
        FsFile srcFile = (FsFile) src;
        FileUtils.moveFile(srcFile.getFile(), destFile);
        getSite().invalidateFolder(getSite().getFolder(srcFile.getParentPath()));
    }
    // directory
    else if (src instanceof FsFolder) {
        FsFolder srcFolder = (FsFolder) src;
        FileUtils.moveDirectory(srcFolder.getDir(), destFile);
        getSite().invalidateFolder(getSite().getFolder(srcFolder.getParentPath()));
    } else {
        throw new BadRequestException("Destination is not a valid folder to move to.");
    }

    getSite().invalidateFolder(destFolder);
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/** Handles an uploaded profile. */
private void addProfile(MultipartHttpServletRequest request, ModelMap model) {
    List<String> lines = new ArrayList<>();
    MultipartFile mpf = request.getFile("file");
    if (mpf != null) {
        String message = "";
        String filename = mpf.getOriginalFilename();
        try {/* w w  w.j a v a 2 s. co m*/
            File tempFile = File.createTempFile("profile", null);
            mpf.transferTo(tempFile);
            boolean exResult = execute(VALIDATE_CMD, tempFile, lines);
            if (exResult) {
                filename = getNextVersionedFilename(filename);
                File newFile = new File(profileDir, filename);
                FileUtils.moveFile(tempFile, newFile);
                model.addAttribute("success", true);
                message = "Success adding profile: ";
            } else {
                model.addAttribute("success", false);
                message = "Error adding profile: ";
            }
        } catch (Exception e) {
            model.addAttribute("success", false);
            message = "Problem saving uploaded profile: ";
            lines.add(e.getMessage());
            log.error("Problem saving uploaded profile", e);
        } finally {
            model.addAttribute("operation", "add");
            model.addAttribute("message", message + filename);
            model.addAttribute("filename", filename);
            model.addAttribute("output", StringUtils.join(lines, "\n"));
        }
    }
}

From source file:org.qifu.util.UploadSupportUtils.java

public static DefaultResult<Boolean> updateType(String oid, String type)
        throws ServiceException, IOException, Exception {
    DefaultResult<SysUploadVO> uploadResult = sysUploadService.findForNoByteContent(oid);
    if (uploadResult.getValue() == null) {
        throw new ServiceException(uploadResult.getSystemMessage().getValue());
    }//from w  ww.ja v a 2  s.  co  m
    SysUploadVO upload = uploadResult.getValue();
    if (!YesNo.YES.equals(upload.getIsFile())) {
        return sysUploadService.updateTypeOnly(oid, type);
    }
    DefaultResult<Boolean> result = sysUploadService.updateTypeOnly(oid, type);
    if (result.getValue() == null || !result.getValue()) {
        return result;
    }
    // move file to new dir.
    String oldFullPath = getUploadFileDir(upload.getSystem(), upload.getSubDir(), upload.getType())
            + upload.getFileName();
    String newFullPath = getUploadFileDir(upload.getSystem(), upload.getSubDir(), type) + upload.getFileName();
    File newFile = new File(newFullPath);
    if (newFile.isFile() && newFile.exists()) {
        newFile = null;
        throw new Exception("error. file exists, cannot operate!");
    }
    //newFile = null;
    File oldFile = new File(oldFullPath);
    if (!oldFile.exists()) {
        oldFile = null;
        throw new Exception("error. file no exists: " + oldFullPath);
    }
    //oldFile = null;
    //FSUtils.mv(oldFullPath, newFullPath);
    try {
        FileUtils.moveFile(oldFile, newFile);
    } catch (Exception e) {
        newFile = null;
        oldFile = null;
        throw e;
    }
    return result;
}

From source file:org.restcomm.connect.commons.cache.DiskCache.java

private URI handleLocalFile(final DiskCacheRequest request) throws IOException {
    File origFile = new File(request.uri());
    File destFile = new File(cacheDir + origFile.getName());
    if (!destFile.exists()) {
        FileUtils.moveFile(origFile, destFile);
    }//from   ww  w  . ja  v  a2  s  . c o  m
    return URI.create(this.cacheUri + destFile.getName());
}

From source file:org.rossjohnson.tvdb.TVFileRenamer.java

public boolean rename(File tvFile, File tvShowsBaseDir) throws Exception {
    Matcher matcher = FILENAME_PATTERN.matcher(tvFile.getName());
    if (!matcher.matches()) {
        log.info("File " + tvFile.getName() + " does not match pattern XXX - YYY (ZZZ)*");
        return false;
    }/*from  ww  w  . j  av a 2 s. c  om*/

    String seriesName = getSeriesName(matcher);
    String episodeName = getEpisodeName(matcher);
    String endOfFilename = getEndOfFilename(matcher);

    EpisodeInfo episode = tvDAO.getEpisodeInfo(seriesName, episodeName);
    if (episode == null) {
        log.info("Could not get Episode information for " + tvFile.getAbsolutePath());
        return false;
    }
    String seasonEpisode = getSeasonAndEpisode(episode);

    File destinationDir;
    if (tvShowsBaseDir == null) {
        // if they didn't specify a destination tvshows dir, just rename in current directory
        destinationDir = tvFile.getParentFile();
    } else {
        destinationDir = createDestinationDirectory(tvShowsBaseDir, episode.getSeries().getSafeSeriesName());
    }

    File newFile = new File(destinationDir,
            seriesName + "." + seasonEpisode + "." + episodeName + "." + endOfFilename);

    if (newFile.exists()) {
        log.info("File " + newFile.getAbsolutePath() + " already exists.  Renaming cancelled.");
        return false;
    }

    try {
        FileUtils.moveFile(tvFile, newFile);
        log.info("Renamed " + tvFile.getAbsolutePath() + " to " + newFile.getAbsolutePath());
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}