Util.java revision 1145
493N/A/*
0N/A * CDDL HEADER START
416N/A *
0N/A * The contents of this file are subject to the terms of the
0N/A * Common Development and Distribution License (the "License").
0N/A * You may not use this file except in compliance with the License.
0N/A *
0N/A * See LICENSE.txt included in this distribution for the specific
0N/A * language governing permissions and limitations under the License.
0N/A *
0N/A * When distributing Covered Code, include this CDDL HEADER in each
0N/A * file and include the License file at LICENSE.txt.
0N/A * If applicable, add the following below this CDDL HEADER, with the
0N/A * fields enclosed by brackets "[]" replaced with your own identifying
0N/A * information: Portions Copyright [yyyy] [name of copyright owner]
0N/A *
0N/A * CDDL HEADER END
0N/A */
0N/A
0N/A/*
0N/A * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
0N/A */
0N/Apackage org.opensolaris.opengrok.web;
0N/A
0N/Aimport java.io.IOException;
0N/Aimport java.io.UnsupportedEncodingException;
0N/Aimport java.io.Writer;
0N/Aimport java.net.URI;
0N/Aimport java.net.URISyntaxException;
595N/Aimport java.net.URLEncoder;
0N/Aimport java.text.DecimalFormat;
0N/Aimport java.text.NumberFormat;
0N/Aimport java.util.ArrayList;
0N/Aimport java.util.Collection;
0N/Aimport java.util.logging.Level;
0N/Aimport org.opensolaris.opengrok.OpenGrokLogger;
0N/Aimport org.opensolaris.opengrok.configuration.RuntimeEnvironment;
0N/Aimport org.opensolaris.opengrok.history.Annotation;
0N/Aimport org.opensolaris.opengrok.history.HistoryException;
0N/Aimport org.opensolaris.opengrok.history.HistoryGuru;
0N/A
561N/A/**
561N/A * File for useful functions
0N/A */
0N/Apublic final class Util {
0N/A /**
0N/A * Return a string which represents a <code>CharSequence</code> in HTML.
0N/A *
493N/A * @param q a character sequence
493N/A * @return a string representing the character sequence in HTML
493N/A */
0N/A
493N/A private Util() {
493N/A // Util class, should not be constructed
0N/A }
493N/A
493N/A public static String htmlize(CharSequence q) {
577N/A StringBuilder sb = new StringBuilder(q.length() * 2);
493N/A htmlize(q, sb);
493N/A return sb.toString();
493N/A }
493N/A
493N/A /**
493N/A * Append a character sequence to an <code>Appendable</code> object. Escape
493N/A * special characters for HTML.
493N/A *
493N/A * @param q a character sequence
493N/A * @param out the object to append the character sequence to
0N/A * @exception IOException if an I/O error occurs
493N/A */
493N/A public static void htmlize(CharSequence q, Appendable out)
493N/A throws IOException {
493N/A for (int i = 0; i < q.length(); i++) {
493N/A htmlize(q.charAt(i), out);
493N/A }
493N/A }
493N/A
493N/A /**
493N/A * Append a character sequence to a <code>StringBuilder</code>
493N/A * object. Escape special characters for HTML. This method is identical to
493N/A * <code>htmlize(CharSequence,Appendable)</code>, except that it is
493N/A * guaranteed not to throw <code>IOException</code> because it uses a
493N/A * <code>StringBuilder</code>.
0N/A *
0N/A * @param q a character sequence
0N/A * @param out the object to append the character sequence to
0N/A * @see #htmlize(CharSequence, Appendable)
561N/A */
561N/A @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
561N/A public static void htmlize(CharSequence q, StringBuilder out) {
561N/A try {
561N/A htmlize(q, (Appendable) out);
561N/A } catch (IOException ioe) {
561N/A // StringBuilder's append methods are not declared to throw
561N/A // IOException, so this should never happen.
561N/A throw new RuntimeException("StringBuilder should not throw IOException", ioe);
561N/A }
561N/A }
561N/A
561N/A public static void htmlize(char[] cs, int length, Appendable out)
561N/A throws IOException {
561N/A for (int i = 0; i < length && i < cs.length; i++) {
561N/A htmlize(cs[i], out);
561N/A }
561N/A }
561N/A
561N/A /**
561N/A * Append a character to a an <code>Appendable</code> object. If the
561N/A * character has special meaning in HTML, append a sequence of characters
561N/A * representing the special character.
561N/A *
561N/A * @param c the character to append
561N/A * @param out the object to append the character to
561N/A * @exception IOException if an I/O error occurs
0N/A */
561N/A private static void htmlize(char c, Appendable out) throws IOException {
561N/A switch (c) {
561N/A case '&':
561N/A out.append("&amp;");
561N/A break;
493N/A case '>':
493N/A out.append("&gt;");
493N/A break;
493N/A case '<':
493N/A out.append("&lt;");
493N/A break;
493N/A case '\n':
493N/A out.append("<br/>");
493N/A break;
0N/A default:
493N/A out.append(c);
493N/A }
493N/A }
493N/A
493N/A private static String versionP=htmlize(org.opensolaris.opengrok.Info.getRevision());
493N/A /**
0N/A * used by BUI - CSS needs this parameter for proper cache refresh (per changeset) in client browser
493N/A * @return html escaped version (hg changeset)
493N/A */
493N/A public static String versionParameter() {
493N/A return versionP;
493N/A }
493N/A
493N/A /**
493N/A * Same as {@code breadcrumbPath(urlPrefix, l, '/')}.
493N/A * @see #breadcrumbPath(String, String, char)
561N/A */
493N/A public static String breadcrumbPath(String urlPrefix, String l) {
561N/A return breadcrumbPath(urlPrefix, l, '/');
0N/A }
0N/A
493N/A private static final String anchorLinkStart = "<a href=\"";
493N/A private static final String anchorClassStart = "<a class=\"";
0N/A private static final String anchorEnd = "</a>";
561N/A private static final String closeQuotedTag = "\">";
355N/A
355N/A /**
493N/A * Same as {@code breadcrumbPath(urlPrefix, l, sep, "", false)}.
561N/A * @see #breadcrumbPath(String, String, char, String, boolean)
493N/A */
493N/A public static String breadcrumbPath(String urlPrefix, String l, char sep) {
493N/A return breadcrumbPath(urlPrefix, l, sep, "", false);
561N/A }
493N/A
493N/A /**
493N/A * Create a breadcrumb path to allow navigation to each element of a path.
493N/A *
493N/A * @param urlPrefix what comes before the path in the URL
493N/A * @param l the full path from which the breadcrumb path is built
493N/A * @param sep the character that separates the path elements in {@code l}
493N/A * @param urlPostfix what comes after the path in the URL
493N/A * @param compact if {@code true}, remove {@code ..} and empty path
493N/A * elements from the path in the links
493N/A * @return HTML markup for the breadcrumb path
493N/A */
0N/A public static String breadcrumbPath(
493N/A String urlPrefix, String l, char sep, String urlPostfix,
493N/A boolean compact) {
493N/A if (l == null || l.length() <= 1) {
0N/A return l;
0N/A }
493N/A StringBuilder hyperl = new StringBuilder(20);
0N/A String[] path = l.split(escapeForRegex(sep), -1);
493N/A for (int i = 0; i < path.length; i++) {
0N/A leaveBreadcrumb(
493N/A urlPrefix, sep, urlPostfix, compact, hyperl, path, i);
493N/A }
0N/A return hyperl.toString();
493N/A }
493N/A
0N/A /**
0N/A * Leave a breadcrumb to allow navigation to one of the parent directories.
0N/A * Write a hyperlink to the specified {@code StringBuilder}.
0N/A *
493N/A * @param urlPrefix what comes before the path in the URL
355N/A * @param sep the character that separates path elements
493N/A * @param urlPostfix what comes after the path in the URL
493N/A * @param compact if {@code true}, remove {@code ..} and empty path
493N/A * elements from the path in the link
493N/A * @param hyperl a string builder to which the hyperlink is written
493N/A * @param path all the elements of the full path
493N/A * @param index which path element to create a link to
493N/A */
493N/A private static void leaveBreadcrumb(
493N/A String urlPrefix, char sep, String urlPostfix, boolean compact,
493N/A StringBuilder hyperl, String[] path, int index) {
493N/A // Only generate the link if the path element is non-empty. Empty
493N/A // path elements could occur if the path contains two consecutive
368N/A // separator characters, or if the path begins or ends with a path
0N/A // separator.
0N/A if (path[index].length() > 0) {
0N/A hyperl.append(anchorLinkStart).append(urlPrefix);
0N/A appendPath(path, index, hyperl, compact);
0N/A hyperl.append(urlPostfix).append(closeQuotedTag).
493N/A append(path[index]).append(anchorEnd);
0N/A }
595N/A // Add a separator between each path element, but not after the last
0N/A // one. If the original path ended with a separator, the last element
493N/A // of the path array is an empty string, which means that the final
0N/A // separator will be printed.
0N/A if (index < path.length - 1) {
595N/A hyperl.append(sep);
0N/A }
493N/A }
0N/A
0N/A /**
0N/A * Append parts of a file path to a {@code StringBuilder}. Separate each
0N/A * element in the path with "/". The path elements from index 0 up to
493N/A * index {@code lastIndex} (inclusive) are used.
0N/A *
0N/A * @param path array of path elements
0N/A * @param lastIndex the index of the last path element to use
0N/A * @param out the {@code StringBuilder} to which the path is appended
0N/A * @param compact if {@code true}, remove {@code ..} and empty path
493N/A * elements from the path in the link
493N/A */
493N/A private static void appendPath(
493N/A String[] path, int lastIndex, StringBuilder out, boolean compact) {
0N/A final ArrayList<String> elements = new ArrayList<String>(lastIndex + 1);
493N/A
493N/A // Copy the relevant part of the path. If compact is false, just
561N/A // copy the lastIndex first elements. If compact is true, remove empty
561N/A // path elements, and follow .. up to the parent directory. Occurrences
561N/A // of .. at the beginning of the path will be removed.
561N/A for (int i = 0; i <= lastIndex; i++) {
561N/A if (compact) {
561N/A if ("..".equals(path[i])) {
561N/A if (!elements.isEmpty()) {
561N/A elements.remove(elements.size() - 1);
561N/A }
561N/A } else if (!"".equals(path[i])) {
561N/A elements.add(URIEncodePath(path[i]));
493N/A }
0N/A } else {
493N/A elements.add(URIEncodePath(path[i]));
493N/A }
493N/A }
493N/A
493N/A // Print the path with / between each element. No separator before
493N/A // the first element or after the last element.
493N/A for (int i = 0; i < elements.size(); i++) {
493N/A out.append(elements.get(i));
493N/A if (i < elements.size() - 1) {
493N/A out.append("/");
493N/A }
493N/A }
493N/A }
493N/A
493N/A /**
0N/A * Generate a regex that matches the specified character. Escape it in
0N/A * case it is a character that has a special meaning in a regex.
493N/A *
0N/A * @param c the character that the regex should match
493N/A * @return a six-character string on the form <tt>&#92;u</tt><i>hhhh</i>
493N/A */
493N/A private static String escapeForRegex(char c) {
493N/A StringBuilder sb = new StringBuilder(6);
29N/A sb.append("\\u");
561N/A String hex = Integer.toHexString((int) c);
493N/A for (int i = 0; i < 4 - hex.length(); i++) {
0N/A sb.append('0');
0N/A }
561N/A sb.append(hex);
561N/A return sb.toString();
561N/A }
561N/A
561N/A public static String redableSize(long num) {
561N/A float l = (float) num;
561N/A NumberFormat formatter = new DecimalFormat("#,###,###,###.#");
29N/A if (l < 1024) {
29N/A return formatter.format(l);
0N/A } else if (l < 1048576) {
493N/A return (formatter.format(l / 1024) + "K");
} else {
return ("<b>" + formatter.format(l / 1048576) + "M</b>");
}
}
/**
* Converts different html special characters into their encodings used in html
* currently used only for tooltips of annotation revision number view
* @param s input text
* @return encoded text for use in <a title=""> tag
*/
public static String encode(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"':
sb.append('\'');
break; // \\\"
case '&':
sb.append("&amp;");
break;
case '>':
sb.append("&gt;");
break;
case '<':
sb.append("&lt;");
break;
case ' ':
sb.append("&nbsp;");
break;
case '\t':
sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
break;
case '\n':
sb.append("<br/>");
break;
case '\r':
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
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("\" href=\"#");
out.write(snum);
out.write(closeQuotedTag);
out.write((num > 999 ? "&nbsp;&nbsp;&nbsp;" : (num > 99 ? "&nbsp;&nbsp;&nbsp;&nbsp;" : (num > 9 ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"))));
out.write(snum);
out.write("&nbsp;");
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&amp;r=");
out.write(URIEncode(r));
String msg=annotation.getDesc(r);
if (msg!=null) {
out.write("\" name=\"r\" title=\""+msg+"\"");
}
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();
String suffix = RuntimeEnvironment.getInstance().getUserPageSuffix();
if (link != null && link.length() > 0) {
out.write(anchorLinkStart);
out.write(link);
out.write(URIEncode(a));
if (suffix != null && 0 < suffix.length()) {
out.write(suffix);
}
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
}
/**
* wrapper arround UTF-8 URL encoding of a string
* @param q query to be encoded
* @return null if fail, otherwise the encoded string
*/
public static String URIEncode(String q) {
try {
return URLEncoder.encode(q, "UTF-8");
} catch (UnsupportedEncodingException e) {
// Should not happen. UTF-8 must be supported by 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();
}
/**
* Highlight the diffs between line1 and line2
* @param line1
* @param line2
* @return new strings with html tags highlighting the diffs
*/
public static String[] diffline(String line1, String line2) {
String[] ret = new String[2];
int s=0;
int m=line1.length()-1;
int n=line2.length()-1;
while (s <= m && s <= n && (line1.charAt(s) == line2.charAt(s)))
{ s++; }
while (s <= m && s <= n && (line1.charAt(m) == line2.charAt(n)))
{ m--;n--; }
StringBuilder sb = new StringBuilder(line1);
String spand="<span class=\"d\">";
if(s <= m) {
sb.insert(s, spand);
sb.insert(spand.length()+m+1, "</span>");
ret[0] = sb.toString();
} else {
ret[0] = line1;
}
String spana="<span class=\"a\">";
if(s <= n) {
sb = new StringBuilder(line2);
sb.insert(s, spana);
sb.insert(spana.length()+n+1, "</span>");
ret[1] = sb.toString();
} else {
ret[1] = line2;
}
return ret;
}
/**
* Dump the configuration as an HTML table.
*
* @param out destination for the HTML output
* @throws IOException if an error happens while writing to {@code out}
* @throws HistoryException if the history guru cannot be accesses
*/
public static void dumpConfiguration(Appendable out)
throws IOException, HistoryException {
out.append("<table border=\"1\" width=\"100%\">");
out.append("<tr><th>Variable</th><th>Value</th></tr>");
RuntimeEnvironment env = RuntimeEnvironment.getInstance();
printTableRow(out, "Source root", env.getSourceRootPath());
printTableRow(out, "Data root", env.getDataRootPath());
printTableRow(out, "CTags", env.getCtags());
printTableRow(out, "Bug page", env.getBugPage());
printTableRow(out, "Bug pattern", env.getBugPattern());
printTableRow(out, "User page", env.getUserPage());
printTableRow(out, "Review page", env.getReviewPage());
printTableRow(out, "Review pattern", env.getReviewPattern());
printTableRow(out, "Using projects", env.hasProjects());
out.append("<tr><td>Ignored files</td><td>");
printUnorderedList(out, env.getIgnoredNames().getItems());
out.append("</td></tr>");
printTableRow(out, "Index word limit", env.getIndexWordLimit());
printTableRow(out, "Allow leading wildcard in search",
env.isAllowLeadingWildcard());
printTableRow(out, "History cache",
HistoryGuru.getInstance().getCacheInfo());
out.append("</table>");
}
/**
* Print a row in an HTML table.
*
* @param out destination for the HTML output
* @param cells the values to print in the cells of the row
* @throws IOException if an error happens while writing to {@code out}
*/
private static void printTableRow(Appendable out, Object... cells)
throws IOException {
out.append("<tr>");
for (Object cell : cells) {
out.append("<td>");
String str = (cell == null) ? "null" : cell.toString();
htmlize(str, out);
out.append("</td>");
}
out.append("</tr>");
}
/**
* Print an unordered list (HTML).
*
* @param out destination for the HTML output
* @param items the list items
* @throws IOException if an error happens while writing to {@code out}
*/
private static void printUnorderedList(
Appendable out, Collection<String> items) throws IOException {
out.append("<ul>");
for (String item : items) {
out.append("<li>");
htmlize(item, out);
out.append("</li>");
}
out.append("</ul>");
}
/**
* Create a string literal for use in JavaScript functions.
* @param str the string to be represented by the literal
* @return a JavaScript string literal
*/
public static String jsStringLiteral(String str) {
StringBuilder sb = new StringBuilder();
sb.append('"');
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
default:
sb.append(c);
}
}
sb.append('"');
return sb.toString();
}
}