Java URI Parse parseLeaf(final URI uri)

Here you can find the source of parseLeaf(final URI uri)

Description

parse Leaf

License

Apache License

Declaration

public static String parseLeaf(final URI uri) throws Exception 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.net.URI;

public class Main {
    public static String parseLeaf(final URI uri) throws Exception {
        String[] path = getPathAsArray(uri);
        return path[path.length - 1];
    }/*from w w w  .j ava2 s .c om*/

    public static String[] getPathAsArray(URI uri) {
        StringBuilder path = new StringBuilder(uri.getPath());

        // we treat URI paths at lists of trees, where the first "node"
        // is a tree root... for this reason, a uri path of "/" is not
        // a root, but an empty path

        // guard against empty path (root)
        if (uri.getPath().equals("/") || uri.getPath().equals("\\")) {
            // do not want to return null, since that indicates
            // uri is a "root"... need to distinguish
            String back = "\"" + "\\" + "\"";
            String forward = "\"" + "/" + "\"";
            String ie = "(ie: " + back + " or " + forward + ")";
            throw new RuntimeException("URI path cannot be a root " + ie);
        }

        // strip leading slash (path will always begin with "/")
        path.deleteCharAt(0);

        stripTrailingSlash(path);

        // obtain path from root to leaf
        String s[] = path.toString().split("/");

        return s;
    }

    /**
     * Strips trailing slash from the end of a StringBuilder object, if one
     * exists, and return whether the slash was removed.
     * 
     * @return boolean - whether a trailing slash was removed
     */
    private static boolean stripTrailingSlash(StringBuilder s) {
        final boolean hasTrailingSlash = s.charAt(s.length() - 1) == '/';

        // strip trailing slash
        s = hasTrailingSlash ? s.deleteCharAt(s.length() - 1) : s;

        return hasTrailingSlash;
    }
}

Related

  1. parse(final String uri)
  2. parse(final URI uri, boolean decodeQueryParam)
  3. parseAWSUri(URI uri, String defaultAccessKey, String defaultSecretAccessKey)
  4. parseParameters(URI uri)
  5. parseParentURI(final URI uri)
  6. parsePathElements(URI uri)
  7. parsePorts(URI connectionURI)