List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:org.openthinclient.pkgmgr.UpdateDatabase.java
private boolean downloadChangelogFile(NetworkConfiguration.ProxyConfiguration proxyConfiguration, Source source, Package pkg, PackageManagerTaskSummary taskSummary) throws PackageManagerException { try {// ww w . j a v a 2s . c o m final Path changelogFile = directoryStructure.changelogFileLocation(source, pkg); Files.createDirectories(changelogFile.getParent()); downloadManager.downloadTo(createPackageChangeLogURL(pkg), changelogFile.toFile()); return true; } catch (final Exception e) { if (null != taskSummary) { taskSummary.addWarning(e.toString()); } LOG.warn("Changelog download failed for package " + pkg.getName()); return false; } }
From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { SandboxedExecutor.logger.debug("Copying program into jail"); final Path chrootedProgram = this.storage.getPath().resolve("chroot") .resolve(program.getFileName().toString()); chrootedProgram.getParent().toFile().mkdirs(); FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument(MessageFormat.format("--jail={0}", this.storage.getPath().resolve("chroot").toAbsolutePath().toString())); commandLine.addArgument("--"); commandLine/*ww w. j a v a 2s .c o m*/ .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString()); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the // sandbox to // complete executor.setWorkingDirectory(this.storage.getPath().toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString()); try { executor.execute(commandLine); } catch (final ExecuteException e) { SandboxedExecutor.logger.info("Execution failed: {}", e); throw e; } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt")); }
From source file:it.tidalwave.northernwind.util.test.TestHelper.java
/******************************************************************************************************************* * * Create a {@link TestResource} for the given name. The actual file will be created under * {@code target/test-artifacts/test-class-simple-name/resourceName}. The expected file should be * placed in {@code src/test/resources/test-class-simple-name/expected-resoults/resource-name}. Note that the file * actually loaded is the one under {@code target/test-classes} copied there (and eventually filtered) by Maven. * The {@code test-class-simple-name} is tried first with the current test, and then with its eventual * super-classes; this allows to extend existing test suites. Note that if the resource files for a super class are * not in the current project module, they should be explicitly copied here (for instance, by means of the * Maven dependency plugin).// w ww .ja v a 2 s . c o m * * @param resourceName the name * @return the {@code TestResource} * @throws IOException in case of error * ******************************************************************************************************************/ @Nonnull public TestResource testResourceFor(final @Nonnull String resourceName) throws IOException { final String testName = test.getClass().getSimpleName(); final Path expectedFile = findExpectedFilePath(resourceName); final Path actualFile = Paths.get("target/test-artifacts", testName, resourceName); Files.createDirectories(actualFile.getParent()); return new TestResource(resourceName, actualFile, expectedFile); }
From source file:it.polito.ai.polibox.client.http.action.AbstractFileAction.java
public void createFileFs(Resource r) { String s = r.getName();/* w w w. j a v a 2 s. com*/ // System.out.println(r.getName()+" file creation in filesystem: "); try { if (!s.startsWith(getTargetFolderCanonicalPath())) { s = getTargetFolderCanonicalPath() + r.getName(); } Path p = Paths.get(s); if (!Files.exists(p.getParent())) Files.createDirectories(p.getParent()); r.setName(s); Files.createFile(p); } catch (FileAlreadyExistsException e) { // System.out.println(r.getName()+" file esisteva gi"); } catch (IOException e) { // System.out.println(r.getName()+" ha lanciato eccezione."); throw new RuntimeException(e); } }
From source file:org.roda_project.commons_ip.model.impl.bagit.BagitSIP.java
private void createFiles(IPFile file, Path representationPath) { String relativeFilePath = ModelUtils.getFoldersFromList(file.getRelativeFolders()) + file.getFileName(); Path destination = representationPath.resolve(relativeFilePath); try {//from ww w. j a v a 2 s. c om Files.createDirectories(destination.getParent()); try (InputStream input = Files.newInputStream(file.getPath()); OutputStream output = Files.newOutputStream(destination);) { IOUtils.copyLarge(input, output); } } catch (IOException e) { LOGGER.error("Error creating file {} on bagit data folder", file.getFileName(), e); } }
From source file:de.tiqsolutions.hdfs.HadoopFileSystemPath.java
Deque<Path> getPathSegments() { Deque<Path> paths = new ArrayDeque<>(); Path root = getRoot();//from ww w.jav a2s . c o m Path p = this; while (p != null && !p.equals(root)) { paths.push(p.getFileName()); p = p.getParent(); } return paths; }
From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java
@Override public PutObjectResult putObject(PutObjectRequest request) { if (request.getObjectMetadata() != null) { request.setObjectMetadata(null); }//from ww w . j a va2 s. c o m try { Path path = Paths.get(this.baseDir, request.getBucketName(), request.getKey()); Files.createDirectories(path.getParent()); Files.createFile(path); } catch (IOException e) { throw new S3Exception(e.getMessage(), 0, e); } PutObjectResult retVal = new PutObjectResult(); if (request.getAcl() != null) { long size = 0; if (request.getRange() != null) { size = request.getRange().getLast() + 1; } aclMap.putIfAbsent(request.getKey(), new AclSize(request.getAcl(), size)); } return retVal; }
From source file:at.tfr.securefs.ws.FileServiceBean.java
@MTOM(enabled = true, threshold = 10240) @WebMethod//from w w w . j a va2 s .c o m @Override public void write(@WebParam(name = "relativePath") String relPath, @WebParam(name = "bytes") byte[] b) throws IOException { log.debug("write File: " + relPath); try { String tmpFileName = Paths.get(relPath).getFileName().toString() + System.currentTimeMillis(); Path tmpPath = Files.createFile(configuration.getTmpPath().resolve(tmpFileName)); try { try (OutputStream os = Files.newOutputStream(tmpPath)) { IOUtils.write(b, os); } preProcessor.preProcess(tmpPath); log.debug("preprocessed File: " + relPath); } finally { Files.deleteIfExists(tmpPath); } } catch (ModuleException me) { String message = "preProcessing of relPath failed: " + me.getMessage(); if (log.isDebugEnabled()) { log.debug(message, me); } log.info(message); throw new IOException(message); } Path path = SecureFileSystemBean.resolvePath(relPath, configuration.getBasePath(), configuration.isRestrictedToBasePath()); log.debug("write File: " + relPath + " to " + path); Path parent = path.getParent(); Files.createDirectories(parent); // create parent directories unconditionally OutputStream encrypter = crypterProvider.getEncrypter(path); try { IOUtils.copyLarge(new ByteArrayInputStream(b), encrypter); } finally { encrypter.close(); } logInfo("written File: " + path, null); }
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 w w .ja v a2 s.com 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:com.sastix.cms.server.services.content.HashedDirectoryServiceTest.java
private int listRecursive(Path path) throws IOException { final int[] counter = { 0 }; Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override//w w w . j a va2 s . co m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { counter[0]++; LOGGER.trace("Listing: [" + counter[0] + "]\t" + file.getParent() + "/" + file.getFileName()); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); return counter[0]; }