List of usage examples for java.nio.file Path getParent
Path getParent();
From source file:ch.bender.evacuate.Helper.java
/** * Appends a number suffix to the name of the Path object. If the flag BeforeExtension is * <code>true</code>, the number is appended before the last dot in the file name. * <p>//www . j a va 2 s. c o m * See examples in {@link #appendNumberSuffix(Path, int)} * <p> * * @param aPath * the path whose name should be suffixed * @param aNumber * the number to suffix * @param aBeforeExtension * <code>true</code>: the extension stays the last part of the filename. * @return the new path */ public static Path appendNumberSuffix(Path aPath, int aNumber, boolean aBeforeExtension) { DecimalFormat df = new DecimalFormat("00"); String suffix = "_" + df.format(aNumber); String parent = aPath.getParent() == null ? "" : aPath.getParent().toString(); String extension = ""; String name = aPath.getFileName().toString(); if (aBeforeExtension) { extension = FilenameUtils.getExtension(name); if (extension.length() > 0) { extension = "." + extension; } name = FilenameUtils.getBaseName(name); } return Paths.get(parent, name + suffix + extension); }
From source file:com.blackducksoftware.integration.hub.detect.util.DetectZipUtil.java
public static void unzip(File zip, File dest, Charset charset) throws IOException { Path destPath = dest.toPath(); try (ZipFile zipFile = new ZipFile(zip, ZipFile.OPEN_READ, charset)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); Path entryPath = destPath.resolve(entry.getName()); if (!entryPath.normalize().startsWith(dest.toPath())) throw new IOException("Zip entry contained path traversal"); if (entry.isDirectory()) { Files.createDirectories(entryPath); } else { Files.createDirectories(entryPath.getParent()); try (InputStream in = zipFile.getInputStream(entry)) { try (OutputStream out = new FileOutputStream(entryPath.toFile())) { IOUtils.copy(in, out); }/*from w ww . java 2 s .c o m*/ } } } } }
From source file:org.opendatakit.briefcase.export.SubmissionParser.java
/** * Returns a parsed {@link Submission}, wrapped inside an {@link Optional} instance if * it meets some criteria:// w ww . j a v a2s.co m * <ul> * <li>The given {@link Path} points to a parseable submission file</li> * <li>If the form is encrypted, the submission can be decrypted</li> * </ul> * Returns an {@link Optional#empty()} otherwise. * * @param path the {@link Path} to the submission file * @param isEncrypted a {@link Boolean} indicating whether the form is encrypted or not. * @param privateKey the {@link PrivateKey} to be used to decrypt the submissions, * wrapped inside an {@link Optional} when the form is encrypted, or * {@link Optional#empty()} otherwise * @return the {@link Submission} wrapped inside an {@link Optional} when it meets all the * criteria, or {@link Optional#empty()} otherwise * @see #decrypt(Submission, SubmissionExportErrorCallback) */ static Optional<Submission> parseSubmission(Path path, boolean isEncrypted, Optional<PrivateKey> privateKey, SubmissionExportErrorCallback onError) { Path workingDir = isEncrypted ? createTempDirectory("briefcase") : path.getParent(); return parse(path, onError).flatMap(document -> { XmlElement root = XmlElement.of(document); SubmissionMetaData metaData = new SubmissionMetaData(root); // If all the needed parts are present, prepare the CipherFactory instance Optional<CipherFactory> cipherFactory = OptionalProduct .all(metaData.getInstanceId(), metaData.getBase64EncryptedKey(), privateKey) .map(CipherFactory::from); // If all the needed parts are present, decrypt the signature Optional<byte[]> signature = OptionalProduct.all(privateKey, metaData.getEncryptedSignature()) .map((pk, es) -> decrypt(signatureDecrypter(pk), decodeBase64(es))); Submission submission = Submission.notValidated(path, workingDir, root, metaData, cipherFactory, signature); return isEncrypted // If it's encrypted, validate the parsed contents with the attached signature ? decrypt(submission, onError).map(s -> s.copy(ValidationStatus.of(isValid(submission, s)))) // Return the original submission otherwise : Optional.of(submission); }); }
From source file:org.roda_project.commons_ip.utils.ZIPUtils.java
public static void unzip(Path zip, final Path dest) throws IOException { ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zip.toFile())); ZipEntry zipEntry = zipInputStream.getNextEntry(); if (zipEntry == null) { // No entries in ZIP zipInputStream.close();/*from w ww. j a va 2 s .c o m*/ } else { while (zipEntry != null) { // for each entry to be extracted String entryName = zipEntry.getName(); Path newFile = dest.resolve(entryName); if (zipEntry.isDirectory()) { Files.createDirectories(newFile); } else { if (!Files.exists(newFile.getParent())) { Files.createDirectories(newFile.getParent()); } OutputStream newFileOutputStream = Files.newOutputStream(newFile); IOUtils.copyLarge(zipInputStream, newFileOutputStream); newFileOutputStream.close(); zipInputStream.closeEntry(); } zipEntry = zipInputStream.getNextEntry(); } // end while zipInputStream.close(); } }
From source file:io.webfolder.cdp.ChromiumDownloader.java
private static void unpack(File archive, File destionation) throws IOException { try (ZipFile zip = new ZipFile(archive)) { Map<File, String> symLinks = new LinkedHashMap<>(); Enumeration<ZipArchiveEntry> iterator = zip.getEntries(); // Top directory name we are going to ignore String parentDirectory = iterator.nextElement().getName(); // Iterate files & folders while (iterator.hasMoreElements()) { ZipArchiveEntry entry = iterator.nextElement(); String name = entry.getName().substring(parentDirectory.length()); File outputFile = new File(destionation, name); if (name.startsWith("interactive_ui_tests")) { continue; }/*from w w w.j a v a 2 s.co m*/ if (entry.isUnixSymlink()) { symLinks.put(outputFile, zip.getUnixSymlink(entry)); } else if (!entry.isDirectory()) { if (!outputFile.getParentFile().isDirectory()) { outputFile.getParentFile().mkdirs(); } try (FileOutputStream outStream = new FileOutputStream(outputFile)) { IOUtils.copy(zip.getInputStream(entry), outStream); } } // Set permission if (!entry.isUnixSymlink() && outputFile.exists()) try { Files.setPosixFilePermissions(outputFile.toPath(), modeToPosixPermissions(entry.getUnixMode())); } catch (Exception e) { // ignore } } for (Map.Entry<File, String> entry : symLinks.entrySet()) { try { Path source = Paths.get(entry.getKey().getAbsolutePath()); Path target = source.getParent().resolve(entry.getValue()); if (!source.toFile().exists()) Files.createSymbolicLink(source, target); } catch (Exception e) { // ignore } } } }
From source file:objective.taskboard.utils.ZipUtils.java
public static void unzip(Stream<ZipStreamEntry> stream, Path output) { if (output.toFile().isFile()) throw new RuntimeException("Output must be a directory"); try {/* w ww . ja v a 2 s. co m*/ stream.forEach(ze -> { Path entryPath = output.resolve(ze.getName()); try { if (ze.isDirectory()) { createDirectories(entryPath); } else { createDirectories(entryPath.getParent()); copy(ze.getInputStream(), entryPath); } } catch (IOException e) { throw new UncheckedIOException(e); } }); } finally { stream.close(); } }
From source file:divconq.util.IOUtil.java
public static OperationResult saveEntireFile(Path dest, String content) { OperationResult or = new OperationResult(); try {//from www . j a va2 s .c om Files.createDirectories(dest.getParent()); Files.write(dest, Utf8Encoder.encode(content), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.SYNC); } catch (Exception x) { or.error(1, "Error saving file contents: " + x); } return or; }
From source file:com.netflix.nicobar.core.utils.ClassPathUtils.java
private static Path getRootPathFromDirectory(String resourceName, URL resource) { try {/*w w w . ja va2 s. c o m*/ Path result = Paths.get(resource.toURI()); int relativePathSize = Paths.get(resourceName).getNameCount(); for (int i = 0; i < relativePathSize; i++) { result = result.getParent(); } return result; } catch (URISyntaxException e) { throw new IllegalStateException("Unsupported URL syntax: " + resource, e); } }
From source file:org.ballerinalang.langserver.command.executors.CreateTestExecutor.java
/** * Returns a pair of current module path and calculated target test path. * * @param sourceFilePath source file path * @param projectRoot project root/* www . j a v a 2 s . c o m*/ * @return a pair of currentModule path(left-side) and target test path(right-side) */ private static ImmutablePair<Path, Path> getTestsDirPath(Path sourceFilePath, Path projectRoot) { if (sourceFilePath == null || projectRoot == null) { return null; } Path currentModulePath = projectRoot; Path prevSourceRoot = sourceFilePath.getParent(); List<String> pathParts = new ArrayList<>(); try { while (prevSourceRoot != null) { Path newSourceRoot = prevSourceRoot.getParent(); currentModulePath = prevSourceRoot; if (newSourceRoot == null || Files.isSameFile(newSourceRoot, projectRoot)) { // We have reached the project root break; } pathParts.add(prevSourceRoot.getFileName().toString()); prevSourceRoot = newSourceRoot; } } catch (IOException e) { // do nothing } // Append `tests` path Path testDirPath = currentModulePath.resolve(ProjectDirConstants.TEST_DIR_NAME); // Add same directory structure inside the module for (String part : pathParts) { testDirPath = testDirPath.resolve(part); } return new ImmutablePair<>(currentModulePath, testDirPath); }
From source file:org.phenotips.variantstore.shared.ResourceManager.java
/** * Copy resources bundled with the application to a specified folder. * * @param source the path of the resources relative to the resource folder * @param destination the destination/* w w w .j av a2 s . c o m*/ * @param clazz the class that owns the resource we want * @throws DatabaseException if an error occurs */ public static void copyResourcesToPath(final Path source, Path destination, Class<?> clazz) throws DatabaseException { Path dest = destination; // Check if storage dirs exists if (Files.isDirectory(dest)) { return; } // Make sure that we aren't double-nesting directories if (dest.endsWith(source)) { dest = dest.getParent(); } if (clazz.getProtectionDomain().getCodeSource() == null) { throw new DatabaseException("This is running in a jar loaded from the system class loader. " + "Don't know how to handle this."); } // Windows adds leading `/` to the path resulting in // java.nio.file.InvalidPathException: Illegal char <:> at index 2: /C:/... URL path = clazz.getProtectionDomain().getCodeSource().getLocation(); Path resourcesPath; try { resourcesPath = Paths.get(path.toURI()); } catch (URISyntaxException ex) { throw new DatabaseException("Incorrect resource path", ex); } try { // make destination folder Files.createDirectories(dest); // if we are running in a jar, get the resources from the jar if ("jar".equals(FilenameUtils.getExtension(resourcesPath.toString()))) { copyResourcesFromJar(resourcesPath, source, dest); // if running from an IDE or the filesystem, get the resources from the folder } else { copyResourcesFromFilesystem(resourcesPath.resolve(source), dest.resolve(source)); } } catch (IOException e) { throw new DatabaseException("Error setting up variant store, unable to install resources.", e); } }