List of usage examples for org.apache.commons.io FileUtils moveFile
public static void moveFile(File srcFile, File destFile) throws IOException
From source file:org.goobi.io.SafeFile.java
public void moveFile(SafeFile dest) throws IOException { FileUtils.moveFile(delegate, dest.delegate); }
From source file:org.gradle.api.internal.filestore.PathKeyFileStore.java
protected FileStoreEntry saveIntoFileStore(File source, File destination, boolean isMove) { if (!source.exists()) { throw new GradleException(String.format("Cannot copy '%s' into filestore @ '%s' as it does not exist", source, destination));/*from w w w. j a v a 2 s .c om*/ } File parentDir = destination.getParentFile(); if (!parentDir.mkdirs() && !parentDir.exists()) { throw new GradleException(String.format("Unable to create filestore directory %s", parentDir)); } String verb = isMove ? "move" : "copy"; try { deleteAction.delete(destination); if (isMove) { FileUtils.moveFile(source, destination); } else { FileUtils.copyFile(source, destination); } } catch (IOException e) { throw new GradleException( String.format("Failed to %s file '%s' into filestore at '%s' ", verb, source, destination), e); } return entryAt(destination); }
From source file:org.gradle.util.GFileUtils.java
public static void moveFile(File source, File destination) { try {/*from w ww. j ava 2 s. com*/ FileUtils.moveFile(source, destination); } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:org.grycap.gpf4med.DownloadService.java
/** * Uses a group of URIs to retrieve objects and writes them to the same number of files. This method will do * its best effort to optimally handle the downloads, opening a pool of connections to the servers and reusing * them as much as possible. Also, it will create several concurrent threads in the JVM in order to perform * simultaneous downloads./*from w ww . j av a 2s. c o m*/ * @param requests a key-value map with the list of requests to handle. The source of the object is the key of * the map, while the value is the destination file. * @param validator checks the file for correctness. * @param config download settings. * @param encryptionProvider an optional encryption provider that, when available, is used to encrypt the * files after download. * @param task an optional task that will be executed passing each individual file as parameter, when the download * of the file ends. * @return the requests that could not be served after exhausting the individual retries. * @throws IOException if an error occurs in the execution of the operation. */ public ImmutableMap<URI, File> download(final ImmutableMap<URI, File> requests, final @Nullable FileValidator validator, final DownloadConfiguration config, final @Nullable FileEncryptionProvider encryptionProvider, final @Nullable PostProcessTask<File> task) throws IOException { checkArgument(requests != null, "Uninitialized request"); checkArgument(config != null, "Uninitialized configuration"); ImmutableMap<URI, File> pending = ImmutableMap.copyOf(requests); final List<URI> cancelled = new ArrayList<URI>(); try { for (int attempt = 0; attempt < config.getRetries() && !pending.isEmpty() && pending.size() > cancelled.size(); attempt++) { LOGGER.info("Attempt " + (attempt + 1) + " to download " + requests.size() + " files"); // create connection manager final PoolingNHttpClientConnectionManager connectionManager = createConnectionManager(); // create HTTP asynchronous client int eSoTimeoutMs = config.soToMs + (int) (config.soToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); int eConnTimeoutMs = config.connToMs + (int) (config.connToMs * attempt * (config.toIncPercent >= 0.0d && config.toIncPercent <= 1.0d ? config.toIncPercent : 0.0d)); final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(eConnTimeoutMs) .setConnectionRequestTimeout(eConnTimeoutMs).setSocketTimeout(eSoTimeoutMs).build(); final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build(); httpclient.start(); // attempt to perform download try { final CountDownLatch latch = new CountDownLatch(pending.size()); for (final Map.Entry<URI, File> entry : pending.entrySet()) { final URI uri = entry.getKey(); if (cancelled.contains(uri)) { continue; } final File file = entry.getValue(); FileUtils.forceMkdir(file.getParentFile()); final HttpGet request = new HttpGet(uri); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer( new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), request); final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(file) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { releaseResources(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { FileUtils.deleteQuietly(file); throw new ClientProtocolException( "Download failed: " + response.getStatusLine()); } if (validator != null && !validator.isValid(file)) { FileUtils.deleteQuietly(file); cancelled.add(uri); throw new IOException( file.getCanonicalPath() + " not recognised as a supported file format"); } if (encryptionProvider != null) { try { final File cipherFile = File .createTempFile(RandomStringUtils.random(8, true, true), ".tmp"); encryptionProvider.encrypt(new FileInputStream(file), new FileOutputStream(cipherFile)); FileUtils.deleteQuietly(file); FileUtils.moveFile(cipherFile, file); LOGGER.info("File encrypted: " + file.getCanonicalPath()); } catch (Exception e) { FileUtils.deleteQuietly(file); cancelled.add(uri); LOGGER.warn("Failed to encrypt: " + file.getCanonicalPath(), e); throw new IOException("File encryption failed"); } } LOGGER.info("Download succeed to file: " + file.getCanonicalPath()); return file; } }; httpclient.execute(producer, consumer, new FutureCallback<File>() { @Override public void completed(final File result) { request.releaseConnection(); latch.countDown(); if (task != null) { task.apply(result); } LOGGER.info("Request succeed: " + request.getRequestLine() + " => Response file length: " + result.length()); } @Override public void failed(final Exception ex) { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request failed: " + request.getRequestLine() + "=>" + ex); } @Override public void cancelled() { request.releaseConnection(); FileUtils.deleteQuietly(file); latch.countDown(); LOGGER.error("Request cancelled: " + request.getRequestLine()); } }); } latch.await(); } finally { try { httpclient.close(); } catch (Exception ignore) { } try { shutdown(connectionManager, 0l); } catch (Exception ignore) { } } // populate the pending list with the files that does not exist final ImmutableMap.Builder<URI, File> builder = new ImmutableMap.Builder<URI, File>(); for (final Map.Entry<URI, File> entry : requests.entrySet()) { if (!entry.getValue().exists()) { builder.put(entry.getKey(), entry.getValue()); } } pending = builder.build(); if ((attempt + 1) < config.retries && !pending.isEmpty() && pending.size() > cancelled.size()) { final long waitingTime = (long) (config.soToMs * 0.1d); LOGGER.info("Waiting " + waitingTime + " ms before attempt " + (attempt + 2) + " to download " + requests.size() + " pending files"); Thread.sleep(waitingTime); } } } catch (IOException ioe) { throw ioe; } catch (Exception e) { throw new IOException("Download has failed", e); } return pending; }
From source file:org.ikasan.component.endpoint.filesystem.producer.FileProducer.java
protected void process(Object payload) { try {//from ww w . j a va 2 s . c o m File file = new File(configuration.getFilename()); if (file.exists()) { if (!configuration.isOverwrite()) { throw new EndpointException("File [" + configuration.getFilename() + "] already exists and overwrite option is set to [" + configuration.isOverwrite() + "]"); } file.delete(); } if (configuration.isUseTempFile()) { File tempFile = new File(configuration.getTempFilename()); this.writeFile(tempFile, payload); FileUtils.moveFile(tempFile, file); } else { this.writeFile(file, payload); } if (configuration.isWriteChecksum()) { long checksum = FileUtils.checksumCRC32(file); File checksumFile = new File(configuration.getFilename() + ".cr32"); FileUtils.writeStringToFile(checksumFile, String.valueOf(checksum), configuration.getEncoding()); } } catch (IOException e) { throw new EndpointException(e); } }
From source file:org.isatools.isatab.export.isatab.filesdispatching.ISATabExportRepoFilesChecker.java
/** * Process all files that results non referenced, ie they're not in {@link #referencedFiles}, after that this was * computed by {@link #collectReferredFiles(AssayGroup, Mode)}. For these files issues a warning and also * copies them on a backup location, if mode == {@link Mode#BACKUP}. *//*w ww . j a v a 2 s .c om*/ private void processOrphanFiles(final AssayGroup ag, Mode mode) throws IOException { if (ag == null) { return; } SectionInstance assaySectionInstance = ag.getAssaySectionInstance(); if (assaySectionInstance == null) { log.warn("I cannot find any record in the DB for the file: " + ag.getFilePath() + ", hope it's fine"); return; } Study study = ag.getStudy(); // TODO: generic for (AnnotationTypes targetType : AnnotationTypes.DATA_PATH_ANNOTATIONS) { String dataLocationPath = StringUtils.trimToNull( dataLocationMgr.getDataLocation(study, ag.getMeasurement(), ag.getTechnology(), targetType)); if (dataLocationPath == null) { continue; } File dataLocationDir = new File(dataLocationPath); dataLocationPath = dataLocationDir.getCanonicalPath(); if (!dataLocationDir.isDirectory() && !dataLocationDir.canRead() && !dataLocationDir.canWrite()) { log.warn("Directory '" + dataLocationPath + "' is not accessible, skipping it"); continue; } log.debug("Checking unreferenced files into '" + dataLocationPath + "'"); Collection<File> existingFiles = FileUtils.listFiles(dataLocationDir, null, true); for (File existingFile : existingFiles) { if (this.referencedFiles.containsKey(existingFile)) { continue; } String existingPath = existingFile.getCanonicalPath(); log.warn("WARNING: The file '" + existingPath + "' is no longer referred by the exported submission"); if (mode != Mode.BACKUP) { continue; } String backupPath = dataLocationPath + "/original"; log.warn("Moving it to the backup location: '" + backupPath + "'"); String fileRelPath = existingPath.substring(dataLocationPath.length() + 1); String backupFilePath = backupPath + "/" + fileRelPath; File backupFile = new File(backupFilePath); if (backupFile.exists() && backupFile.lastModified() == existingFile.lastModified()) { log.debug("Not copying " + existingPath + "' to '" + backupFilePath + "': they seem to be the same."); continue; } log.trace("Copying data file '" + existingPath + "' / '" + backupFilePath + "' to data repository..."); FileUtils.moveFile(existingFile, backupFile); // Needed cause of a bug in the previous function backupFile.setLastModified(existingFile.lastModified()); log.trace("...done"); // Do it only once this.referencedFiles.put(existingFile, ""); } } }
From source file:org.jasig.resource.aggr.ResourcesAggregatorImpl.java
/** * Aggregate the specified Deque of elements into a single element. The provided MessageDigest is used for * building the file name based on the hash of the file contents. The callback is used for type specific * operations.//from w w w . java2s. c o m */ protected <T extends BasicInclude> T aggregateList(final MessageDigest digest, final Deque<T> elements, final List<File> skinDirectories, final File outputRoot, final File alternateOutput, final String extension, final AggregatorCallback<T> callback) throws IOException { if (null == elements || elements.size() == 0) { return null; } // reference to the head of the list final T headElement = elements.getFirst(); if (elements.size() == 1 && this.resourcesDao.isAbsolute(headElement)) { return headElement; } final File tempFile = File.createTempFile("working.", extension); final File aggregateOutputFile; try { //Make sure we're working with a clean MessageDigest digest.reset(); TrimmingWriter trimmingWriter = null; try { final BufferedOutputStream bufferedFileStream = new BufferedOutputStream( new FileOutputStream(tempFile)); final MessageDigestOutputStream digestStream = new MessageDigestOutputStream(bufferedFileStream, digest); final OutputStreamWriter aggregateWriter = new OutputStreamWriter(digestStream, this.encoding); trimmingWriter = new TrimmingWriter(aggregateWriter); for (final T element : elements) { final File resourceFile = this.findFile(skinDirectories, element.getValue()); FileInputStream fis = null; try { fis = new FileInputStream(resourceFile); final BOMInputStream bomIs = new BOMInputStream(new BufferedInputStream(fis)); if (bomIs.hasBOM()) { logger.debug("Stripping UTF-8 BOM from: " + resourceFile); } final Reader resourceIn = new InputStreamReader(bomIs, this.encoding); if (element.isCompressed()) { IOUtils.copy(resourceIn, trimmingWriter); } else { callback.compress(resourceIn, trimmingWriter); } } catch (IOException e) { throw new IOException( "Failed to read '" + resourceFile + "' for skin: " + skinDirectories.get(0), e); } finally { IOUtils.closeQuietly(fis); } trimmingWriter.write(SystemUtils.LINE_SEPARATOR); } } finally { IOUtils.closeQuietly(trimmingWriter); } if (trimmingWriter.getCharCount() == 0) { return null; } // temp file is created, get checksum final String checksum = Base64.encodeBase64URLSafeString(digest.digest()); digest.reset(); // create a new file name final String newFileName = checksum + extension; // Build the new file name and path if (alternateOutput == null) { final String elementRelativePath = FilenameUtils.getFullPath(headElement.getValue()); final File directoryInOutputRoot = new File(outputRoot, elementRelativePath); // create the same directory structure in the output root directoryInOutputRoot.mkdirs(); aggregateOutputFile = new File(directoryInOutputRoot, newFileName).getCanonicalFile(); } else { aggregateOutputFile = new File(alternateOutput, newFileName).getCanonicalFile(); } //Move the aggregate file into the correct location FileUtils.deleteQuietly(aggregateOutputFile); FileUtils.moveFile(tempFile, aggregateOutputFile); } finally { //Make sure the temp file gets deleted FileUtils.deleteQuietly(tempFile); } final String newResultValue = RelativePath.getRelativePath(outputRoot, aggregateOutputFile); this.logAggregation(elements, newResultValue); return callback.getAggregateElement(newResultValue, elements); }
From source file:org.jboss.arquillian.extension.screenRecorder.LifecycleObserver.java
/** * Moves already taken screenshot and uses it as a 'before' one. Then * takes another screenshot.//from www. ja v a 2 s .c o m */ private void takeScreenshot(File before, TestClass testClass, Method testMethod, String appender) throws AWTException, IOException { File testClassDirectory = getDirectory(configuration.getScreenshotFolder(), testClass); testClassDirectory.mkdirs(); File beforeDestination = FileUtils.getFile(testClassDirectory, testMethod.getName() + "_before." + configuration.getImageFileType()); if (beforeDestination.exists()) { beforeDestination.delete(); } FileUtils.moveFile(before, beforeDestination); Rectangle screenSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage image = new Robot().createScreenCapture(screenSize); String imageName = testMethod.getName() + "_" + appender + "." + configuration.getImageFileType(); File outputFile = FileUtils.getFile(testClassDirectory, imageName); if (outputFile.exists()) { outputFile.delete(); } ImageIO.write(image, configuration.getImageFileType().toString(), outputFile); }
From source file:org.jboss.arquillian.extension.screenRecorder.ScreenRecorder.java
/** * Starts recording a video to the temporary file. If {@link #stopRecording(java.io.File) } * is invoked, this method stops recording. *//*from w w w . j ava2 s . c o m*/ public void startRecording() { running = true; thread = new Thread(new Runnable() { public void run() { File output; try { output = File.createTempFile("arquillain-screen-recorder", "." + videoType); output.deleteOnExit(); output.createNewFile(); } catch (IOException e) { throw new IllegalStateException("Can't create a temporary file for recording.", e); } IMediaWriter writer = ToolFactory.makeWriter(output.getAbsolutePath()); writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4, screenBounds.width / 2, screenBounds.height / 2); long startTime = System.nanoTime(); while (running) { BufferedImage screen = getDesktopScreenshot(); BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR); writer.encodeVideo(0, bgrScreen, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); try { Thread.sleep((long) (1000 / FRAME_RATE)); } catch (InterruptedException ex) { logger.error("Exception occured during video recording", ex); } if (!running) { writer.close(); try { if (destination != null) { if (destination.exists()) { destination.delete(); } FileUtils.moveFile(output, destination); } } catch (IOException e) { throw new IllegalStateException( "Can't move the temporary recorded content to the destination file.", e); } finally { output.delete(); } } } } }); thread.start(); }
From source file:org.jboss.arquillian.extension.videoRecorder.impl.VideoRecorder.java
/** * Starts recording a video to the temporary file. If {@link #stopRecording(java.io.File) } * is invoked, this method stops recording. *///from ww w . ja v a 2 s .c om public void startRecording() { running = true; thread = new Thread(new Runnable() { @Override public void run() { File output; try { output = File.createTempFile("arquillain-screen-recorder", "." + videoType); output.deleteOnExit(); output.createNewFile(); } catch (IOException e) { throw new IllegalStateException("Can't create a temporary file for recording.", e); } IMediaWriter writer = ToolFactory.makeWriter(output.getAbsolutePath()); writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4, screenBounds.width / 2, screenBounds.height / 2); long startTime = System.nanoTime(); while (running) { BufferedImage screen = getDesktopScreenshot(); BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR); writer.encodeVideo(0, bgrScreen, System.nanoTime() - startTime, TimeUnit.NANOSECONDS); try { Thread.sleep((long) (1000 / FRAME_RATE)); } catch (InterruptedException ex) { logger.error("Exception occured during video recording", ex); } if (!running) { writer.close(); try { if (destination != null) { FileUtils.moveFile(output, destination); } } catch (IOException e) { throw new IllegalStateException( "Can't move the temporary recorded content to the destination file.", e); } finally { output.delete(); } } } } }); thread.start(); }