List of usage examples for java.nio.file Path getNameCount
int getNameCount();
From source file:edu.illinois.cs.cogcomp.nlp.corpusreaders.ereReader.EREDocumentReader.java
private String getFileStem(Path filePath, String extension) { String fileName = filePath.getName(filePath.getNameCount() - 1).toString(); int lastIndex = fileName.lastIndexOf(extension); return fileName.substring(0, lastIndex); }
From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPath.java
@Override public boolean startsWith(Path other) { if (other.isAbsolute() != isAbsolute()) { return false; } else if (other.getNameCount() > getNameCount()) { return false; } else {// w ww .j av a2 s . c om for (int idx = 0; idx < other.getNameCount(); idx++) { Path otherElem = other.getName(idx); if (otherElem.getFileName().equals(this.elements.get(idx))) { return false; } } return true; } }
From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java
public boolean isTarGz(final Path archivePath) { try {// w w w. ja v a 2 s . c o m openTarGz(archivePath); return true; } catch (final Exception e) { LOGGER.debug("Verification of " + archivePath.getName(archivePath.getNameCount() - 1) + " failed: " + e.getMessage()); return false; } }
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 *///from ww w . ja va 2 s . 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:com.liferay.blade.cli.CreateCommand.java
private List<String> getTemplates() throws Exception { List<String> templateNames = new ArrayList<>(); File templatesZip = getGradleTemplatesZip(); try (Jar jar = new Jar(templatesZip)) { Map<String, Map<String, Resource>> directories = jar.getDirectories(); for (String key : directories.keySet()) { Path path = Paths.get(key); if (path.getNameCount() == 2 && path.startsWith("standalone")) { templateNames.add(path.getName(1).toString()); }//w w w .j av a 2 s .c om } } return templateNames; }
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 w w . j a va 2 s. c o m*/ 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); } }
From source file:org.restcomm.connect.http.ProfileEndpoint.java
private String retrieveSid(URI uri) { Path paths = Paths.get(uri.getPath()); return paths.getName(paths.getNameCount() - 1).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 va2s . c om*/ * @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:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java
@Test public void testCreateSymlinks() throws IOException, URISyntaxException { Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent(); Path newDir = rootPath.resolve("newDir"); Assert.assertFalse(Files.isSymbolicLink(newDir)); Path innerDir = newDir.resolve("innerDir"); Assert.assertFalse(Files.isSymbolicLink(innerDir)); Path newSymlink = rootPath.resolve("newSymlink"); Assert.assertTrue(Files.isSymbolicLink(newSymlink)); Path innerSymlink = newSymlink.resolve("innerSymlink"); Assert.assertTrue(Files.isSymbolicLink(innerSymlink)); Path f = innerSymlink.getRoot(); for (int i = 0; i < innerSymlink.getNameCount(); i++) { f = f.resolve(innerSymlink.getName(i).toString()); System.out.println(f + " " + Files.isSymbolicLink(f)); }//w w w . j av a 2 s . c om f = f.resolve("."); System.out.println(f + " " + Files.isSymbolicLink(f)); }
From source file:de.alexkamp.sandbox.ChrootSandbox.java
@Override public void walkDirectoryTree(String basePath, final DirectoryWalker walker) throws IOException { final int baseNameCount = data.getBaseDir().toPath().getNameCount(); File base = new File(data.getBaseDir(), basePath); Files.walkFileTree(base.toPath(), new FileVisitor<Path>() { @Override/*from w w w . j a va 2 s . c o m*/ public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes) throws IOException { if (walker.visitDirectory(calcSubpath(path))) { return FileVisitResult.CONTINUE; } return FileVisitResult.SKIP_SUBTREE; } private String calcSubpath(Path path) { if (path.getNameCount() == baseNameCount) { return "/"; } return "/" + path.subpath(baseNameCount, path.getNameCount()).toString(); } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException { String subpath = calcSubpath(path); if (walker.visitFile(subpath)) { try (InputStream is = Files.newInputStream(path)) { walker.visitFileContent(subpath, is); } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException { if (walker.failed(e)) { return FileVisitResult.CONTINUE; } else { return FileVisitResult.TERMINATE; } } @Override public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException { return FileVisitResult.CONTINUE; } }); }