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.jboss.loom.actions.FileAbstractAction.java

@Override
public void rollback() throws MigrationException {
    if (!this.isAfterPerform())
        return;// ww  w .  j  a v a  2 s  . co  m

    // Delete the new file.
    FileUtils.deleteQuietly(this.dest);

    // Restore the backup file, if we created any.
    if (this.temp != null) {
        try {
            FileUtils.moveFile(this.temp, this.dest);
        } catch (IOException ex) {
            throw new ActionException(this, "Restoring the previous file failed: " + ex.getMessage(), ex);
        }
    }
    setState(IMigrationAction.State.ROLLED_BACK);
}

From source file:org.jenkinsci.modules.optpluginhelper.PluginHelper.java

/**
 * List all the optional plugins (while populating the staging area with any new ones we discover).
 *
 * @return the list of optional plugins available from all the current defined {@link PluginSource} extensions.
 *//*from w  ww.j  av a  2 s. c o  m*/
private List<File> listPlugins() {
    // TODO figure out what to do if two sources provide different versions of the same plugin, currently undefined
    List<File> result = new ArrayList<File>();
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        return result;
    }
    File baseDir = new File(jenkins.root, OPTIONAL_PLUGIN_DIR);
    if (baseDir.exists() && !baseDir.isDirectory()) {
        LOGGER.log(Level.SEVERE, "Optional plugin working directory {0} exists and is not a directory",
                baseDir);
        return result;
    }
    if (!baseDir.isDirectory()) {
        if (!baseDir.mkdirs()) {
            LOGGER.log(Level.SEVERE, "Could not create optional plugin working directory {0}", baseDir);
            return result;
        }
    }
    for (URL resource : PluginSource.allPlugins()) {
        try {
            final String externalForm = resource.toExternalForm();
            ExtractedPluginMetadata metadata = extractedPluginMetadataMap.get(externalForm);
            if (metadata != null) {
                File archive = new File(baseDir, metadata.shortName + ".jpi");
                if (archive.isFile() && archive.length() == metadata.length
                        && Util.getDigestOf(archive).equals(metadata.digest)) {
                    result.add(archive);
                    continue;
                }
            }
            final URLConnection connection = resource.openConnection();
            long lastModified = connection.getLastModified();
            long size = connection.getContentLength();
            String path = resource.getPath();
            String fileName = FilenameUtils.getBaseName(path);
            boolean nameCheck = false;
            if (StringUtils.isBlank(fileName)) {
                nameCheck = true;
                fileName = Util.getDigestOf(resource.toString());
            }
            File file = new File(baseDir, fileName + ".jpi");
            if (file.isFile() && (file.lastModified() == lastModified || lastModified == 0)
                    && file.length() == size) {
                final String fileDigest = Util.getDigestOf(file);
                final String resourceDigest;
                final InputStream stream = connection.getInputStream();
                try {
                    resourceDigest = Util.getDigestOf(stream);
                } finally {
                    IOUtils.closeQuietly(stream);
                }
                if (fileDigest.equals(resourceDigest)) {
                    result.add(file);
                    extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file));
                    continue;
                }
            }
            FileUtils.copyURLToFile(resource, file);
            if (nameCheck) {
                final String shortName = jenkins.getPluginManager().getPluginStrategy().getShortName(file);
                if (!fileName.equals(shortName)) {
                    File newFile = new File(baseDir, shortName + ".jpi");
                    if (!newFile.isFile() || !Util.getDigestOf(newFile).equals(Util.getDigestOf(file))) {
                        FileUtils.moveFile(file, newFile);
                    }
                    file = newFile;
                }
            }
            if (lastModified != 0) {
                if (!file.setLastModified(lastModified)) {
                    LOGGER.log(Level.FINE, "Couldn't set last modified on {0}", file);
                }
            }
            result.add(file);
            extractedPluginMetadataMap.put(externalForm, new ExtractedPluginMetadata(file));
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, String.format("Could not process optional plugin from %s", resource), e);
        }
    }

    LOGGER.log(Level.FINE, "List of plugins: " + result);
    return result;
}

From source file:org.jitsi.meet.test.base.Participant.java

/**
 * Takes screenshot.//from   w  w  w .j a v a2  s.  c  o  m
 * @param outputDir the screenshots output directory.
 * @param fileName the destination screenshot file name.
 */
public void takeScreenshot(File outputDir, String fileName) {
    if (!(driver instanceof TakesScreenshot)) {
        TestUtils.print("Driver does not support taking screenshots ! FileName:" + fileName);
        return;
    }

    TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
    File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
    File dstFile = new File(outputDir, fileName);
    try {
        FileUtils.moveFile(scrFile, dstFile);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to move the screenshot file, from: " + scrFile.toString() + " to: "
                + dstFile.toString(), ioe);
    }
}

From source file:org.jncc.base.file.Fileupload.java

public boolean file_Upload() throws Exception {

    if (null != upload) {
        File saveFile = new File(getPath(), fileName.substring(fileName.indexOf("/") + 1));
        // upload.renameTo(saveFile);
        if (saveFile.exists()) {
            saveFile.setWritable(true, false);
            saveFile.delete();//from ww  w . j  a va2s.  co m
        }
        FileUtils.moveFile(upload, saveFile);
        // m_filecontent.put("Product1",fileread.readFileByLines(getPath()+"\\"+fileName));
    }
    return true;
}

From source file:org.jncc.base.file.Fileupload.java

public static File file_Upload(String contextPath, File fileupload, String origFilename) {
    String path = ServletActionContext.getServletContext().getRealPath(contextPath);
    File file = new File(path); // ?,?
    if (!file.exists()) {
        file.mkdir();//  w w  w . ja  v  a 2 s .  c o m
    }
    try {
        if (fileupload != null) {
            // String fileName = java.util.UUID.randomUUID().toString(); //
            // +UUID?????
            java.text.DateFormat formatStr = new java.text.SimpleDateFormat("yyMMddhhmmss");
            String fileName = formatStr.format(new Date());
            fileName = fileName + origFilename;
            File saveFile = new File(path, fileName);

            // upload.renameTo(saveFile);
            if (saveFile.exists()) {
                saveFile.setWritable(true, false);
                saveFile.delete();
            }
            FileUtils.moveFile(fileupload, saveFile);
            return saveFile;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:org.jsweet.transpiler.JSweetTranspiler.java

private void onTsTranspilationCompleted(boolean fullPass, ErrorCountTranspilationHandler handler,
        SourceFile[] files) {// ww  w .ja  v  a 2s.com
    try {
        if (isGenerateDeclarations()) {
            if (getDeclarationsOutputDir() != null) {
                logger.info("moving d.ts files to " + getDeclarationsOutputDir());
                LinkedList<File> dtsFiles = new LinkedList<File>();
                File rootDir = jsOutputDir == null ? tsOutputDir : jsOutputDir;
                Util.addFiles(".d.ts", rootDir, dtsFiles);
                for (File dtsFile : dtsFiles) {
                    String relativePath = Util.getRelativePath(rootDir.getAbsolutePath(),
                            dtsFile.getAbsolutePath());
                    File targetFile = new File(getDeclarationsOutputDir(), relativePath);
                    logger.info("moving " + dtsFile + " to " + targetFile);
                    if (targetFile.exists()) {
                        FileUtils.deleteQuietly(targetFile);
                    }
                    try {
                        FileUtils.moveFile(dtsFile, targetFile);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }
        }
        if (handler.getErrorCount() == 0) {
            Set<File> handledFiles = new HashSet<>();
            for (SourceFile sourceFile : files) {
                if (!sourceFile.getTsFile().getAbsolutePath().startsWith(tsOutputDir.getAbsolutePath())) {
                    throw new RuntimeException("ts directory isn't configured properly, please use setTsDir: "
                            + sourceFile.getTsFile().getAbsolutePath() + " != "
                            + tsOutputDir.getAbsolutePath());
                }
                String outputFileRelativePath = sourceFile.getTsFile().getAbsolutePath()
                        .substring(tsOutputDir.getAbsolutePath().length());
                File outputFile = new File(jsOutputDir == null ? tsOutputDir : jsOutputDir,
                        Util.removeExtension(outputFileRelativePath) + ".js");
                sourceFile.jsFile = outputFile;
                if (outputFile.lastModified() > sourceFile.jsFileLastTranspiled) {
                    if (handledFiles.contains(outputFile)) {
                        continue;
                    }
                    handledFiles.add(outputFile);
                    logger.info("js output file: " + outputFile);
                    File mapFile = new File(outputFile.getAbsolutePath() + ".map");

                    if (mapFile.exists() && generateSourceMap) {

                        SourceMapGeneratorV3 generator = (SourceMapGeneratorV3) SourceMapGeneratorFactory
                                .getInstance(SourceMapFormat.V3);
                        Path javaSourcePath = sourceFile.javaSourceDir.getCanonicalFile().toPath();
                        String sourceRoot = getSourceRoot() != null ? getSourceRoot().toString()
                                : sourceFile.getJsFile().getParentFile().getCanonicalFile().toPath()
                                        .relativize(javaSourcePath) + "/";
                        generator.setSourceRoot(sourceRoot);

                        sourceFile.jsMapFile = mapFile;
                        logger.info("redirecting map file: " + mapFile);
                        String contents = FileUtils.readFileToString(mapFile);
                        SourceMapping mapping = SourceMapConsumerFactory.parse(contents);

                        int line = 1;
                        int columnIndex = 0;
                        for (String lineContent : FileUtils.readLines(outputFile, (Charset) null)) {
                            columnIndex = 0;
                            while (columnIndex < lineContent.length() && (lineContent.charAt(columnIndex) == ' '
                                    || lineContent.charAt(columnIndex) == '\t')) {
                                columnIndex++;
                            }

                            OriginalMapping originalMapping = mapping.getMappingForLine(line, columnIndex + 1);
                            if (originalMapping != null) {
                                // TODO: this is quite slow and should be
                                // optimized
                                SourcePosition originPosition = SourceFile
                                        .findOriginPosition(new SourcePosition(sourceFile.tsFile, null,
                                                new Position(originalMapping.getLineNumber(),
                                                        originalMapping.getColumnPosition())),
                                                files);
                                if (originPosition != null) {
                                    // as a first approximation, we only map
                                    // line numbers (ignore columns)
                                    generator.addMapping(
                                            javaSourcePath.relativize(
                                                    originPosition.getFile().getCanonicalFile().toPath())
                                                    .toString(),
                                            null, new FilePosition(originPosition.getStartLine() - 1, 0),
                                            new FilePosition(line - 1, 0),
                                            new FilePosition(line - 1, lineContent.length() - 1));
                                }
                            }

                            line++;
                        }

                        try (FileWriter writer = new FileWriter(mapFile, false)) {
                            generator.appendTo(writer, outputFile.getName());
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        handler.onCompleted(this, fullPass, files);
    }
}

From source file:org.kalypso.gml.ui.internal.coverage.imports.AbstractTriangulatedSurfaceCoverageImporter.java

@Override
public ICoverage importCoverage(final ICoverageCollection coverageContainer, final File dataFile,
        final String crs, final IContainer dataContainer, IProgressMonitor monitor) throws CoreException {
    /* Monitor. */
    if (monitor == null)
        monitor = new NullProgressMonitor();

    /* Get a temporary file. */
    final File tempFile = FileUtilities.getNewTempFile("hmoConverter", "gmlz");//$NON-NLS-1$ //$NON-NLS-2$

    try {/*from   www . j  av a 2  s .com*/
        /* Monitor. */
        monitor.beginTask(Messages.getString("AbstractTriangulatedSurfaceCoverageImporter_0"), 300); //$NON-NLS-1$
        monitor.subTask(Messages.getString("AbstractTriangulatedSurfaceCoverageImporter_1")); //$NON-NLS-1$

        /* Read the input data. */
        final GM_TriangulatedSurface gmSurface = readInputData(dataFile, crs,
                new SubProgressMonitor(monitor, 100));

        /* Monitor. */
        monitor.subTask(Messages.getString("AbstractTriangulatedSurfaceCoverageImporter_2")); //$NON-NLS-1$

        /* Transform into the Kalypso coordinate system. */
        final IGeoTransformer geoTransformer = GeoTransformerFactory
                .getGeoTransformer(KalypsoDeegreePlugin.getDefault().getCoordinateSystem());
        final GM_Object transformedSurface = geoTransformer.transform(gmSurface);

        /* Create the workspace. */
        final GMLWorkspace tmpWorkspace = FeatureFactory
                .createGMLWorkspace(TriangulatedSurfaceFeature.FEATURE_TRIANGULATED_SURFACE, null, null);
        final TriangulatedSurfaceFeature rootFeature = (TriangulatedSurfaceFeature) tmpWorkspace
                .getRootFeature();
        rootFeature.setTriangulatedSurface((GM_TriangulatedSurface) transformedSurface);

        /* Save the workspace. */
        GmlSerializer.serializeWorkspace(tempFile, tmpWorkspace, "UTF-8"); //$NON-NLS-1$

        /* Monitor. */
        monitor.worked(100);
        monitor.subTask(Messages.getString("AbstractTriangulatedSurfaceCoverageImporter_4")); //$NON-NLS-1$

        /* Get the target file. */
        final File targetDir = dataContainer.getLocation().toFile();
        final File targetFile = AbstractGridCoverageImporter.createTargetFile(dataFile, targetDir, "gmlz"); //$NON-NLS-1$

        /* Add as MultiSurface-Coverage. */
        final IFeatureBindingCollection<ICoverage> coverages = coverageContainer.getCoverages();
        final ICoverage newCoverage = coverages.addNew(MultiSurfaceCoverage.FEATURE_MULTI_SURFACE_COVERAGE);
        newCoverage.setName(dataFile.getName());

        /* Update the bounded by property. */
        final GM_Envelope boundedBy = gmSurface.getEnvelope();
        final GM_Envelope boundedByTransformed = geoTransformer.transform(boundedBy);
        newCoverage.setProperty(Feature.QN_BOUNDED_BY, boundedByTransformed);

        /* Update the range set property. */
        final String externalResource = buildRelativePath(dataContainer,
                coverageContainer.getWorkspace().getContext(), targetFile);
        final RangeSetFile rangeSetFile = new RangeSetFile(externalResource);
        rangeSetFile.setMimeType("application/gml+xml"); //$NON-NLS-1$
        newCoverage.setRangeSet(rangeSetFile);

        /* Update the envelopes. */
        newCoverage.setEnvelopesUpdated();

        /* Move the file. */
        FileUtils.moveFile(tempFile, targetFile);

        /* Fire model event. */
        final GMLWorkspace workspace = coverageContainer.getWorkspace();
        workspace.fireModellEvent(new FeatureStructureChangeModellEvent(workspace, coverageContainer,
                newCoverage, FeatureStructureChangeModellEvent.STRUCTURE_CHANGE_ADD));

        /* Monitor. */
        monitor.worked(100);

        return newCoverage;
    } catch (final Exception e) {
        final IStatus status = new Status(IStatus.ERROR, KalypsoGmlUIPlugin.id(),
                Messages.getString("AbstractTriangulatedSurfaceCoverageImporter_6"), e); //$NON-NLS-1$
        throw new CoreException(status);
    } finally {
        FileUtils.deleteQuietly(tempFile);
        dataContainer.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        monitor.done();
    }
}

From source file:org.kalypso.ogc.sensor.zml.ObservationMarshaller.java

public void marshall(final File targetFile) throws SensorException {
    final String name = targetFile.getName();
    final File dir = targetFile.getParentFile();

    final File saveFile = new File(dir, name + ".saving"); //$NON-NLS-1$
    final File backupFile = new File(dir, name + "~"); //$NON-NLS-1$

    /* Delete old backup file if it still exists */
    FileUtils.deleteQuietly(backupFile);

    try (OutputStream outs = openOutputStream(saveFile)) {
        marshall(outs);//from w w w . j a  va 2s . c o m

        /* Explicitly close, else next move fails */
        outs.close();

        /* backup old target */
        if (targetFile.exists())
            FileUtils.moveFile(targetFile, backupFile);

        /* rename saved file to target */
        FileUtils.moveFile(saveFile, targetFile);

        /* delete backup, we have successfully saved the file */
        FileUtils.deleteQuietly(backupFile);
    } catch (final IOException | OutOfMemoryError e) {
        LOG.log(Level.WARNING, Messages.getString("org.kalypso.ogc.sensor.zml.ZmlFactory.30"), e); //$NON-NLS-1$

        throw new SensorException(e);
    } finally {
        FileUtils.deleteQuietly(saveFile);
    }
}

From source file:org.kalypso.ui.rrm.internal.conversion.to12_02.ChangeTimeseriesParameterTypeWorker.java

@Override
public IStatus execute(final IProgressMonitor monitor) {
    final StatusCollector collector = new StatusCollector(KalypsoUIRRMPlugin.getID());
    final ZmlLink link = m_timeseries.getDataLink();
    final File file = link.getJavaFile();

    try {/*  w ww.  ja v  a 2s.co m*/
        final IObservation sourceObservation = ZmlFactory.parseXML(file.toURI().toURL());
        final ITupleModel sourceModel = sourceObservation.getValues(null);
        final MetadataList metadata = sourceObservation.getMetadataList();
        final ChangeParameterTypeVisitor visitor = new ChangeParameterTypeVisitor(metadata, m_targetType);
        sourceModel.accept(visitor, 0);

        final SimpleTupleModel targetModel = new SimpleTupleModel(visitor.getTargetAxis());
        final DataSourceHandler dataSources = new DataSourceHandler(metadata);

        final Map<Date, TupleModelDataSet> converted = visitor.getConverted();
        final Set<Entry<Date, TupleModelDataSet>> entries = converted.entrySet();
        for (final Entry<Date, TupleModelDataSet> entry : entries) {
            final Date date = entry.getKey();
            final TupleModelDataSet dataset = entry.getValue();

            final Object value = dataset.getValue();
            final Object status = Objects.firstNonNull(dataset.getStatus(), KalypsoStati.BIT_OK);
            final String source = Objects.firstNonNull(dataset.getSource(), IDataSourceItem.SOURCE_UNKNOWN);
            final Object sourceIndex = dataSources.addDataSource(source, source);

            targetModel.addTuple(new Object[] { date, value, status, sourceIndex });
        }

        final SimpleObservation targetObservation = new SimpleObservation(sourceObservation.getHref(),
                sourceObservation.getName(), metadata, targetModel);
        ZmlFactory.writeToFile(targetObservation, file);

        m_timeseries.setParameterType(m_targetType);

        final ZmlLink updatedLnk = m_timeseries.getDataLink();
        final File updatedFile = updatedLnk.getJavaFile();

        FileUtils.moveFile(file, updatedFile);
    } catch (final Exception e) {
        collector.add(IStatus.WARNING, Messages.getString("ChangeTimeseriesParameterTypeWorker_0"), e); //$NON-NLS-1$
    }

    return collector.asMultiStatusOrOK(String.format(
            Messages.getString("ChangeTimeseriesParameterTypeWorker_1"), m_timeseries.getName(), m_targetType)); //$NON-NLS-1$
}

From source file:org.kie.commons.java.nio.fs.file.SimpleFileSystemProvider.java

@Override
public void move(final Path source, final Path target, final CopyOption... options)
        throws DirectoryNotEmptyException, AtomicMoveNotSupportedException, IOException, SecurityException {
    checkNotNull("source", source);
    checkNotNull("target", target);
    checkCondition("source must exist", source.toFile().exists());

    if (target.toFile().exists()) {
        throw new FileAlreadyExistsException(target.toString());
    }//from  www. ja  v a  2s  . c om

    if (source.toFile().isDirectory() && source.toFile().list().length > 0) {
        throw new DirectoryNotEmptyException(source.toString());
    }

    try {
        if (source.toFile().isDirectory()) {
            FileUtils.moveDirectory(source.toFile(), target.toFile());
        } else {
            FileUtils.moveFile(source.toFile(), target.toFile());
        }
    } catch (java.io.IOException ex) {
        throw new IOException(ex);
    }
}