Java Code Examples for java.nio.file.Path#getFileName()

The following examples show how to use java.nio.file.Path#getFileName() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * @since 3.20
 */
@Override
public boolean validateFilePath(final String filePath, final int maxLength) {
  requireNonNull(filePath);
  checkArgument(maxLength > 0, "maxLength should be greater than zero.");

  Path path = Paths.get(separatorsToSystem(filePath)).toAbsolutePath();
  List<String> fileNames = new ArrayList<>();

  Path pathParent = path.getParent();
  while (pathParent != null) {
    if (path.getFileName() != null) {
      fileNames.add(path.getFileName().toString());
    }
    path = pathParent;
    pathParent = path.getParent();
  }
  return !fileNames.stream().anyMatch(fileOrDirectory -> fileOrDirectory.length() > maxLength);
}
 
Example 2
Source Project: testgrid   File: TestNgResultsParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Searches the provided path for files named "TEST-.*.xml",
 * and returns the list of paths.
 *
 * @param dataBucket the data bucket folder where build artifacts are located.
 * @return list of paths of TEST-TestSuite.xml.
 */
private Set<Path> getResultInputFiles(Path dataBucket) {
    try {
        final Stream<Path> ls = Files.list(dataBucket);
        final Set<Path> files = ls.collect(Collectors.toSet());
        final Set<Path> inputFiles = new HashSet<>();
        for (Path file : files) {
            final Path fileName = file.getFileName();
            if (fileName == null) {
                continue;
            } else if (Files.isDirectory(file) && !"junitreports".equalsIgnoreCase(fileName.toString())) {
                final Set<Path> anInputFilesList = getResultInputFiles(file);
                inputFiles.addAll(anInputFilesList);
            } else if (fileName.toString().matches(RESULTS_TEST_SUITE_FILES_REGEX)) {
                inputFiles.add(file);
            }
        }
        return inputFiles;
    } catch (IOException e) {
        logger.error("Error while reading " + RESULTS_TEST_SUITE_FILES_REGEX + " files in " + dataBucket, e);
        return Collections.emptySet();
    }
}
 
Example 3
@Override
protected String implProbeContentType(Path path) {
    Path fn = path.getFileName();
    if (fn == null)
        return null;  // no file name

    String ext = getExtension(fn.toString());
    if (ext.isEmpty())
        return null;  // no extension

    loadMimeTypes();
    if (mimeTypeMap == null || mimeTypeMap.isEmpty())
        return null;

    // Case-sensitive search
    String mimeType;
    do {
        mimeType = mimeTypeMap.get(ext);
        if (mimeType == null)
            ext = getExtension(ext);
    } while (mimeType == null && !ext.isEmpty());

    return mimeType;
}
 
Example 4
Source Project: cava   File: Sodium.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Load and initialize the native libsodium shared library.
 *
 * <p>
 * If this method returns successfully (without throwing a {@link LinkageError}), then all future calls to methods
 * provided by this class will use the loaded library.
 *
 * @param path The path to the shared library.
 * @throws LinkageError If the library cannot be found, dependent libraries are missing, or cannot be initialized.
 */
public static void loadLibrary(Path path) {
  requireNonNull(path);
  if (!Files.exists(path)) {
    throw new IllegalArgumentException("Non-existent path");
  }

  Path dir = path.getParent();
  Path library = path.getFileName();

  LibSodium lib =
      LibraryLoader.create(LibSodium.class).search(dir.toFile().getAbsolutePath()).load(library.toString());
  initializeLibrary(lib);

  synchronized (LibSodium.class) {
    Sodium.libSodium = lib;
  }
}
 
Example 5
Source Project: update4j   File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static URI fromPath(Path path) {
    if (path.isAbsolute()) {
        Path filename = path.getFileName();

        return fromPath(filename);
    }

    try {
        String uri = URLEncoder.encode(path.toString().replace("\\", "/"), "UTF-8");

        uri = uri.replace("%2F", "/") // We still need directory structure
                        .replace("+", "%20"); // "+" only means space in queries, not in paths
        return URI.create(uri);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }

}
 
Example 6
private void sendEmail(Path output) throws Exception {
    String durationLabel = report.reportType.getDurationLabel().toLowerCase();
    String subj = "Your " + durationLabel + " " + report.getReportName() + " is ready";
    String gzipDownloadUrl = downloadUrl + output.getFileName();
    String dynamicSection = report.buildDynamicSection();
    mailWrapper.sendReportEmail(report.recipients, subj, gzipDownloadUrl, dynamicSection);
}
 
Example 7
Source Project: promagent   File: JarFileNames.java    License: Apache License 2.0 5 votes vote down vote up
public static JarFileNames renameOrigJarFile(MavenProject project) throws MojoExecutionException {
    Path finalName = makePath(project.getBuild().getFinalName(), project);
    if (!Files.exists(finalName)) {
        throw new MojoExecutionException(finalName.getFileName() + ": file not found. This happens if promagent-maven-plugin is called before the original artifact was created.");
    }
    Path defaultFinalName = makePath(project.getArtifactId() + "-" + project.getArtifact().getVersion(), project);
    if (!Files.exists(defaultFinalName)) {
        mv(finalName, defaultFinalName);
        return new JarFileNames(finalName, defaultFinalName, defaultFinalName);
    } else {
        Path defaultFinalNameWithSuffix = makePath(project.getArtifactId() + "-" + project.getArtifact().getVersion() + "-orig", project);
        mv(finalName, defaultFinalNameWithSuffix);
        return new JarFileNames(finalName, defaultFinalName, defaultFinalNameWithSuffix);
    }
}
 
Example 8
protected static boolean hasExtension(Path path, String... extensions) {
	final Path namePath = path.getFileName();
	if (namePath == null) {
		return false;
	}
	final String name = namePath.toString();
	for (String ext : extensions) {
		if (name.endsWith(ext)) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source Project: Velocity   File: JavaPluginLoader.java    License: MIT License 5 votes vote down vote up
private Optional<SerializedPluginDescription> getSerializedPluginInfo(Path source)
    throws Exception {
  boolean foundBungeeBukkitPluginFile = false;
  try (JarInputStream in = new JarInputStream(
      new BufferedInputStream(Files.newInputStream(source)))) {
    JarEntry entry;
    while ((entry = in.getNextJarEntry()) != null) {
      if (entry.getName().equals("velocity-plugin.json")) {
        try (Reader pluginInfoReader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
          return Optional.of(VelocityServer.GSON
              .fromJson(pluginInfoReader, SerializedPluginDescription.class));
        }
      }

      if (entry.getName().equals("plugin.yml") || entry.getName().equals("bungee.yml")) {
        foundBungeeBukkitPluginFile = true;
      }
    }

    if (foundBungeeBukkitPluginFile) {
      throw new InvalidPluginException("The plugin file " + source.getFileName() + " appears to "
          + "be a Bukkit or BungeeCord plugin. Velocity does not support Bukkit or BungeeCord "
          + "plugins.");
    }

    return Optional.empty();
  }
}
 
Example 10
Source Project: buck   File: Resolver.java    License: Apache License 2.0 5 votes vote down vote up
private Path copy(ArtifactResult result, Path destDir) throws IOException {
  Path source = result.getArtifact().getFile().toPath();
  Path sink = destDir.resolve(source.getFileName());

  if (!Files.exists(sink)) {
    Files.copy(source, sink);
  }

  return sink.getFileName();
}
 
Example 11
Source Project: uima-uimaj   File: MigrateJCas.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * For Jars inside other Jars, we copy the Jar to a temp spot in the default file system
 * Extracted Jar is marked delete-on-exit
 * 
 * @param path embedded Jar to copy (only the last name is used, in constructing the temp dir)
 * @return a temporary file in the local temp directory that is a copy of the Jar
 * @throws IOException -
 */
private static Path getTempOutputPathForJarOrPear(Path path) throws IOException {
  Path localTempDir = getTempDir();
  if (path == null ) {
    throw new IllegalArgumentException();
  }
  Path fn = path.getFileName();
  if (fn == null) {
    throw new IllegalArgumentException();
  }
  Path tempPath = Files.createTempFile(localTempDir, fn.toString(),  "");
  tempPath.toFile().deleteOnExit();
  return tempPath;
}
 
Example 12
/**
 * Extract the ballerina file name from a given file path.
 *
 * @param jarFilePath Uber jar file path.
 * @return Uber jar file name without ".jar"
 */
public static String extractJarName(Path jarFilePath) {
    if (null != jarFilePath) {
        Path fileName = jarFilePath.getFileName();
        if (null != fileName && fileName.toString().endsWith(".jar")) {
            return fileName.toString().replace(".jar", "");
        }
    }

    return null;
}
 
Example 13
@Override
@FxThread
public @NotNull String getFileName() {
    final Path editFile = getEditFile();
    final Path fileName = editFile.getFileName();
    return fileName.toString();
}
 
Example 14
Source Project: openjdk-jdk9   File: Basic.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir,
                                         BasicFileAttributes attrs)
{
    if (dir.getFileName() != null) {
        indent();
        System.out.println(dir.getFileName() + "/");
        indent++;
    }
    return FileVisitResult.CONTINUE;
}
 
Example 15
private void find(final Path path) throws IOException {
    final Path name = path.getFileName();
    if (name != null && matcher.matches(name)) {
        try (final InputStream inputStream = Files.newInputStream(path)) {
            final ClassParser classParser = new ClassParser(inputStream, name.toAbsolutePath().toString());
            final JavaClass javaClass = classParser.parse();
            Assert.assertNotNull(javaClass);
        }

    }
}
 
Example 16
/**
 * Constructs a {@code BundleInfo} instance out of the OSGi bundle file path specified.
 * <p>
 * If the specified file path does not satisfy the requirements of an OSGi bundle, no {@code BundleInfo} instance
 * will be created.
 *
 * @param bundlePath path to the OSGi bundle from which the {@link BundleInfo} is to be generated
 * @return a {@link BundleInfo} instance
 * @throws IOException if an I/O error occurs or if an invalid {@code bundlePath} is found
 */
private static Optional<BundleInfo> getBundleInfo(Path bundlePath) throws IOException {
    if ((bundlePath == null) || (!Files.exists(bundlePath))) {
        throw new IOException("Invalid OSGi bundle path. The specified path may not exist or " +
                "user may not have required file permissions for the specified path");
    }

    Path bundleFileName = bundlePath.getFileName();
    if (bundleFileName == null) {
        throw new IOException("Specified OSGi bundle file name is null: " + bundlePath);
    }

    String fileName = bundleFileName.toString();
    if (!fileName.endsWith(".jar")) {
        return Optional.empty();
    }

    try (JarFile jarFile = new JarFile(bundlePath.toString())) {
        Manifest manifest = jarFile.getManifest();

        if ((manifest == null) || (manifest.getMainAttributes() == null)) {
            throw new IOException("Invalid OSGi bundle found in the " + Constants.OSGI_LIB + " folder");
        }

        String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
        String bundleVersion = manifest.getMainAttributes().getValue("Bundle-Version");

        if (bundleSymbolicName == null || bundleVersion == null) {
            throw new IOException("Required bundle manifest headers do not exist");
        }

        logger.log(Level.FINE,
                "Loading information from OSGi bundle: " + bundleSymbolicName + ":" + bundleVersion + "...");

        if (bundleSymbolicName.contains(";")) {
            bundleSymbolicName = bundleSymbolicName.split(";")[0];
        }

        //  checks whether this bundle is a fragment or not
        boolean isFragment = (manifest.getMainAttributes().getValue("Fragment-Host") != null);
        int defaultBundleStartLevel = 4;
        BundleInfo generated = new BundleInfo(bundleSymbolicName, bundleVersion,
                "../../" + Constants.OSGI_LIB + "/" + fileName, defaultBundleStartLevel, isFragment);
        logger.log(Level.FINE,
                "Successfully loaded information from OSGi bundle: " + bundleSymbolicName + ":" + bundleVersion);
        return Optional.of(generated);
    }
}
 
Example 17
Source Project: sis   File: TreeTables.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Finds the node for the given path, or creates a new node if none exists.
 * First, this method searches in the node {@linkplain TreeTable.Node#getChildren()
 * children collection} for the root element of the given path. If no such node is found,
 * a {@linkplain TreeTable.Node#newChild() new child} is created. Then this method
 * repeats the process (searching in the children of the child for the second path
 * element), until the last path element is reached.
 *
 * <p>For example if the given path is {@code "users/alice/data"}, then this method
 * finds or creates the nodes for the following tree, where {@code "from"} is the
 * node given in argument to this method:</p>
 *
 * {@preformat text
 *   from
 *     └─users
 *         └─alice
 *             └─data
 * }
 *
 * @param  from    the root node from which to start the search.
 * @param  column  the column containing the file name.
 * @param  path    the path for which to find or create a node.
 * @return the node for the given path, either as an existing node or a new node.
 */
public static TreeTable.Node nodeForPath(TreeTable.Node from,
        final TableColumn<? super String> column, final Path path)
{
    final Path parent = path.getParent();
    if (parent != null) {
        from = nodeForPath(from, column, parent);
    }
    Path filename = path.getFileName();
    if (filename == null) {
        filename = path.getRoot();
    }
    final String name = filename.toString();
    for (final TreeTable.Node child : from.getChildren()) {
        if (name.equals(child.getValue(column))) {
            return child;
        }
    }
    from = from.newChild();
    from.setValue(column, name);
    return from;
}
 
Example 18
protected ClassFileReader(Path path) {
    this.path = path;
    this.baseFileName = path.getFileName() != null
                            ? path.getFileName().toString()
                            : path.toString();
}
 
Example 19
Source Project: hadoop-ozone   File: SQLCLI.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int run(String[] args) throws Exception {
  CommandLine commandLine = parseArgs(args);
  if (commandLine.hasOption("help")) {
    displayHelp();
    return 0;
  }
  if (!commandLine.hasOption("p") || !commandLine.hasOption("o")) {
    displayHelp();
    return -1;
  }
  String value = commandLine.getOptionValue("p");
  LOG.info("DB path {}", value);
  // the value is supposed to be an absolute path to a container file
  Path dbPath = Paths.get(value);
  if (!Files.exists(dbPath)) {
    LOG.error("DB path not exist:{}", dbPath);
  }
  Path parentPath = dbPath.getParent();
  Path dbName = dbPath.getFileName();
  if (parentPath == null || dbName == null) {
    LOG.error("Error processing db path {}", dbPath);
    return -1;
  }

  value = commandLine.getOptionValue("o");
  Path outPath = Paths.get(value);
  if (outPath == null || outPath.getParent() == null) {
    LOG.error("Error processing output path {}", outPath);
    return -1;
  }

  if (outPath.toFile().isDirectory()) {
    LOG.error("The db output path should be a file instead of a directory");
    return -1;
  }

  Path outParentPath = outPath.getParent();
  if (outParentPath != null) {
    if (!Files.exists(outParentPath)) {
      Files.createDirectories(outParentPath);
    }
  }
  LOG.info("Parent path [{}] db name [{}]", parentPath, dbName);
  if (dbName.toString().endsWith(CONTAINER_DB_SUFFIX)) {
    LOG.info("Converting container DB");
    convertContainerDB(dbPath, outPath);
  } else if (dbName.toString().equals(OM_DB_NAME)) {
    LOG.info("Converting om DB");
    convertOMDB(dbPath, outPath);
  } else {
    LOG.error("Unrecognized db name {}", dbName);
  }
  return 0;
}
 
Example 20
Source Project: extract   File: PosixHiddenFileMatcher.java    License: MIT License 4 votes vote down vote up
@Override
public boolean matches(final Path path) {
	final Path fileName = path.getFileName();

	return null != fileName && fileName.toString().startsWith(".");
}