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.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Recorre el war para escribir los archivos web.xml, la api de dspace y los jar de lucene
 *
 * @throws IOException/* w  w w  .  java 2  s .c om*/
 * @throws TransformerException
 */
private void writeNewJar() throws IOException, TransformerException {
    final int BUFFER_SIZE = 1024;
    // directorio de trabajo
    File jarDir = new File(this.eDMExportWarJarFile.getName()).getParentFile();
    // archivo temporal del nuevo war
    File newJarFile = File.createTempFile("EDMExport", ".jar", jarDir);
    newJarFile.deleteOnExit();
    // flujo de escritura para el nuevo war
    JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(newJarFile));

    try {
        // recorrer los archivos del war
        Enumeration<JarEntry> entries = eDMExportWarJarFile.entries();
        // libreras de lucene
        Pattern luceneLibPattern = Pattern.compile("^WEB-INF/lib/(lucene-.+?)-\\d+.+\\.jar$");
        boolean newApiCopied = false;
        if (dspaceApi == null)
            newApiCopied = true;
        boolean replace = false;
        // recorrer
        while (entries.hasMoreElements()) {
            replace = false;
            installerEDMDisplay.showProgress('.');
            JarEntry entry = entries.nextElement();
            InputStream intputStream = null;
            // todos menos web.xml
            if (!entry.getName().equals("WEB-INF/web.xml")) {
                // api de dspace, se muestra la actual y la de dspace para pedir si se copia
                if (!newApiCopied && entry.getName().matches("^WEB-INF/lib/dspace-api-\\d+.+\\.jar$")) {
                    String response = null;
                    do {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace.question",
                                new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                        dspaceApi.getAbsolutePath() });
                        response = br.readLine();
                        if (response == null)
                            continue;
                        response = response.trim();
                        if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                            replace = true;
                            break;
                        } else if (response.equalsIgnoreCase("n")) {
                            break;
                        }
                    } while (true);
                    // se reemplaza por la de dspace
                    if (replace) {
                        JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + dspaceApi.getName());
                        newJarEntry.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(newJarEntry);
                        intputStream = new FileInputStream(dspaceApi);
                        newApiCopied = true;
                        if (debug) {
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                    new String[] { entry.getName(), "WEB-INF/lib/" + dspaceApi.getName(),
                                            dspaceApi.getAbsolutePath() });
                            installerEDMDisplay.showLn();
                        }
                    }
                } else {
                    // libreras de lucene
                    Matcher luceneLibMatcher = luceneLibPattern.matcher(entry.getName());
                    if (luceneLibMatcher.find()) {
                        String prefixLuceneLib = luceneLibMatcher.group(1);
                        File luceneLibFile = null;
                        String patternFile = prefixLuceneLib + "-\\d+.+\\.jar";
                        for (File file : luceneLibs) {
                            if (file.getName().matches(patternFile)) {
                                luceneLibFile = file;
                                break;
                            }
                        }
                        if (luceneLibFile != null) {
                            String response = null;
                            do {
                                installerEDMDisplay.showLn();
                                installerEDMDisplay.showQuestion(currentStepGlobal,
                                        "writeNewJar.replace.question",
                                        new String[] { entry.getName(),
                                                "WEB-INF/lib/" + luceneLibFile.getName(),
                                                luceneLibFile.getAbsolutePath() });
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty() || response.equalsIgnoreCase(answerYes)) {
                                    replace = true;
                                    break;
                                } else if (response.equalsIgnoreCase("n")) {
                                    break;
                                }
                            } while (true);
                            // se reemplaza por la de dspace
                            if (replace) {
                                JarEntry newJarEntry = new JarEntry("WEB-INF/lib/" + luceneLibFile.getName());
                                newJarEntry.setCompressedSize(-1);
                                jarOutputStream.putNextEntry(newJarEntry);
                                intputStream = new FileInputStream(luceneLibFile);
                                if (debug) {
                                    installerEDMDisplay.showLn();
                                    installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.replace",
                                            new String[] { entry.getName(),
                                                    "WEB-INF/lib/" + luceneLibFile.getName(),
                                                    luceneLibFile.getAbsolutePath() });
                                    installerEDMDisplay.showLn();
                                }
                            }
                        }
                        // si no era la api de dspace o las libreras de lucene se copia tal cual
                    } else if (!replace) {
                        JarEntry entryOld = new JarEntry(entry);
                        entryOld.setCompressedSize(-1);
                        jarOutputStream.putNextEntry(entryOld);
                        intputStream = eDMExportWarJarFile.getInputStream(entry);
                    }
                }
                if (intputStream == null) {
                    if (debug)
                        installerEDMDisplay.showQuestion(currentStepGlobal, "writeNewJar.notIS",
                                new String[] { entry.getName() });
                    continue;
                }
                // se lee el archivo y se copia al flujo de escritura del war
                int count;
                byte data[] = new byte[BUFFER_SIZE];
                while ((count = intputStream.read(data, 0, BUFFER_SIZE)) != -1) {
                    jarOutputStream.write(data, 0, count);
                }
                intputStream.close();
            }
        }
        installerEDMDisplay.showLn();
        // se aade web.xml al war
        addNewWebXml(jarOutputStream);
        // cerramos el archivo jar y borramos el war
        eDMExportWarJarFile.close();
        eDMExportWarWorkFile.delete();
        // sustituimos el viejo por el temporal
        try {
            /*if (newJarFile.renameTo(eDMExportWarWorkFile) && eDMExportWarWorkFile.setExecutable(true, true)) {
            eDMExportWarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            } else {
            throw new IOException();
            }*/
            if (jarOutputStream != null)
                jarOutputStream.close();
            FileUtils.moveFile(newJarFile, eDMExportWarWorkFile);
            //newJarFile.renameTo(eDMExportWarWorkFile);
            eDMExportWarWorkFile.setExecutable(true, true);
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
        } catch (Exception io) {
            io.printStackTrace();
            throw new IOException();
        }
    } finally {
        if (jarOutputStream != null) {
            jarOutputStream.close();
        }
    }
}

From source file:org.duracloud.retrieval.mgmt.RetrievalWorker.java

protected File renameFile(File localFile) throws IOException {
    File origFile = new File(localFile.getAbsolutePath());
    File copiedFile = new File(localFile.getParent(), localFile.getName() + COPY);
    for (int i = 2; copiedFile.exists(); i++) {
        copiedFile = new File(localFile.getParent(), localFile.getName() + COPY + "-" + i);
    }/*  w w  w .j a  va  2 s.c om*/
    FileUtils.moveFile(origFile, copiedFile);
    return copiedFile;
}

From source file:org.eclipse.che.api.fs.server.impl.FsOperations.java

void move(Path srcFsPath, Path dstFsPath) throws ServerException {
    try {//from   ww w .  j a v a  2  s .  c om
        if (Files.isDirectory(srcFsPath)) {
            FileUtils.moveDirectory(srcFsPath.toFile(), dstFsPath.toFile());
        } else {
            FileUtils.moveFile(srcFsPath.toFile(), dstFsPath.toFile());
        }
    } catch (IOException e) {
        throw new ServerException("Failed to move item " + srcFsPath + " to " + dstFsPath, e);
    }
}

From source file:org.eclipse.che.api.fs.server.impl.FsOperations.java

void moveWithParents(Path srcFsPath, Path dstFsPath) throws ServerException {
    try {/*from w ww .ja v a  2 s  . c  o  m*/
        Files.createDirectories(dstFsPath.getParent());

        if (Files.isDirectory(srcFsPath)) {
            FileUtils.moveDirectory(srcFsPath.toFile(), dstFsPath.toFile());
        } else {
            FileUtils.moveFile(srcFsPath.toFile(), dstFsPath.toFile());
        }
    } catch (IOException e) {
        throw new ServerException("Failed to move item " + srcFsPath + " to " + dstFsPath, e);
    }
}

From source file:org.ednovo.gooru.application.util.GooruImageUtil.java

public static String moveImage(String srcFilePath, String destFolderPath, String fileNamePrefix)
        throws IOException {
    File srcFile = new File(srcFilePath);
    String fileExtension = StringUtils.substringAfterLast(srcFilePath, ".");
    File destFile = new File(destFolderPath + fileNamePrefix + "." + fileExtension);
    try {//  www .jav  a  2s.c  om
        if (destFile.exists() && srcFile.exists()) {
            destFile.delete();
        }
        FileUtils.moveFile(srcFile, destFile);
    } catch (IOException exception) {
        LOGGER.error("Move File Failed:" + exception);
        throw exception;
    }
    return destFile.getAbsolutePath();
}

From source file:org.ednovo.gooru.application.util.ResourceImageUtil.java

public void moveFileAndSendMsgToGenerateThumbnails(Resource resource, String fileName,
        Boolean isUpdateSlideResourceThumbnail) throws IOException {
    String repoPath = UserGroupSupport.getUserOrganizationNfsInternalPath();
    final String mediaFolderPath = repoPath + Constants.UPLOADED_MEDIA_FOLDER;
    final String contentGooruOid = resource.getGooruOid();

    String resourceImageFile = mediaFolderPath + "/" + fileName;
    File mediaImage = new File(resourceImageFile);
    if (!mediaImage.exists() || !mediaImage.isFile()) {
        return;//from w w w . ja  v a  2s.  c  om
    }
    if (mediaImage.exists() && resource != null) {

        // get resource internal path
        repoPath = resource.getOrganization().getNfsStorageArea().getInternalPath();

        File resourceFolder = new File(repoPath + "/" + resource.getFolder());
        if (!resourceFolder.exists()) {
            resourceFolder.mkdir();
        }
        File newImage = new File(resourceFolder, contentGooruOid + "_" + fileName);
        if (resource.getThumbnail() != null && !resource.getThumbnail().startsWith(contentGooruOid)
                && !resource.getThumbnail().contains(GOORU_DEFAULT)) {
            // Collection image exists, but doesn't start with new ID.
            // migrate to new pattern
            File existingImage = new File(resourceFolder, resource.getThumbnail());
            existingImage.delete();
        }
        if (newImage.exists()) {
            newImage.delete();
        }
        FileUtils.moveFile(mediaImage, newImage);

        fileName = newImage.getName();
        String resourceTypeName = resource.getResourceType().getName();
        if (resourceTypeName.equals(ResourceType.Type.PRESENTATION.getType())
                || resourceTypeName.equals(ResourceType.Type.HANDOUTS.getType())
                || resourceTypeName.equals(ResourceType.Type.TEXTBOOK.getType())) {
            if (isUpdateSlideResourceThumbnail) {
                resource.setThumbnail(fileName);
            } else {
                resource.setThumbnail("slides/slides1.jpg");
            }

        } else {
            resource.setThumbnail(fileName);
        }
        this.setDefaultThumbnailImageIfFileNotExist(resource);
        if (resource.getUrl() != null && !resource.getUrl().toLowerCase().startsWith("http://")
                && !resource.getUrl().toLowerCase().startsWith("https://")
                && !resourceTypeName.equalsIgnoreCase(ResourceType.Type.RESOURCE.getType())
                && !resourceTypeName.equalsIgnoreCase(ResourceType.Type.VIDEO.getType())) {
            if (!isUpdateSlideResourceThumbnail) {
                resource.setUrl(fileName);
            }
        }
    }

    resourceRepository.save(resource);
    if (resource.getResourceType() != null) {
        String indexType = RESOURCE;
        if (resource.getResourceType().getName().equalsIgnoreCase(SCOLLECTION)) {
            indexType = SCOLLECTION;
        }
        try {
            indexHandler.setReIndexRequest(resource.getGooruOid(), IndexProcessor.INDEX, indexType, null, false,
                    false);
        } catch (Exception e) {
            LOGGER.debug("failed to index {}", e);
        }
    }
    sendMsgToGenerateThumbnails(resource);
}

From source file:org.entando.entando.aps.system.services.storage.LocalStorageManager.java

@Override
public void editFile(String subPath, boolean isProtectedResource, InputStream is) throws ApsSystemException {
    subPath = (null == subPath) ? "" : subPath;
    String fullPath = this.createFullPath(subPath, isProtectedResource);
    String tempFilePath = null;//  w ww . j a  v a 2s .co m
    try {
        File oldFile = new File(fullPath);
        if (oldFile.exists()) {
            String tempDir = System.getProperty("java.io.tmpdir");
            tempFilePath = tempDir + File.separator + subPath;
            FileUtils.moveFile(oldFile, new File(tempFilePath));
        }
        this.saveFile(subPath, isProtectedResource, is);
    } catch (Throwable t) {
        try {
            if (null != tempFilePath) {
                FileUtils.moveFile(new File(tempFilePath), new File(fullPath));
            }
        } catch (Throwable tr) {
            _logger.error("Error restoring File from path {} to path", tempFilePath, fullPath, tr);
        }
        _logger.error("Error writing File with path {}", subPath, t);
        throw new ApsSystemException("Error editing file", t);
    } finally {
        if (null != tempFilePath) {
            new File(tempFilePath).delete();
        }
    }
}

From source file:org.evosuite.utils.Utils.java

/**
 * Move file to another directory. If file already exist in {@code dest} it
 * will be rewritten./*  w  ww  . j av  a 2 s.  c o  m*/
 *
 * @param source
 *            - source file
 * @param dest
 *            - destination file
 * @return true, if file was moved, false otherwise
 */
public static boolean moveFile(File source, File dest) {
    if (source.isDirectory() || dest.isDirectory())
        return false;

    try {
        if (dest.exists())
            dest.delete();

        FileUtils.moveFile(source, dest);
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:org.exist.replication.jms.obsolete.FileSystemListener.java

private void handleDocument(eXistMessage em) {

    LOG.info(em.getReport());//from  w  ww  .  j a  v a  2  s .com

    // Get original path
    String resourcePath = em.getResourcePath();

    String[] srcSplitPath = splitPath(resourcePath);
    String srcDir = srcSplitPath[0];
    String srcDoc = srcSplitPath[1];

    File dir = new File(baseDir, srcDir);
    File file = new File(dir, srcDoc);

    switch (em.getResourceOperation()) {
    case CREATE:
    case UPDATE:
        // Create dirs if not existent

        dir.mkdirs();

        // Create file reference

        LOG.info(file.getAbsolutePath());

        try {
            // Prepare streams
            FileOutputStream fos = new FileOutputStream(file);
            ByteArrayInputStream bais = new ByteArrayInputStream(em.getPayload());
            GZIPInputStream gis = new GZIPInputStream(bais);

            // Copy and unzip
            IOUtils.copy(gis, fos);

            // Cleanup
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(gis);
        } catch (IOException ex) {
            LOG.error(ex);

        }
        break;

    case DELETE:
        FileUtils.deleteQuietly(file);
        break;

    case MOVE:
        File mvFile = new File(baseDir, em.getDestinationPath());
        try {
            FileUtils.moveFile(file, mvFile);
        } catch (IOException ex) {
            LOG.error(ex);
        }
        break;

    case COPY:
        File cpFile = new File(baseDir, em.getDestinationPath());
        try {
            FileUtils.copyFile(file, cpFile);
        } catch (IOException ex) {
            LOG.error(ex);
        }
        break;

    default:
        LOG.error("Unknown change type");
    }
}

From source file:org.fao.fenix.web.modules.latex.server.LatexServiceImpl.java

private String exportLatexPDF(String cleanLatexAreaContent, boolean isSweave) throws FenixGWTException {
    try {//from  www.  j  av  a  2s.c  o m
        String pdfPath = null;
        if (isSweave)
            pdfPath = latexUtils.exportSweavePDF(cleanLatexAreaContent);
        else
            pdfPath = latexUtils.exportLatexPDF(cleanLatexAreaContent);
        File srcFile = new File(pdfPath);
        String filename = UUID.randomUUID() + ".pdf";
        File destFile = new File(dir + File.separator + filename);
        FileUtils.moveFile(srcFile, destFile);
        System.out.println("File moved to " + destFile.getAbsolutePath());
        return filename;
    } catch (FenixException e) {
        throw new FenixGWTException(e.getMessage());
    } catch (IOException e) {
        throw new FenixGWTException(e.getMessage());
    }
}