List of usage examples for java.nio.file Path subpath
Path subpath(int beginIndex, int endIndex);
From source file:org.apache.nifi.processors.standard.MergeContent.java
private String getPath(final FlowFile flowFile) { Path path = Paths.get(flowFile.getAttribute(CoreAttributes.PATH.key())); if (path.getNameCount() == 0) { return ""; }//from w ww. java 2s . c om if (".".equals(path.getName(0).toString())) { path = path.getNameCount() == 1 ? null : path.subpath(1, path.getNameCount()); } return path == null ? "" : path.toString() + "/"; }
From source file:org.apache.rya.api.path.PathUtils.java
/** * Indicates whether file lives in a secure directory relative to the * program's user.//from w ww . j a va2 s.c o m * @param file {@link Path} to test. * @param user {@link UserPrincipal} to test. If {@code null}, defaults to * current user. * @param symlinkDepth Number of symbolic links allowed. * @return {@code true} if file's directory is secure. */ public static boolean isInSecureDir(Path file, UserPrincipal user, final int symlinkDepth) { if (!file.isAbsolute()) { file = file.toAbsolutePath(); } if (symlinkDepth <= 0) { // Too many levels of symbolic links return false; } // Get UserPrincipal for specified user and superuser final Path fileRoot = file.getRoot(); if (fileRoot == null) { return false; } final FileSystem fileSystem = Paths.get(fileRoot.toString()).getFileSystem(); final UserPrincipalLookupService upls = fileSystem.getUserPrincipalLookupService(); UserPrincipal root = null; try { if (SystemUtils.IS_OS_UNIX) { root = upls.lookupPrincipalByName("root"); } else { root = upls.lookupPrincipalByName("Administrators"); } if (user == null) { user = upls.lookupPrincipalByName(System.getProperty("user.name")); } if (root == null || user == null) { return false; } } catch (final IOException x) { return false; } // If any parent dirs (from root on down) are not secure, dir is not secure for (int i = 1; i <= file.getNameCount(); i++) { final Path partialPath = Paths.get(fileRoot.toString(), file.subpath(0, i).toString()); try { if (Files.isSymbolicLink(partialPath)) { if (!isInSecureDir(Files.readSymbolicLink(partialPath), user, symlinkDepth - 1)) { // Symbolic link, linked-to dir not secure return false; } } else { final UserPrincipal owner = Files.getOwner(partialPath); if (!user.equals(owner) && !root.equals(owner)) { // dir owned by someone else, not secure return SystemUtils.IS_OS_UNIX ? false : Files.isWritable(partialPath); } } } catch (final IOException x) { return false; } } return true; }
From source file:org.ballerinalang.util.parser.antlr4.BLangAntlr4Listener.java
public BLangAntlr4Listener(BLangModelBuilder modelBuilder, Path sourceFilePath) { this.modelBuilder = modelBuilder; this.fileName = sourceFilePath.getFileName().toString(); if (sourceFilePath.getNameCount() >= 2) { this.packageDirPath = sourceFilePath.subpath(0, sourceFilePath.getNameCount() - 1).toString(); } else {// w w w. j av a 2 s . co m this.packageDirPath = null; } }
From source file:org.codice.ddf.configuration.migration.ImportMigrationEntryImpl.java
/** * Instantiates a new migration entry by parsing the provided zip entry's name for a migratable * identifier and an entry relative name. * * @param contextProvider a provider for migration contexts given a migratable id * @param ze the zip entry for which we are creating an entry */// ww w. ja va 2s . c om ImportMigrationEntryImpl(Function<String, ImportMigrationContextImpl> contextProvider, ZipEntry ze) { // we still must sanitize because there could be a mix of / and \ and Paths.get() doesn't // support that final Path fqn = Paths.get(FilenameUtils.separatorsToSystem(ze.getName())); final int count = fqn.getNameCount(); if (count > 1) { this.context = contextProvider.apply(fqn.getName(0).toString()); this.path = fqn.subpath(1, count); } else { // system entry this.context = contextProvider.apply(null); this.path = fqn; } this.absolutePath = context.getPathUtils().resolveAgainstDDFHome(path); this.file = absolutePath.toFile(); this.name = FilenameUtils.separatorsToUnix(path.toString()); this.entry = ze; this.isFile = true; }
From source file:org.craftercms.studio.impl.v1.repository.job.RebuildRepositoryMetadata.java
protected boolean populateRebuildRepositoryMetadataQueue(String site) { logger.debug("Populating Rebuild Repository Metadata queue for site " + site); Path siteContentRootPath = Paths.get(previewRepoRootPath, contentService.expandRelativeSitePath(site, "")); logger.debug("Retrieving files list for content repository"); Iterator<File> fileIterator = FileUtils.iterateFiles( Paths.get(previewRepoRootPath, contentService.expandRelativeSitePath(site, "")).toFile(), null, true);/*w w w . ja v a2 s .co m*/ List<String> paths = new ArrayList<String>(); int id = 1; while (fileIterator.hasNext()) { File file = fileIterator.next(); Path filePath = Paths.get(file.toURI()); String relativePath = "/" + filePath.subpath(siteContentRootPath.getNameCount(), filePath.getNameCount()); logger.debug("Processing " + relativePath); paths.add(relativePath); if (paths.size() == batchSize) { logger.debug("Insert batch of file paths into queue."); Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); params.put("site", site); params.put("pathList", paths); rebuildRepositoryMetadataMapper.insertRebuildRepoMetadataQueue(params); id = id + paths.size(); paths = new ArrayList<String>(); } } if (paths != null && paths.size() > 0) { logger.debug("Insert batch of file paths into queue."); Map<String, Object> params = new HashMap<String, Object>(); params.put("id", id); params.put("site", site); params.put("pathList", paths); rebuildRepositoryMetadataMapper.insertRebuildRepoMetadataQueue(params); paths = new ArrayList<String>(); } return true; }
From source file:org.dataconservancy.dcs.util.UriUtility.java
/** * Create a URI string for a file in a BagIt bag, * @param file The file to check. This doesn't have to be an actual existing file * @param basedir The directory to make the file URI relative to. Can be null. If not null, the basedir must be * in the path of the file parameter, or an exception will be thrown * @return A string representing the URI to the file on the local disk. * @throws URISyntaxException if there is an error in the URI syntax *///from w w w . j a v a2s. co m public static URI makeBagUriString(File file, File basedir) throws URISyntaxException { if (basedir == null) { basedir = new File("."); } Path relativePath = file.toPath(); if (relativePath.startsWith(basedir.toPath())) { relativePath = basedir.toPath().relativize(file.toPath()); } String path = FilenameUtils.separatorsToUnix(relativePath.toString()); if (relativePath.getNameCount() > 1) { Path uriAuthority = relativePath.getName(0); Path uriPath = relativePath.subpath(1, relativePath.getNameCount()); path = FilenameUtils.separatorsToUnix(uriPath.toString()); if (!uriPath.isAbsolute()) { path = "/" + path; } return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null); } return new URI(BAG_URI_SCHEME, path, null, null, null); }
From source file:org.dataconservancy.packaging.impl.UriUtility.java
/** * Create a URI string for a file in a BagIt bag, * * @param file The file to check. This doesn't have to be an actual existing file * @param basedir The directory to make the file URI relative to. Can be null. If not null, the basedir must be in * the path of the file parameter, or an exception will be thrown * @return A string representing the URI to the file on the local disk. * @throws URISyntaxException if there is an error in the URI syntax */// www . ja v a 2s . com public static URI makeBagUriString(final File file, final File basedir) throws URISyntaxException { final File dir = basedir == null ? new File(".") : basedir; Path relativePath = file.toPath(); if (relativePath.startsWith(dir.toPath())) { relativePath = dir.toPath().relativize(file.toPath()); } String path = FilenameUtils.separatorsToUnix(relativePath.toString()); if (relativePath.getNameCount() > 1) { final Path uriAuthority = relativePath.getName(0); final Path uriPath = relativePath.subpath(1, relativePath.getNameCount()); path = FilenameUtils.separatorsToUnix(uriPath.toString()); if (!uriPath.isAbsolute()) { path = "/" + path; } return new URI(BAG_URI_SCHEME, uriAuthority.toString(), path, null, null); } return new URI(BAG_URI_SCHEME, path, null, null, null); }
From source file:org.dataconservancy.packaging.tool.impl.generator.RemediationUtil.java
/** * Generate a unique path for {@code node} based on the suggested location. * * @param node the node/*from www . j av a 2 s.c o m*/ * @param locationHint the suggested location * @return the unique location based on the node and the hint */ static String unique(Node node, String locationHint) throws URISyntaxException { final Path path = Paths.get(locationHint); final StringBuilder remediatedPath = new StringBuilder(); if (path.toString().startsWith(File.separator)) { remediatedPath.append("/"); } if (path.getNameCount() > 1) { remediatedPath.append(path.subpath(0, path.getNameCount() - 1).toString()); remediatedPath.append("/"); } final StringBuilder toRemediate = new StringBuilder(shaHex(node.getIdentifier().toString())); remediatedPath.append(toRemediate); if (locationHint.endsWith("/")) { remediatedPath.append("/"); } return remediatedPath.toString().replace(File.separatorChar, '/'); }
From source file:org.dd4t.core.util.HttpUtils.java
public static Locale buildLocale(String url) { Locale pageLocale = null;/* w ww . ja v a 2s. c om*/ try { Path path = Paths.get(url); if (path != null) { String[] pathInfo = path.subpath(0, 1).toString().split("_", 2); if (pathInfo.length == 2) { pageLocale = new Locale(pathInfo[0], pathInfo[1]); } } } catch (InvalidPathException ipe) { LOG.error("Could not parse the path: " + url, ipe); } return pageLocale; }
From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java
public static void downloadAndInstall(String url, String archiveFileName, Path installPath, IProgressMonitor monitor) throws IOException { Exception error = null;/*from w ww. jav a 2s . c om*/ for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) { try { URL dl = new URL(url); Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$ Files.createDirectories(dlDir); Path archivePath = dlDir.resolve(archiveFileName); URLConnection conn = dl.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING); boolean isWin = Platform.getOS().equals(Platform.OS_WIN32); // extract ArchiveInputStream archiveIn = null; try { String compressor = null; String archiver = null; if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$ compressor = CompressorStreamFactory.BZIP2; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$ compressor = CompressorStreamFactory.GZIP; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$ compressor = CompressorStreamFactory.XZ; archiver = ArchiveStreamFactory.TAR; } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$ archiver = ArchiveStreamFactory.ZIP; } InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile())); if (compressor != null) { in = new CompressorStreamFactory().createCompressorInputStream(compressor, in); } archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in); for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn .getNextEntry()) { if (entry.isDirectory()) { continue; } // Magic file for git tarballs Path path = Paths.get(entry.getName()); if (path.endsWith("pax_global_header")) { //$NON-NLS-1$ continue; } // Strip the first directory of the path Path entryPath; switch (path.getName(0).toString()) { case "i586": case "i686": // Cheat for Intel entryPath = installPath.resolve(path); break; default: entryPath = installPath.resolve(path.subpath(1, path.getNameCount())); } Files.createDirectories(entryPath.getParent()); if (entry instanceof TarArchiveEntry) { TarArchiveEntry tarEntry = (TarArchiveEntry) entry; if (tarEntry.isLink()) { Path linkPath = Paths.get(tarEntry.getLinkName()); linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount())); Files.deleteIfExists(entryPath); Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath)); } else if (tarEntry.isSymbolicLink()) { Path linkPath = Paths.get(tarEntry.getLinkName()); Files.deleteIfExists(entryPath); Files.createSymbolicLink(entryPath, linkPath); } else { Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING); } if (!isWin && !tarEntry.isSymbolicLink()) { int mode = tarEntry.getMode(); Files.setPosixFilePermissions(entryPath, toPerms(mode)); } } else { Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING); } } } finally { if (archiveIn != null) { archiveIn.close(); } } return; } catch (IOException | CompressorException | ArchiveException e) { error = e; // retry } } // out of retries if (error instanceof IOException) { throw (IOException) error; } else { throw new IOException(error); } }