Example usage for java.nio.file Path endsWith

List of usage examples for java.nio.file Path endsWith

Introduction

In this page you can find the example usage for java.nio.file Path endsWith.

Prototype

default boolean endsWith(String other) 

Source Link

Document

Tests if this path ends with a Path , constructed by converting the given path string, in exactly the manner specified by the #endsWith(Path) endsWith(Path) method.

Usage

From source file:Main.java

public static void main(String[] args) {

    Path path01 = Paths.get("/tutorial/Java/JavaFX/Topic.txt");
    Path path02 = Paths.get("C:/tutorial/Java/JavaFX/Topic.txt");

    boolean ew = path01.endsWith("Topic.txt");

    System.out.println(ew);/* w ww  . ja  va  2  s  .  c  o m*/

}

From source file:Main.java

public static void main(String[] args) {
    Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");

    Path path1 = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");

    System.out.println(path.endsWith(path1));

}

From source file:net.tirasa.ilgrosso.lngenerator.Main.java

public static void main(final String[] args) throws IOException, URISyntaxException {
    assert args.length > 0 : "No arguments provided";

    File source = new File(args[0]);
    if (!source.isDirectory()) {
        throw new IllegalArgumentException("Not a directory: " + args[0]);
    }/*from ww w . ja v a2s.  c om*/

    String destPath = args.length > 1 ? args[1] : System.getProperty("java.io.tmpdir");
    File dest = new File(destPath);
    if (!dest.isDirectory() || !dest.canWrite()) {
        throw new IllegalArgumentException("Not a directory, or not writable: " + destPath);
    }

    LOG.debug("Local Maven repo is {}", LOCAL_M2_REPO);
    LOG.debug("Source Path is {}", source.getAbsolutePath());
    LOG.debug("Destination Path is {}", dest.getAbsolutePath());
    LOG.warn("Existing LICENSE and NOTICE files in {} will be overwritten!", dest.getAbsolutePath());

    Set<String> keys = new HashSet<>();

    Files.walk(source.toPath()).filter(Files::isRegularFile)
            .map((final Path path) -> path.getFileName().toString())
            .filter((String path) -> path.endsWith(".jar")).sorted().forEach((filename) -> {
                try (Stream<Path> stream = Files.find(LOCAL_M2_REPO_PATH, 10,
                        (path, attr) -> String.valueOf(path.getFileName().toString()).equals(filename))) {

                    String fullPath = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
                    if (fullPath.isEmpty()) {
                        LOG.warn("Could not find {} in the local Maven repo", filename);
                    } else {
                        String path = fullPath.substring(LOCAL_M2_REPO.length() + 1);
                        Gav gav = GAV_CALCULATOR.pathToGav(path);
                        if (gav == null) {
                            LOG.error("Invalid Maven path: {}", path);
                        } else if (!gav.getGroupId().startsWith("org.apache.")
                                && !gav.getGroupId().startsWith("commons-")
                                && !gav.getGroupId().equals("org.codehaus.groovy")
                                && !gav.getGroupId().equals("jakarta-regexp")
                                && !gav.getGroupId().equals("xml-apis") && !gav.getGroupId().equals("batik")) {

                            if (ArrayUtils.contains(CONSOLIDATING_GROUP_IDS, gav.getGroupId())) {
                                keys.add(gav.getGroupId());
                            } else if (gav.getGroupId().startsWith("com.fasterxml.jackson")) {
                                keys.add("com.fasterxml.jackson");
                            } else if (gav.getGroupId().equals("org.webjars.bower") && (gav.getArtifactId()
                                    .startsWith("angular-animate")
                                    || gav.getArtifactId().startsWith("angular-cookies")
                                    || gav.getArtifactId().startsWith("angular-resource")
                                    || gav.getArtifactId().startsWith("angular-sanitize")
                                    || gav.getArtifactId().startsWith("angular-treasure-overlay-spinner"))) {

                                keys.add("org.webjars.bower:angular");
                            } else if (gav.getGroupId().equals("org.webjars.bower")
                                    && gav.getArtifactId().startsWith("angular-translate")) {

                                keys.add("org.webjars.bower:angular-translate");
                            } else if (gav.getGroupId().startsWith("de.agilecoders")) {
                                keys.add("wicket-bootstrap");
                            } else if ("org.webjars".equals(gav.getGroupId())) {
                                if (gav.getArtifactId().startsWith("jquery-ui")) {
                                    keys.add("jquery-ui");
                                } else {
                                    keys.add(gav.getArtifactId());
                                }
                            } else {
                                keys.add(gav.getGroupId() + ":" + gav.getArtifactId());
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.error("While looking for Maven artifacts from the local Maven repo", e);
                }
            });

    final Properties licenses = new Properties();
    licenses.loadFromXML(Main.class.getResourceAsStream("/licenses.xml"));

    final Properties notices = new Properties();
    notices.loadFromXML(Main.class.getResourceAsStream("/notices.xml"));

    BufferedWriter licenseWriter = Files.newBufferedWriter(new File(dest, "LICENSE").toPath(),
            StandardOpenOption.CREATE);
    licenseWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/LICENSE.template").toURI()))));

    BufferedWriter noticeWriter = Files.newBufferedWriter(new File(dest, "NOTICE").toPath(),
            StandardOpenOption.CREATE);
    noticeWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/NOTICE.template").toURI()))));

    EnumSet<LICENSE> outputLicenses = EnumSet.noneOf(LICENSE.class);

    keys.stream().sorted().forEach((final String dependency) -> {
        if (licenses.getProperty(dependency) == null) {
            LOG.error("Could not find license information about {}", dependency);
        } else {
            try {
                licenseWriter.write("\n==\n\nFor " + licenses.getProperty(dependency) + ":\n");

                String depLicense = licenses.getProperty(dependency + ".license");
                if (depLicense == null) {
                    licenseWriter.write("This is licensed under the AL 2.0, see above.");
                } else {
                    LICENSE license = LICENSE.valueOf(depLicense);

                    if (license == LICENSE.PUBLIC_DOMAIN) {
                        licenseWriter.write("This is " + license.getLabel() + ".");
                    } else {
                        licenseWriter.write("This is licensed under the " + license.getLabel());

                        if (outputLicenses.contains(license)) {
                            licenseWriter.write(", see above.");
                        } else {
                            outputLicenses.add(license);

                            licenseWriter.write(":\n\n");
                            licenseWriter.write(new String(Files.readAllBytes(
                                    Paths.get(Main.class.getResource("/LICENSE." + license.name()).toURI()))));
                        }
                    }
                }
                licenseWriter.write('\n');

                if (notices.getProperty(dependency) != null) {
                    noticeWriter.write("\n==\n\n" + notices.getProperty(dependency) + "\n");
                }
            } catch (Exception e) {
                LOG.error("While dealing with {}", dependency, e);
            }
        }
    });

    licenseWriter.close();
    noticeWriter.close();

    LOG.debug("Execution completed successfully, look at {} for the generated LICENSE and NOTICE files",
            dest.getAbsolutePath());
}

From source file:paketti.AbstractReader.java

public static JSONArray getSubPathsDirs(String subDir) throws IOException {
    System.out.println("imgRootDir:" + getMediaFilesRootDir());
    System.out.println("urlRootPath:" + urlRootPath);
    if (isDir(Paths.get(getMediaFilesRootDir()))) {
        for (Path dir : getDirStream(Paths.get(getMediaFilesRootDir()))) {
            System.out.println(dir);
            if (dir.endsWith(subDir)) {
                return getDirListing(dir);
            }/*from   w w  w  .  j a v a 2 s.  c  o  m*/
        }
    }
    return null;
}

From source file:de.prozesskraft.pkraft.Waitinstance.java

/**
 * ermittelt alle process binaries innerhalb eines directory baumes
 * @param pathScandir//from  w  w w . j  a  va  2  s . com
 * @return
 */
private static String[] getProcessBinaries(String pathScandir) {
    final ArrayList<String> allProcessBinaries = new ArrayList<String>();

    // den directory-baum durchgehen und fuer jeden eintrag ein entity erstellen
    try {
        Files.walkFileTree(Paths.get(pathScandir), new FileVisitor<Path>() {
            // called after a directory visit is complete
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            // called before a directory visit
            public FileVisitResult preVisitDirectory(Path walkingDir, BasicFileAttributes attrs)
                    throws IOException {
                return FileVisitResult.CONTINUE;
            }

            // called for each file visited. the basic file attributes of the file are also available
            public FileVisitResult visitFile(Path walkingFile, BasicFileAttributes attrs) throws IOException {
                // ist es ein process.pmb file?
                if (walkingFile.endsWith("process.pmb")) {
                    allProcessBinaries.add(new java.io.File(walkingFile.toString()).getAbsolutePath());
                }

                return FileVisitResult.CONTINUE;
            }

            // called for each file if the visit failed
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return allProcessBinaries.toArray(new String[allProcessBinaries.size()]);
}

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/*from   w  ww  .j av  a2  s  .  com*/
 * @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);
    }

}

From source file:org.sonar.java.AbstractJavaClasspath.java

private static Set<File> getMatchesInDir(Path dirPath, boolean isLibraryProperty) throws IOException {
    if (isLibraryProperty) {
        for (Path end : STANDARD_CLASSES_DIRS) {
            if (dirPath.endsWith(end)) {
                // don't scan these, as they should only contain .classes with paths starting from the root
                return Collections.singleton(dirPath.toFile());
            }/*from  w w w .  ja  v  a 2  s . c o m*/
        }
        Set<File> matches = new LibraryFinder().find(dirPath, p -> true);
        matches.add(dirPath.toFile());
        return matches;
    } else {
        return Collections.singleton(dirPath.toFile());
    }
}

From source file:org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager.java

private static JSONObject readJaggeryConfig(Context context, Path appBase) {
    String content = null;/*from  ww w  .j  av a  2  s. c  om*/
    String path = null;
    if (context.getDocBase().contains(WAR_EXTENSION)) {
        try {
            if (!appBase.endsWith("/")) {
                path = appBase + File.separator + context.getDocBase();
            } else {
                path = appBase + context.getDocBase();
            }
            ZipFile zip = new ZipFile(path);
            for (Enumeration e = zip.entries(); e.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) e.nextElement();
                if (entry.getName().toLowerCase().contains(JAGGERY_CONF)) {
                    InputStream inputStream = zip.getInputStream(entry);
                    content = IOUtils.toString(inputStream);
                }
            }
        } catch (IOException e) {
            log.error("Error occuered when the accessing the jaggery.conf file of "
                    + context.getPath().substring(1), e);
        }
    } else {
        File file = new File(appBase + context.getPath() + File.separator + JAGGERY_CONF);
        try {
            content = FileUtils.readFileToString(file);
        } catch (IOException e) {
            log.error("IOException is thrown when accessing the jaggery.conf file of "
                    + context.getPath().substring(1), e);
        }
    }
    JSONObject jaggeryConfig = null;
    try {
        JSONParser jp = new JSONParser();
        jaggeryConfig = (JSONObject) jp.parse(content);
    } catch (ParseException e) {
        log.error("Error in parsing the jaggery.conf file", e);
    }
    return jaggeryConfig;
}

From source file:nl.coinsweb.sdk.FileManager.java

/**
 * Extracts all the content of the .ccr-file specified in the constructor to [TEMP_ZIP_PATH] / [internalRef].
 *
 *//*from  www  .  j av a  2s  . c om*/
public static void unzipTo(File sourceFile, Path destinationPath) {

    byte[] buffer = new byte[1024];
    String startFolder = null;

    try {

        // Get the zip file content
        ZipInputStream zis = new ZipInputStream(new FileInputStream(sourceFile));
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {

            if (ze.isDirectory()) {
                ze = zis.getNextEntry();
                continue;
            }

            String fileName = ze.getName();

            log.info("Dealing with file " + fileName);

            // If the first folder is a somename/bim/file.ref skip it
            Path filePath = Paths.get(fileName);
            Path pathPath = filePath.getParent();

            if (pathPath.endsWith("bim") || pathPath.endsWith("bim/repository") || pathPath.endsWith("doc")
                    || pathPath.endsWith("woa")) {

                Path pathRoot = pathPath.endsWith("repository") ? pathPath.getParent().getParent()
                        : pathPath.getParent();

                String prefix = "";
                if (pathRoot != null) {
                    prefix = pathRoot.toString();
                }

                if (startFolder == null) {
                    startFolder = prefix;
                    log.debug("File root set to: " + startFolder);

                } else if (startFolder != null && !prefix.equals(startFolder)) {
                    throw new InvalidContainerFileException(
                            "The container file has an inconsistent file root, was " + startFolder
                                    + ", now dealing with " + prefix + ".");
                }
            } else {
                log.debug("Skipping file: " + filePath.toString());
                continue;
            }

            String insideStartFolder = filePath.toString().substring(startFolder.length());
            File newFile = new File(destinationPath + "/" + insideStartFolder);
            log.info("Extract " + newFile);

            // Create all non exists folders
            // else you will hit FileNotFoundException for compressed folder
            new File(newFile.getParent()).mkdirs();

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }

            fos.close();
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.facebook.buck.util.Escaper.java

/**
 * Escapes forward slashes in a Path as a String that is safe to consume with other tools (such
 * as gcc).  On Unix systems, this is equivalent to {@link java.nio.file.Path Path.toString()}.
 * @param path the Path to escape/* w  w w. j  ava  2  s . c  o  m*/
 * @return the escaped Path
 */
public static String escapePathForCIncludeString(Path path) {
    if (File.separatorChar != '\\') {
        return path.toString();
    }
    StringBuilder result = new StringBuilder();
    if (path.startsWith(File.separator)) {
        result.append("\\\\");
    }
    for (Iterator<Path> iterator = path.iterator(); iterator.hasNext();) {
        result.append(iterator.next());
        if (iterator.hasNext()) {
            result.append("\\\\");
        }
    }
    if (path.getNameCount() > 0 && path.endsWith(File.separator)) {
        result.append("\\\\");
    }
    return result.toString();
}