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:de.qucosa.webapi.v1.DocumentResourceFileTest.java
@Test public void addsFileSize() throws Exception { Path src = new File(this.getClass().getResource("/blank.pdf").toURI()).toPath(); Path dest = tempFolder.getRoot().toPath().resolve(src.getFileName()); Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING); mockMvc.perform(post("/document").accept(new MediaType("application", "vnd.slub.qucosa-v1+xml")) .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml")) .content("<Opus version=\"2.0\">" + "<Opus_Document>" + " <DocumentId>815</DocumentId>" + " <PersonAuthor>" + " <LastName>Shakespear</LastName>" + " <FirstName>William</FirstName>" + " </PersonAuthor>" + " <TitleMain>" + " <Value>Macbeth</Value>" + " </TitleMain>" + " <IdentifierUrn>" + " <Value>urn:nbn:foo-4711</Value>" + " </IdentifierUrn>" + " <File>" + " <PathName>1057131155078-6506.pdf</PathName>" + " <Label>Volltextdokument (PDF)</Label>" + " <TempFile>blank.pdf</TempFile>" + " <OaiExport>1</OaiExport>" + " <FrontdoorVisible>1</FrontdoorVisible>" + " </File>" + "</Opus_Document>" + "</Opus>")) .andExpect(status().isCreated()); ArgumentCaptor<InputStream> argCapt = ArgumentCaptor.forClass(InputStream.class); verify(fedoraRepository).modifyDatastreamContent(eq("qucosa:815"), eq("QUCOSA-XML"), anyString(), argCapt.capture());/*from w ww . j ava 2s. co m*/ Document control = XMLUnit.buildControlDocument(new InputSource(argCapt.getValue())); assertXpathExists("/Opus/Opus_Document/File[FileSize='11112']", control); }
From source file:org.wso2.developerstudio.eclipse.registry.base.model.RegistryResourceNode.java
public boolean removeLocalContent() { InputStream contentStream = null; try {/*from www . j a v a2 s .co m*/ contentStream = getConnectionInfo().getRegistry().get(getRegistryResourcePath()).getContentStream(); Files.copy(contentStream, getFile().toPath(), StandardCopyOption.REPLACE_EXISTING); return true; } catch (InvalidRegistryURLException e) { log.error("Error while Connecting to registry due to " + e.getMessage(), e); } catch (UnknownRegistryException e) { log.error("Error while Connecting to registry due to " + e.getMessage(), e); } catch (RegistryException e) { log.error("Error while Connecting to registry due to " + e.getMessage(), e); } catch (IOException e) { log.error("Error while Copying contents due to " + e.getMessage(), e); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return false; }
From source file:com.microfocus.application.automation.tools.pc.PcClient.java
public boolean downloadTrendReportAsPdf(String trendReportId, String directory) throws PcException { try {/* ww w . j ava2 s. co m*/ logger.println(String.format("%s - %s: %s %s", dateFormatter.getDate(), Messages.DownloadingTrendReport(), trendReportId, Messages.InPDFFormat())); InputStream in = restProxy.getTrendingPDF(trendReportId); File dir = new File(directory); if (!dir.exists()) { dir.mkdirs(); } String filePath = directory + IOUtils.DIR_SEPARATOR + "trendReport" + trendReportId + ".pdf"; Path destination = Paths.get(filePath); Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING); logger.println(String.format("%s - %s: %s %s", dateFormatter.getDate(), Messages.TrendReport(), trendReportId, Messages.SuccessfullyDownloaded())); } catch (Exception e) { logger.println(String.format("%s - %s: %s", dateFormatter.getDate(), Messages.FailedToDownloadTrendReport(), e.getMessage())); throw new PcException(e.getMessage()); } return true; }
From source file:com.joyent.manta.client.MantaClient.java
/** * Copies Manta object's data to a temporary file on the file system and return * a reference to the file using a NIO {@link Path}. This method is memory * efficient because it uses streams to do the copy. * * @param path The fully qualified path of the object. i.e. /user/stor/foo/bar/baz * @return reference to the temporary file as a {@link Path} object * @throws IOException when there is a problem getting the object over the network *///from www .j ava2 s. c o m public Path getToTempPath(final String path) throws IOException { try (InputStream is = getAsInputStream(path)) { final Path temp = Files.createTempFile("manta-object", "tmp"); Files.copy(is, temp, StandardCopyOption.REPLACE_EXISTING); return temp; } }
From source file:gr.abiss.calipso.tiers.controller.AbstractModelController.java
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" }) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf;/* w ww. j ava 2s . com*/ BinaryFile bf = new BinaryFile(); try { if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } return bf; }
From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" }) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf;// ww w . j a v a2 s . c o m BinaryFile bf = new BinaryFile(); try { if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } // Map<String, Object> files= new HashMap<String, Object>(); //files.put("files", list); return bf; }
From source file:org.opencb.opencga.server.rest.FileWSServer.java
@Deprecated @GET//from w w w . jav a 2 s.co m @Path("/{fileId}/set-header") @ApiOperation(value = "Set file header", position = 10, notes = "Deprecated method. Moved to update.") public Response setHeader(@PathParam(value = "fileId") @FormDataParam("fileId") String fileStr, @ApiParam(value = "header", required = true) @DefaultValue("") @QueryParam("header") String header) { String content = ""; DataInputStream stream; QueryResult<File> fileQueryResult; InputStream streamBody = null; // System.out.println("header: "+header); try { long fileId = catalogManager.getFileId(convertPath(fileStr, sessionId), sessionId); /** Obtain file uri **/ File file = catalogManager.getFile(fileId, sessionId).getResult().get(0); URI fileUri = catalogManager.getFileUri(file); System.out.println("getUri: " + fileUri.getPath()); /** Set header **/ stream = catalogManager.downloadFile(fileId, sessionId); content = org.apache.commons.io.IOUtils.toString(stream); String lines[] = content.split(System.getProperty("line.separator")); StringBuilder body = new StringBuilder(); body.append(header); body.append(System.getProperty("line.separator")); for (int i = 0; i < lines.length; i++) { String line = lines[i]; if (!line.startsWith("#")) { body.append(line); if (i != lines.length - 1) body.append(System.getProperty("line.separator")); } } /** Write/Copy file **/ streamBody = new ByteArrayInputStream(body.toString().getBytes(StandardCharsets.UTF_8)); Files.copy(streamBody, Paths.get(fileUri), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { return createErrorResponse(e); } // createOkResponse(content, MediaType.TEXT_PLAIN) return createOkResponse(streamBody, MediaType.TEXT_PLAIN_TYPE); }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void moveChildrenFailsIfTryingToMoveAFileToANonEmptyDirectory() throws IOException { expected.expect(IOException.class); tmp.newFolder("dir1"); Files.write(tmp.newFile("dir1/file1"), "new file 1".getBytes(Charsets.UTF_8)); tmp.newFolder("dir2"); tmp.newFolder("dir2/file1"); tmp.newFile("dir2/file1/file2"); filesystem.mergeChildren(Paths.get("dir1"), Paths.get("dir2"), StandardCopyOption.REPLACE_EXISTING); }
From source file:org.tinymediamanager.core.Utils.java
/** * modified version of commons-io FileUtils.moveFile(); adapted to Java 7 NIO<br> * since renameTo() might not work in first place, retry it up to 5 times.<br> * (better wait 5 sec for success, than always copying a 50gig directory ;)<br> * <b>And NO, we're NOT doing a copy+delete as fallback!</b> * /*from ww w .j a va 2 s .c om*/ * @param srcFile * the file to be moved * @param destFile * the destination file * @throws NullPointerException * if source or destination is {@code null} * @throws FileExistsException * if the destination file exists * @throws IOException * if source or destination is invalid * @throws IOException * if an IO error occurs moving the file */ public static boolean moveFileSafe(final Path srcFile, final Path destFile) throws IOException { if (srcFile == null) { throw new NullPointerException("Source must not be null"); } if (destFile == null) { throw new NullPointerException("Destination must not be null"); } // if (!srcFile.equals(destFile)) { if (!srcFile.toAbsolutePath().toString().equals(destFile.toAbsolutePath().toString())) { LOGGER.debug("try to move file " + srcFile + " to " + destFile); if (!Files.exists(srcFile)) { throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); } if (Files.isDirectory(srcFile)) { throw new IOException("Source '" + srcFile + "' is a directory"); } if (Files.exists(destFile) && !Files.isSameFile(destFile, srcFile)) { // extra check for windows, where the File.equals is case insensitive // so we know now, that the File is the same, but the absolute name does not match throw new FileExistsException("Destination '" + destFile + "' already exists"); } if (Files.isDirectory(destFile)) { throw new IOException("Destination '" + destFile + "' is a directory"); } // rename folder; try 5 times and wait a sec boolean rename = false; for (int i = 0; i < 5; i++) { try { // need atomic fs move for changing cASE Files.move(srcFile, destFile, StandardCopyOption.ATOMIC_MOVE); rename = true;// no exception } catch (AtomicMoveNotSupportedException a) { // if it fails (b/c not on same file system) use that try { Files.move(srcFile, destFile, StandardCopyOption.REPLACE_EXISTING); rename = true; // no exception } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } } catch (IOException e) { LOGGER.warn("rename problem: " + e.getMessage()); } if (rename) { break; // ok it worked, step out } try { LOGGER.debug("rename did not work - sleep a while and try again..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn("I'm so excited - could not sleep"); } } if (!rename) { LOGGER.error("Failed to rename file '" + srcFile + " to " + destFile); MessageManager.instance .pushMessage(new Message(MessageLevel.ERROR, srcFile, "message.renamer.failedrename")); return false; } else { LOGGER.info("Successfully moved file from " + srcFile + " to " + destFile); return true; } } return true; // files are equal }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void moveChildrenMergesOneDirectoryIntoAnother() throws IOException { Path srcDir = tmp.newFolder("dir1"); Files.write(tmp.newFile("dir1/file1"), "new file 1".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1"); Files.write(tmp.newFile("dir1/subdir1/file2"), "new file 2".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1/subdir2"); Files.write(tmp.newFile("dir1/subdir1/subdir2/file3"), "new file 3".getBytes(Charsets.UTF_8)); tmp.newFolder("dir1/subdir1/subdir2/subdir3"); tmp.newFolder("dir2"); Path destRoot = tmp.newFolder("dir2/dir3"); Files.write(tmp.newFile("dir2/dir3/file1"), "old file 1".getBytes(Charsets.UTF_8)); Files.write(tmp.newFile("dir2/dir3/file1_1"), "old file 1_1".getBytes(Charsets.UTF_8)); tmp.newFolder("dir2/dir3/dir4"); tmp.newFolder("dir2/dir3/subdir1"); filesystem.mergeChildren(Paths.get("dir1"), Paths.get("dir2/dir3"), StandardCopyOption.REPLACE_EXISTING); assertTrue(Files.isDirectory(srcDir)); assertEquals("new file 1", Files.readAllLines(destRoot.resolve("file1")).get(0)); assertEquals("old file 1_1", Files.readAllLines(destRoot.resolve("file1_1")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("dir4"))); assertTrue(Files.isDirectory(destRoot.resolve("subdir1"))); assertEquals("new file 2", Files.readAllLines(destRoot.resolve("subdir1").resolve("file2")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2"))); assertEquals("new file 3", Files.readAllLines(destRoot.resolve("subdir1").resolve("subdir2").resolve("file3")).get(0)); assertTrue(Files.isDirectory(destRoot.resolve("subdir1").resolve("subdir2").resolve("subdir3"))); assertFalse(Files.exists(srcDir.resolve("subdir1"))); assertFalse(Files.exists(srcDir.resolve("file1"))); }