Util.java revision 604
98N/A/*
98N/A * CDDL HEADER START
98N/A *
98N/A * The contents of this file are subject to the terms of the
98N/A * Common Development and Distribution License (the "License").
98N/A * You may not use this file except in compliance with the License.
98N/A *
98N/A * See LICENSE.txt included in this distribution for the specific
98N/A * language governing permissions and limitations under the License.
98N/A *
98N/A * When distributing Covered Code, include this CDDL HEADER in each
98N/A * file and include the License file at LICENSE.txt.
98N/A * If applicable, add the following below this CDDL HEADER, with the
98N/A * fields enclosed by brackets "[]" replaced with your own identifying
98N/A * information: Portions Copyright [yyyy] [name of copyright owner]
98N/A *
98N/A * CDDL HEADER END
98N/A */
98N/A
98N/A/*
98N/A * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
98N/A * Use is subject to license terms.
98N/A */
98N/Apackage org.opensolaris.opengrok.web;
98N/A
98N/Aimport java.io.IOException;
98N/Aimport java.io.UnsupportedEncodingException;
98N/Aimport java.io.Writer;
98N/Aimport java.net.URI;
98N/Aimport java.net.URISyntaxException;
98N/Aimport java.net.URLEncoder;
98N/Aimport java.text.DecimalFormat;
161N/Aimport java.text.NumberFormat;
98N/Aimport java.util.logging.Level;
98N/Aimport org.opensolaris.opengrok.OpenGrokLogger;
98N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
98N/Aimport org.opensolaris.opengrok.history.Annotation;
98N/A
156N/A/**
156N/A * File for useful functions
156N/A */
156N/Apublic final class Util {
98N/A /**
98N/A * Return a string which represents a <code>CharSequence</code> in HTML.
98N/A *
98N/A * @param q a character sequence
98N/A * @return a string representing the character sequence in HTML
98N/A */
98N/A
98N/A private Util() {
98N/A // Util class, should not be constructed
156N/A }
98N/A
98N/A public static String htmlize(CharSequence q) {
98N/A StringBuilder sb = new StringBuilder(q.length() * 2);
98N/A htmlize(q, sb);
101N/A return sb.toString();
117N/A }
98N/A
98N/A /**
122N/A * Append a character sequence to an <code>Appendable</code> object. Escape
127N/A * special characters for HTML.
131N/A *
145N/A * @param q a character sequence
98N/A * @param out the object to append the character sequence to
98N/A * @exception IOException if an I/O error occurs
98N/A */
98N/A public static void htmlize(CharSequence q, Appendable out)
98N/A throws IOException {
98N/A for (int i = 0; i < q.length(); i++) {
98N/A htmlize(q.charAt(i), out);
98N/A }
98N/A }
98N/A
98N/A /**
98N/A * Append a character sequence to a <code>StringBuilder</code>
98N/A * object. Escape special characters for HTML. This method is identical to
98N/A * <code>htmlize(CharSequence,Appendable)</code>, except that it is
98N/A * guaranteed not to throw <code>IOException</code> because it uses a
98N/A * <code>StringBuilder</code>.
98N/A *
98N/A * @param q a character sequence
98N/A * @param out the object to append the character sequence to
98N/A * @see #htmlize(CharSequence, Appendable)
98N/A */
98N/A @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
98N/A public static void htmlize(CharSequence q, StringBuilder out) {
98N/A try {
98N/A htmlize(q, (Appendable) out);
98N/A } catch (IOException ioe) {
98N/A // StringBuilder's append methods are not declared to throw
98N/A // IOException, so this should never happen.
98N/A throw new RuntimeException("StringBuilder should not throw IOException", ioe);
98N/A }
98N/A }
98N/A
98N/A public static void htmlize(char[] cs, int length, Appendable out)
140N/A throws IOException {
154N/A for (int i = 0; i < length && i < cs.length; i++) {
158N/A htmlize(cs[i], out);
161N/A }
161N/A }
98N/A
98N/A /**
98N/A * Append a character to a an <code>Appendable</code> object. If the
98N/A * character has special meaning in HTML, append a sequence of characters
98N/A * representing the special character.
98N/A *
98N/A * @param c the character to append
98N/A * @param out the object to append the character to
98N/A * @exception IOException if an I/O error occurs
98N/A */
98N/A private static void htmlize(char c, Appendable out) throws IOException {
98N/A switch (c) {
98N/A case '&':
98N/A out.append("&amp;");
98N/A break;
98N/A case '>':
98N/A out.append("&gt;");
98N/A break;
98N/A case '<':
98N/A out.append("&lt;");
98N/A break;
98N/A case '\n':
98N/A out.append("<br/>");
98N/A break;
98N/A default:
98N/A out.append(c);
98N/A }
98N/A }
98N/A
98N/A /**
98N/A * Same as {@code breadcrumbPath(urlPrefix, l, '/')}.
98N/A * @see #breadcrumbPath(String, String, char)
98N/A */
98N/A public static String breadcrumbPath(String urlPrefix, String l) {
98N/A return breadcrumbPath(urlPrefix, l, '/');
98N/A }
98N/A
98N/A private static final String anchorLinkStart = "<a href=\"";
98N/A private static final String anchorClassStart = "<a class=\"";
98N/A private static final String anchorEnd = "</a>";
156N/A private static final String closeQuotedTag = "\">";
98N/A
98N/A /**
98N/A * Same as {@code breadcrumbPath(urlPrefix, l, sep, "")}.
98N/A * @see #breadcrumbPath(String, String, char, String)
98N/A */
98N/A public static String breadcrumbPath(String urlPrefix, String l, char sep) {
98N/A return breadcrumbPath(urlPrefix, l, sep, "");
98N/A }
98N/A
98N/A /**
98N/A * Create a breadcrumb path to allow navigation to each element of a path.
98N/A *
98N/A * @param urlPrefix what comes before the path in the URL
98N/A * @param l the full path from which the breadcrumb path is built
98N/A * @param sep the character that separates the path elements in {@code l}
156N/A * @param urlPostfix what comes after the path in the URL
156N/A * @return HTML markup for the breadcrumb path
156N/A */
98N/A public static String breadcrumbPath(
98N/A String urlPrefix, String l, char sep, String urlPostfix) {
98N/A if (l == null || l.length() <= 1) {
98N/A return l;
98N/A }
98N/A StringBuilder hyperl = new StringBuilder(20);
98N/A String[] path = l.split(escapeForRegex(sep), -1);
98N/A for (int i = 0; i < path.length; i++) {
98N/A leaveBreadcrumb(urlPrefix, sep, urlPostfix, hyperl, path, i);
98N/A }
98N/A return hyperl.toString();
98N/A }
98N/A
98N/A /**
98N/A * Leave a breadcrumb to allow navigation to one of the parent directories.
106N/A * Write a hyperlink to the specified {@code StringBuilder}.
98N/A *
98N/A * @param urlPrefix what comes before the path in the URL
98N/A * @param sep the character that separates path elements
98N/A * @param urlPostfix what comes after the path in the URL
98N/A * @param hyperl a string builder to which the hyperlink is written
98N/A * @param path all the elements of the full path
98N/A * @param index which path element to create a link to
98N/A */
98N/A private static void leaveBreadcrumb(
98N/A String urlPrefix, char sep, String urlPostfix, StringBuilder hyperl,
98N/A String[] path, int index) {
98N/A // Only generate the link if the path element is non-empty. Empty
98N/A // path elements could occur if the path contains two consecutive
98N/A // separator characters, or if the path begins or ends with a path
98N/A // separator.
98N/A if (path[index].length() > 0) {
98N/A hyperl.append(anchorLinkStart).append(urlPrefix);
98N/A appendPath(path, index, hyperl);
98N/A hyperl.append(urlPostfix).append(closeQuotedTag).
98N/A append(path[index]).append(anchorEnd);
98N/A }
98N/A // Add a separator between each path element, but not after the last
98N/A // one. If the original path ended with a separator, the last element
156N/A // of the path array is an empty string, which means that the final
156N/A // separator will be printed.
156N/A if (index < path.length - 1) {
98N/A hyperl.append(sep);
98N/A }
98N/A }
156N/A
156N/A /**
156N/A * Append parts of a file path to a {@code StringBuilder}. Separate each
98N/A * element in the path with "/". The path elements from index 0 up to
98N/A * index {@code lastIndex} (inclusive) are used.
98N/A *
98N/A * @param path array of path elements
98N/A * @param lastIndex the index of the last path element to use
98N/A * @param out the {@code StringBuilder} to which the path is appended
98N/A */
98N/A private static void appendPath(
98N/A String[] path, int lastIndex, StringBuilder out) {
98N/A for (int i = 0; i <= lastIndex; i++) {
98N/A out.append(path[i]);
98N/A if (i < lastIndex) {
98N/A out.append("/");
98N/A }
98N/A }
98N/A }
98N/A
98N/A /**
98N/A * Generate a regex that matches the specified character. Escape it in
98N/A * case it is a character that has a special meaning in a regex.
98N/A *
111N/A * @param c the character that the regex should match
111N/A * @return a six-character string on the form <tt>&#92;u</tt><i>hhhh</i>
111N/A */
111N/A private static String escapeForRegex(char c) {
111N/A StringBuilder sb = new StringBuilder(6);
111N/A sb.append("\\u");
98N/A String hex = Integer.toHexString((int) c);
98N/A for (int i = 0; i < 4 - hex.length(); i++) {
98N/A sb.append('0');
98N/A }
98N/A sb.append(hex);
98N/A return sb.toString();
98N/A }
98N/A
98N/A public static String redableSize(long num) {
float l = (float) num;
NumberFormat formatter = new DecimalFormat("#,###,###,###.#");
if (l < 1024) {
return formatter.format(l);
} else if (l < 1048576) {
return (formatter.format(l / 1024) + "K");
} else {
return ("<b>" + formatter.format(l / 1048576) + "M</b>");
}
}
public static void readableLine(int num, Writer out, Annotation annotation)
throws IOException {
String snum = String.valueOf(num);
if (num > 1) {
out.write("\n");
}
out.write(anchorClassStart);
out.write((num % 10 == 0 ? "hl" : "l"));
out.write("\" name=\"");
out.write(snum);
out.write(closeQuotedTag);
out.write((num > 999 ? " " : (num > 99 ? " " : (num > 9 ? " " : " "))));
out.write(snum);
out.write(" ");
out.write(anchorEnd);
if (annotation != null) {
String r = annotation.getRevision(num);
boolean enabled = annotation.isEnabled(num);
out.write("<span class=\"blame\"><span class=\"l\"> ");
for (int i = r.length(); i < annotation.getWidestRevision(); i++) {
out.write(" ");
}
if (enabled) {
out.write(anchorLinkStart);
out.write(URIEncode(annotation.getFilename()));
out.write("?a=true&r=");
out.write(URIEncode(r));
out.write(closeQuotedTag);
}
htmlize(r, out);
if (enabled) {
out.write(anchorEnd);
}
out.write(" </span>");
String a = annotation.getAuthor(num);
out.write("<span class=\"l\"> ");
for (int i = a.length(); i < annotation.getWidestAuthor(); i++) {
out.write(" ");
}
String link = RuntimeEnvironment.getInstance().getUserPage();
if (link != null && link.length() > 0) {
out.write(anchorLinkStart);
out.write(link);
out.write(URIEncode(a));
out.write(closeQuotedTag);
htmlize(a, out);
out.write(anchorEnd);
} else {
htmlize(a, out);
}
out.write(" </span></span>");
}
}
/**
* Append path and date into a string in such a way that lexicographic
* sorting gives the same results as a walk of the file hierarchy. Thus
* null (\u0000) is used both to separate directory components and to
* separate the path from the date.
*/
public static String uid(String path, String date) {
return path.replace('/', '\u0000') + "\u0000" + date;
}
public static String uid2url(String uid) {
String url = uid.replace('\u0000', '/'); // replace nulls with slashes
return url.substring(0, url.lastIndexOf('/')); // remove date from end
}
public static String URIEncode(String q) {
try {
// We should probably use an encoding which supports a larger
// character set, but use ISO-8859-1 for now, since that's what
// we use other places in the code.
return URLEncoder.encode(q, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// Should not happen. ISO-8859-1 must be supported by all JVMs.
return null;
}
}
public static String URIEncodePath(String path) {
try {
URI uri = new URI(null, null, path, null);
return uri.getRawPath();
} catch (URISyntaxException ex) {
OpenGrokLogger.getLogger().log(Level.WARNING, "Could not encode path " + path, ex);
return "";
}
}
public static String formQuoteEscape(String q) {
if (q == null) {
return "";
}
StringBuilder sb = new StringBuilder();
char c;
for (int i = 0; i < q.length(); i++) {
c = q.charAt(i);
if (c == '"') {
sb.append("&quot;");
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* Build a string that may be converted to a Query and passed to Lucene.
* All parameters may be passed as null or an empty string to indicate that
* they are unused.
*
* @param freetext The string from the "Full Search" text-field. This field
* will be applied as it is specified.
* @param defs The string from the "Definition" text-field. This field
* will be searched for in the <b>defs</b> field in the lucene
* index. All occurences of ":" will be replaced with "\:"
* @param refs The string from the "Symbol" text-field. This field
* will be searched for in the <b>refs</b> field in the lucene
* index. All occurences of ":" will be replaced with "\:"
* @param path The string from the "File Path" text-field. This field
* will be searched for in the <b>path</b> field in the lucene
* index. All occurences of ":" will be replaced with "\:"
* @param hist The string from the "History" text-field. This field
* will be searched for in the <b>hist</b> field in the lucene
* index. All occurences of ":" will be replaced with "\:"
* @return A string to be parsed by the Lucene parser.
*/
public static String buildQueryString(String freetext, String defs, String refs, String path, String hist) {
StringBuilder sb = new StringBuilder();
if (freetext != null && freetext.length() > 0) {
sb.append(freetext.replace("::", "\\:\\:"));
}
if (defs != null && defs.length() > 0) {
sb.append(" defs:(");
sb.append(escapeQueryString(defs));
sb.append(")");
}
if (refs != null && refs.length() > 0) {
sb.append(" refs:(");
sb.append(escapeQueryString(refs));
sb.append(")");
}
if (path != null && path.length() > 0) {
sb.append(" path:(");
sb.append(escapeQueryString(path));
sb.append(")");
}
if (hist != null && hist.length() > 0) {
sb.append(" hist:(");
sb.append(escapeQueryString(hist));
sb.append(")");
}
return sb.toString();
}
private static String escapeQueryString(String input) {
return input.replace(":", "\\:");
}
}