List of usage examples for java.nio.file Files move
public static Path move(Path source, Path target, CopyOption... options) throws IOException
From source file:es.upv.grycap.coreutils.fiber.http.HttpDataFetcher.java
/** * Allows fetching and saving a bunch of objects to the specified directory from a server that uses a REST or REST-like API * where each object is retrieved from the URL formed appending the object's identifier to the path of the the base URL, and * optionally from a server that uses a parameter to identify the objects. Supports additional configuration options to name * the fetched objects./* w ww . j a v a2s .c om*/ * @param baseUrl - base URL from where the objects will be fetched * @param queryParam - if defined, a query parameter will be appended to the base URL with the identifier of the request * @param ids - a list with the identifiers of the all requests that will be attempted * @param prefix - optionally prepend this prefix to the filenames of the saved files * @param suffix - optionally append this suffix to the filenames of the saved files * @param outdir - directory where the files will be stored * @return A {@link CompletableFuture} that allows cancellation. Once each fetch operation is completed, its status is updated * in the future with one of the possible values provided by the enumeration {@link FetchStatus}. * @throws IOException If an error occurs during the execution of the method that prevents fetching or saving the files. */ public FecthFuture fetchToDir(final URL baseUrl, final @Nullable String queryParam, final List<String> ids, final @Nullable String prefix, final @Nullable String suffix, final File outdir) throws IOException { // check mandatory parameters requireNonNull(baseUrl, "A valid URL expected"); final FecthFuture toBeCompleted = new FecthFuture( requireNonNull(ids, "A valid list of identifiers expected").stream().map(StringUtils::trimToNull) .filter(Objects::nonNull).distinct().collect(Collectors.toList())); requireNonNull(outdir, "A valid output directory expected"); checkArgument((outdir.isDirectory() && outdir.canWrite()) || outdir.mkdirs(), new StringBuilder("Cannot write to the output directory: ").append(outdir.getAbsolutePath()) .toString()); // get optional parameters final Optional<String> queryParam2 = ofNullable(trimToNull(queryParam)); final String prefix2 = ofNullable(prefix).orElse(""); final String suffix2 = ofNullable(suffix).orElse(""); try (final CloseableHttpAsyncClient asyncHttpClient = createFiberCloseableHttpAsyncClient()) { asyncHttpClient.start(); final UrlBuilder urlBuilder = getUrlBuilder(baseUrl); // an explanation is needed since this code is instrumented by Quasar and Comsat: requests are created during the first part of // this lambda expression (map), but they are not executed until the get() method is called in the second part of the expression // (forEach). Here that parallel stream is used to block and wait for the requests to complete. In case that a single stream is // used, each request will be created and executed sequentially. Therefore, the alternative to parallel stream is to separate // the lambda expression in two loops, creating the requests in the first loop and calling get() in the second one. toBeCompleted.monList.parallelStream().map(m -> { try { // create output file final File outfile = new File(outdir, new StringBuilder(prefix2).append(m.id).append(suffix2).append(".partial").toString()); checkState(outfile.createNewFile(), new StringBuilder("Cannot create the output file: ") .append(outfile.getAbsolutePath()).toString()); // create the HTTP request final HttpHost target = URIUtils.extractHost(baseUrl.toURI()); final HttpRequest request = new BasicHttpRequest("GET", urlBuilder.buildRelativeUrl(queryParam2.isPresent() ? null : m.id, queryParam2.isPresent() ? of(queryParam2.get(), m.id) : null)); final HttpAsyncRequestProducer producer = new BasicAsyncRequestProducer(target, request); // create the consumer final ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(outfile) { @Override protected File process(final HttpResponse response, final File file, final ContentType contentType) throws Exception { final StatusLine status = response.getStatusLine(); if (LOGGER.isDebugEnabled()) LOGGER.debug( new StringBuilder("Got file: statusCode=").append(status.getStatusCode()) .append(", file=").append(file.getAbsolutePath()).toString()); if (status.getStatusCode() != HttpStatus.SC_OK) throw new ClientProtocolException( new StringBuilder("Object fetch failed: ").append(status).toString()); return file; } }; // prepare request m.future = asyncHttpClient.execute(producer, consumer, new FutureCallback<File>() { @Override public void cancelled() { toBeCompleted.update(m.id, FetchStatus.CANCELLED); LOGGER.info("Task cancelled"); } @Override public void completed(final File result) { try { final Path path = result.toPath(); Files.move(path, path.resolveSibling(removeEnd(result.getName(), ".partial")), REPLACE_EXISTING); toBeCompleted.update(m.id, FetchStatus.COMPLETED); } catch (IOException ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed to move file to its final destination with error", ex); } } @Override public void failed(final Exception ex) { toBeCompleted.update(m.id, FetchStatus.FAILED); LOGGER.error("Fecth failed with error", ex); } }); } catch (Exception e) { LOGGER.error(new StringBuilder("Failed to fetch object with id: ").append(m.id).toString(), e); } return m; }).forEach(m -> { try { // submit requests and wait for completion m.future.get(); } catch (Exception ignore) { /* exceptions are handled in the callback functions */ } }); } return toBeCompleted; }
From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java
private void commitUpdates(StorageRequest request) throws StorageException { try {//from www .ja va 2s . c o m for (String contentUri : updateMap.get(request.getId())) { Path contentIdDir = getTempContentItemDir(request.getId(), new URI(contentUri)); Path target = getContentItemDir(new URI(contentUri)); try { if (Files.exists(contentIdDir)) { if (Files.exists(target)) { List<Path> files = listPaths(target); for (Path file : files) { if (!Files.isDirectory(file)) { Files.deleteIfExists(file); } } } Files.createDirectories(target.getParent()); Files.move(contentIdDir, target, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { LOGGER.debug( "Unable to move files by simple rename, resorting to copy. This will impact performance.", e); try { Path createdTarget = Files.createDirectories(target); List<Path> files = listPaths(contentIdDir); Files.copy(files.get(0), Paths.get(createdTarget.toAbsolutePath().toString(), files.get(0).getFileName().toString())); } catch (IOException e1) { throw new StorageException("Unable to commit changes for request: " + request.getId(), e1); } } } } catch (URISyntaxException e) { throw new StorageException(e); } finally { rollback(request); } }
From source file:org.apache.storm.localizer.LocalizedResource.java
@Override public void commitNewVersion(long version) throws IOException { String key = getKey();/*from w ww. j av a2 s . c om*/ LOG.info("Blob: {} updated to version {} from version {}", key, version, getLocalVersion()); Path localVersionFile = versionFilePath; // The false parameter ensures overwriting the version file, not appending try (PrintWriter writer = new PrintWriter( new BufferedWriter(new FileWriter(localVersionFile.toFile(), false)))) { writer.println(version); } setBlobPermissions(conf, user, localVersionFile); // Update the key.current symlink. First create tmp symlink and do // move of tmp to current so that the operation is atomic. Path tmpSymlink = tmpSymlinkLocation(); Path targetOfSymlink = constructBlobWithVersionFileName(baseDir, getKey(), version); LOG.debug("Creating a symlink @{} linking to: {}", tmpSymlink, targetOfSymlink); Files.createSymbolicLink(tmpSymlink, targetOfSymlink); Path currentSymLink = getCurrentSymlinkPath(); Files.move(tmpSymlink, currentSymLink, ATOMIC_MOVE); //Update the size of the objects setSize(); }
From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java
@Test public void testInitMovesFilesToProcessedDirectory() throws Exception { setUpTwoConfigFileIterator(configurationDirectoryStream); setUpConfigurationFileFactoryForTwoFiles(); when(Files.move(CONFIG_PATH1, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING)) .thenReturn(PROCESSED_DIRECTORY_PATH); when(Files.move(CONFIG_PATH2, PROCESSED_DIRECTORY_PATH, REPLACE_EXISTING)) .thenReturn(PROCESSED_DIRECTORY_PATH); ConfigurationAdminMigration configurationAdminMigrator = new ConfigurationAdminMigration( configurationDirectoryStream, PROCESSED_DIRECTORY_PATH, FAILED_DIRECTORY_PATH, configurationFileFactory, configurationFilePoller, configurationAdmin, CONFIGURATION_FILE_EXTENSION); configurationAdminMigrator.init();//from w w w.java 2 s . com verifyStatic(); Files.move(CONFIG_PATH1, CONFIG_FILE_IN_PROCESSED_DIRECTORY.resolve(CONFIG_FILE_PATH1), REPLACE_EXISTING); Files.move(CONFIG_PATH2, CONFIG_FILE_IN_PROCESSED_DIRECTORY, REPLACE_EXISTING); verify(configurationDirectoryStream).close(); }
From source file:it.reexon.lib.files.FileUtils.java
/** * Moves a file to a destination. /*www . j av a 2s . co m*/ * * @param file the path to the file to move * @param destination the destination path * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if file is null or not exists, destination is null */ public static void moveFile(Path file, Path destination) throws IOException, IllegalArgumentException { if ((file == null) || !Files.exists(file, LinkOption.NOFOLLOW_LINKS) || (destination == null)) { throw new IllegalArgumentException("The filepath is null or points to an invalid location! " + file); } Files.move(file, destination, StandardCopyOption.REPLACE_EXISTING); }
From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java
/** * Uses the given `http_client` to download `url` into `out_tmp`. * Renames `out_tmp` to the value of the filename param of the Content-Disposition header field. * Returns a path to the renamed file./*from w ww .j a v a 2 s.c o m*/ * * @param http_client synchronous interruptible HTTP client. * @param out_tmp download destination file on disk (will be created if does not exist). * @param url what to download. * @return Path to file with its actual name. * @throws IOException Anything went wrong (with IO or network, or if the HTTP header field * Content-Disposition is missing). * @throws InterruptedException Thread has been interrupted. */ private DownloadResult downloadValidateRename(InterruptibleHttpClient http_client, Path out_tmp, String url) throws IOException, InterruptedException { try (FileChannel output = FileChannel.open(out_tmp, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) { HttpResponse response = http_client.interruptibleGet(url, output); // If the response's status code is not 200, something wrong happened if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Formatter ff = new Formatter(); ff.format( "Synchronizer#%d cannot download product at %s," + " remote dhus returned message '%s' (HTTP%d)", getId(), url, response.getStatusLine().getReasonPhrase(), response.getStatusLine().getStatusCode()); throw new IOException(ff.out().toString()); } // Gets the filename from the HTTP header field `Content-Disposition' Pattern pat = Pattern.compile("filename=\"(.+?)\"", Pattern.CASE_INSENSITIVE); String contdis = response.getFirstHeader("Content-Disposition").getValue(); Matcher m = pat.matcher(contdis); if (!m.find()) { throw new IOException("Synchronizer#" + getId() + " Missing HTTP header field `Content-Disposition` that determines the filename"); } String filename = m.group(1); if (filename == null || filename.isEmpty()) { throw new IOException( "Synchronizer#" + getId() + " Invalid filename in HTTP header field `Content-Disposition`"); } // Renames the downloaded file output.close(); Path dest = out_tmp.getParent().resolve(filename); Files.move(out_tmp, dest, StandardCopyOption.ATOMIC_MOVE); DownloadResult res = new DownloadResult(dest, response.getEntity().getContentType().getValue(), response.getEntity().getContentLength()); return res; } finally { if (Files.exists(out_tmp)) { Files.delete(out_tmp); } } }
From source file:com.vasquez.FileSwitcher.java
private void switchTo(GameType gameType) { String sourcePath = null;/*www . jav a2 s . c o m*/ String targetPath = null; File sourceMpq = null; File targetMpq = null; if (gameType == GameType.Expansion) { Logger.LogInfo("The game will use the Expansion MPQs. Enabling Expansion ..."); sourcePath = root.getAbsolutePath() + "\\Expansion\\"; targetPath = root.getAbsolutePath() + "\\"; } else { Logger.LogInfo("The game will not use the Expansion MPQs. Enabling Classic ..."); sourcePath = root.getAbsolutePath() + "\\"; targetPath = root.getAbsolutePath() + "\\Expansion\\"; } for (String mpq : expansionMPQs) { if (gameType == GameType.Expansion) { sourceMpq = new File(sourcePath + mpq); targetMpq = new File(targetPath + mpq); } else { sourceMpq = new File(sourcePath + mpq); targetMpq = new File(targetPath + mpq); } Path sourceMpqPath = Paths.get(sourceMpq.getAbsolutePath()); Path targetMpqPath = Paths.get(targetMpq.getAbsolutePath()); if (sourceMpq.exists()) { try { Files.move(sourceMpqPath, targetMpqPath, REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java
private Path renameToTmpFilePath(Path sourceFilePath) throws IOException { String tmp_name = UUID.randomUUID() + "_" + sourceFilePath.getFileName().toString(); Path new_path = sourceFilePath.resolveSibling(tmp_name); Files.move(sourceFilePath, new_path, StandardCopyOption.ATOMIC_MOVE); return new_path; }
From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java
public void copyFiles() { if (!core.getDataFolder().exists()) { core.getDataFolder().mkdirs();//w w w. ja va 2 s. co m } if (!messagesFolder.exists()) { messagesFolder.mkdirs(); } { File[] files = core.getDataFolder().listFiles(); for (File f : files) { if (f.isFile() && f.getName().startsWith("messages")) { try { Files.move(f.toPath(), new File(messagesFolder, f.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, "An error has ocurred while moving messages files to the new messages folder.", ex); } } } } messagesFiles.keySet().forEach(filename -> { File messages = messagesFiles.get(filename); if (!messages.exists()) { copy(core.getResource(messages.getName()), messages); } }); if (!configFile.exists()) { copy(core.getResource("config.yml"), configFile); } }
From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetImplTestUtils.java
@Override public void changeStoredGenerationStamp(ExtendedBlock block, long newGenStamp) throws IOException { File blockFile = dataset.getBlockFile(block.getBlockPoolId(), block.getBlockId()); File metaFile = FsDatasetUtil.findMetaFile(blockFile); File newMetaFile = new File(DatanodeUtil.getMetaName(blockFile.getAbsolutePath(), newGenStamp)); Files.move(metaFile.toPath(), newMetaFile.toPath(), StandardCopyOption.ATOMIC_MOVE); }