List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:com.liferay.sync.engine.document.library.handler.DownloadFileHandler.java
protected void copyFile(final SyncFile syncFile, Path filePath, InputStream inputStream, boolean append) throws Exception { OutputStream outputStream = null; Watcher watcher = WatcherManager.getWatcher(getSyncAccountId()); try {//from www. ja v a 2 s . c om Path tempFilePath = FileUtil.getTempFilePath(syncFile); boolean exists = FileUtil.exists(filePath); if (append) { outputStream = Files.newOutputStream(tempFilePath, StandardOpenOption.APPEND); IOUtils.copyLarge(inputStream, outputStream); } else { if (exists && (boolean) getParameterValue("patch")) { if (_logger.isDebugEnabled()) { _logger.debug("Patching {}", syncFile.getFilePathName()); } Files.copy(filePath, tempFilePath, StandardCopyOption.REPLACE_EXISTING); IODeltaUtil.patch(tempFilePath, inputStream); } else { Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING); } } watcher.addDownloadedFilePathName(filePath.toString()); if (GetterUtil.getBoolean(syncFile.getLocalExtraSettingValue("restoreEvent"))) { syncFile.unsetLocalExtraSetting("restoreEvent"); syncFile.setUiEvent(SyncFile.UI_EVENT_RESTORED_REMOTE); } else if (exists) { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_UPDATE); } else { syncFile.setUiEvent(SyncFile.UI_EVENT_DOWNLOADED_NEW); } FileKeyUtil.writeFileKey(tempFilePath, String.valueOf(syncFile.getSyncFileId()), false); FileUtil.setModifiedTime(tempFilePath, syncFile.getModifiedTime()); if (MSOfficeFileUtil.isLegacyExcelFile(filePath)) { syncFile.setLocalExtraSetting("lastSavedDate", MSOfficeFileUtil.getLastSavedDate(tempFilePath)); } Files.move(tempFilePath, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); ExecutorService executorService = SyncEngine.getExecutorService(); Runnable runnable = new Runnable() { @Override public void run() { IODeltaUtil.checksums(syncFile); syncFile.setState(SyncFile.STATE_SYNCED); SyncFileService.update(syncFile); } }; executorService.execute(runnable); } catch (FileSystemException fse) { if (fse instanceof AccessDeniedException) { _logger.error(fse.getMessage(), fse); syncFile.setState(SyncFile.STATE_ERROR); syncFile.setUiEvent(SyncFile.UI_EVENT_ACCESS_DENIED_LOCAL); SyncFileService.update(syncFile); return; } else if (fse instanceof NoSuchFileException) { if (isEventCancelled()) { SyncFileService.deleteSyncFile(syncFile); return; } } watcher.removeDownloadedFilePathName(filePath.toString()); String message = fse.getMessage(); _logger.error(message, fse); syncFile.setState(SyncFile.STATE_ERROR); if (message.contains("File name too long")) { syncFile.setUiEvent(SyncFile.UI_EVENT_FILE_NAME_TOO_LONG); } SyncFileService.update(syncFile); } finally { StreamUtil.cleanUp(outputStream); } }
From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java
private void moveInternal(DavNode destination) throws DavException { if (Files.isDirectory(destination.path.getParent())) { try {/*from www .j ava2 s . co m*/ Files.move(path, destination.path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new DavException(DavServletResponse.SC_INTERNAL_SERVER_ERROR, e); } } else { throw new DavException(DavServletResponse.SC_CONFLICT, "Destination's parent doesn't exist."); } }
From source file:de.digiway.rapidbreeze.server.model.download.Download.java
private int handleRunning() throws IOException { long position = targetChannel.position(); long transferred = targetChannel.transferFrom(sourceChannel, position, BLOCK_SIZE); targetChannel.position(position + transferred); if (targetChannel.size() == getUrlStatus().getFileSize()) { closeChannels();// w ww. j a v a 2s . c o m Files.move(tempFile, targetFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); done = true; statusHandler.newStatus(DownloadStatus.FINISHED_SUCCESSFUL); } return throttledInputStream.nextTransfer(BLOCK_SIZE); }
From source file:io.undertow.server.handlers.file.FileHandlerTestCase.java
@Test public void testFileTransferLargeFile() throws IOException, URISyntaxException { TestHttpClient client = new TestHttpClient(); Path tmp = Paths.get(System.getProperty("java.io.tmpdir")); StringBuilder message = new StringBuilder(); for (int i = 0; i < 100000; ++i) { message.append("Hello World"); }/*from w ww . j a v a 2 s. co m*/ Path large = Files.createTempFile(null, ".txt"); try { Files.copy(new ByteArrayInputStream(message.toString().getBytes(StandardCharsets.UTF_8)), large, StandardCopyOption.REPLACE_EXISTING); DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path", new ResourceHandler(new PathResourceManager(tmp, 1)) // 1 byte = force transfer .setDirectoryListingEnabled(true)))); HttpGet get = new HttpGet( DefaultServer.getDefaultServerURL() + "/path/" + large.getFileName().toString()); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); final String response = HttpClientUtils.readResponse(result); Header[] headers = result.getHeaders("Content-Type"); Assert.assertEquals("text/plain", headers[0].getValue()); Assert.assertTrue(response, response.equals(message.toString())); } finally { client.getConnectionManager().shutdown(); } }
From source file:fi.helsinki.cs.iot.kahvihub.admin.ServiceHttpRequestHandler.java
private File copyPluginFile(File file) { /* /* ww w . j av a 2 s.c o m*/ * TODO A number of features would need to be added, first it would be nice to have * separate folders for native and javascript plugins * then we need to make sure to manage different plugins version * Update them if necessary (similar to apps and services) */ if (file != null && file.exists() && !file.isDirectory()) { try { String filename = file.getName(); File nfile = new File(libFolder + filename); Files.copy(file.toPath(), nfile.toPath(), StandardCopyOption.REPLACE_EXISTING); return nfile; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } return null; }
From source file:org.tinymediamanager.core.tvshow.TvShowExporter.java
/** * exports movie list according to template file. * /*from w w w. j av a 2 s . co m*/ * @param tvShowsToExport * list of movies * @param exportDir * the path to export * @throws Exception * the exception */ @Override public <T extends MediaEntity> void export(List<T> tvShowsToExport, Path exportDir) throws Exception { LOGGER.info("preparing tv show export; using " + properties.getProperty("name")); // register own renderers engine.registerNamedRenderer(new NamedDateRenderer()); engine.registerNamedRenderer(new TvShowFilenameRenderer()); engine.registerNamedRenderer(new ArtworkCopyRenderer(exportDir)); // prepare export destination if (!Files.exists(exportDir)) { try { Files.createDirectories(exportDir); } catch (Exception e) { throw new Exception("error creating export directory"); } } // prepare listfile Path listExportFile = null; if (fileExtension.equalsIgnoreCase("html")) { listExportFile = exportDir.resolve("index.html"); } if (fileExtension.equalsIgnoreCase("xml")) { listExportFile = exportDir.resolve("tvshows.xml"); } if (fileExtension.equalsIgnoreCase("csv")) { listExportFile = exportDir.resolve("tvshows.csv"); } if (listExportFile == null) { throw new Exception("error creating tv show list file"); } // load episode template String episodeTemplateFile = properties.getProperty("episode"); String episodeTemplate = ""; if (StringUtils.isNotBlank(episodeTemplateFile)) { episodeTemplate = Utils.readFileToString(templateDir.resolve(episodeTemplateFile)); } // create the list LOGGER.info("generating tv show list"); Utils.deleteFileSafely(listExportFile); Map<String, Object> root = new HashMap<>(); root.put("tvShows", new ArrayList<>(tvShowsToExport)); String output = engine.transform(listTemplate, root); Utils.writeStringToFile(listExportFile, output); LOGGER.info("movie list generated: " + listExportFile); if (StringUtils.isNotBlank(detailTemplate)) { for (MediaEntity me : tvShowsToExport) { TvShow show = (TvShow) me; // create a TV show dir Path showDir = exportDir.resolve(getFilename(show)); if (Files.isDirectory(showDir)) { Utils.deleteDirectoryRecursive(showDir); } Files.createDirectory(showDir); Path detailsExportFile = showDir.resolve("tvshow." + fileExtension); root = new HashMap<>(); root.put("tvShow", show); output = engine.transform(detailTemplate, root); Utils.writeStringToFile(detailsExportFile, output); if (StringUtils.isNotBlank(episodeTemplate)) { for (TvShowEpisode episode : show.getEpisodes()) { List<MediaFile> mfs = episode.getMediaFiles(MediaFileType.VIDEO); if (!mfs.isEmpty()) { Path seasonDir = showDir.resolve(TvShowRenamer.generateSeasonDir("", episode)); if (!Files.isDirectory(seasonDir)) { Files.createDirectory(seasonDir); } String episodeFileName = getFilename(episode) + "." + fileExtension; Path episodeExportFile = seasonDir.resolve(episodeFileName); root = new HashMap<>(); root.put("episode", episode); output = engine.transform(episodeTemplate, root); Utils.writeStringToFile(episodeExportFile, output); } } } } } // copy all non .jtme/template.conf files to destination dir try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(templateDir)) { for (Path path : directoryStream) { if (Utils.isRegularFile(path)) { if (path.getFileName().toString().endsWith(".jmte") || path.getFileName().toString().endsWith("template.conf")) { continue; } Files.copy(path, exportDir.resolve(path.getFileName()), StandardCopyOption.REPLACE_EXISTING); } else if (Files.isDirectory(path)) { Utils.copyDirectoryRecursive(path, exportDir.resolve(path.getFileName())); } } } catch (IOException ex) { LOGGER.error("could not copy resources: ", ex); } }
From source file:org.apache.beam.sdk.io.LocalFileSystem.java
@Override protected void rename(List<LocalResourceId> srcResourceIds, List<LocalResourceId> destResourceIds) throws IOException { checkArgument(srcResourceIds.size() == destResourceIds.size(), "Number of source files %s must equal number of destination files %s", srcResourceIds.size(), destResourceIds.size());//from w w w. j a va2s . com int numFiles = srcResourceIds.size(); for (int i = 0; i < numFiles; i++) { LocalResourceId src = srcResourceIds.get(i); LocalResourceId dst = destResourceIds.get(i); LOG.debug("Renaming {} to {}", src, dst); File parent = dst.getCurrentDirectory().getPath().toFile(); if (!parent.exists()) { checkArgument(parent.mkdirs() || parent.exists(), "Unable to make output directory %s in order to move into file %s", parent, dst.getPath()); } // Rename the source file, replacing the existing destination. Files.move(src.getPath(), dst.getPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } }
From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java
/** * ?????.//w w w . j a v a2 s .co m * * @param metadata ?urlTree * @param ctx urlTree */ @Override public void save(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx) throws BadContentException { String localFileName = metadata.getAbsolutePath(); logger.debug("saving " + localFileName); Path f = this.generateFileObj(localFileName); InputStream b = metadata.getData(); // null????????? if (b == null) { return; } try { Path parent = f.getParent(); // ??????? if (Files.notExists(parent)) { Files.createDirectories(parent); } Files.copy(b, f, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new GenericResourceException(e); } }
From source file:edu.harvard.iq.dataverse.ThemeWidgetFragment.java
/** * Copy uploaded file to temp area, until we are ready to save * Copy filename into Dataverse logo /*from w w w . jav a 2 s. co m*/ * @param event */ public void handleImageFileUpload(FileUploadEvent event) { logger.finer("entering fileUpload"); if (this.tempDir == null) { createTempDir(); logger.finer("created tempDir"); } UploadedFile uFile = event.getFile(); try { uploadedFile = new File(tempDir, uFile.getFileName()); if (!uploadedFile.exists()) { uploadedFile.createNewFile(); } logger.finer("created file"); Files.copy(uFile.getInputstream(), uploadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); logger.finer("copied inputstream to file"); editDv.getDataverseTheme().setLogo(uFile.getFileName()); } catch (IOException e) { logger.finer("caught IOException"); logger.throwing("ThemeWidgetFragment", "handleImageFileUpload", e); throw new RuntimeException("Error uploading logo file", e); // improve error handling } // If needed, set the default values for the logo if (editDv.getDataverseTheme().getLogoFormat() == null) { editDv.getDataverseTheme().setLogoFormat(DataverseTheme.ImageFormat.SQUARE); } logger.finer("end handelImageFileUpload"); }
From source file:org.owasp.dependencycheck.data.update.RetireJSDataSource.java
/** * Initializes the local RetireJS repository * * @param settings a reference to the dependency-check settings * @param repoUrl the URL to the RetireJS repo to use * @throws UpdateException thrown if there is an exception during * initialization/*from w ww. j a v a 2 s . c o m*/ */ private void initializeRetireJsRepo(Settings settings, URL repoUrl) throws UpdateException { try { final File dataDir = settings.getDataDirectory(); final File tmpDir = settings.getTempDirectory(); boolean useProxy = false; if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) { useProxy = true; LOGGER.debug("Using proxy"); } LOGGER.debug("RetireJS Repo URL: {}", repoUrl.toExternalForm()); final URLConnectionFactory factory = new URLConnectionFactory(settings); final HttpURLConnection conn = factory.createHttpURLConnection(repoUrl, useProxy); final String filename = repoUrl.getFile().substring(repoUrl.getFile().lastIndexOf("/") + 1, repoUrl.getFile().length()); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { final File tmpFile = new File(tmpDir, filename); final File repoFile = new File(dataDir, filename); try (InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(tmpFile)) { IOUtils.copy(inputStream, outputStream); } //using move fails if target and destination are on different disks which does happen (see #1394 and #1404) Files.copy(tmpFile.toPath(), repoFile.toPath(), StandardCopyOption.REPLACE_EXISTING); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } } catch (IOException e) { throw new UpdateException("Failed to initialize the RetireJS repo", e); } }