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.facebook.buck.rules.HttpArtifactCache.java
public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException { Request request = createRequestBuilder(ruleKey.toString()).get().build(); Response response = fetchCall(request); if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) { LOGGER.info("fetch(%s): cache miss", ruleKey); return CacheResult.MISS; }/*from w ww . j av a 2 s. co m*/ if (response.code() != HttpURLConnection.HTTP_OK) { LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code()); return CacheResult.MISS; } // The hash code shipped with the artifact to/from the cache. HashCode expectedHashCode, actualHashCode; // Setup a temporary file, which sits next to the destination, to write to and // make sure all parent dirs exist. Path path = file.toPath(); projectFilesystem.createParentDirs(path); Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp"); // Open the stream to server just long enough to read the hash code and artifact. try (DataInputStream input = new DataInputStream(response.body().byteStream())) { // First, extract the size of the file data portion, which we put in the beginning of // the artifact. long length = input.readLong(); // Now, write the remaining response data to the temp file, while grabbing the hash. try (BoundedInputStream boundedInput = new BoundedInputStream(input, length); HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput); OutputStream output = projectFilesystem.newFileOutputStream(temp)) { ByteStreams.copy(hashingInput, output); actualHashCode = hashingInput.hash(); } // Lastly, extract the hash code from the end of the request data. byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE]; ByteStreams.readFully(input, hashCodeBytes); expectedHashCode = HashCode.fromBytes(hashCodeBytes); // We should be at the end of output -- verify this. Also, we could just try to read a // single byte here, instead of all remaining input, but some network stack implementations // require that we exhaust the input stream before the connection can be reusable. try (OutputStream output = ByteStreams.nullOutputStream()) { if (ByteStreams.copy(input, output) != 0) { LOGGER.warn("fetch(%s): unexpected end of input", ruleKey); return CacheResult.MISS; } } } // Now form the checksum on the file we got and compare it to the checksum form the // the HTTP header. If it's incorrect, log this and return a miss. if (!expectedHashCode.equals(actualHashCode)) { LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey); projectFilesystem.deleteFileAtPath(temp); return CacheResult.MISS; } // Finally, move the temp file into it's final place. projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING); LOGGER.info("fetch(%s): cache hit", ruleKey); return CacheResult.HTTP_HIT; }
From source file:org.sonarlint.cli.report.HtmlReport.java
private void copyDependency(Path target, String filename) { String resource = "sonarlintreport_files/" + filename; try (InputStream in = getClass().getResourceAsStream(resource)) { Files.copy(in, target.resolve(filename), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new IllegalStateException("Fail to copy file " + filename + " to " + target, e); }/* w w w . j a v a2 s . c o m*/ }
From source file:com.networknt.codegen.eventuate.EventuateHybridServiceGenerator.java
@Override public void generate(String targetPath, Object model, Any config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean("overwriteHandlerTest"); boolean enableHttp = config.toBoolean("enableHttp"); boolean enableHttps = config.toBoolean("enableHttps"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean supportClient = config.toBoolean("supportClient"); String version = config.toString("version"); transfer(targetPath, "", "pom.xml", templates.eventuate.hybrid.service.pom.template(config)); //transfer(targetPath, "", "Dockerfile", templates.dockerfile.template(config)); transfer(targetPath, "", ".gitignore", templates.eventuate.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.eventuate.hybrid.service.README.template()); transfer(targetPath, "", "LICENSE", templates.eventuate.hybrid.LICENSE.template()); transfer(targetPath, "", ".classpath", templates.eventuate.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.eventuate.hybrid.project.template()); // config//w w w. j a v a2 s. c o m transfer(targetPath, ("src.main.resources.config").replace(".", separator), "service.yml", templates.eventuate.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.eventuate.hybrid.serverYml.template( config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secret.yml", templates.eventuate.hybrid.secretYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "hybrid-security.yml", templates.eventuate.hybrid.securityYml.template()); if (supportClient) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "client.yml", templates.eventuate.hybrid.clientYml.template()); } else { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.eventuate.hybrid.clientYml.template()); } transfer(targetPath, ("src.test.resources.config").replace(".", separator), "primary.crt", templates.eventuate.hybrid.primaryCrt.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secondary.crt", templates.eventuate.hybrid.secondaryCrt.template()); // logging transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.eventuate.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.eventuate.hybrid.logback.template()); // handler Map<String, Object> services = new HashMap<String, Object>(); Any anyModel = (Any) model; String host = anyModel.toString("host"); String service = anyModel.toString("service"); List<Any> items = anyModel.get("action").asList(); if (items != null && items.size() > 0) { for (Any item : items) { Any any = item.get("example"); String example = any.valueType() != ValueType.INVALID ? StringEscapeUtils.escapeJson(any.toString()).trim() : ""; if (overwriteHandler) transfer(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java", templates.eventuate.hybrid.handler .template(handlerPackage, host, service, item, example)); String serviceId = host + "/" + service + "/" + item.get("name") + "/" + item.get("version"); Map<String, Object> map = new HashMap<>(); map.put("schema", item.get("schema")); map.put("scope", item.get("scope")); services.put(serviceId, map); } // handler test cases transfer(targetPath, ("src.test.java." + handlerPackage + ".").replace(".", separator), "TestServer.java", templates.eventuate.hybrid.testServer.template(handlerPackage)); if (overwriteHandlerTest) { for (Any item : items) { transfer(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java", templates.eventuate.hybrid.handlerTest.template(handlerPackage, host, service, item)); } } } // transfer binary files without touching them. try (InputStream is = EventuateHybridServiceGenerator.class .getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = EventuateHybridServiceGenerator.class .getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if (Files.notExists(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator)))) { Files.createDirectories(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator))); } // write the generated schema into the config folder for schema validation. JsonStream.serialize(services, new FileOutputStream(FileSystems.getDefault() .getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.json").toFile())); }
From source file:de.ks.file.FileStoreTest.java
@Test public void testGetFileReferences() throws Exception { Path path = Files.createTempFile("img", ".jpg"); URL resource = getClass().getResource("/de/ks/idnadrev/entity/img.jpg"); Path src = Paths.get(resource.toURI()); Files.copy(src, path, StandardCopyOption.REPLACE_EXISTING); File file = path.toFile();/*from w ww . j a v a 2 s .co m*/ file.deleteOnExit(); FileReference fileReference = fileStore.getReference(file).get(); PersistentWork.run(em -> { fileStore.scheduleCopy(fileReference, file); em.persist(fileReference); }); assertThat(fileReference.getMimeType(), containsString("image")); List<FileReference> references = fileStore.getFilesByMimeType(MediaType.ANY_IMAGE_TYPE); assertEquals(1, references.size()); references = fileStore.getFilesByMimeType(MediaType.ANY_AUDIO_TYPE); assertEquals(0, references.size()); references = fileStore.getFilesByMimeType(MediaType.ANY_TYPE); assertEquals(1, references.size()); }
From source file:com.networknt.codegen.hybrid.HybridServiceGenerator.java
@Override public void generate(String targetPath, Object model, Any config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean("overwriteHandlerTest"); boolean enableHttp = config.toBoolean("enableHttp"); boolean enableHttps = config.toBoolean("enableHttps"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean supportClient = config.toBoolean("supportClient"); String version = config.toString("version"); transfer(targetPath, "", "pom.xml", templates.hybrid.service.pom.template(config)); //transfer(targetPath, "", "Dockerfile", templates.dockerfile.template(config)); transfer(targetPath, "", ".gitignore", templates.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.hybrid.service.README.template()); transfer(targetPath, "", "LICENSE", templates.hybrid.LICENSE.template()); transfer(targetPath, "", ".classpath", templates.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.hybrid.project.template()); // config/* w w w .ja v a2 s.c om*/ transfer(targetPath, ("src.test.resources.config").replace(".", separator), "service.yml", templates.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.hybrid.serverYml.template( config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secret.yml", templates.hybrid.secretYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "hybrid-security.yml", templates.hybrid.securityYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.hybrid.clientYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "primary.crt", templates.hybrid.primaryCrt.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secondary.crt", templates.hybrid.secondaryCrt.template()); // logging transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.hybrid.logback.template()); // handler Map<String, Object> services = new HashMap<String, Object>(); Any anyModel = (Any) model; String host = anyModel.toString("host"); String service = anyModel.toString("service"); List<Any> items = anyModel.get("action").asList(); if (items != null && items.size() > 0) { for (Any item : items) { Any any = item.get("example"); String example = any.valueType() != ValueType.INVALID ? StringEscapeUtils.escapeJson(any.toString()).trim() : ""; if (!overwriteHandler && checkExist(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java")) { continue; } transfer(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java", templates.hybrid.handler.template(handlerPackage, host, service, item, example)); String serviceId = host + "/" + service + "/" + item.get("name") + "/" + item.get("version"); Map<String, Object> map = new HashMap<>(); map.put("schema", item.get("schema")); map.put("scope", item.get("scope")); services.put(serviceId, map); } // handler test cases transfer(targetPath, ("src.test.java." + handlerPackage + ".").replace(".", separator), "TestServer.java", templates.hybrid.testServer.template(handlerPackage)); for (Any item : items) { if (!overwriteHandlerTest && checkExist(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java")) { continue; } transfer(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java", templates.hybrid.handlerTest.template(handlerPackage, host, service, item)); } } // transfer binary files without touching them. try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if (Files.notExists(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator)))) { Files.createDirectories(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator))); } // write the generated schema into the config folder for schema validation. JsonStream.serialize(services, new FileOutputStream(FileSystems.getDefault() .getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.json").toFile())); }
From source file:course.cloud.computing.rest.ImageService.java
@POST @Consumes("image/jpeg") public Response upload(InputStream in, @HeaderParam("Content-Type") String fileType, @HeaderParam("Content-Length") long fileSize) throws IOException { System.out.println("Received call to load"); // Make sure the file is not larger than the maximum allowed size. if (fileSize > 1024 * 1024 * MAX_SIZE_IN_MB) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST) .entity("Image is larger than " + MAX_SIZE_IN_MB + "MB").build()); }/* www . j a v a 2 s .c o m*/ String fileName = "" + System.currentTimeMillis(); if (fileType.equals("image/jpeg")) { fileName += ".jpg"; } else { fileName += ".png"; } System.out.println("Set new filename to " + fileName); File directory = new File("images"); if (!directory.isDirectory()) { boolean created = directory.mkdir(); if (!created) { System.out.println("Unable to create a folder for images"); return Response.serverError().build(); } } java.nio.file.Path path = Paths.get("images"); Files.copy(in, path.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); return Response.status(Status.CREATED).location(URI.create("/" + fileName)).build(); }
From source file:org.codehaus.cargo.website.WebsiteGenerator.java
private static void parse() throws Exception { System.out.println("Parsing files and generating Web site"); File target = new File("target"); File attachments = new File(target, "attachments"); File classes = new File(target, "classes"); Files.copy(new File(classes, "blank.gif").toPath(), new File(attachments, "blank.gif").toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(new File(classes, "favicon.ico").toPath(), new File(attachments, "favicon.ico").toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(new File(classes, "rss.gif").toPath(), new File(attachments, "rss.gif").toPath(), StandardCopyOption.REPLACE_EXISTING); writeFile(new File(attachments, "site.css"), readFile(new File(classes, "site.css"))); File sourceDirectory = new File(target, "source"); Files.copy(new File(classes, "search.html").toPath(), new File(sourceDirectory, "Search").toPath(), StandardCopyOption.REPLACE_EXISTING); String template = readFile(new File(target, "classes/cargo-template.html")); String navigation = readFile(new File(sourceDirectory, "Navigation")); template = template.replace("$navigation", navigation); for (File sourceFile : sourceDirectory.listFiles()) { String name = sourceFile.getName(); File file = new File(target, name + ".html"); String value = readFile(sourceFile); value = value.replaceAll("<script type=\"syntaxhighlighter\"[^>]+><\\!\\[CDATA\\[", "<pre>"); value = value.replace("]]></script>", "</pre>"); value = value.replaceAll("<div id=\"refresh-module-\\d*\"", "<div"); value = value.replaceAll("<div id=\"jira-issues-\\d*\"", "<div"); value = value.replaceAll("<span id=\"total-issues-count-\\d*\"", "<span"); value = value.replaceAll("(?s)<div id=\"refresh-\\d*\".*?</div>", ""); value = value.replaceAll("(?s)<span id=\"error-message-\\d*\".*?</span>", ""); value = value.replaceAll("(?s)<span class=\"refresh-action-group\".*?</span>", ""); value = value.replaceAll("(?s)<textarea id=\"refresh-wiki-\\d*\".*?</textarea>", ""); value = value.replaceAll("<input id=\"refresh-page-id-\\d*\"[^>]+>", ""); List<Integer> headerIndexes = new ArrayList<Integer>(); int lastIndex = 0; while (lastIndex >= 0) { if (headerIndexes.size() > 0) { lastIndex = headerIndexes.get(headerIndexes.size() - 1) + 1; }/* www . j a va 2s.c o m*/ int nextIndex = value.length(); int h1 = value.indexOf("<h1", lastIndex); if (h1 != -1) { nextIndex = Math.min(nextIndex, h1); } int h2 = value.indexOf("<h2", lastIndex); if (h2 != -1) { nextIndex = Math.min(nextIndex, h2); } int h3 = value.indexOf("<h3", lastIndex); if (h3 != -1) { nextIndex = Math.min(nextIndex, h3); } int h4 = value.indexOf("<h4", lastIndex); if (h4 != -1) { nextIndex = Math.min(nextIndex, h4); } if (nextIndex == value.length()) { nextIndex = -1; } lastIndex = nextIndex; if (lastIndex >= 0) { headerIndexes.add(lastIndex); } } lastIndex = headerIndexes.size() - 2; while (lastIndex > 1) { int cut = headerIndexes.get(lastIndex); value = value.substring(0, cut) + googleAds + value.substring(cut); lastIndex = lastIndex - 2; } writeFile(file, Jsoup.parse(template.replace("$name", name).replace("$title", URLDecoder.decode(name, "UTF-8")) .replace("$value", value) .replace("http://jira.codehaus.org/browse/CARGO-", "https://codehaus-cargo.atlassian.net/browse/CARGO-") .replace("https://jira.codehaus.org/browse/CARGO-", "https://codehaus-cargo.atlassian.net/browse/CARGO-")) .html()); System.out.println(" - Wrote file " + file.getAbsolutePath()); } System.out.println("Parsing complete"); }
From source file:onl.area51.gfs.grib2.job.GribRetriever.java
public Path retrieveOffset(Path dir, int offset, boolean forceRetrive) throws IOException { LOG.log(Level.INFO, () -> "Looking for GFS file for offset " + offset); String ending = String.format("z.pgrb2.0p25.f%03d", offset); @SuppressWarnings("ThrowableInstanceNotThrown") FTPFile remote = client.files().filter(f -> f.getName().startsWith("gfs.t")) .filter(f -> f.getName().endsWith(ending)).peek(f -> LOG.warning(f.getName())).findAny() .orElseThrow(() -> new FileNotFoundException("Unable to find GFS file for " + offset)); Path file = dir.resolve(remote.getName()); if (forceRetrive || client.isPathRetrievable(file, remote)) { LOG.log(Level.INFO, () -> "Retrieving " + remote.getSize() + " bytes to " + file); try (InputStream is = client.retrieveFileStream(remote)) { Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING); }/* www .ja v a 2 s.co m*/ LOG.log(Level.INFO, () -> "Retrieved " + remote.getSize() + " bytes"); } else { LOG.log(Level.INFO, () -> "Skipping retrieval as local file is newer"); } return file; }
From source file:org.apache.tika.server.CXFTestBase.java
private Path writeTemporaryArchiveFile(InputStream inputStream, String archiveType) throws IOException { Path tmp = Files.createTempFile("apache-tika-server-test-tmp-", "." + archiveType); Files.copy(inputStream, tmp, StandardCopyOption.REPLACE_EXISTING); return tmp;/*from w ww .ja va 2 s.c o m*/ }
From source file:org.roda.core.storage.fs.FSUtils.java
private static void moveRecursively(final Path sourcePath, final Path targetPath, final boolean replaceExisting) throws GenericException { final CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING } : new CopyOption[] {}; try {//from w ww.j a va2 s . c om Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path sourceDir, BasicFileAttributes attrs) throws IOException { Path targetDir = targetPath.resolve(sourcePath.relativize(sourceDir)); LOGGER.trace("Creating target directory {}", targetDir); Files.createDirectories(targetDir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException { Path targetFile = targetPath.resolve(sourcePath.relativize(sourceFile)); LOGGER.trace("Moving file from {} to {}", sourceFile, targetFile); Files.move(sourceFile, targetFile, copyOptions); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path sourceFile, IOException exc) throws IOException { LOGGER.trace("Deleting source directory {}", sourceFile); Files.delete(sourceFile); return FileVisitResult.CONTINUE; } }); } catch (IOException e) { throw new GenericException( "Error while moving (recursively) directory from " + sourcePath + " to " + targetPath, e); } }