Java Path File Read nio breadcrumbPath(String urlPrefix, String path, char sep)

Here you can find the source of breadcrumbPath(String urlPrefix, String path, char sep)

Description

Convenience method for breadcrumbPath(urlPrefix, path, sep, "", false) .

License

Open Source License

Parameter

Parameter Description
urlPrefix prefix to add to each url
path path to crack
sep separator to use to crack the given path

Return

HTML markup fro the breadcrumb or the path itself.

Declaration

public static String breadcrumbPath(String urlPrefix, String path,
        char sep) 

Method Source Code

//package com.java2s;
/*/*from   w  w w. j a v  a  2  s  .c  o m*/
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * See LICENSE.txt included in this distribution for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at LICENSE.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

import java.nio.charset.Charset;

import java.util.LinkedList;
import java.util.Locale;

public class Main {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private static final String anchorLinkStart = "<a href=\"";
    private static final String anchorEnd = "</a>";
    private static final String closeQuotedTag = "\">";

    /**
     * Convenience method for {@code breadcrumbPath(urlPrefix, path, '/')}.
     *
     * @param urlPrefix prefix to add to each url
     * @param path path to crack
     * @return HTML markup fro the breadcrumb or the path itself.
     *
     * @see #breadcrumbPath(String, String, char)
     */
    public static String breadcrumbPath(String urlPrefix, String path) {
        return breadcrumbPath(urlPrefix, path, '/');
    }

    /**
     * Convenience method for
     * {@code breadcrumbPath(urlPrefix, path, sep, "", false)}.
     *
     * @param urlPrefix prefix to add to each url
     * @param path path to crack
     * @param sep separator to use to crack the given path
     *
     * @return HTML markup fro the breadcrumb or the path itself.
     * @see #breadcrumbPath(String, String, char, String, boolean, boolean)
     */
    public static String breadcrumbPath(String urlPrefix, String path,
            char sep) {
        return breadcrumbPath(urlPrefix, path, sep, "", false);
    }

    /**
     * Convenience method for
     * {@code breadcrumbPath(urlPrefix, path, sep, "", false, path.endsWith(sep)}.
     *
     * @param urlPrefix prefix to add to each url
     * @param path path to crack
     * @param sep separator to use to crack the given path
     * @param urlPostfix suffix to add to each url
     * @param compact if {@code true} the given path gets transformed into its
     * canonical form (.i.e. all '.' and '..' and double separators removed, but
     * not always resolves to an absolute path) before processing starts.
     * @return HTML markup fro the breadcrumb or the path itself.
     * @see #breadcrumbPath(String, String, char, String, boolean, boolean)
     * @see #getCanonicalPath(String, char)
     */
    public static String breadcrumbPath(String urlPrefix, String path,
            char sep, String urlPostfix, boolean compact) {
        if (path == null || path.length() == 0) {
            return path;
        }
        return breadcrumbPath(urlPrefix, path, sep, urlPostfix, compact,
                path.charAt(path.length() - 1) == sep);
    }

    /**
     * Create a breadcrumb path to allow navigation to each element of a path.
     * Consecutive separators (<var>sep</var>) in the given <var>path</var> are
     * always collapsed into a single separator automatically. If
     * <var>compact</var> is {@code true} path gets translated into a canonical
     * path similar to {@link File#getCanonicalPath()}, however the current
     * working directory is assumed to be "/" and no checks are done (e.g.
     * neither whether the path [component] exists nor which type it is).
     *
     * @param urlPrefix what should be prepend to the constructed URL
     * @param path the full path from which the breadcrumb path is built.
     * @param sep the character that separates the path components in
     * <var>path</var>
     * @param urlPostfix what should be append to the constructed URL
     * @param compact if {@code true}, a canonical path gets constructed before
     * processing.
     * @param isDir if {@code true} a "/" gets append to the last path
     * component's link and <var>sep</var> to its name
     * @return <var>path</var> if it resolves to an empty or "/" or {@code null}
     * path, the HTML markup for the breadcrumb path otherwise.
     */
    public static String breadcrumbPath(String urlPrefix, String path,
            char sep, String urlPostfix, boolean compact, boolean isDir) {
        if (path == null || path.length() == 0) {
            return path;
        }
        String[] pnames = normalize(path.split(escapeForRegex(sep)),
                compact);
        if (pnames.length == 0) {
            return path;
        }
        String prefix = urlPrefix == null ? "" : urlPrefix;
        String postfix = urlPostfix == null ? "" : urlPostfix;
        StringBuilder pwd = new StringBuilder(path.length() + pnames.length);
        StringBuilder markup = new StringBuilder((pnames.length + 3 >> 1)
                * path.length() + pnames.length
                * (17 + prefix.length() + postfix.length()));
        int k = path.indexOf(pnames[0]);
        if (path.lastIndexOf(sep, k) != -1) {
            pwd.append('/');
            markup.append(sep);
        }
        for (int i = 0; i < pnames.length; i++) {
            pwd.append(URIEncodePath(pnames[i]));
            if (isDir || i < pnames.length - 1) {
                pwd.append('/');
            }
            markup.append(anchorLinkStart).append(prefix).append(pwd)
                    .append(postfix).append(closeQuotedTag)
                    .append(pnames[i]).append(anchorEnd);
            if (isDir || i < pnames.length - 1) {
                markup.append(sep);
            }
        }
        return markup.toString();
    }

    /**
     * Remove all empty and {@code null} string elements from the given
     * <var>names</var> and optionally all redundant information like "." and
     * "..".
     *
     * @param names names to check
     * @param canonical if {@code true}, remove redundant elements as well.
     * @return a possible empty array of names all with a length &gt; 0.
     */
    private static String[] normalize(String[] names, boolean canonical) {
        LinkedList<String> res = new LinkedList<>();
        if (names == null || names.length == 0) {
            return new String[0];
        }
        for (String name : names) {
            if (name == null || name.length() == 0) {
                continue;
            }
            if (canonical) {
                if (name.equals("..")) {
                    if (!res.isEmpty()) {
                        res.removeLast();
                    }
                } else if (name.equals(".")) {
                } else {
                    res.add(name);
                }
            } else {
                res.add(name);
            }
        }
        return res.size() == names.length ? names : res
                .toArray(new String[res.size()]);
    }

    /**
     * Generate a regex that matches the specified character. Escape it in case
     * it is a character that has a special meaning in a regex.
     *
     * @param c the character that the regex should match
     * @return a six-character string on the form <tt>&#92;u</tt><i>hhhh</i>
     */
    private static String escapeForRegex(char c) {
        StringBuilder sb = new StringBuilder(6);
        sb.append("\\u");
        String hex = Integer.toHexString(c);
        for (int i = 0; i < 4 - hex.length(); i++) {
            sb.append('0');
        }
        sb.append(hex);
        return sb.toString();
    }

    /**
     * URI encode the given path.
     *
     * @param path path to encode.
     * @return the encoded path.
     * @throws NullPointerException if a parameter is {@code null}
     */
    public static String URIEncodePath(String path) {
        // Bug #19188: Ideally, we'd like to use the standard class library to
        // encode the paths. We're aware of the following two methods:
        //
        // 1) URLEncoder.encode() - this method however transforms space to +
        // instead of %20 (which is right for HTML form data, but not for
        // paths), and it also does not preserve the separator chars (/).
        //
        // 2) URI.getRawPath() - transforms space and / as expected, but gets
        // confused when the path name contains a colon character (it thinks
        // parts of the path is schema in that case)
        //
        // For now, encode manually the way we want it.
        StringBuilder sb = new StringBuilder(path.length());
        for (byte b : path.getBytes(UTF8)) {
            // URLEncoder's javadoc says a-z, A-Z, ., -, _ and * are safe
            // characters, so we preserve those to make the encoded string
            // shorter and easier to read. We also preserve the separator
            // chars (/). All other characters are encoded (as UTF-8 byte
            // sequences).
            if ((b == '/') || (b >= 'a' && b <= 'z')
                    || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9')
                    || (b == '.') || (b == '-') || (b == '_') || (b == '*')) {
                sb.append((char) b);
            } else {
                sb.append('%');
                int u = b & 0xFF; // Make the byte value unsigned.
                if (u <= 0x0F) {
                    // Add leading zero if required.
                    sb.append('0');
                }
                sb.append(Integer.toHexString(u)
                        .toUpperCase(Locale.ENGLISH));
            }
        }
        return sb.toString();
    }
}

Related

  1. checkReadableDirectory(final Path directory)
  2. getReaderForFile(final Path file)
  3. getResourceAsStream(String resourcePath, ClassLoader classLoader, Class clazz, String resourceDesc, Consumer logger)
  4. getTestClassPathURLClassLoader(ClassLoader parent)