Java/Servlets/HTML Output
Содержание
- 1 A collection of all character entites defined in the HTML4 standard.
- 2 break Lines with HTML
- 3 Convert an integer to an HTML RGB value
- 4 Convert HTML to text
- 5 Convert to HTML string
- 6 Decode an HTML color string like "#F567BA;" into a Color
- 7 Definitions of HTML character entities and conversions between unicode characters and HTML character entities
- 8 Encode special characters and do formatting for HTML output
- 9 Entity Decoder
- 10 Escape and unescape string
- 11 Escape HTML
- 12 Escapes newlines, tabs, backslashes, and quotes in the specified string
- 13 Filter the specified message string for characters that are sensitive in HTML
- 14 Format a color to HTML RGB color format (e.g. #FF0000 for Color.red)
- 15 Get HTML Color String from Java Color object
- 16 HTML color and Java Color
- 17 HTML color names
- 18 HTML Decoder
- 19 Html Dimensions
- 20 HTML form Utilites
- 21 HTML Helper
- 22 HTML Parser
- 23 Html Parse Servlet
- 24 Please submit a new valid stock symbol
- 25 Sorry, the stock symbol parameter was either empty or null
- 26 Here is the latest value of " + symbol + "
- 27 Html utilities
- 28 insert HTML block dynamically
- 29 Java object representations of the HTML table structure
- 30 Normalize Post Data
- 31 Prints a conversion table of miles per gallon to kilometers per liter
- 32 Fuel Efficiency Conversion Chart
A collection of all character entites defined in the HTML4 standard.
<source lang="java">
/**
* * LibXML : a free Java layouting library * * * Project Info: http://reporting.pentaho.org/libxml/ * * (C) Copyright 2006-2008, by Object Refinery Ltd, Pentaho Corporation and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * * ------------ * HtmlCharacterEntities.java * ------------ */
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; /**
* A collection of all character entites defined in the HTML4 standard. The key * is the entity name, the property value is the decoded string. * * @author Thomas Morgner */
public class HtmlCharacterEntities extends Properties {
/** * The singleton instance for this entity-parser implementation. */ private static CharacterEntityParser entityParser; private static final long serialVersionUID = 5118172339379209383L; /** * Gets the character entity parser for HTML content. The CharacterEntity * parser translates known characters into predefined entities. * * @return the character entity parser instance. */ public static CharacterEntityParser getEntityParser() { if (entityParser == null) { entityParser = new CharacterEntityParser(new HtmlCharacterEntities()); } return entityParser; } /** * Creates an instance. */ public HtmlCharacterEntities() { setProperty("ang", "\u2220"); setProperty("spades", "\u2660"); setProperty("frasl", "\u2044"); setProperty("copy", "\u00a9"); setProperty("Upsilon", "\u03a5"); setProperty("rsquo", "\u2019"); setProperty("sdot", "\u22c5"); setProperty("beta", "\u03b2"); setProperty("egrave", "\u00e8"); setProperty("Pi", "\u03a0"); setProperty("micro", "\u00b5"); setProperty("lArr", "\u21d0"); setProperty("Beta", "\u0392"); setProperty("eacute", "\u00e9"); setProperty("agrave", "\u00e0"); setProperty("sbquo", "\u201a"); setProperty("ucirc", "\u00fb"); setProperty("mdash", "\u2014"); setProperty("rho", "\u03c1"); setProperty("Nu", "\u039d"); setProperty("ne", "\u2260"); setProperty("nsub", "\u2284"); setProperty("AElig", "\u00c6"); setProperty("raquo", "\u00bb"); setProperty("aacute", "\u00e1"); setProperty("le", "\u2264"); setProperty("harr", "\u2194"); setProperty("frac34", "\u00be"); setProperty("bdquo", "\u201e"); setProperty("cup", "\u222a"); setProperty("frac14", "\u00bc"); setProperty("exist", "\u2203"); setProperty("Ccedil", "\u00c7"); setProperty("phi", "\u03c6"); setProperty("Lambda", "\u039b"); setProperty("alpha", "\u03b1"); setProperty("sigma", "\u03c3"); setProperty("thetasym", "\u03d1"); setProperty("Rho", "\u03a1"); setProperty("hArr", "\u21d4"); setProperty("Dagger", "\u2021"); setProperty("otilde", "\u00f5"); setProperty("Epsilon", "\u0395"); setProperty("iuml", "\u00ef"); setProperty("Phi", "\u03a6"); setProperty("prod", "\u220f"); setProperty("Aring", "\u00c5"); setProperty("rlm", "\u200f"); setProperty("yen", "\u00a5"); setProperty("emsp", "\u2003"); setProperty("rang", "\u232a"); setProperty("Atilde", "\u00c3"); setProperty("Iuml", "\u00cf"); setProperty("iota", "\u03b9"); setProperty("deg", "\u00b0"); setProperty("prop", "\u221d"); setProperty("and", "\u2227"); setProperty("para", "\u00b6"); setProperty("darr", "\u2193"); setProperty("curren", "\u00a4"); setProperty("crarr", "\u21b5"); setProperty("not", "\u00ac"); setProperty("Iota", "\u0399"); setProperty("aelig", "\u00e6"); setProperty("rdquo", "\u201d"); setProperty("Ocirc", "\u00d4"); setProperty("ntilde", "\u00f1"); setProperty("reg", "\u00ae"); setProperty("zeta", "\u03b6"); setProperty("middot", "\u00b7"); setProperty("cent", "\u00a2"); setProperty("quot", "\""); setProperty("hellip", "\u2026"); setProperty("Zeta", "\u0396"); setProperty("rceil", "\u2309"); setProperty("eta", "\u03b7"); setProperty("nbsp", "\u00a0"); setProperty("rarr", "\u2192"); setProperty("frac12", "\u00bd"); setProperty("real", "\u211c"); setProperty("mu", "\u03bc"); setProperty("dArr", "\u21d3"); setProperty("divide", "\u00f7"); setProperty("cap", "\u2229"); setProperty("chi", "\u03c7"); setProperty("times", "\u00d7"); setProperty("euml", "\u00eb"); setProperty("Gamma", "\u0393"); setProperty("loz", "\u25ca"); setProperty("acute", "\u00b4"); setProperty("Omega", "\u03a9"); setProperty("ndash", "\u2013"); setProperty("clubs", "\u2663"); setProperty("macr", "\u00af"); setProperty("Yacute", "\u00dd"); setProperty("Ugrave", "\u00d9"); setProperty("Euml", "\u00cb"); setProperty("Eta", "\u0397"); setProperty("sect", "\u00a7"); setProperty("asymp", "\u2248"); setProperty("ordm", "\u00ba"); setProperty("rArr", "\u21d2"); setProperty("radic", "\u221a"); setProperty("Uacute", "\u00da"); setProperty("omicron", "\u03bf"); setProperty("Chi", "\u03a7"); setProperty("aring", "\u00e5"); setProperty("Theta", "\u0398"); setProperty("supe", "\u2287"); setProperty("ensp", "\u2002"); setProperty("uml", "\u00a8"); setProperty("ccedil", "\u00e7"); setProperty("lambda", "\u03bb"); setProperty("gt", "\u003e"); setProperty("uarr", "\u2191"); setProperty("alefsym", "\u2135"); setProperty("auml", "\u00e4"); setProperty("sup3", "\u00b3"); setProperty("circ", "\u02c6"); setProperty("lsquo", "\u2018"); setProperty("Auml", "\u00c4"); setProperty("dagger", "\u2020"); setProperty("Kappa", "\u039a"); setProperty("cong", "\u2245"); setProperty("zwnj", "\u200c"); setProperty("shy", "\u00ad"); setProperty("ouml", "\u00f6"); setProperty("diams", "\u2666"); setProperty("uArr", "\u21d1"); setProperty("atilde", "\u00e3"); setProperty("THORN", "\u00de"); setProperty("or", "\u2228"); setProperty("Ograve", "\u00d2"); setProperty("ocirc", "\u00f4"); setProperty("plusm", "\u00b1"); setProperty("Ouml", "\u00d6"); setProperty("nabla", "\u2207"); setProperty("psi", "\u03c8"); setProperty("sigmaf", "\u03c2"); setProperty("euro", "\u20ac"); setProperty("sube", "\u2286"); setProperty("sup2", "\u00b2"); setProperty("laquo", "\u00ab"); setProperty("forall", "\u2200"); setProperty("Oacute", "\u00d3"); setProperty("iexcl", "\u00a1"); fillMoreEntities(); } /** * Externalized initialization method to make CheckStyle happy. */ private void fillMoreEntities() { setProperty("piv", "\u03d6"); setProperty("minus", "\u2212"); setProperty("zwj", "\u200d"); setProperty("tau", "\u03c4"); setProperty("Mu", "\u039c"); setProperty("gamma", "\u03b3"); setProperty("sup", "\u2283"); setProperty("Psi", "\u03a8"); setProperty("omega", "\u03c9"); setProperty("Oslash", "\u00d8"); setProperty("weierp", "\u2118"); setProperty("Igrave", "\u00cc"); setProperty("OElig", "\u0152"); setProperty("sup1", "\u00b9"); setProperty("cedil", "\u00b8"); setProperty("upsilon", "\u03c5"); setProperty("equiv", "\u2261"); setProperty("isin", "\u2208"); setProperty("Delta", "\u0394"); setProperty("yacute", "\u00fd"); setProperty("ugrave", "\u00f9"); setProperty("ge", "\u2265"); setProperty("Iacute", "\u00cd"); setProperty("brvbar", "\u00a6"); setProperty("Tau", "\u03a4"); setProperty("Prime", "\u2033"); setProperty("rfloor", "\u22a7"); setProperty("Ecirc", "\u00ca"); setProperty("ETH", "\u00d0"); setProperty("int", "\u222b"); setProperty("xi", "\u03be"); setProperty("uacute", "\u00fa"); setProperty("bull", "\u2022"); setProperty("Scaron", "\u0160"); setProperty("theta", "\u03b8"); setProperty("yuml", "\u00ff"); setProperty("oplus", "\u2295"); setProperty("part", "\u2202"); setProperty("ldquo", "\u201c"); setProperty("Icirc", "\u00ce"); setProperty("Yuml", "\u0178"); setProperty("eth", "\u00f0"); setProperty("Acirc", "\u00c2"); setProperty("sub", "\u2282"); setProperty("lceil", "\u2308"); setProperty("Egrave", "\u00c8"); setProperty("tilde", "\u02dc"); setProperty("pi", "\u03c0"); setProperty("rsaquo", "\u203a"); setProperty("kappa", "\u03ba"); setProperty("upsih", "\u03d2"); setProperty("Omicron", "\u039f"); setProperty("otimes", "\u2297"); setProperty("ni", "\u220b"); setProperty("amp", "\u0026"); setProperty("Eacute", "\u00c9"); setProperty("nu", "\u03bd"); setProperty("Ucirc", "\u00db"); setProperty("uuml", "\u00fc"); setProperty("oslash", "\u00f8"); setProperty("thorn", "\u00fe"); setProperty("trade", "\u2122"); setProperty("epsilon", "\u03b5"); setProperty("ograve", "\u00f2"); setProperty("hearts", "\u2665"); setProperty("iquest", "\u00bf"); setProperty("Uuml", "\u00dc"); setProperty("empty", "\u2205"); setProperty("lowast", "\u2217"); setProperty("sum", "\u2211"); setProperty("lfloor", "\u22a6"); setProperty("lrm", "\u200e"); setProperty("oacute", "\u00f3"); setProperty("image", "\u2111"); setProperty("Agrave", "\u00c0"); setProperty("oline", "\u203e"); setProperty("oelig", "\u0153"); setProperty("Sigma", "\u03a3"); setProperty("permil", "\u2030"); setProperty("perp", "\u22a5"); setProperty("lt", "\u003c"); setProperty("Aacute", "\u00c1"); setProperty("acirc", "\u00e2"); setProperty("lang", "\u2329"); setProperty("delta", "\u03b4"); setProperty("infin", "\u221e"); setProperty("igrave", "\u00ec"); setProperty("ordf", "\u00aa"); setProperty("lsaquo", "\u2039"); setProperty("prime", "\u2032"); setProperty("ecirc", "\u00ea"); setProperty("there4", "\u2234"); setProperty("iacute", "\u00ed"); setProperty("sim", "\u223c"); setProperty("Alpha", "\u0391"); setProperty("pound", "\u00a3"); setProperty("notin", "\u2209"); setProperty("Ntilde", "\u00d1"); setProperty("Xi", "\u039e"); setProperty("thinsp", "\u2009"); setProperty("Otilde", "\u00d5"); setProperty("icirc", "\u00ee"); setProperty("scaron", "\u0161"); setProperty("szlig", "\u00df"); setProperty("larr", "\u2190"); }
} /**
* * LibXML : a free Java layouting library * * * Project Info: http://reporting.pentaho.org/libxml/ * * (C) Copyright 2006-2008, by Object Refinery Ltd, Pentaho Corporation and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * * ------------ * CharacterEntityParser.java * ------------ */
/**
* The character entity parser replaces all known occurrences of an entity in * the format &entityname;. * * @author Thomas Morgner */ class CharacterEntityParser
{
private String[] charMap;
/**
* the entities, keyed by entity name.
*/
private final HashMap entities;
/**
* Creates a new CharacterEntityParser and initializes the parser with the
* given set of entities.
*
* @param characterEntities the entities used for the parser
*/
public CharacterEntityParser(final Properties characterEntities)
{
if (characterEntities == null)
{
throw new NullPointerException("CharacterEntities must not be null");
}
entities = new HashMap(characterEntities);
charMap = new String[65536];
final Iterator entries = entities.entrySet().iterator();
while (entries.hasNext())
{
final Map.Entry entry = (Map.Entry) entries.next();
final String value = (String) entry.getValue();
final String entityName = (String) entry.getKey();
if (value.length() != 1)
{
throw new IllegalStateException();
}
charMap[value.charAt(0)] = entityName;
}
}
/**
* Creates a new CharacterEntityParser and initializes the parser with the
* given set of entities.
*
* @param characterEntities the entities used for the parser
*/
public CharacterEntityParser(final HashMap characterEntities)
{
if (characterEntities == null)
{
throw new NullPointerException("CharacterEntities must not be null");
}
entities = (HashMap) characterEntities.clone();
charMap = new String[65536];
final Iterator entries = entities.entrySet().iterator();
while (entries.hasNext())
{
final Map.Entry entry = (Map.Entry) entries.next();
final String value = (String) entry.getValue();
final String entityName = (String) entry.getKey();
if (value.length() != 1)
{
throw new IllegalStateException();
}
charMap[value.charAt(0)] = entityName;
}
}
/**
* create a new Character entity parser and initializes the parser with the
* entities defined in the XML standard.
*
* @return the CharacterEntityParser initialized with XML entities.
*/
public static CharacterEntityParser createXMLEntityParser()
{
final HashMap entities = new HashMap();
entities.put("amp", "&");
entities.put("quot", "\"");
entities.put("lt", "<");
entities.put("gt", ">");
entities.put("apos", "\u0027");
return new CharacterEntityParser(entities);
}
/**
* returns the entities used in the parser.
*
* @return the properties for this parser.
*/
private HashMap getEntities()
{
return entities;
}
/**
* Looks up the character for the entity name specified in key
.
*
* @param key the entity name
* @return the character as string with a length of 1
*/
private String lookupCharacter(final String key)
{
return (String) getEntities().get(key);
}
/**
* Encode the given String, so that all known entites are encoded. All
* characters represented by these entites are now removed from the string.
*
* @param value the original string
* @return the encoded string.
*/
public String encodeEntities(final String value)
{
if (value == null)
{
throw new NullPointerException();
}
final int length = value.length();
final StringBuffer writer = new StringBuffer(length);
for (int i = 0; i < length; i++)
{
final char character = value.charAt(i);
final String lookup = charMap[character];
if (lookup == null)
{
writer.append(character);
}
else
{
writer.append("&");
writer.append(lookup);
writer.append(";");
}
}
return writer.toString();
}
/**
* Decode the string, all known entities are replaced by their resolved
* characters.
*
* @param value the string that should be decoded.
* @return the decoded string.
*/
public String decodeEntities(final String value)
{
if (value == null)
{
throw new NullPointerException();
}
int parserIndex = 0;
int subStart = value.indexOf("&", parserIndex);
if (subStart == -1)
{
return value;
}
int subEnd = value.indexOf(";", subStart);
if (subEnd == -1)
{
return value;
}
final StringBuffer bufValue = new StringBuffer(value.substring(0, subStart));
do
{
// at this point we know, that there is at least one entity ..
if (value.charAt(subStart + 1) == "#")
{
final int subValue = parseInt(value.substring(subStart + 2, subEnd), 0);
if ((subValue >= 1) && (subValue <= 65536))
{
final char[] chr = new char[1];
chr[0] = (char) subValue;
bufValue.append(chr);
}
else
{
// invalid entity, do not decode ..
bufValue.append(value.substring(subStart, subEnd));
}
}
else
{
final String entity = value.substring(subStart + 1, subEnd);
final String replaceString = lookupCharacter(entity);
if (replaceString != null)
{
bufValue.append(decodeEntities(replaceString));
}
else
{
bufValue.append("&");
bufValue.append(entity);
bufValue.append(";");
}
}
parserIndex = subEnd + 1;
subStart = value.indexOf("&", parserIndex);
if (subStart == -1)
{
bufValue.append(value.substring(parserIndex));
subEnd = -1;
}
else
{
subEnd = value.indexOf(";", subStart);
if (subEnd == -1)
{
bufValue.append(value.substring(parserIndex));
}
else
{
bufValue.append(value.substring(parserIndex, subStart));
}
}
}
while (subStart != -1 && subEnd != -1);
return bufValue.toString();
}
/**
* Parses the given string into an int-value. On errors the default value
* is returned.
*
* @param s the string
* @param defaultVal the default value that should be used in case of errors
* @return the parsed int or the default value.
*/
private int parseInt(final String s, final int defaultVal)
{
if (s == null)
{
return defaultVal;
}
try
{
return Integer.parseInt(s);
}
catch (Exception e)
{
// ignored ..
}
return defaultVal;
}
}
</source>
break Lines with HTML
<source lang="java">
/**
* @author matthew_hicks */
public class Utils {
public static final String breakLinesHTML(String s, int width) { if (s == null) return null; StringBuffer buffer = new StringBuffer(); buffer.append("<html><body>"); int p = 0; char c; for (int i = 0; i < s.length(); i++) { c = s.charAt(i); if (((p >= width) && (c == " "))||(c == "\n")) { buffer.append("
"); p = 0; } else { buffer.append(c); } p++; } buffer.append("</body></html>"); return buffer.toString(); }
}
</source>
Convert an integer to an HTML RGB value
<source lang="java">
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/
/**
* Collection of string utilities. * */
public class StringUtil {
/** * Convert an integer to an HTML RGB value. The result is of the form * #hhhhhh. The input rgb integer value will be clipped into the range 0 ~ * 0xFFFFFF * * @param rgb * the integer RGB value * @return the value as an HTML RGB string */ public static String toRgbText( int rgb ) { // clip input value. if ( rgb > 0xFFFFFF ) rgb = 0xFFFFFF; if ( rgb < 0 ) rgb = 0; String str = "000000" + Integer.toHexString( rgb ); //$NON-NLS-1$ return "#" + str.substring( str.length( ) - 6 ); //$NON-NLS-1$ }
}
</source>
Convert HTML to text
<source lang="java">
/*
* 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. * * You can get a copy of the License at http://www.thinkingrock.ru.au/cddl.html * or http://www.thinkingrock.ru.au/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.thinkingrock.ru.au/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * The Original Software is ThinkingRock. The Initial Developer of the Original * Software is Avente Pty Ltd, Australia. * * Portions Copyright 2006-2007 Avente Pty Ltd. All Rights Reserved. */
import java.awt.Color; import java.io.Reader; import java.io.StringReader; import java.util.logging.Logger; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; /**
* Some static utility methods for HTML stuff. * * @author Jeremy Moore */
public final class HTML {
/** * Utility method to format a color to HTML RGB color format (e.g. #FF0000 for Color.red). * @param color The color. * @return the HTML RGB color string. */ public static final String format(Color c) { String r = (c.getRed() < 16) ? "0" + Integer.toHexString(c.getRed()) : Integer.toHexString(c.getRed()); String g = (c.getGreen() < 16) ? "0" + Integer.toHexString(c.getGreen()) : Integer.toHexString(c.getGreen()); String b = (c.getBlue() < 16) ? "0" + Integer.toHexString(c.getBlue()) : Integer.toHexString(c.getBlue()); return "#" + r + g + b; } /** * Utility method to convert HTML to text. * @param html The string containing HTML. * @return a String containing the derived text . */ public static final String html2text(String html) { EditorKit kit = new HTMLEditorKit(); Document doc = kit.createDefaultDocument(); doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); try { Reader reader = new StringReader(html); kit.read(reader, doc, 0); return doc.getText(0, doc.getLength()); } catch (Exception e) { return ""; } }
}
</source>
Convert to HTML string
<source lang="java">
import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; /*
* soapUI, copyright (C) 2004-2009 eviware.ru * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details at gnu.org. */
public class Utils {
public static String toHtml( String string ) { if( StringUtils.isNullOrEmpty( string ) ) return "<html><body></body></html>"; BufferedReader st = new BufferedReader( new StringReader( string ) ); StringBuffer buf = new StringBuffer( "<html><body>" ); try { String str = st.readLine(); while( str != null ) { if( str.equalsIgnoreCase( "
" ) ) { str = "
"; } buf.append( str ); if( !str.equalsIgnoreCase( "
" ) ) { buf.append( "
" ); } str = st.readLine(); } } catch( IOException e ) { e.printStackTrace(); } buf.append( "</body></html>" ); string = buf.toString(); return string; }
}
</source>
Decode an HTML color string like "#F567BA;" into a Color
<source lang="java">
/*
* Copyright 2005 Joe Walker * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
import java.awt.Color; /**
* Utilities for working with colors. * @author Joe Walker [joe at getahead dot ltd dot uk] */
public class ColorUtil {
/** * Decode an HTML color string like "#F567BA;" into a {@link Color} * @param colorString The string to decode * @return The decoded color * @throws IllegalArgumentException if the color sequence is not valid */ public static Color decodeHtmlColorString(String colorString) { Color color; if (colorString.startsWith("#")) { colorString = colorString.substring(1); } if (colorString.endsWith(";")) { colorString = colorString.substring(0, colorString.length() - 1); } int red, green, blue; switch (colorString.length()) { case 6: red = Integer.parseInt(colorString.substring(0, 2), 16); green = Integer.parseInt(colorString.substring(2, 4), 16); blue = Integer.parseInt(colorString.substring(4, 6), 16); color = new Color(red, green, blue); break; case 3: red = Integer.parseInt(colorString.substring(0, 1), 16); green = Integer.parseInt(colorString.substring(1, 2), 16); blue = Integer.parseInt(colorString.substring(2, 3), 16); color = new Color(red, green, blue); break; case 1: red = green = blue = Integer.parseInt(colorString.substring(0, 1), 16); color = new Color(red, green, blue); break; default: throw new IllegalArgumentException("Invalid color: " + colorString); } return color; }
}
</source>
Definitions of HTML character entities and conversions between unicode characters and HTML character entities
<source lang="java">
/*
* Enhydra Java Application Server Project * * The contents of this file are subject to the Enhydra Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License on * the Enhydra web site ( http://www.enhydra.org/ ). * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific terms governing rights and limitations * under the License. * * The Initial Developer of the Enhydra Application Server is Lutris * Technologies, Inc. The Enhydra Application Server and portions created * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc. * All Rights Reserved. * * Contributor(s): * * $Id: HTMLEntities.java,v 1.1.1.1 2003-03-10 16:36:17 taweili Exp $ */
// FIXME: convert this to an interface and then have implementing classes // for HTML3.2 and 4.0
/**
* Definitions of HTML character entities and conversions * between unicode characters and HTML character entities. */
public class HTMLEntities {
/** * Unicode character for entity quot (\u0022). */ public static final char quot = "\u0022"; /** * Unicode character for entity amp (\u0026). */ public static final char amp = "\u0026"; /** * Unicode character for entity lt (\u003c). */ public static final char lt = "\u003c"; /** * Unicode character for entity gt (\u003e). */ public static final char gt = "\u003e"; /** * Unicode character for entity nbsp (\u00a0). */ public static final char nbsp = "\u00a0"; /** * Unicode character for entity iexcl (\u00a1). */ public static final char iexcl = "\u00a1"; /** * Unicode character for entity cent (\u00a2). */ public static final char cent = "\u00a2"; /** * Unicode character for entity pound (\u00a3). */ public static final char pound = "\u00a3"; /** * Unicode character for entity curren (\u00a4). */ public static final char curren = "\u00a4"; /** * Unicode character for entity yen (\u00a5). */ public static final char yen = "\u00a5"; /** * Unicode character for entity brvbar (\u00a6). */ public static final char brvbar = "\u00a6"; /** * Unicode character for entity sect (\u00a7). */ public static final char sect = "\u00a7"; /** * Unicode character for entity uml (\u00a8). */ public static final char uml = "\u00a8"; /** * Unicode character for entity copy (\u00a9). */ public static final char copy = "\u00a9"; /** * Unicode character for entity ordf (\u00aa). */ public static final char ordf = "\u00aa"; /** * Unicode character for entity laquo (\u00ab). */ public static final char laquo = "\u00ab"; /** * Unicode character for entity not (\u00ac). */ public static final char not = "\u00ac"; /** * Unicode character for entity shy (\u00ad). */ public static final char shy = "\u00ad"; /** * Unicode character for entity reg (\u00ae). */ public static final char reg = "\u00ae"; /** * Unicode character for entity macr (\u00af). */ public static final char macr = "\u00af"; /** * Unicode character for entity deg (\u00b0). */ public static final char deg = "\u00b0"; /** * Unicode character for entity plusmn (\u00b1). */ public static final char plusmn = "\u00b1"; /** * Unicode character for entity sup2 (\u00b2). */ public static final char sup2 = "\u00b2"; /** * Unicode character for entity sup3 (\u00b3). */ public static final char sup3 = "\u00b3"; /** * Unicode character for entity acute (\u00b4). */ public static final char acute = "\u00b4"; /** * Unicode character for entity micro (\u00b5). */ public static final char micro = "\u00b5"; /** * Unicode character for entity para (\u00b6). */ public static final char para = "\u00b6"; /** * Unicode character for entity middot (\u00b7). */ public static final char middot = "\u00b7"; /** * Unicode character for entity cedil (\u00b8). */ public static final char cedil = "\u00b8"; /** * Unicode character for entity sup1 (\u00b9). */ public static final char sup1 = "\u00b9"; /** * Unicode character for entity ordm (\u00ba). */ public static final char ordm = "\u00ba"; /** * Unicode character for entity raquo (\u00bb). */ public static final char raquo = "\u00bb"; /** * Unicode character for entity frac14 (\u00bc). */ public static final char frac14 = "\u00bc"; /** * Unicode character for entity frac12 (\u00bd). */ public static final char frac12 = "\u00bd"; /** * Unicode character for entity frac34 (\u00be). */ public static final char frac34 = "\u00be"; /** * Unicode character for entity iquest (\u00bf). */ public static final char iquest = "\u00bf"; /** * Unicode character for entity Agrave (\u00c0). */ public static final char Agrave = "\u00c0"; /** * Unicode character for entity Aacute (\u00c1). */ public static final char Aacute = "\u00c1"; /** * Unicode character for entity Acirc (\u00c2). */ public static final char Acirc = "\u00c2"; /** * Unicode character for entity Atilde (\u00c3). */ public static final char Atilde = "\u00c3"; /** * Unicode character for entity Auml (\u00c4). */ public static final char Auml = "\u00c4"; /** * Unicode character for entity Aring (\u00c5). */ public static final char Aring = "\u00c5"; /** * Unicode character for entity AElig (\u00c6). */ public static final char AElig = "\u00c6"; /** * Unicode character for entity Ccedil (\u00c7). */ public static final char Ccedil = "\u00c7"; /** * Unicode character for entity Egrave (\u00c8). */ public static final char Egrave = "\u00c8"; /** * Unicode character for entity Eacute (\u00c9). */ public static final char Eacute = "\u00c9"; /** * Unicode character for entity Ecirc (\u00ca). */ public static final char Ecirc = "\u00ca"; /** * Unicode character for entity Euml (\u00cb). */ public static final char Euml = "\u00cb"; /** * Unicode character for entity Igrave (\u00cc). */ public static final char Igrave = "\u00cc"; /** * Unicode character for entity Iacute (\u00cd). */ public static final char Iacute = "\u00cd"; /** * Unicode character for entity Icirc (\u00ce). */ public static final char Icirc = "\u00ce"; /** * Unicode character for entity Iuml (\u00cf). */ public static final char Iuml = "\u00cf"; /** * Unicode character for entity ETH (\u00d0). */ public static final char ETH = "\u00d0"; /** * Unicode character for entity Ntilde (\u00d1). */ public static final char Ntilde = "\u00d1"; /** * Unicode character for entity Ograve (\u00d2). */ public static final char Ograve = "\u00d2"; /** * Unicode character for entity Oacute (\u00d3). */ public static final char Oacute = "\u00d3"; /** * Unicode character for entity Ocirc (\u00d4). */ public static final char Ocirc = "\u00d4"; /** * Unicode character for entity Otilde (\u00d5). */ public static final char Otilde = "\u00d5"; /** * Unicode character for entity Ouml (\u00d6). */ public static final char Ouml = "\u00d6"; /** * Unicode character for entity times (\u00d7). */ public static final char times = "\u00d7"; /** * Unicode character for entity Oslash (\u00d8). */ public static final char Oslash = "\u00d8"; /** * Unicode character for entity Ugrave (\u00d9). */ public static final char Ugrave = "\u00d9"; /** * Unicode character for entity Uacute (\u00da). */ public static final char Uacute = "\u00da"; /** * Unicode character for entity Ucirc (\u00db). */ public static final char Ucirc = "\u00db"; /** * Unicode character for entity Uuml (\u00dc). */ public static final char Uuml = "\u00dc"; /** * Unicode character for entity Yacute (\u00dd). */ public static final char Yacute = "\u00dd"; /** * Unicode character for entity THORN (\u00de). */ public static final char THORN = "\u00de"; /** * Unicode character for entity szlig (\u00df). */ public static final char szlig = "\u00df"; /** * Unicode character for entity agrave (\u00e0). */ public static final char agrave = "\u00e0"; /** * Unicode character for entity aacute (\u00e1). */ public static final char aacute = "\u00e1"; /** * Unicode character for entity acirc (\u00e2). */ public static final char acirc = "\u00e2"; /** * Unicode character for entity atilde (\u00e3). */ public static final char atilde = "\u00e3"; /** * Unicode character for entity auml (\u00e4). */ public static final char auml = "\u00e4"; /** * Unicode character for entity aring (\u00e5). */ public static final char aring = "\u00e5"; /** * Unicode character for entity aelig (\u00e6). */ public static final char aelig = "\u00e6"; /** * Unicode character for entity ccedil (\u00e7). */ public static final char ccedil = "\u00e7"; /** * Unicode character for entity egrave (\u00e8). */ public static final char egrave = "\u00e8"; /** * Unicode character for entity eacute (\u00e9). */ public static final char eacute = "\u00e9"; /** * Unicode character for entity ecirc (\u00ea). */ public static final char ecirc = "\u00ea"; /** * Unicode character for entity euml (\u00eb). */ public static final char euml = "\u00eb"; /** * Unicode character for entity igrave (\u00ec). */ public static final char igrave = "\u00ec"; /** * Unicode character for entity iacute (\u00ed). */ public static final char iacute = "\u00ed"; /** * Unicode character for entity icirc (\u00ee). */ public static final char icirc = "\u00ee"; /** * Unicode character for entity iuml (\u00ef). */ public static final char iuml = "\u00ef"; /** * Unicode character for entity eth (\u00f0). */ public static final char eth = "\u00f0"; /** * Unicode character for entity ntilde (\u00f1). */ public static final char ntilde = "\u00f1"; /** * Unicode character for entity ograve (\u00f2). */ public static final char ograve = "\u00f2"; /** * Unicode character for entity oacute (\u00f3). */ public static final char oacute = "\u00f3"; /** * Unicode character for entity ocirc (\u00f4). */ public static final char ocirc = "\u00f4"; /** * Unicode character for entity otilde (\u00f5). */ public static final char otilde = "\u00f5"; /** * Unicode character for entity ouml (\u00f6). */ public static final char ouml = "\u00f6"; /** * Unicode character for entity divide (\u00f7). */ public static final char divide = "\u00f7"; /** * Unicode character for entity oslash (\u00f8). */ public static final char oslash = "\u00f8"; /** * Unicode character for entity ugrave (\u00f9). */ public static final char ugrave = "\u00f9"; /** * Unicode character for entity uacute (\u00fa). */ public static final char uacute = "\u00fa"; /** * Unicode character for entity ucirc (\u00fb). */ public static final char ucirc = "\u00fb"; /** * Unicode character for entity uuml (\u00fc). */ public static final char uuml = "\u00fc"; /** * Unicode character for entity yacute (\u00fd). */ public static final char yacute = "\u00fd"; /** * Unicode character for entity thorn (\u00fe). */ public static final char thorn = "\u00fe"; /** * Unicode character for entity yuml (\u00ff). */ public static final char yuml = "\u00ff"; /** * Unicode character for entity fnof (\u0192). */ public static final char fnof = "\u0192"; /** * Unicode character for entity Alpha (\u0391). */ public static final char Alpha = "\u0391"; /** * Unicode character for entity Beta (\u0392). */ public static final char Beta = "\u0392"; /** * Unicode character for entity Gamma (\u0393). */ public static final char Gamma = "\u0393"; /** * Unicode character for entity Delta (\u0394). */ public static final char Delta = "\u0394"; /** * Unicode character for entity Epsilon (\u0395). */ public static final char Epsilon = "\u0395"; /** * Unicode character for entity Zeta (\u0396). */ public static final char Zeta = "\u0396"; /** * Unicode character for entity Eta (\u0397). */ public static final char Eta = "\u0397"; /** * Unicode character for entity Theta (\u0398). */ public static final char Theta = "\u0398"; /** * Unicode character for entity Iota (\u0399). */ public static final char Iota = "\u0399"; /** * Unicode character for entity Kappa (\u039a). */ public static final char Kappa = "\u039a"; /** * Unicode character for entity Lambda (\u039b). */ public static final char Lambda = "\u039b"; /** * Unicode character for entity Mu (\u039c). */ public static final char Mu = "\u039c"; /** * Unicode character for entity Nu (\u039d). */ public static final char Nu = "\u039d"; /** * Unicode character for entity Xi (\u039e). */ public static final char Xi = "\u039e"; /** * Unicode character for entity Omicron (\u039f). */ public static final char Omicron = "\u039f"; /** * Unicode character for entity Pi (\u03a0). */ public static final char Pi = "\u03a0"; /** * Unicode character for entity Rho (\u03a1). */ public static final char Rho = "\u03a1"; /** * Unicode character for entity Sigma (\u03a3). */ public static final char Sigma = "\u03a3"; /** * Unicode character for entity Tau (\u03a4). */ public static final char Tau = "\u03a4"; /** * Unicode character for entity Upsilon (\u03a5). */ public static final char Upsilon = "\u03a5"; /** * Unicode character for entity Phi (\u03a6). */ public static final char Phi = "\u03a6"; /** * Unicode character for entity Chi (\u03a7). */ public static final char Chi = "\u03a7"; /** * Unicode character for entity Psi (\u03a8). */ public static final char Psi = "\u03a8"; /** * Unicode character for entity Omega (\u03a9). */ public static final char Omega = "\u03a9"; /** * Unicode character for entity alpha (\u03b1). */ public static final char alpha = "\u03b1"; /** * Unicode character for entity beta (\u03b2). */ public static final char beta = "\u03b2"; /** * Unicode character for entity gamma (\u03b3). */ public static final char gamma = "\u03b3"; /** * Unicode character for entity delta (\u03b4). */ public static final char delta = "\u03b4"; /** * Unicode character for entity epsilon (\u03b5). */ public static final char epsilon = "\u03b5"; /** * Unicode character for entity zeta (\u03b6). */ public static final char zeta = "\u03b6"; /** * Unicode character for entity eta (\u03b7). */ public static final char eta = "\u03b7"; /** * Unicode character for entity theta (\u03b8). */ public static final char theta = "\u03b8"; /** * Unicode character for entity iota (\u03b9). */ public static final char iota = "\u03b9"; /** * Unicode character for entity kappa (\u03ba). */ public static final char kappa = "\u03ba"; /** * Unicode character for entity lambda (\u03bb). */ public static final char lambda = "\u03bb"; /** * Unicode character for entity mu (\u03bc). */ public static final char mu = "\u03bc"; /** * Unicode character for entity nu (\u03bd). */ public static final char nu = "\u03bd"; /** * Unicode character for entity xi (\u03be). */ public static final char xi = "\u03be"; /** * Unicode character for entity omicron (\u03bf). */ public static final char omicron = "\u03bf"; /** * Unicode character for entity pi (\u03c0). */ public static final char pi = "\u03c0"; /** * Unicode character for entity rho (\u03c1). */ public static final char rho = "\u03c1"; /** * Unicode character for entity sigmaf (\u03c2). */ public static final char sigmaf = "\u03c2"; /** * Unicode character for entity sigma (\u03c3). */ public static final char sigma = "\u03c3"; /** * Unicode character for entity tau (\u03c4). */ public static final char tau = "\u03c4"; /** * Unicode character for entity upsilon (\u03c5). */ public static final char upsilon = "\u03c5"; /** * Unicode character for entity phi (\u03c6). */ public static final char phi = "\u03c6"; /** * Unicode character for entity chi (\u03c7). */ public static final char chi = "\u03c7"; /** * Unicode character for entity psi (\u03c8). */ public static final char psi = "\u03c8"; /** * Unicode character for entity omega (\u03c9). */ public static final char omega = "\u03c9"; /** * Unicode character for entity thetasym (\u03d1). */ public static final char thetasym = "\u03d1"; /** * Unicode character for entity upsih (\u03d2). */ public static final char upsih = "\u03d2"; /** * Unicode character for entity piv (\u03d6). */ public static final char piv = "\u03d6"; /** * Unicode character for entity bull (\u2022). */ public static final char bull = "\u2022"; /** * Unicode character for entity hellip (\u2026). */ public static final char hellip = "\u2026"; /** * Unicode character for entity prime (\u2032). */ public static final char prime = "\u2032"; /** * Unicode character for entity Prime (\u2033). */ public static final char Prime = "\u2033"; /** * Unicode character for entity oline (\u203e). */ public static final char oline = "\u203e"; /** * Unicode character for entity frasl (\u2044). */ public static final char frasl = "\u2044"; /** * Unicode character for entity weierp (\u2118). */ public static final char weierp = "\u2118"; /** * Unicode character for entity image (\u2111). */ public static final char image = "\u2111"; /** * Unicode character for entity real (\u211c). */ public static final char real = "\u211c"; /** * Unicode character for entity trade (\u2122). */ public static final char trade = "\u2122"; /** * Unicode character for entity alefsym (\u2135). */ public static final char alefsym = "\u2135"; /** * Unicode character for entity larr (\u2190). */ public static final char larr = "\u2190"; /** * Unicode character for entity uarr (\u2191). */ public static final char uarr = "\u2191"; /** * Unicode character for entity rarr (\u2192). */ public static final char rarr = "\u2192"; /** * Unicode character for entity darr (\u2193). */ public static final char darr = "\u2193"; /** * Unicode character for entity harr (\u2194). */ public static final char harr = "\u2194"; /** * Unicode character for entity crarr (\u21b5). */ public static final char crarr = "\u21b5"; /** * Unicode character for entity lArr (\u21d0). */ public static final char lArr = "\u21d0"; /** * Unicode character for entity uArr (\u21d1). */ public static final char uArr = "\u21d1"; /** * Unicode character for entity rArr (\u21d2). */ public static final char rArr = "\u21d2"; /** * Unicode character for entity dArr (\u21d3). */ public static final char dArr = "\u21d3"; /** * Unicode character for entity hArr (\u21d4). */ public static final char hArr = "\u21d4"; /** * Unicode character for entity forall (\u2200). */ public static final char forall = "\u2200"; /** * Unicode character for entity part (\u2202). */ public static final char part = "\u2202"; /** * Unicode character for entity exist (\u2203). */ public static final char exist = "\u2203"; /** * Unicode character for entity empty (\u2205). */ public static final char empty = "\u2205"; /** * Unicode character for entity nabla (\u2207). */ public static final char nabla = "\u2207"; /** * Unicode character for entity isin (\u2208). */ public static final char isin = "\u2208"; /** * Unicode character for entity notin (\u2209). */ public static final char notin = "\u2209"; /** * Unicode character for entity ni (\u220b). */ public static final char ni = "\u220b"; /** * Unicode character for entity prod (\u220f). */ public static final char prod = "\u220f"; /** * Unicode character for entity sum (\u2211). */ public static final char sum = "\u2211"; /** * Unicode character for entity minus (\u2212). */ public static final char minus = "\u2212"; /** * Unicode character for entity lowast (\u2217). */ public static final char lowast = "\u2217"; /** * Unicode character for entity radic (\u221a). */ public static final char radic = "\u221a"; /** * Unicode character for entity prop (\u221d). */ public static final char prop = "\u221d"; /** * Unicode character for entity infin (\u221e). */ public static final char infin = "\u221e"; /** * Unicode character for entity ang (\u2220). */ public static final char ang = "\u2220"; /** * Unicode character for entity and (\u2227). */ public static final char and = "\u2227"; /** * Unicode character for entity or (\u2228). */ public static final char or = "\u2228"; /** * Unicode character for entity cap (\u2229). */ public static final char cap = "\u2229"; /** * Unicode character for entity cup (\u222a). */ public static final char cup = "\u222a"; /** * Unicode character for entity int (\u222b). */ public static final char intChar = "\u222b"; /** * Unicode character for entity there4 (\u2234). */ public static final char there4 = "\u2234"; /** * Unicode character for entity sim (\u223c). */ public static final char sim = "\u223c"; /** * Unicode character for entity cong (\u2245). */ public static final char cong = "\u2245"; /** * Unicode character for entity asymp (\u2248). */ public static final char asymp = "\u2248"; /** * Unicode character for entity ne (\u2260). */ public static final char ne = "\u2260"; /** * Unicode character for entity equiv (\u2261). */ public static final char equiv = "\u2261"; /** * Unicode character for entity le (\u2264). */ public static final char le = "\u2264"; /** * Unicode character for entity ge (\u2265). */ public static final char ge = "\u2265"; /** * Unicode character for entity sub (\u2282). */ public static final char sub = "\u2282"; /** * Unicode character for entity sup (\u2283). */ public static final char sup = "\u2283"; /** * Unicode character for entity nsub (\u2284). */ public static final char nsub = "\u2284"; /** * Unicode character for entity sube (\u2286). */ public static final char sube = "\u2286"; /** * Unicode character for entity supe (\u2287). */ public static final char supe = "\u2287"; /** * Unicode character for entity oplus (\u2295). */ public static final char oplus = "\u2295"; /** * Unicode character for entity otimes (\u2297). */ public static final char otimes = "\u2297"; /** * Unicode character for entity perp (\u22a5). */ public static final char perp = "\u22a5"; /** * Unicode character for entity sdot (\u22c5). */ public static final char sdot = "\u22c5"; /** * Unicode character for entity lceil (\u2308). */ public static final char lceil = "\u2308"; /** * Unicode character for entity rceil (\u2309). */ public static final char rceil = "\u2309"; /** * Unicode character for entity lfloor (\u230a). */ public static final char lfloor = "\u230a"; /** * Unicode character for entity rfloor (\u230b). */ public static final char rfloor = "\u230b"; /** * Unicode character for entity lang (\u2329). */ public static final char lang = "\u2329"; /** * Unicode character for entity rang (\u232a). */ public static final char rang = "\u232a"; /** * Unicode character for entity loz (\u25ca). */ public static final char loz = "\u25ca"; /** * Unicode character for entity spades (\u2660). */ public static final char spades = "\u2660"; /** * Unicode character for entity clubs (\u2663). */ public static final char clubs = "\u2663"; /** * Unicode character for entity hearts (\u2665). */ public static final char hearts = "\u2665"; /** * Unicode character for entity diams (\u2666). */ public static final char diams = "\u2666"; /** * Unicode character for entity OElig (\u0152). */ public static final char OElig = "\u0152"; /** * Unicode character for entity oelig (\u0153). */ public static final char oelig = "\u0153"; /** * Unicode character for entity Scaron (\u0160). */ public static final char Scaron = "\u0160"; /** * Unicode character for entity scaron (\u0161). */ public static final char scaron = "\u0161"; /** * Unicode character for entity Yuml (\u0178). */ public static final char Yuml = "\u0178"; /** * Unicode character for entity circ (\u02c6). */ public static final char circ = "\u02c6"; /** * Unicode character for entity tilde (\u02dc). */ public static final char tilde = "\u02dc"; /** * Unicode character for entity ensp (\u2002). */ public static final char ensp = "\u2002"; /** * Unicode character for entity emsp (\u2003). */ public static final char emsp = "\u2003"; /** * Unicode character for entity thinsp (\u2009). */ public static final char thinsp = "\u2009"; /** * Unicode character for entity zwnj (\u200c). */ public static final char zwnj = "\u200c"; /** * Unicode character for entity zwj (\u200d). */ public static final char zwj = "\u200d"; /** * Unicode character for entity lrm (\u200e). */ public static final char lrm = "\u200e"; /** * Unicode character for entity rlm (\u200f). */ public static final char rlm = "\u200f"; /** * Unicode character for entity ndash (\u2013). */ public static final char ndash = "\u2013"; /** * Unicode character for entity mdash (\u2014). */ public static final char mdash = "\u2014"; /** * Unicode character for entity lsquo (\u2018). */ public static final char lsquo = "\u2018"; /** * Unicode character for entity rsquo (\u2019). */ public static final char rsquo = "\u2019"; /** * Unicode character for entity sbquo (\u201a). */ public static final char sbquo = "\u201a"; /** * Unicode character for entity ldquo (\u201c). */ public static final char ldquo = "\u201c"; /** * Unicode character for entity rdquo (\u201d). */ public static final char rdquo = "\u201d"; /** * Unicode character for entity bdquo (\u201e). */ public static final char bdquo = "\u201e"; /** * Unicode character for entity dagger (\u2020). */ public static final char dagger = "\u2020"; /** * Unicode character for entity Dagger (\u2021). */ public static final char Dagger = "\u2021"; /** * Unicode character for entity permil (\u2030). */ public static final char permil = "\u2030"; /** * Unicode character for entity lsaquo (\u2039). */ public static final char lsaquo = "\u2039"; /** * Unicode character for entity rsaquo (\u203a). */ public static final char rsaquo = "\u203a"; /** * Unicode character for entity euro (\u20ac). */ public static final char euro = "\u20ac"; /** * Prevent instanciation. */ private HTMLEntities() { } /** * Convert a text character to an entity name. This does * not include newer character entities that are not supported * by HTML 3.2 browsers. * * @return The entity name or null if there is no entity for the * character. */ public static final String charToEntity(char textChar) { switch (textChar) { // // Character entity references for markup-significant // case "\u0022": return "quot"; case "\u0026": return "amp"; case "\u003c": return "lt"; case "\u003e": return "gt"; case "\u00a0": return "nbsp"; // // Character entity references for ISO 8859-1 characters // case "\u00a1": return "iexcl"; case "\u00a2": return "cent"; case "\u00a3": return "pound"; case "\u00a4": return "curren"; case "\u00a5": return "yen"; case "\u00a6": return "brvbar"; case "\u00a7": return "sect"; case "\u00a8": return "uml"; case "\u00a9": return "copy"; case "\u00aa": return "ordf"; case "\u00ab": return "laquo"; case "\u00ac": return "not"; case "\u00ad": return "shy"; case "\u00ae": return "reg"; case "\u00af": return "macr"; case "\u00b0": return "deg"; case "\u00b1": return "plusmn"; case "\u00b2": return "sup2"; case "\u00b3": return "sup3"; case "\u00b4": return "acute"; case "\u00b5": return "micro"; case "\u00b6": return "para"; case "\u00b7": return "middot"; case "\u00b8": return "cedil"; case "\u00b9": return "sup1"; case "\u00ba": return "ordm"; case "\u00bb": return "raquo"; case "\u00bc": return "frac14"; case "\u00bd": return "frac12"; case "\u00be": return "frac34"; case "\u00bf": return "iquest"; case "\u00c0": return "Agrave"; case "\u00c1": return "Aacute"; case "\u00c2": return "Acirc"; case "\u00c3": return "Atilde"; case "\u00c4": return "Auml"; case "\u00c5": return "Aring"; case "\u00c6": return "AElig"; case "\u00c7": return "Ccedil"; case "\u00c8": return "Egrave"; case "\u00c9": return "Eacute"; case "\u00ca": return "Ecirc"; case "\u00cb": return "Euml"; case "\u00cc": return "Igrave"; case "\u00cd": return "Iacute"; case "\u00ce": return "Icirc"; case "\u00cf": return "Iuml"; case "\u00d0": return "ETH"; case "\u00d1": return "Ntilde"; case "\u00d2": return "Ograve"; case "\u00d3": return "Oacute"; case "\u00d4": return "Ocirc"; case "\u00d5": return "Otilde"; case "\u00d6": return "Ouml"; case "\u00d7": return "times"; case "\u00d8": return "Oslash"; case "\u00d9": return "Ugrave"; case "\u00da": return "Uacute"; case "\u00db": return "Ucirc"; case "\u00dc": return "Uuml"; case "\u00dd": return "Yacute"; case "\u00de": return "THORN"; case "\u00df": return "szlig"; case "\u00e0": return "agrave"; case "\u00e1": return "aacute"; case "\u00e2": return "acirc"; case "\u00e3": return "atilde"; case "\u00e4": return "auml"; case "\u00e5": return "aring"; case "\u00e6": return "aelig"; case "\u00e7": return "ccedil"; case "\u00e8": return "egrave"; case "\u00e9": return "eacute"; case "\u00ea": return "ecirc"; case "\u00eb": return "euml"; case "\u00ec": return "igrave"; case "\u00ed": return "iacute"; case "\u00ee": return "icirc"; case "\u00ef": return "iuml"; case "\u00f0": return "eth"; case "\u00f1": return "ntilde"; case "\u00f2": return "ograve"; case "\u00f3": return "oacute"; case "\u00f4": return "ocirc"; case "\u00f5": return "otilde"; case "\u00f6": return "ouml"; case "\u00f7": return "divide"; case "\u00f8": return "oslash"; case "\u00f9": return "ugrave"; case "\u00fa": return "uacute"; case "\u00fb": return "ucirc"; case "\u00fc": return "uuml"; case "\u00fd": return "yacute"; case "\u00fe": return "thorn"; case "\u00ff": return "yuml"; default: return null; } } /** * Convert a text character to a HTML 4.0 entity name. * THis includes newer character entities that are not supported * by HTML 3.2 browsers. * * @return The entity name or null if there is no entity for the * character. */ public static String charToEntity4(char textChar) { String charStr = charToEntity(textChar); if (charStr != null) { return charStr; } switch (textChar) { // // Character entity references for symbols, mathematical symbols, and Greek letters // // Latin Extended case "\u0192": return "fnof"; // // Greek case "\u0391": return "Alpha"; case "\u0392": return "Beta"; case "\u0393": return "Gamma"; case "\u0394": return "Delta"; case "\u0395": return "Epsilon"; case "\u0396": return "Zeta"; case "\u0397": return "Eta"; case "\u0398": return "Theta"; case "\u0399": return "Iota"; case "\u039a": return "Kappa"; case "\u039b": return "Lambda"; case "\u039c": return "Mu"; case "\u039d": return "Nu"; case "\u039e": return "Xi"; case "\u039f": return "Omicron"; case "\u03a0": return "Pi"; case "\u03a1": return "Rho"; case "\u03a3": return "Sigma"; case "\u03a4": return "Tau"; case "\u03a5": return "Upsilon"; case "\u03a6": return "Phi"; case "\u03a7": return "Chi"; case "\u03a8": return "Psi"; case "\u03a9": return "Omega"; case "\u03b1": return "alpha"; case "\u03b2": return "beta"; case "\u03b3": return "gamma"; case "\u03b4": return "delta"; case "\u03b5": return "epsilon"; case "\u03b6": return "zeta"; case "\u03b7": return "eta"; case "\u03b8": return "theta"; case "\u03b9": return "iota"; case "\u03ba": return "kappa"; case "\u03bb": return "lambda"; case "\u03bc": return "mu"; case "\u03bd": return "nu"; case "\u03be": return "xi"; case "\u03bf": return "omicron"; case "\u03c0": return "pi"; case "\u03c1": return "rho"; case "\u03c2": return "sigmaf"; case "\u03c3": return "sigma"; case "\u03c4": return "tau"; case "\u03c5": return "upsilon"; case "\u03c6": return "phi"; case "\u03c7": return "chi"; case "\u03c8": return "psi"; case "\u03c9": return "omega"; case "\u03d1": return "thetasym"; case "\u03d2": return "upsih"; case "\u03d6": return "piv"; // // General Punctuation case "\u2022": return "bull"; case "\u2026": return "hellip"; case "\u2032": return "prime"; case "\u2033": return "Prime"; case "\u203e": return "oline"; case "\u2044": return "frasl"; // // Letterlike Symbols case "\u2118": return "weierp"; case "\u2111": return "image"; case "\u211c": return "real"; case "\u2122": return "trade"; case "\u2135": return "alefsym"; // // Arrows case "\u2190": return "larr"; case "\u2191": return "uarr"; case "\u2192": return "rarr"; case "\u2193": return "darr"; case "\u2194": return "harr"; case "\u21b5": return "crarr"; case "\u21d0": return "lArr"; case "\u21d1": return "uArr"; case "\u21d2": return "rArr"; case "\u21d3": return "dArr"; case "\u21d4": return "hArr"; // // Mathematical Operators case "\u2200": return "forall"; case "\u2202": return "part"; case "\u2203": return "exist"; case "\u2205": return "empty"; case "\u2207": return "nabla"; case "\u2208": return "isin"; case "\u2209": return "notin"; case "\u220b": return "ni"; case "\u220f": return "prod"; case "\u2211": return "sum"; case "\u2212": return "minus"; case "\u2217": return "lowast"; case "\u221a": return "radic"; case "\u221d": return "prop"; case "\u221e": return "infin"; case "\u2220": return "ang"; case "\u2227": return "and"; case "\u2228": return "or"; case "\u2229": return "cap"; case "\u222a": return "cup"; case "\u222b": return "int"; case "\u2234": return "there4"; case "\u223c": return "sim"; case "\u2245": return "cong"; case "\u2248": return "asymp"; case "\u2260": return "ne"; case "\u2261": return "equiv"; case "\u2264": return "le"; case "\u2265": return "ge"; case "\u2282": return "sub"; case "\u2283": return "sup"; case "\u2284": return "nsub"; case "\u2286": return "sube"; case "\u2287": return "supe"; case "\u2295": return "oplus"; case "\u2297": return "otimes"; case "\u22a5": return "perp"; case "\u22c5": return "sdot"; // // Miscellaneous Technical case "\u2308": return "lceil"; case "\u2309": return "rceil"; case "\u230a": return "lfloor"; case "\u230b": return "rfloor"; case "\u2329": return "lang"; case "\u232a": return "rang"; // // Geometric Shapes case "\u25ca": return "loz"; // // Miscellaneous Symbols case "\u2660": return "spades"; case "\u2663": return "clubs"; case "\u2665": return "hearts"; case "\u2666": return "diams"; // // Character entity references for internationalization characters // // Latin Extended-A case "\u0152": return "OElig"; case "\u0153": return "oelig"; case "\u0160": return "Scaron"; case "\u0161": return "scaron"; case "\u0178": return "Yuml"; // // Spacing Modifier Letters case "\u02c6": return "circ"; case "\u02dc": return "tilde"; // // General Punctuation case "\u2002": return "ensp"; case "\u2003": return "emsp"; case "\u2009": return "thinsp"; case "\u200c": return "zwnj"; case "\u200d": return "zwj"; case "\u200e": return "lrm"; case "\u200f": return "rlm"; case "\u2013": return "ndash"; case "\u2014": return "mdash"; case "\u2018": return "lsquo"; case "\u2019": return "rsquo"; case "\u201a": return "sbquo"; case "\u201c": return "ldquo"; case "\u201d": return "rdquo"; case "\u201e": return "bdquo"; case "\u2020": return "dagger"; case "\u2021": return "Dagger"; case "\u2030": return "permil"; case "\u2039": return "lsaquo"; case "\u203a": return "rsaquo"; case "\u20ac": return "euro"; default: return null; } }
}
</source>
Encode special characters and do formatting for HTML output
<source lang="java">
/*
* Helma License Notice * * The contents of this file are subject to the Helma License * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://adele.helma.org/download/helma/license.txt * * http://adele.helma.org/download/helma/license.txt: * Copyright (c) 1999-2002 Helma Project. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Products derived from this software may not be called "Helma" or "Hop", nor may "Helma" or "Hop" appear in their name, without prior written permission of the Helma Project Group. For written permission, please contact helma@helma.org.
THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HELMA PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
import java.util.*; /**
* This is a utility class to encode special characters and do formatting * for HTML output. * @author Hannes Wallnoefer */
public final class HtmlEncoder {
// transformation table for characters 128 to 255. These actually fall into two // groups, put together for efficiency: "Windows" chacacters 128-159 such as // "smart quotes", which are encoded to valid Unicode entities, and // valid ISO-8859 caracters 160-255, which are encoded to the symbolic HTML // entity. Everything >= 256 is encoded to a numeric entity. // // for mor on HTML entities see http://www.pemberley.ru/janeinfo/latin1.html and // ftp://ftp.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT // static final String[] transform = { "€", // 128 "", // empty string means character is undefined in unicode "‚", "ƒ", "„", "…", "†", "‡", "ˆ", "‰", "Š", "‹", "Œ", "", "Ž", "", "", "‘", "’", "“", "”", "•", "–", "—", "˜", "™", "š", "›", "œ", "", "ž", "Ÿ", // 159 " ", // 160 "¡", "¢", "£", "¤", "¥", "¦", "§", "¨", "©", "ª", "«", "¬", "", "®", "¯", "°", "±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»", "¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï", "Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í", "î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷", "ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ" // 255 }; static final HashSet allTags = new HashSet(); static { allTags.add("a"); allTags.add("abbr"); allTags.add("acronym"); allTags.add("address"); allTags.add("applet"); allTags.add("area"); allTags.add("b"); allTags.add("base"); allTags.add("basefont"); allTags.add("bdo"); allTags.add("bgsound"); allTags.add("big"); allTags.add("blink"); allTags.add("blockquote"); allTags.add("bq"); allTags.add("body"); allTags.add("br"); allTags.add("button"); allTags.add("caption"); allTags.add("center"); allTags.add("cite"); allTags.add("code"); allTags.add("col"); allTags.add("colgroup"); allTags.add("del"); allTags.add("dfn"); allTags.add("dir"); allTags.add("div"); allTags.add("dl"); allTags.add("dt"); allTags.add("dd"); allTags.add("em"); allTags.add("embed"); allTags.add("fieldset"); allTags.add("font"); allTags.add("form"); allTags.add("frame"); allTags.add("frameset"); allTags.add("h1"); allTags.add("h2"); allTags.add("h3"); allTags.add("h4"); allTags.add("h5"); allTags.add("h6"); allTags.add("head"); allTags.add("html"); allTags.add("hr"); allTags.add("i"); allTags.add("iframe"); allTags.add("img"); allTags.add("input"); allTags.add("ins"); allTags.add("isindex"); allTags.add("kbd"); allTags.add("label"); allTags.add("legend"); allTags.add("li"); allTags.add("link"); allTags.add("listing"); allTags.add("map"); allTags.add("marquee"); allTags.add("menu"); allTags.add("meta"); allTags.add("nobr"); allTags.add("noframes"); allTags.add("noscript"); allTags.add("object"); allTags.add("ol"); allTags.add("option"); allTags.add("optgroup"); allTags.add("p"); allTags.add("param"); allTags.add("plaintext"); allTags.add("pre"); allTags.add("q"); allTags.add("s"); allTags.add("samp"); allTags.add("script"); allTags.add("select"); allTags.add("small"); allTags.add("span"); allTags.add("strike"); allTags.add("strong"); allTags.add("style"); allTags.add("sub"); allTags.add("sup"); allTags.add("table"); allTags.add("tbody"); allTags.add("td"); allTags.add("textarea"); allTags.add("tfoot"); allTags.add("th"); allTags.add("thead"); allTags.add("title"); allTags.add("tr"); allTags.add("tt"); allTags.add("u"); allTags.add("ul"); allTags.add("var"); allTags.add("wbr"); allTags.add("xmp"); } // HTML block tags need to suppress automatic newline to// where to insert the
// conversion around them to look good. However, they differ // in how many newlines around them should ignored. These sets // help to treat each tag right in newline conversion. static final HashSet internalTags = new HashSet(); static final HashSet blockTags = new HashSet(); static final HashSet semiBlockTags = new HashSet(); static { // actual block level elements semiBlockTags.add("address"); semiBlockTags.add("dir"); semiBlockTags.add("div"); semiBlockTags.add("table"); blockTags.add("blockquote"); blockTags.add("center"); blockTags.add("dl"); blockTags.add("fieldset"); blockTags.add("form"); blockTags.add("h1"); blockTags.add("h2"); blockTags.add("h3"); blockTags.add("h4"); blockTags.add("h5"); blockTags.add("h6"); blockTags.add("hr"); blockTags.add("isindex"); blockTags.add("ol"); blockTags.add("p"); blockTags.add("pre"); blockTags.add("ul"); internalTags.add("menu"); internalTags.add("noframes"); internalTags.add("noscript"); /// to be treated as block level elements semiBlockTags.add("th"); blockTags.add("br"); blockTags.add("dd"); blockTags.add("dt"); blockTags.add("frameset"); blockTags.add("li"); blockTags.add("td"); internalTags.add("tbody"); internalTags.add("tfoot"); internalTags.add("thead"); internalTags.add("tr"); } // set of tags that are always empty static final HashSet emptyTags = new HashSet(); static { emptyTags.add("area"); emptyTags.add("base"); emptyTags.add("basefont"); emptyTags.add("br"); emptyTags.add("col"); emptyTags.add("frame"); emptyTags.add("hr"); emptyTags.add("img"); emptyTags.add("input"); emptyTags.add("isindex"); emptyTags.add("link"); emptyTags.add("meta"); emptyTags.add("param"); } static final byte TAG_NAME = 0; static final byte TAG_SPACE = 1; static final byte TAG_ATT_NAME = 2; static final byte TAG_ATT_VAL = 3; static final byte TEXT = 0; static final byte SEMIBLOCK = 1; static final byte BLOCK = 2; static final byte INTERNAL = 3; static final String newLine = System.getProperty("line.separator"); /** * Do "smart" encodging on a string. This means that valid HTML entities and tags, * Helma macros and HTML comments are passed through unescaped, while * other occurrences of "<", ">" and "&" are encoded to HTML entities. */ public final static String encode(String str) { if (str == null) { return null; } int l = str.length(); if (l == 0) { return ""; } // try to make stringbuffer large enough from the start StringBuffer ret = new StringBuffer(Math.round(l * 1.4f)); encode(str, ret, false, null); return ret.toString(); } /** * Do "smart" encodging on a string. This means that valid HTML entities and tags, * Helma macros and HTML comments are passed through unescaped, while * other occurrences of "<", ">" and "&" are encoded to HTML entities. */ public final static void encode(String str, StringBuffer ret) { encode(str, ret, false, null); } /** * Do "smart" encodging on a string. This means that valid HTML entities and tags, * Helma macros and HTML comments are passed through unescaped, while * other occurrences of "<", ">" and "&" are encoded to HTML entities. * * @param str the string to encode * @param ret the string buffer to encode to * @param paragraphs if true use p tags for paragraphs, otherwise just use br"s * @param allowedTags a set containing the names of allowed tags as strings. All other * tags will be escaped */ public final static void encode(String str, StringBuffer ret, boolean paragraphs, Set allowedTags) { if (str == null) { return; } int l = str.length();
tag in case we want to create a paragraph later on
int paragraphStart = ret.length();
// what kind of element/text are we leaving and entering?
// this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL
// depending on this information, we decide whether and how to insert
// paragraphs and line breaks. "entering" a tag means we"re at the "<"
// and exiting means we"re at the ">", not that it"s a start or close tag.
byte entering = TEXT;
byte exiting = TEXT;
Stack openTags = new Stack();
// are we currently within a < and a > that consitute some kind of tag?
// we use tag balancing to know whether we are inside a tag (and should
// pass things through unchanged) or outside (and should encode stuff).
boolean insideTag = false;
// are we inside an HTML tag?
boolean insideHtmlTag = false;
boolean insideCloseTag = false;
byte htmlTagMode = TAG_NAME;
// if we are inside a /**
import java.util.StringTokenizer;
public class EntityDecoder {
}
import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
public class StringUtils {
tag, we encode everything to make
// documentation work easier
boolean insideCodeTag = false;
boolean insidePreTag = false;
// are we within a Helma <% macro %> tag? We treat macro tags and
// comments specially, since we can"t rely on tag balancing
// to know when we leave a macro tag or comment.
boolean insideMacroTag = false;
// are we inside an HTML comment?
boolean insideComment = false;
// the quotation mark we are in within an HTML or Macro tag, if any
char htmlQuoteChar = "\u0000";
char macroQuoteChar = "\u0000";
// number of newlines met since the last non-whitespace character
int linebreaks = 0;
// did we meet a backslash escape?
boolean escape = false;
boolean triggerBreak = false;
for (int i = 0; i < l; i++) {
char c = str.charAt(i);
// step one: check if this is the beginning of an HTML tag, comment or
// Helma macro.
if (c == "<") {
if (i < (l - 2)) {
if (!insideMacroTag && ("%" == str.charAt(i + 1))) {
// this is the beginning of a Helma macro tag
if (!insideCodeTag) {
insideMacroTag = insideTag = true;
macroQuoteChar = "\u0000";
}
} else if (("!" == str.charAt(i + 1)) && ("-" == str.charAt(i + 2))) {
// the beginning of an HTML comment?
if (!insideCodeTag) {
insideComment = insideTag = ((i < (l - 3)) &&
("-" == str.charAt(i + 3)));
}
} else if (!insideTag) {
// check if this is a HTML tag.
insideCloseTag = ("/" == str.charAt(i + 1));
int tagStart = insideCloseTag ? (i + 2) : (i + 1);
int j = tagStart;
while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
j++;
if ((j > tagStart) && (j < l)) {
String tagName = str.substring(tagStart, j).toLowerCase();
if ("code".equals(tagName) && insideCloseTag &&
insideCodeTag) {
insideCodeTag = false;
}
if (((allowedTags == null) || allowedTags.contains(tagName)) &&
allTags.contains(tagName) && !insideCodeTag) {
insideHtmlTag = insideTag = true;
htmlQuoteChar = "\u0000";
htmlTagMode = TAG_NAME;
exiting = entering;
entering = TEXT;
if (internalTags.contains(tagName)) {
entering = INTERNAL;
} else if (blockTags.contains(tagName)) {
entering = BLOCK;
} else if (semiBlockTags.contains(tagName)) {
entering = paragraphs ? BLOCK : SEMIBLOCK;
}
if (entering > 0) {
triggerBreak = !insidePreTag;
}
if (insideCloseTag) {
int t = openTags.search(tagName);
if (t == -1) {
i = j;
insideHtmlTag = insideTag = false;
continue;
} else if (t > 1) {
for (int k = 1; k < t; k++) {
Object tag = openTags.pop();
if (!emptyTags.contains(tag)) {
ret.append("</");
ret.append(tag);
ret.append(">");
}
}
}
openTags.pop();
} else {
openTags.push(tagName);
}
if ("code".equals(tagName) && !insideCloseTag) {
insideCodeTag = true;
}
if ("pre".equals(tagName)) {
insidePreTag = !insideCloseTag;
}
}
}
}
} // if (i < l-2)
}
if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) {
if (!insideTag) {
exiting = entering;
entering = TEXT;
if (exiting >= SEMIBLOCK) {
paragraphStart = ret.length();
}
}
if (entering != INTERNAL && exiting != INTERNAL) {
int swallowBreaks = 0;
if (paragraphs &&
(entering != BLOCK || exiting != BLOCK) &&
(exiting < BLOCK) &&
(linebreaks > 1) &&
paragraphStart < ret.length()) {
ret.insert(paragraphStart, "<p>");
ret.append("</p>");
swallowBreaks = 2;
}
// treat entering a SEMIBLOCK as entering a TEXT
int _entering = entering == SEMIBLOCK ? TEXT : entering;
for (int k = linebreaks-1; k>=0; k--) {
if (k >= swallowBreaks && k >= _entering && k >= exiting) {
ret.append("
because that method does not
* tell us if the string ended with a newline or not.
*
* @param str
* any string
* @return a new string with all newlines replaced by "\n<br
* />"
*/
public static String newlinesToXHTMLBreaks(String str) {
if (str == null || str.length() == 0)
return "";
StringBuffer buf = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
switch (c) {
case "\n":
buf.append("\n
");
}
ret.append(newLine);
}
if (exiting >= SEMIBLOCK || linebreaks > 1) {
paragraphStart = ret.length();
}
}
linebreaks = 0;
triggerBreak = false;
}
switch (c) {
case "<":
if (insideTag) {
ret.append("<");
} else {
ret.append("<");
}
break;
case "&":
// check if this is an HTML entity already,
// in which case we pass it though unchanged
if ((i < (l - 3)) && !insideCodeTag) {
// is this a numeric entity?
if (str.charAt(i + 1) == "#") {
int j = i + 2;
while ((j < l) && Character.isDigit(str.charAt(j)))
j++;
if ((j < l) && (str.charAt(j) == ";")) {
ret.append("&");
break;
}
} else {
int j = i + 1;
while ((j < l) && Character.isLetterOrDigit(str.charAt(j)))
j++;
if ((j < l) && (str.charAt(j) == ";")) {
ret.append("&");
break;
}
}
}
// we didn"t reach a break, so encode the ampersand as HTML entity
ret.append("&");
break;
case "\\":
ret.append(c);
if (insideTag && !insideComment) {
escape = !escape;
}
break;
case """:
case "\"":
ret.append(c);
if (!insideComment) {
// check if the quote is escaped
if (insideMacroTag) {
if (escape) {
escape = false;
} else if (macroQuoteChar == c) {
macroQuoteChar = "\u0000";
} else if (macroQuoteChar == "\u0000") {
macroQuoteChar = c;
}
} else if (insideHtmlTag) {
if (escape) {
escape = false;
} else if (htmlQuoteChar == c) {
htmlQuoteChar = "\u0000";
htmlTagMode = TAG_SPACE;
} else if (htmlQuoteChar == "\u0000") {
htmlQuoteChar = c;
}
}
}
break;
case "\n":
if (insideTag || insidePreTag) {
ret.append("\n");
} else {
linebreaks++;
}
break;
case "\r":
if (insideTag || insidePreTag) {
ret.append("\r");
}
break;
case ">":
// For Helma macro tags and comments, we overrule tag balancing,
// i.e. we don"t require that "<" and ">" be balanced within
// macros and comments. Rather, we check for the matching closing tag.
if (insideComment) {
ret.append(">");
insideComment = !((str.charAt(i - 2) == "-") &&
(str.charAt(i - 1) == "-"));
} else if (insideMacroTag) {
ret.append(">");
insideMacroTag = !((str.charAt(i - 1) == "%") &&
(macroQuoteChar == "\u0000"));
} else if (insideHtmlTag) {
ret.append(">");
// only leave HTML tag if quotation marks are balanced
// within that tag.
insideHtmlTag = htmlQuoteChar != "\u0000";
// Check if this is an empty tag so we don"t generate an
// additional </close> tag.
if (str.charAt(i - 1) == "/") {
// this is to avoid misinterpreting tags like
// <a href=http://foo/> as empty
if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) {
openTags.pop();
}
}
exiting = entering;
if (exiting > 0) {
triggerBreak = !insidePreTag;
}
} else {
ret.append(">");
}
// check if we still are inside any kind of tag
insideTag = insideComment || insideMacroTag || insideHtmlTag;
insideCloseTag = insideTag;
break;
default:
if (insideHtmlTag && !insideCloseTag) {
switch(htmlTagMode) {
case TAG_NAME:
if (!Character.isLetterOrDigit(c)) {
htmlTagMode = TAG_SPACE;
}
break;
case TAG_SPACE:
if (Character.isLetterOrDigit(c)) {
htmlTagMode = TAG_ATT_NAME;
}
break;
case TAG_ATT_NAME:
if (c == "=") {
htmlTagMode = TAG_ATT_VAL;
} else if (c == " ") {
htmlTagMode = TAG_SPACE;
}
break;
case TAG_ATT_VAL:
if (Character.isWhitespace(c) && htmlQuoteChar == "\u0000") {
htmlTagMode = TAG_SPACE;
}
break;
}
}
if (c < 128) {
ret.append(c);
} else if ((c >= 128) && (c < 256)) {
ret.append(transform[c - 128]);
} else {
ret.append("&#");
ret.append((int) c);
ret.append(";");
}
escape = false;
}
}
// if tags were opened but not closed, close them.
int o = openTags.size();
if (o > 0) {
for (int k = 0; k < o; k++) {
Object tag = openTags.pop();
if (!emptyTags.contains(tag)) {
ret.append("</");
ret.append(tag);
ret.append(">");
}
}
}
// add remaining newlines we may have collected
int swallowBreaks = 0;
if (paragraphs && entering < BLOCK) {
ret.insert(paragraphStart, "<p>");
ret.append("</p>");
swallowBreaks = 2;
}
if (linebreaks > 0) {
for (int i = linebreaks-1; i>=0; i--) {
if (i >= swallowBreaks && i > exiting) {
ret.append("
");
}
ret.append(newLine);
}
}
}
/**
*
*/
public final static String encodeFormValue(String str) {
if (str == null) {
return null;
}
int l = str.length();
if (l == 0) {
return "";
}
StringBuffer ret = new StringBuffer(Math.round(l * 1.2f));
encodeAll(str, ret, false);
return ret.toString();
}
/**
*
*/
public final static void encodeFormValue(String str, StringBuffer ret) {
encodeAll(str, ret, false);
}
/**
*
*/
public final static String encodeAll(String str) {
if (str == null) {
return null;
}
int l = str.length();
if (l == 0) {
return "";
}
StringBuffer ret = new StringBuffer(Math.round(l * 1.2f));
encodeAll(str, ret, true);
return ret.toString();
}
/**
*
*/
public final static void encodeAll(String str, StringBuffer ret) {
encodeAll(str, ret, true);
}
/**
*
*/
public final static void encodeAll(String str, StringBuffer ret, boolean encodeNewline) {
if (str == null) {
return;
}
int l = str.length();
for (int i = 0; i < l; i++) {
char c = str.charAt(i);
switch (c) {
case "<":
ret.append("<");
break;
case ">":
ret.append(">");
break;
case "&":
ret.append("&");
break;
case """:
ret.append(""");
break;
case "\n":
if (encodeNewline) {
ret.append("
");
}
ret.append("\n");
break;
default:
// ret.append (c);
if (c < 128) {
ret.append(c);
} else if ((c >= 128) && (c < 256)) {
ret.append(transform[c - 128]);
} else {
ret.append("&#");
ret.append((int) c);
ret.append(";");
}
}
}
}
/**
*
*
* @param str ...
*
* @return ...
*/
public final static String encodeXml(String str) {
if (str == null) {
return null;
}
int l = str.length();
if (l == 0) {
return "";
}
StringBuffer ret = new StringBuffer(Math.round(l * 1.2f));
encodeXml(str, ret);
return ret.toString();
}
/**
*
*
* @param str ...
* @param ret ...
*/
public final static void encodeXml(String str, StringBuffer ret) {
if (str == null) {
return;
}
int l = str.length();
for (int i = 0; i < l; i++) {
char c = str.charAt(i);
switch (c) {
case "<":
ret.append("<");
break;
case ">":
ret.append(">");
break;
case "&":
ret.append("&");
break;
case """:
ret.append(""");
break;
case "\"":
ret.append("'");
break;
default:
if (c < 0x20) {
// sort out invalid XML characters below 0x20 - all but 0x9, 0xA and 0xD.
// The trick is an adaption of java.lang.Character.isSpace().
if (((((1L << 0x9) | (1L << 0xA) | (1L << 0xD)) >> c) & 1L) != 0) {
ret.append(c);
}
} else {
ret.append(c);
}
}
}
}
// test method
public static String printCharRange(int from, int to) {
StringBuffer response = new StringBuffer();
for (int i = from; i < to; i++) {
response.append(i);
response.append(" ");
response.append((char) i);
response.append(" ");
if (i < 128) {
response.append((char) i);
} else if ((i >= 128) && (i < 256)) {
response.append(transform[i - 128]);
} else {
response.append("&#");
response.append(i);
response.append(";");
}
response.append("\r\n");
}
return response.toString();
}
// for testing...
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.err.println(encode(args[i]));
}
}
// end of class
</source>
Entity Decoder
<source lang="java">
* Copyright (C) 2003 Manfred Andres
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
public final static String htmlEntities[] = { "€", "", "‚",
"ƒ", "„", "…", "†", "‡", "ˆ",
"‰", "Š", "‹", "Œ", "", "Ž", "",
"", "‘", "’", "“", "”", "•",
"–", "—", "˜", "™", "š", "›",
"œ", "", "ž", "Ÿ", " ", "¡", "¢",
"£", "¤", "¥", "¦", "§", "¨",
"©", "ª", "«", "¬", "", "®", "¯",
"°", "±", "²", "³", "´", "µ",
"¶", "·", "¸", "¹", "º", "»",
"¼", "½", "¾", "¿", "À",
"Á", "Â", "Ã", "Ä", "Å", "Æ",
"Ç", "È", "É", "Ê", "Ë",
"Ì", "Í", "Î", "Ï", "Ð", "Ñ",
"Ò", "Ó", "Ô", "Õ", "Ö", "×",
"Ø", "Ù", "Ú", "Û", "Ü",
"Ý", "Þ", "ß", "à", "á",
"â", "ã", "ä", "å", "æ", "ç",
"è", "é", "ê", "ë", "ì",
"í", "î", "ï", "ð", "ñ", "ò",
"ó", "ô", "õ", "ö", "÷",
"ø", "ù", "ú", "û", "ü",
"ý", "þ", "ÿ"};
public final static String entities[] = { "F6", "E4", "FC", "D6", "C4",
"DC", "DF", "3F", "5C", "2C", "3A", "3B", "23", "2B", "7E", "21",
"22", "A7", "24", "25", "26", "28", "29", "3D", "3C", "3E", "7B",
"5B", "5D", "7D", "2F", "E2", "EA", "EE", "F4", "FB", "C2", "CA",
"CE", "D4", "DB", "E1", "E9", "ED", "F3", "FA", "C1", "C9", "CD",
"D3", "DA", "E0", "E8", "EC", "F2", "F9", "C1", "C9", "CD", "D3",
"DA", "B0", "B3", "B2", "80", "7C", "5E", "60", "B4", "27", "20",
"40", "98", "2A"};
public final static String charsHtml[] = { "ö", "ä", "ü", "Ö", "Ä", "Ü",
"ß", "?", "\\", ",", ":", ";", "#", "+", "˜", "!", "\"",
"§", "$", "%", "&", "(", ")", "=", "<", ">", "{",
"[", "]", "}", "/", "â", "ê", "î", "ô",
"û", "Â", "Ê", "Î", "Ô", "Û",
"á", "é", "í", "ó", "ú",
"Á", "É", "Í", "Ó", "Ú",
"à", "è", "ì", "ò", "Ù",
"À", "È", "Ì", "Ò", "Ù",
"°", "³", "²", "€", "|", "ˆ", "`",
"´", """, " ", "@", "~", "*"};
public final static String chars[] = { "ö", "ä", "ü", "Ö", "Ä", "Ü", "ß",
"?", "\\", ",", ":", ";", "#", "+", "~", "!", "\"", "§", "$", "%",
"&", "(", ")", "=", "<", ">", "{", "[", "]", "}", "/", "â", "ê",
"î", "ô", "û", "�", "�", "�", "�", "�", "á", "é", "í", "ó", "ú",
"�", "�", "�", "�", "�", "à", "è", "ì", "ò", "ù", "�", "�", "�",
"�", "�", "�", "�", "�", "�", "|", "^", "`", "�", """, " ", "@",
"~", "*"};
public static String entityToChar (String raw) {
return (entityTo (raw, chars));
}
public static String entityToHtml (String raw) {
return (charToHtml(entityTo (raw, chars)));
}
public static String htmlToChar (String raw) {
return convert (raw, charsHtml, chars);
}
public static String charToHtml (String raw) {
if (raw == null)
return null;
char[] chars = raw.toCharArray();
StringBuffer encoded = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c == "<")
encoded.append("<");
else if (c == ">")
encoded.append(">");
else if (c < 128)
encoded.append(c);
else if (c < 256)
encoded.append(htmlEntities[c-128]);
else {
encoded.append("&#");
encoded.append((int) c);
encoded.append(";");
}
}
return encoded.toString();
}
public static String entityTo (String raw, String[] tc) {
StringBuffer sb = new StringBuffer ();
boolean entity = false;
raw = raw.replace ("+", " ");
String tokens = tc == charsHtml ? "%<>" : "%";
for (StringTokenizer st = new StringTokenizer (raw, tokens, true); st.hasMoreTokens (); ) {
String token = st.nextToken ();
if (entity) {
boolean replaced = false;
for (int i = 0; i < entities.length; i++) {
if (token.startsWith (entities[i])) {
sb.append (tc[i]);
sb.append (token.substring (2));
replaced = true;
break;
}
}
if (!replaced)
sb.append (token);
entity = false;
} else if (token.equals ("%")) {
entity = true;
continue;
} else if (token.equals ("<")) {
sb.append ("<");
} else if (token.equals (">")) {
sb.append (">");
} else {
sb.append (token);
}
}
return (sb.toString ());
}
public static String convert (String raw, String[] from, String[] to) {
String result = raw;
for (int i = 0 ; i < from.length; i++) {
int idx = result.indexOf(from[i]);
if (idx < 0)
continue;
StringBuffer sb = new StringBuffer();
while (idx > -1) {
sb.append (result.substring(0,idx));
sb.append (to[i]);
result = result.substring(idx + from[i].length());
idx = result.indexOf(from[i]);
}
sb.append (result);
result = sb.toString();
}
return result;
}
</source>
Escape and unescape string
<source lang="java">
* Globally available utility classes, mostly for string manipulation.
*
* @author Jim Menard,
*/
/**
* Returns a string with HTML special characters replaced by their entity
* equivalents.
*
* @param str
* the string to escape
* @return a new string without HTML special characters
*/
public static String escapeHTML(String str) {
if (str == null || str.length() == 0)
return "";
StringBuffer buf = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
switch (c) {
case "&":
buf.append("&");
break;
case "<":
buf.append("<");
break;
case ">":
buf.append(">");
break;
case """:
buf.append(""");
break;
case "\"":
buf.append("'");
break;
default:
buf.append(c);
break;
}
}
return buf.toString();
}
/**
* Returns a new string where all newlines ("\n", "\r", or
* "\r\n") have been replaced by "\n" plus XHTML break
* tags ("\n<br />").
* <p>
* We don"t call <code>splitIntoLines
");
break;
case "\r":
if (i + 1 < len && str.charAt(i + 1) == "\n") // Look for "\n"
++i;
buf.append("\n
");
break;
default:
buf.append(c);
break;
}
}
return buf.toString();
}
/**
* Returns a string with XML special characters replaced by their entity
* equivalents.
*
* @param str
* the string to escape
* @return a new string without XML special characters
*/
public static String escapeXML(String str) {
return escapeHTML(str);
}
/**
* Returns a string with XML entities replaced by their normal characters.
*
* @param str
* the string to un-escape
* @return a new normal string
*/
public static String unescapeXML(String str) {
if (str == null || str.length() == 0)
return "";
StringBuffer buf = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c == "&") {
int pos = str.indexOf(";", i);
if (pos == -1) { // Really evil
buf.append("&");
} else if (str.charAt(i + 1) == "#") {
int val = Integer.parseInt(str.substring(i + 2, pos), 16);
buf.append((char) val);
i = pos;
} else {
String substr = str.substring(i, pos + 1);
if (substr.equals("&"))
buf.append("&");
else if (substr.equals("<"))
buf.append("<");
else if (substr.equals(">"))
buf.append(">");
else if (substr.equals("""))
buf.append(""");
else if (substr.equals("'"))
buf.append("\"");
else
// ????
buf.append(substr);
i = pos;
}
} else {
buf.append(c);
}
}
return buf.toString();
}
/**
* Returns str with leading and trailing spaces trimmed or, if
* str is null
, returns null
.
*
* @return str trimmed or null
*/
public static String nullOrTrimmed(String str) {
return str == null ? str : str.trim();
}
}
</source>
Escape HTML
<source lang="java">
/*
* Static String formatting and query routines. * Copyright (C) 2001-2005 Stephen Ostermiller * http://ostermiller.org/contact.pl?regarding=Java+Utilities * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * See COPYING.TXT for details. */
import java.util.HashMap; import java.util.regex.Pattern; /**
* Utilities for String formatting, manipulation, and queries. * More information about this class is available from . * * @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities * @since ostermillerutils 1.00.00 */
public class StringHelper {
/** * Replaces characters that may be confused by a HTML * parser with their equivalent character entity references. * <p> * Any data that will appear as text on a web page should * be be escaped. This is especially important for data * that comes from untrusted sources such as Internet users. * A common mistake in CGI programming is to ask a user for* data and then put that data on a web page. For example:
* Server: What is your name? * User: <b>Joe<b> * Server: Hello <b>Joe</b>, Welcome
* If the name is put on the page without checking that it doesn"t * contain HTML code or without sanitizing that HTML code, the user * could reformat the page, insert scripts, and control the the * content on your web server. * <p> * This method will replace HTML characters such as > with their * HTML entity reference (>) so that the html parser will * be sure to interpret them as plain text rather than HTML or script. * <p> * This method should be used for both data to be displayed in text * in the html document, and data put in form elements. For example:
*<html><body>This in not a <tag> * in HTML</body></html>
* and
*<form><input type="hidden" name="date" value="This data could * be "malicious""></form>
* In the second example, the form data would be properly be resubmitted * to your cgi script in the URLEncoded format:
*This data could be %22malicious%22
* * @param s String to be escaped * @return escaped String * @throws NullPointerException if s is null. * * @since ostermillerutils 1.00.00 */ public static String escapeHTML(String s){ int length = s.length(); int newLength = length; boolean someCharacterEscaped = false; // first check for characters that might // be dangerous and calculate a length // of the string that has escapes. for (int i=0; i<length; i++){ char c = s.charAt(i); int cint = 0xffff & c; if (cint < 32){ switch(c){ case "\r": case "\n": case "\t": case "\f":{ } break; default: { newLength -= 1; someCharacterEscaped = true; } } } else { switch(c){ case "\"":{ newLength += 5; someCharacterEscaped = true; } break; case "&": case "\"":{ newLength += 4; someCharacterEscaped = true; } break; case "<": case ">":{ newLength += 3; someCharacterEscaped = true; } break; } } } if (!someCharacterEscaped){ // nothing to escape in the string return s; } StringBuffer sb = new StringBuffer(newLength); for (int i=0; i<length; i++){ char c = s.charAt(i); int cint = 0xffff & c; if (cint < 32){ switch(c){ case "\r": case "\n": case "\t": case "\f":{ sb.append(c); } break; default: { // Remove this character } } } else { switch(c){ case "\"":{ sb.append("""); } break; case "\"":{ sb.append("'"); } break; case "&":{ sb.append("&"); } break; case "<":{ sb.append("<"); } break; case ">":{ sb.append(">"); } break; default: { sb.append(c); } } } } return sb.toString(); }
}
</source>
Escapes newlines, tabs, backslashes, and quotes in the specified string
<source lang="java">
/*
* StandardUtilities.java - Various miscallaneous utility functions * :tabSize=8:indentSize=8:noTabs=false: * :folding=explicit:collapseFolds=1: * * Copyright (C) 1999, 2006 Matthieu Casanova, Slava Pestov * Portions copyright (C) 2000 Richard S. Hall * Portions copyright (C) 2001 Dirk Moebius * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
//{{{ Imports import javax.swing.text.Segment; import java.util.ruparator; import java.util.Stack; //}}} /**
* Several tools that depends on JDK only. * * @author Matthieu Casanova * @version $Id: StandardUtilities.java 12884 2008-06-23 18:17:08Z kpouer $ * @since 4.3pre5 */
public class StandardUtilities {
//{{{ Text methods //{{{ charsToEscapes() method /** * Escapes newlines, tabs, backslashes, and quotes in the specified * string. * @param str The string * @since jEdit 4.3pre15 */ public static String charsToEscapes(String str) { return charsToEscapes(str,"\n\t\\\"""); } //}}} //{{{ charsToEscapes() method /** * Escapes the specified characters in the specified string. * @param str The string * @param toEscape Any characters that require escaping * @since jEdit 4.3pre15 */ public static String charsToEscapes(String str, String toEscape) { StringBuilder buf = new StringBuilder(); for(int i = 0; i < str.length(); i++) { char c = str.charAt(i); if(toEscape.indexOf(c) != -1) { if(c == "\n") buf.append("\\n"); else if(c == "\t") buf.append("\\t"); else { buf.append("\\"); buf.append(c); } } else buf.append(c); } return buf.toString(); } //}}}
}
</source>
Filter the specified message string for characters that are sensitive in HTML
<source lang="java">
/*
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- /
/**
* HTML filter utility. * * @author Craig R. McClanahan * @author Tim Tye * @version $Revision: 467217 $ $Date: 2006-10-24 05:14:34 +0200 (Tue, 24 Oct 2006) $ */
public final class HTMLFilter {
/** * Filter the specified message string for characters that are sensitive * in HTML. This avoids potential attacks caused by including JavaScript * codes in the request URL that is often reported in error messages. * * @param message The message string to be filtered */ public static String filter(String message) { if (message == null) return (null); char content[] = new char[message.length()]; message.getChars(0, message.length(), content, 0); StringBuffer result = new StringBuffer(content.length + 50); for (int i = 0; i < content.length; i++) { switch (content[i]) { case "<": result.append("<"); break; case ">": result.append(">"); break; case "&": result.append("&"); break; case """: result.append("""); break; default: result.append(content[i]); } } return (result.toString()); }
}
</source>
Format a color to HTML RGB color format (e.g. #FF0000 for Color.red)
<source lang="java">
/*
* 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. * * You can get a copy of the License at http://www.thinkingrock.ru.au/cddl.html * or http://www.thinkingrock.ru.au/cddl.txt. * * When distributing Covered Code, include this CDDL Header Notice in each file * and include the License file at http://www.thinkingrock.ru.au/cddl.txt. * If applicable, add the following below the CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * The Original Software is ThinkingRock. The Initial Developer of the Original * Software is Avente Pty Ltd, Australia. * * Portions Copyright 2006-2007 Avente Pty Ltd. All Rights Reserved. */
import java.awt.Color; import java.io.Reader; import java.io.StringReader; import java.util.logging.Logger; import javax.swing.text.Document; import javax.swing.text.EditorKit; import javax.swing.text.html.HTMLEditorKit; /**
* Some static utility methods for HTML stuff. * * @author Jeremy Moore */
public final class HTML {
/** * Utility method to format a color to HTML RGB color format (e.g. #FF0000 for Color.red). * @param color The color. * @return the HTML RGB color string. */ public static final String format(Color c) { String r = (c.getRed() < 16) ? "0" + Integer.toHexString(c.getRed()) : Integer.toHexString(c.getRed()); String g = (c.getGreen() < 16) ? "0" + Integer.toHexString(c.getGreen()) : Integer.toHexString(c.getGreen()); String b = (c.getBlue() < 16) ? "0" + Integer.toHexString(c.getBlue()) : Integer.toHexString(c.getBlue()); return "#" + r + g + b; } /** * Utility method to convert HTML to text. * @param html The string containing HTML. * @return a String containing the derived text . */ public static final String html2text(String html) { EditorKit kit = new HTMLEditorKit(); Document doc = kit.createDefaultDocument(); doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); try { Reader reader = new StringReader(html); kit.read(reader, doc, 0); return doc.getText(0, doc.getLength()); } catch (Exception e) { return ""; } }
}
</source>
Get HTML Color String from Java Color object
<source lang="java">
import java.awt.Color; public class Utils {
public static String getHTMLColorString(Color color) { String red = Integer.toHexString(color.getRed()); String green = Integer.toHexString(color.getGreen()); String blue = Integer.toHexString(color.getBlue()); return "#" + (red.length() == 1? "0" + red : red) + (green.length() == 1? "0" + green : green) + (blue.length() == 1? "0" + blue : blue);
} }
</source>
HTML color and Java Color
<source lang="java">
/**
* Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.ru/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */
//Revised from ajax4jsf import java.awt.Color; import java.util.HashMap; import java.util.Map;
/**
* @author shura (latest modification by $Author: slava_kabanovich $) * @version $Revision: 1.2 $ $Date: 2006/07/12 14:59:33 $ * */
public class HtmlColor {
private static Map colorNames; static { // color names. colorNames = new HashMap(); colorNames.put("black", new Color(0x000000)); colorNames.put("green", new Color(0x008000)); colorNames.put("silver", new Color(0xC0C0C0)); colorNames.put("lime", new Color(0x00FF00)); colorNames.put("gray", new Color(0x808080)); colorNames.put("olive", new Color(0x808000)); colorNames.put("white", new Color(0xFFFFFF)); colorNames.put("yellow", new Color(0xFFFF00)); colorNames.put("maroon", new Color(0x800000)); colorNames.put("navy", new Color(0x000080)); colorNames.put("red", new Color(0xFF0000)); colorNames.put("blue", new Color(0x0000FF)); colorNames.put("purple", new Color(0x800080)); colorNames.put("teal", new Color(0x008080)); colorNames.put("fuchsia", new Color(0xFF00FF)); colorNames.put("aqua", new Color(0x00FFFF)); } /** * Decode HTML-attribute style of color to {@link Color} * @param color - color name or #RRGGBB string * @return - color for this value. */ public static Color decode(String color){ if(null == color) { throw new IllegalArgumentException("NULL_COLOR_PARAMETER_ERROR"); } Color c = (Color) colorNames.get(color.trim().toLowerCase()); if (null == c) { try { c = Color.decode(color.trim()); } catch (NumberFormatException e) { throw new IllegalArgumentException("DECODE_COLOR_PARAMETER_ERROR"); } } return c; } public static Integer integerValue(String color){ return new Integer(decode(color).getRGB()); } public static String encodeRGB(Color color){ if(null == color) { throw new IllegalArgumentException("NULL_COLOR_PARAMETER_ERROR_2"); } return "#" + Integer.toHexString(color.getRGB()).substring(2).toUpperCase(); }
}
</source>
HTML color names
<source lang="java">
//Revised from com.greef.ui; import java.util.Map; import java.util.HashMap; import java.util.Collection; import java.lang.reflect.Field; import java.awt.Color; /**
* HTML color names. It"s intended use is for parsing a name and return the * corresponding color or return a name for a given color. * @author Adrian Ber */
public class HTMLColors {
/** Don"t instantiate this, use only the static methods */ private HTMLColors() { } /** map between color names and colors; * tough there are fields for every color we use a map because is a faster * way to get the color */ private static Map<String, Color> name2color = new HashMap<String, Color>(); /** map between colors and color names; * tough there are fields for every color we use a map because is a faster * way to get the color */ private static Map<Color, String> color2name = new HashMap<Color, String>(); /** Initialiase colors map */ private static void initColorsMap() { Field[] fields = HTMLColors.class.getFields(); for (Field field : fields) { if (field.getType().isAssignableFrom(Color.class)) { addColor(field.getName()); } } } /** Used to initialize the map */ private static void addColor(String colorName, Color color) { name2color.put(colorName, color); color2name.put(color, colorName); } /** Used to initialize the map */ private static void addColor(String colorName) { addColor(colorName, getColorFromField(colorName)); } /** Used to initialize the map */ private static void addColor(String colorName, int colorRGB) { addColor(colorName, new Color(colorRGB)); } /** Returns a color with the specified case-insensitive name. */ private static Color getColorFromField(String name) { try { Field colorField = HTMLColors.class.getField(name.toLowerCase()); return (Color) colorField.get(HTMLColors.class); } catch (NoSuchFieldException exc) { } catch (SecurityException exc) { } catch (IllegalAccessException exc) { } catch (IllegalArgumentException exc) { } return null; } /** Returns a color with the specified case-insensitive name.*/ public static String getName(Color color) { return color2name.get(color); } /** Returns a color with the specified case-insensitive name.*/ public static Color getColor(String name) { return name2color.get(name.toLowerCase()); } /** Returns a collection of all color names */ public static Collection<String> colors() { return name2color.keySet(); } /** Transform a color string into a color object. * @param s the color string * @return the color object */ public static Color decodeColor(String s) { if (s == null) return null; Color c; try { c = Color.decode(s); } catch (NumberFormatException exc) { c = HTMLColors.getColor(s); } return c; } public static final Color aliceblue = new Color(0xf0f8ff); public static final Color antiquewhite = new Color(0xfaebd7); public static final Color aqua = new Color(0x00ffff); public static final Color aquamarine = new Color(0x7fffd4); public static final Color azure = new Color(0xf0ffff); public static final Color beige = new Color(0xf5f5dc); public static final Color bisque = new Color(0xffe4c4); public static final Color black = new Color(0x000000); public static final Color blanchedalmond = new Color(0xffebcd); public static final Color blue = new Color(0x0000ff); public static final Color blueviolet = new Color(0x8a2be2); public static final Color brown = new Color(0xa52a2a); public static final Color burlywood = new Color(0xdeb887); public static final Color cadetblue = new Color(0x5f9ea0); public static final Color chartreuse = new Color(0x7fff00); public static final Color chocolate = new Color(0xd2691e); public static final Color coral = new Color(0xff7f50); public static final Color cornflowerblue = new Color(0x6495ed); public static final Color cornsilk = new Color(0xfff8dc); public static final Color crimson = new Color(0xdc143c); public static final Color cyan = new Color(0x00ffff); public static final Color darkblue = new Color(0x00008b); public static final Color darkcyan = new Color(0x008b8b); public static final Color darkgoldenrod = new Color(0xb8860b); public static final Color darkgray = new Color(0xa9a9a9); public static final Color darkgreen = new Color(0x006400); public static final Color darkkhaki = new Color(0xbdb76b); public static final Color darkmagenta = new Color(0x8b008b); public static final Color darkolivegreen = new Color(0x556b2f); public static final Color darkorange = new Color(0xff8c00); public static final Color darkorchid = new Color(0x9932cc); public static final Color darkred = new Color(0x8b0000); public static final Color darksalmon = new Color(0xe9967a); public static final Color darkseagreen = new Color(0x8fbc8f); public static final Color darkslateblue = new Color(0x483d8b); public static final Color darkslategray = new Color(0x2f4f4f); public static final Color darkturquoise = new Color(0x00ced1); public static final Color darkviolet = new Color(0x9400d3); public static final Color deeppink = new Color(0xff1493); public static final Color deepskyblue = new Color(0x00bfff); public static final Color dimgray = new Color(0x696969); public static final Color dodgerblue = new Color(0x1e90ff); public static final Color firebrick = new Color(0xb22222); public static final Color floralwhite = new Color(0xfffaf0); public static final Color forestgreen = new Color(0x228b22); public static final Color fuchsia = new Color(0xff00ff); public static final Color gainsboro = new Color(0xdcdcdc); public static final Color ghostwhite = new Color(0xf8f8ff); public static final Color gold = new Color(0xffd700); public static final Color goldenrod = new Color(0xdaa520); public static final Color gray = new Color(0x808080); public static final Color green = new Color(0x008000); public static final Color greenyellow = new Color(0xadff2f); public static final Color honeydew = new Color(0xf0fff0); public static final Color hotpink = new Color(0xff69b4); public static final Color indianred = new Color(0xcd5c5c); public static final Color indigo = new Color(0x4b0082); public static final Color ivory = new Color(0xfffff0); public static final Color khaki = new Color(0xf0e68c); public static final Color lavender = new Color(0xe6e6fa); public static final Color lavenderblush = new Color(0xfff0f5); public static final Color lawngreen = new Color(0x7cfc00); public static final Color lemonchiffon = new Color(0xfffacd); public static final Color lightblue = new Color(0xadd8e6); public static final Color lightcoral = new Color(0xf08080); public static final Color lightcyan = new Color(0xe0ffff); public static final Color lightgoldenrodyellow = new Color(0xfafad2); public static final Color lightgreen = new Color(0x90ee90); public static final Color lightgrey = new Color(0xd3d3d3); public static final Color lightpink = new Color(0xffb6c1); public static final Color lightsalmon = new Color(0xffa07a); public static final Color lightseagreen = new Color(0x20b2aa); public static final Color lightskyblue = new Color(0x87cefa); public static final Color lightslategray = new Color(0x778899); public static final Color lightsteelblue = new Color(0xb0c4de); public static final Color lightyellow = new Color(0xffffe0); public static final Color lime = new Color(0x00ff00); public static final Color limegreen = new Color(0x32cd32); public static final Color linen = new Color(0xfaf0e6); public static final Color magenta = new Color(0xff00ff); public static final Color maroon = new Color(0x800000); public static final Color mediumaquamarine = new Color(0x66cdaa); public static final Color mediumblue = new Color(0x0000cd); public static final Color mediumorchid = new Color(0xba55d3); public static final Color mediumpurple = new Color(0x9370db); public static final Color mediumseagreen = new Color(0x3cb371); public static final Color mediumslateblue = new Color(0x7b68ee); public static final Color mediumspringgreen = new Color(0x00fa9a); public static final Color mediumturquoise = new Color(0x48d1cc); public static final Color mediumvioletred = new Color(0xc71585); public static final Color midnightblue = new Color(0x191970); public static final Color mintcream = new Color(0xf5fffa); public static final Color mistyrose = new Color(0xffe4e1); public static final Color moccasin = new Color(0xffe4b5); public static final Color navajowhite = new Color(0xffdead); public static final Color navy = new Color(0x000080); public static final Color oldlace = new Color(0xfdf5e6); public static final Color olive = new Color(0x808000); public static final Color olivedrab = new Color(0x6b8e23); public static final Color orange = new Color(0xffa500); public static final Color orangered = new Color(0xff4500); public static final Color orchid = new Color(0xda70d6); public static final Color palegoldenrod = new Color(0xeee8aa); public static final Color palegreen = new Color(0x98fb98); public static final Color paleturquoise = new Color(0xafeeee); public static final Color palevioletred = new Color(0xdb7093); public static final Color papayawhip = new Color(0xffefd5); public static final Color peachpuff = new Color(0xffdab9); public static final Color peru = new Color(0xcd853f); public static final Color pink = new Color(0xffc0cb); public static final Color plum = new Color(0xdda0dd); public static final Color powderblue = new Color(0xb0e0e6); public static final Color purple = new Color(0x800080); public static final Color red = new Color(0xff0000); public static final Color rosybrown = new Color(0xbc8f8f); public static final Color royalblue = new Color(0x4169e1); public static final Color saddlebrown = new Color(0x8b4513); public static final Color salmon = new Color(0xfa8072); public static final Color sandybrown = new Color(0xf4a460); public static final Color seagreen = new Color(0x2e8b57); public static final Color seashell = new Color(0xfff5ee); public static final Color sienna = new Color(0xa0522d); public static final Color silver = new Color(0xc0c0c0); public static final Color skyblue = new Color(0x87ceeb); public static final Color slateblue = new Color(0x6a5acd); public static final Color slategray = new Color(0x708090); public static final Color snow = new Color(0xfffafa); public static final Color springgreen = new Color(0x00ff7f); public static final Color steelblue = new Color(0x4682b4); public static final Color tan = new Color(0xd2b48c); public static final Color teal = new Color(0x008080); public static final Color thistle = new Color(0xd8bfd8); public static final Color tomato = new Color(0xff6347); public static final Color turquoise = new Color(0x40e0d0); public static final Color violet = new Color(0xee82ee); public static final Color wheat = new Color(0xf5deb3); public static final Color white = new Color(0xffffff); public static final Color whitesmoke = new Color(0xf5f5f5); public static final Color yellow = new Color(0xffff00); public static final Color yellowgreen = new Color(0x9acd32); static { initColorsMap(); }
}
</source>
HTML Decoder
<source lang="java">
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. All rights reserved. This program and * the accompanying materials are made available under the terms of the Eclipse * Public License v1.0 which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html Contributors: Actuate Corporation - * initial API and implementation ******************************************************************************/
import java.util.HashMap; /**
* Description: Utility for converting character references e.g.: < > * " å И 水 * */
public class HTMLDecoder {
private static final HashMap charTable; public static String decode(String s) { String t; Character ch; int tmpPos, i; int maxPos = s.length(); StringBuffer sb = new StringBuffer(maxPos); int curPos = 0; while (curPos < maxPos) { char c = s.charAt(curPos++); if (c == "&") { tmpPos = curPos; if (tmpPos < maxPos) { char d = s.charAt(tmpPos++); if (d == "#") { if (tmpPos < maxPos) { d = s.charAt(tmpPos++); if (d == "x" || d == "X") { if (tmpPos < maxPos) { d = s.charAt(tmpPos++); if (isHexDigit(d)) { while (tmpPos < maxPos) { d = s.charAt(tmpPos++); if (!isHexDigit(d)) { if (d == ";") { t = s.substring(curPos + 2, tmpPos - 1); try { i = Integer.parseInt(t, 16); if (i >= 0 && i < 65536) { c = (char) i; curPos = tmpPos; } } catch (NumberFormatException e) { } } break; } } } } } else if (isDigit(d)) { while (tmpPos < maxPos) { d = s.charAt(tmpPos++); if (!isDigit(d)) { if (d == ";") { t = s.substring(curPos + 1, tmpPos - 1); try { i = Integer.parseInt(t); if (i >= 0 && i < 65536) { c = (char) i; curPos = tmpPos; } } catch (NumberFormatException e) { } } break; } } } } } else if (isLetter(d)) { while (tmpPos < maxPos) { d = s.charAt(tmpPos++); if (!isLetterOrDigit(d)) { if (d == ";") { t = s.substring(curPos, tmpPos - 1); ch = (Character) charTable.get(t); if (ch != null) { c = ch.charValue(); curPos = tmpPos; } } break; } } } } } sb.append(c); } return sb.toString(); } private static boolean isLetterOrDigit(char c) { return isLetter(c) || isDigit(c); } private static boolean isHexDigit(char c) { return isHexLetter(c) || isDigit(c); } private static boolean isLetter(char c) { return (c >= "a" && c <= "z") || (c >= "A" && c <= "Z"); } private static boolean isHexLetter(char c) { return (c >= "a" && c <= "f") || (c >= "A" && c <= "F"); } private static boolean isDigit(char c) { return c >= "0" && c <= "9"; } public static String compact(String s) { int maxPos = s.length(); StringBuffer sb = new StringBuffer(maxPos); int curPos = 0; while (curPos < maxPos) { char c = s.charAt(curPos++); if (isWhitespace(c)) { while (curPos < maxPos && isWhitespace(s.charAt(curPos))) { curPos++; } c = "\u0020"; } sb.append(c); } return sb.toString(); } // HTML is very particular about what constitutes white space. public static boolean isWhitespace(char ch) { return ch == "\u0020" || ch == "\r" || ch == "\n" || ch == "\u0009" || ch == "\u000c" || ch == "\u200b"; } static { charTable = new HashMap(); charTable.put("quot", new Character((char) 34)); charTable.put("amp", new Character((char) 38)); charTable.put("apos", new Character((char) 39)); charTable.put("lt", new Character((char) 60)); charTable.put("gt", new Character((char) 62)); charTable.put("nbsp", new Character((char) 160)); charTable.put("iexcl", new Character((char) 161)); charTable.put("cent", new Character((char) 162)); charTable.put("pound", new Character((char) 163)); charTable.put("curren", new Character((char) 164)); charTable.put("yen", new Character((char) 165)); charTable.put("brvbar", new Character((char) 166)); charTable.put("sect", new Character((char) 167)); charTable.put("uml", new Character((char) 168)); charTable.put("copy", new Character((char) 169)); charTable.put("ordf", new Character((char) 170)); charTable.put("laquo", new Character((char) 171)); charTable.put("not", new Character((char) 172)); charTable.put("shy", new Character((char) 173)); charTable.put("reg", new Character((char) 174)); charTable.put("macr", new Character((char) 175)); charTable.put("deg", new Character((char) 176)); charTable.put("plusmn", new Character((char) 177)); charTable.put("sup2", new Character((char) 178)); charTable.put("sup3", new Character((char) 179)); charTable.put("acute", new Character((char) 180)); charTable.put("micro", new Character((char) 181)); charTable.put("para", new Character((char) 182)); charTable.put("middot", new Character((char) 183)); charTable.put("cedil", new Character((char) 184)); charTable.put("sup1", new Character((char) 185)); charTable.put("ordm", new Character((char) 186)); charTable.put("raquo", new Character((char) 187)); charTable.put("frac14", new Character((char) 188)); charTable.put("frac12", new Character((char) 189)); charTable.put("frac34", new Character((char) 190)); charTable.put("iquest", new Character((char) 191)); charTable.put("Agrave", new Character((char) 192)); charTable.put("Aacute", new Character((char) 193)); charTable.put("Acirc", new Character((char) 194)); charTable.put("Atilde", new Character((char) 195)); charTable.put("Auml", new Character((char) 196)); charTable.put("Aring", new Character((char) 197)); charTable.put("AElig", new Character((char) 198)); charTable.put("Ccedil", new Character((char) 199)); charTable.put("Egrave", new Character((char) 200)); charTable.put("Eacute", new Character((char) 201)); charTable.put("Ecirc", new Character((char) 202)); charTable.put("Euml", new Character((char) 203)); charTable.put("Igrave", new Character((char) 204)); charTable.put("Iacute", new Character((char) 205)); charTable.put("Icirc", new Character((char) 206)); charTable.put("Iuml", new Character((char) 207)); charTable.put("ETH", new Character((char) 208)); charTable.put("Ntilde", new Character((char) 209)); charTable.put("Ograve", new Character((char) 210)); charTable.put("Oacute", new Character((char) 211)); charTable.put("Ocirc", new Character((char) 212)); charTable.put("Otilde", new Character((char) 213)); charTable.put("Ouml", new Character((char) 214)); charTable.put("times", new Character((char) 215)); charTable.put("Oslash", new Character((char) 216)); charTable.put("Ugrave", new Character((char) 217)); charTable.put("Uacute", new Character((char) 218)); charTable.put("Ucirc", new Character((char) 219)); charTable.put("Uuml", new Character((char) 220)); charTable.put("Yacute", new Character((char) 221)); charTable.put("THORN", new Character((char) 222)); charTable.put("szlig", new Character((char) 223)); charTable.put("agrave", new Character((char) 224)); charTable.put("aacute", new Character((char) 225)); charTable.put("acirc", new Character((char) 226)); charTable.put("atilde", new Character((char) 227)); charTable.put("auml", new Character((char) 228)); charTable.put("aring", new Character((char) 229)); charTable.put("aelig", new Character((char) 230)); charTable.put("ccedil", new Character((char) 231)); charTable.put("egrave", new Character((char) 232)); charTable.put("eacute", new Character((char) 233)); charTable.put("ecirc", new Character((char) 234)); charTable.put("euml", new Character((char) 235)); charTable.put("igrave", new Character((char) 236)); charTable.put("iacute", new Character((char) 237)); charTable.put("icirc", new Character((char) 238)); charTable.put("iuml", new Character((char) 239)); charTable.put("eth", new Character((char) 240)); charTable.put("ntilde", new Character((char) 241)); charTable.put("ograve", new Character((char) 242)); charTable.put("oacute", new Character((char) 243)); charTable.put("ocirc", new Character((char) 244)); charTable.put("otilde", new Character((char) 245)); charTable.put("ouml", new Character((char) 246)); charTable.put("divide", new Character((char) 247)); charTable.put("oslash", new Character((char) 248)); charTable.put("ugrave", new Character((char) 249)); charTable.put("uacute", new Character((char) 250)); charTable.put("ucirc", new Character((char) 251)); charTable.put("uuml", new Character((char) 252)); charTable.put("yacute", new Character((char) 253)); charTable.put("thorn", new Character((char) 254)); charTable.put("yuml", new Character((char) 255)); charTable.put("OElig", new Character((char) 338)); charTable.put("oelig", new Character((char) 339)); charTable.put("Scaron", new Character((char) 352)); charTable.put("scaron", new Character((char) 353)); charTable.put("Yuml", new Character((char) 376)); charTable.put("fnof", new Character((char) 402)); charTable.put("circ", new Character((char) 710)); charTable.put("tilde", new Character((char) 732)); charTable.put("Alpha", new Character((char) 913)); charTable.put("Beta", new Character((char) 914)); charTable.put("Gamma", new Character((char) 915)); charTable.put("Delta", new Character((char) 916)); charTable.put("Epsilon", new Character((char) 917)); charTable.put("Zeta", new Character((char) 918)); charTable.put("Eta", new Character((char) 919)); charTable.put("Theta", new Character((char) 920)); charTable.put("Iota", new Character((char) 921)); charTable.put("Kappa", new Character((char) 922)); charTable.put("Lambda", new Character((char) 923)); charTable.put("Mu", new Character((char) 924)); charTable.put("Nu", new Character((char) 925)); charTable.put("Xi", new Character((char) 926)); charTable.put("Omicron", new Character((char) 927)); charTable.put("Pi", new Character((char) 928)); charTable.put("Rho", new Character((char) 929)); charTable.put("Sigma", new Character((char) 931)); charTable.put("Tau", new Character((char) 932)); charTable.put("Upsilon", new Character((char) 933)); charTable.put("Phi", new Character((char) 934)); charTable.put("Chi", new Character((char) 935)); charTable.put("Psi", new Character((char) 936)); charTable.put("Omega", new Character((char) 937)); charTable.put("alpha", new Character((char) 945)); charTable.put("beta", new Character((char) 946)); charTable.put("gamma", new Character((char) 947)); charTable.put("delta", new Character((char) 948)); charTable.put("epsilon", new Character((char) 949)); charTable.put("zeta", new Character((char) 950)); charTable.put("eta", new Character((char) 951)); charTable.put("theta", new Character((char) 952)); charTable.put("iota", new Character((char) 953)); charTable.put("kappa", new Character((char) 954)); charTable.put("lambda", new Character((char) 955)); charTable.put("mu", new Character((char) 956)); charTable.put("nu", new Character((char) 957)); charTable.put("xi", new Character((char) 958)); charTable.put("omicron", new Character((char) 959)); charTable.put("pi", new Character((char) 960)); charTable.put("rho", new Character((char) 961)); charTable.put("sigmaf", new Character((char) 962)); charTable.put("sigma", new Character((char) 963)); charTable.put("tau", new Character((char) 964)); charTable.put("upsilon", new Character((char) 965)); charTable.put("phi", new Character((char) 966)); charTable.put("chi", new Character((char) 967)); charTable.put("psi", new Character((char) 968)); charTable.put("omega", new Character((char) 969)); charTable.put("thetasym", new Character((char) 977)); charTable.put("upsih", new Character((char) 978)); charTable.put("piv", new Character((char) 982)); charTable.put("ensp", new Character((char) 8194)); charTable.put("emsp", new Character((char) 8195)); charTable.put("thinsp", new Character((char) 8201)); charTable.put("zwnj", new Character((char) 8204)); charTable.put("zwj", new Character((char) 8205)); charTable.put("lrm", new Character((char) 8206)); charTable.put("rlm", new Character((char) 8207)); charTable.put("ndash", new Character((char) 8211)); charTable.put("mdash", new Character((char) 8212)); charTable.put("lsquo", new Character((char) 8216)); charTable.put("rsquo", new Character((char) 8217)); charTable.put("sbquo", new Character((char) 8218)); charTable.put("ldquo", new Character((char) 8220)); charTable.put("rdquo", new Character((char) 8221)); charTable.put("bdquo", new Character((char) 8222)); charTable.put("dagger", new Character((char) 8224)); charTable.put("Dagger", new Character((char) 8225)); charTable.put("bull", new Character((char) 8226)); charTable.put("hellip", new Character((char) 8230)); charTable.put("permil", new Character((char) 8240)); charTable.put("prime", new Character((char) 8242)); charTable.put("Prime", new Character((char) 8243)); charTable.put("lsaquo", new Character((char) 8249)); charTable.put("rsaquo", new Character((char) 8250)); charTable.put("oline", new Character((char) 8254)); charTable.put("frasl", new Character((char) 8260)); charTable.put("euro", new Character((char) 8364)); charTable.put("image", new Character((char) 8465)); charTable.put("weierp", new Character((char) 8472)); charTable.put("real", new Character((char) 8476)); charTable.put("trade", new Character((char) 8482)); charTable.put("alefsym", new Character((char) 8501)); charTable.put("larr", new Character((char) 8592)); charTable.put("uarr", new Character((char) 8593)); charTable.put("rarr", new Character((char) 8594)); charTable.put("darr", new Character((char) 8595)); charTable.put("harr", new Character((char) 8596)); charTable.put("crarr", new Character((char) 8629)); charTable.put("lArr", new Character((char) 8656)); charTable.put("uArr", new Character((char) 8657)); charTable.put("rArr", new Character((char) 8658)); charTable.put("dArr", new Character((char) 8659)); charTable.put("hArr", new Character((char) 8660)); charTable.put("forall", new Character((char) 8704)); charTable.put("part", new Character((char) 8706)); charTable.put("exist", new Character((char) 8707)); charTable.put("empty", new Character((char) 8709)); charTable.put("nabla", new Character((char) 8711)); charTable.put("isin", new Character((char) 8712)); charTable.put("notin", new Character((char) 8713)); charTable.put("ni", new Character((char) 8715)); charTable.put("prod", new Character((char) 8719)); charTable.put("sum", new Character((char) 8721)); charTable.put("minus", new Character((char) 8722)); charTable.put("lowast", new Character((char) 8727)); charTable.put("radic", new Character((char) 8730)); charTable.put("prop", new Character((char) 8733)); charTable.put("infin", new Character((char) 8734)); charTable.put("ang", new Character((char) 8736)); charTable.put("and", new Character((char) 8743)); charTable.put("or", new Character((char) 8744)); charTable.put("cap", new Character((char) 8745)); charTable.put("cup", new Character((char) 8746)); charTable.put("int", new Character((char) 8747)); charTable.put("there4", new Character((char) 8756)); charTable.put("sim", new Character((char) 8764)); charTable.put("cong", new Character((char) 8773)); charTable.put("asymp", new Character((char) 8776)); charTable.put("ne", new Character((char) 8800)); charTable.put("equiv", new Character((char) 8801)); charTable.put("le", new Character((char) 8804)); charTable.put("ge", new Character((char) 8805)); charTable.put("sub", new Character((char) 8834)); charTable.put("sup", new Character((char) 8835)); charTable.put("nsub", new Character((char) 8836)); charTable.put("sube", new Character((char) 8838)); charTable.put("supe", new Character((char) 8839)); charTable.put("oplus", new Character((char) 8853)); charTable.put("otimes", new Character((char) 8855)); charTable.put("perp", new Character((char) 8869)); charTable.put("sdot", new Character((char) 8901)); charTable.put("lceil", new Character((char) 8968)); charTable.put("rceil", new Character((char) 8969)); charTable.put("lfloor", new Character((char) 8970)); charTable.put("rfloor", new Character((char) 8971)); charTable.put("lang", new Character((char) 9001)); charTable.put("rang", new Character((char) 9002)); charTable.put("loz", new Character((char) 9674)); charTable.put("spades", new Character((char) 9824)); charTable.put("clubs", new Character((char) 9827)); charTable.put("hearts", new Character((char) 9829)); charTable.put("diams", new Character((char) 9830)); }
}
</source>
Html Dimensions
<source lang="java">
/**
* Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.ru/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */
// Revised from ajax4jsf import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.regex.Pattern; public class HtmlDimensions {
private static final Pattern PATTERN_NUMERIC = Pattern.rupile("^[+-]?\\d+(\\.\\d+)?$"); private static final Pattern PATTERN_PX = Pattern.rupile("^[+-]?\\d+(\\.\\d+)?px$"); private static final Pattern PATTERN_PCT = Pattern.rupile("^[+-]?\\d+(\\.\\d+)?%$"); private static final NumberFormat numericFormat = new DecimalFormat(); private static final DecimalFormat pxFormat = new DecimalFormat(); private static final NumberFormat pctFormat = NumberFormat.getPercentInstance(); static{ pxFormat.setPositiveSuffix("px"); pxFormat.setNegativeSuffix("px"); } public static Double decode(String size){ // TODO - handle px,ex,pt enc suffixes. double d = 0; try { if(size != null){ if(PATTERN_NUMERIC.matcher(size).matches()){ synchronized(numericFormat){ d = numericFormat.parse(size).doubleValue(); } } else if(PATTERN_PX.matcher(size).matches()){ synchronized (pxFormat) { d = pxFormat.parse(size).doubleValue(); } } else if(PATTERN_PCT.matcher(size).matches()){ synchronized (pctFormat) { d = pctFormat.parse(size).doubleValue(); } } } } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } return new Double(d); } public static String formatPx(Double value){ return (value.intValue() + "px"); } public static String formatPct(Double value){ String v = ""; synchronized (pctFormat) { v = pctFormat.format(value.doubleValue()); } return v; }
}
</source>
HTML form Utilites
<source lang="java">
//Revised from open ejb public class HtmlUtilities {
public static final String ANCHOR_NAME_TYPE = "name"; public static final String ANCHOR_HREF_TYPE = "href"; //we don"t want anyone creating new instances of this class private HtmlUtilities() { } public static String createAnchor(String value, String display, String type) { //our type must be one of these two if (!(ANCHOR_HREF_TYPE.equals(type) || ANCHOR_NAME_TYPE.equals(type))) { throw new IllegalArgumentException("The type argument must be either \"name\" or \"href\""); } return new StringBuffer(100) .append("<a ") .append(type) .append("=\"") .append(value) .append("\">") .append(display) .append("</a>") .toString(); } public static String createSelectFormField(String name, String onChange) { StringBuffer temp = new StringBuffer(60).append("<select name=\"").append(name); if (onChange != null) { temp.append("\" onChange=\"").append(onChange); } return temp.append("\">").toString(); } public static String createSelectOption(String value, String display, boolean selected) { StringBuffer temp = new StringBuffer(65).append("<option value=\"").append(value).append("\""); if (selected) { temp.append(" selected"); } return temp.append(">").append(display).append("</option>").toString(); } public static String createTextFormField(String name, String value, int size, int maxLength) { return createInputFormField("text", name, value, size, maxLength, null, null, null, null, false, false, false); } public static String createFileFormField(String name, String value, int size) { return createInputFormField("file", name, value, size, 0, null, null, null, null, false, false, false); } public static String createHiddenFormField(String name, String value) { return createInputFormField("hidden", name, value, 0, 0, null, null, null, null, false, false, false); } public static String createSubmitFormButton(String name, String value) { return createInputFormField("submit", name, value, 0, 0, null, null, null, null, false, false, false); } public static String createInputFormField( String type, String name, String value, int size, int maxLength, String onFocus, String onBlur, String onChange, String onClick, boolean checked, boolean disabled, boolean readOnly) { StringBuffer temp = new StringBuffer(150) .append("<input type=\"") .append(type) .append("\" name=\"") .append(name) .append("\" value=\"") .append(value) .append("\""); if (size > 0) { temp.append(" size=\"").append(size).append("\""); } if (maxLength > 0) { temp.append(" maxlength=\"").append(maxLength).append("\""); } if (onFocus != null) { temp.append(" onfocus=\"").append(onFocus).append("\""); } if (onBlur != null) { temp.append(" onblur=\"").append(onBlur).append("\""); } if (onChange != null) { temp.append(" onchange=\"").append(onChange).append("\""); } if (onClick != null) { temp.append(" onclick=\"").append(onClick).append("\""); } if (checked) { temp.append(" checked"); } if (disabled) { temp.append(" disabled"); } if (readOnly) { temp.append(" readonly"); } return temp.append(">").toString(); } public static String createTextArea( String name, String content, int rows, int columns, String onFocus, String onBlur, String onChange) { StringBuffer temp = new StringBuffer(50); temp.append("<textarea name=\"").append(name).append("\" rows=\"").append(rows).append("\" cols=\"").append( columns).append( "\""); if (onFocus != null) { temp.append(" onfocus=\"").append(onFocus).append("\""); } if (onBlur != null) { temp.append(" onblur=\"").append(onBlur).append("\""); } if (onChange != null) { temp.append(" onchange=\"").append(onChange).append("\""); } return temp.append(">").append(content).append("</textarea>").toString(); }
}
</source>
HTML Helper
<source lang="java">
import java.util.HashMap; import java.util.Map; /* -----------------------------------------------------------
* nntp//rss - a bridge between the RSS world and NNTP clients * Copyright (c) 2002, 2003 Jason Brome. All Rights Reserved. * * email: nntprss@methodize.org * mail: Methodize Solutions * PO Box 3865 * Grand Central Station * New York NY 10163 * * This file is part of nntp//rss * * Entities list from: * http://www.w3.org/TR/html401/sgml/entities.html * * Portions � International Organization for Standardization 1986: * Permission to copy in any form is granted for use with * conforming SGML systems and applications as defined in * ISO 8879, provided this notice is included in all copies. * * nntp//rss is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software Foundation; * either version 2 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA * ----------------------------------------------------- */
/**
* @author Jason Brome <jason@methodize.org> * @version $Id: HTMLHelper.java,v 1.1 2003/03/24 03:13:03 jasonbrome Exp $ */
public class HTMLHelper {
private static Map escapeMap = new HashMap(); static { // escapeMap.put("nbsp", new Character((char) 160)); escapeMap.put("nbsp", new Character(" ")); escapeMap.put("iexcl", new Character((char) 161)); escapeMap.put("cent", new Character((char) 162)); escapeMap.put("pound", new Character((char) 163)); escapeMap.put("curren", new Character((char) 164)); escapeMap.put("yen", new Character((char) 165)); escapeMap.put("brvbar", new Character((char) 166)); escapeMap.put("sect", new Character((char) 167)); escapeMap.put("uml", new Character((char) 168)); escapeMap.put("copy", new Character((char) 169)); escapeMap.put("ordf", new Character((char) 170)); escapeMap.put("laquo", new Character((char) 171)); escapeMap.put("not", new Character((char) 172)); escapeMap.put("shy", new Character((char) 173)); escapeMap.put("reg", new Character((char) 174)); escapeMap.put("macr", new Character((char) 175)); escapeMap.put("deg", new Character((char) 176)); escapeMap.put("plusmn", new Character((char) 177)); escapeMap.put("sup2", new Character((char) 178)); escapeMap.put("sup3", new Character((char) 179)); escapeMap.put("acute", new Character((char) 180)); escapeMap.put("micro", new Character((char) 181)); escapeMap.put("para", new Character((char) 182)); escapeMap.put("middot", new Character((char) 183)); escapeMap.put("cedil", new Character((char) 184)); escapeMap.put("sup1", new Character((char) 185)); escapeMap.put("ordm", new Character((char) 186)); escapeMap.put("raquo", new Character((char) 187)); escapeMap.put("frac14", new Character((char) 188)); escapeMap.put("frac12", new Character((char) 189)); escapeMap.put("frac34", new Character((char) 190)); escapeMap.put("iquest", new Character((char) 191)); escapeMap.put("Agrave", new Character((char) 192)); escapeMap.put("Aacute", new Character((char) 193)); escapeMap.put("Acirc", new Character((char) 194)); escapeMap.put("Atilde", new Character((char) 195)); escapeMap.put("Auml", new Character((char) 196)); escapeMap.put("Aring", new Character((char) 197)); escapeMap.put("AElig", new Character((char) 198)); escapeMap.put("Ccedil", new Character((char) 199)); escapeMap.put("Egrave", new Character((char) 200)); escapeMap.put("Eacute", new Character((char) 201)); escapeMap.put("Ecirc", new Character((char) 202)); escapeMap.put("Euml", new Character((char) 203)); escapeMap.put("Igrave", new Character((char) 204)); escapeMap.put("Iacute", new Character((char) 205)); escapeMap.put("Icirc", new Character((char) 206)); escapeMap.put("Iuml", new Character((char) 207)); escapeMap.put("ETH ", new Character((char) 208)); escapeMap.put("Ntilde", new Character((char) 209)); escapeMap.put("Ograve", new Character((char) 210)); escapeMap.put("Oacute", new Character((char) 211)); escapeMap.put("Ocirc", new Character((char) 212)); escapeMap.put("Otilde", new Character((char) 213)); escapeMap.put("Ouml", new Character((char) 214)); escapeMap.put("times", new Character((char) 215)); escapeMap.put("Oslash", new Character((char) 216)); escapeMap.put("Ugrave", new Character((char) 217)); escapeMap.put("Uacute", new Character((char) 218)); escapeMap.put("Ucirc", new Character((char) 219)); escapeMap.put("Uuml", new Character((char) 220)); escapeMap.put("Yacute", new Character((char) 221)); escapeMap.put("THORN", new Character((char) 222)); escapeMap.put("szlig", new Character((char) 223)); escapeMap.put("agrave", new Character((char) 224)); escapeMap.put("aacute", new Character((char) 225)); escapeMap.put("acirc", new Character((char) 226)); escapeMap.put("atilde", new Character((char) 227)); escapeMap.put("auml", new Character((char) 228)); escapeMap.put("aring", new Character((char) 229)); escapeMap.put("aelig", new Character((char) 230)); escapeMap.put("ccedil", new Character((char) 231)); escapeMap.put("egrave", new Character((char) 232)); escapeMap.put("eacute", new Character((char) 233)); escapeMap.put("ecirc", new Character((char) 234)); escapeMap.put("euml", new Character((char) 235)); escapeMap.put("igrave", new Character((char) 236)); escapeMap.put("iacute", new Character((char) 237)); escapeMap.put("icirc", new Character((char) 238)); escapeMap.put("iuml", new Character((char) 239)); escapeMap.put("eth ", new Character((char) 240)); escapeMap.put("ntilde", new Character((char) 241)); escapeMap.put("ograve", new Character((char) 242)); escapeMap.put("oacute", new Character((char) 243)); escapeMap.put("ocirc", new Character((char) 244)); escapeMap.put("otilde", new Character((char) 245)); escapeMap.put("ouml", new Character((char) 246)); escapeMap.put("divide", new Character((char) 247)); escapeMap.put("oslash", new Character((char) 248)); escapeMap.put("ugrave", new Character((char) 249)); escapeMap.put("uacute", new Character((char) 250)); escapeMap.put("ucirc", new Character((char) 251)); escapeMap.put("uuml", new Character((char) 252)); escapeMap.put("yacute", new Character((char) 253)); escapeMap.put("thorn", new Character((char) 254)); escapeMap.put("yuml", new Character((char) 255)); // Mathematical, Greek and Symbolic characters for HTML // Latin Extended-B escapeMap.put("fnof", new Character((char) 402)); // Greek escapeMap.put("Alpha", new Character((char) 913)); escapeMap.put("Beta", new Character((char) 914)); escapeMap.put("Gamma", new Character((char) 915)); escapeMap.put("Delta", new Character((char) 916)); escapeMap.put("Epsilon", new Character((char) 917)); escapeMap.put("Zeta", new Character((char) 918)); escapeMap.put("Eta", new Character((char) 919)); escapeMap.put("Theta", new Character((char) 920)); escapeMap.put("Iota", new Character((char) 921)); escapeMap.put("Kappa", new Character((char) 922)); escapeMap.put("Lambda", new Character((char) 923)); escapeMap.put("Mu", new Character((char) 924)); escapeMap.put("Nu", new Character((char) 925)); escapeMap.put("Xi", new Character((char) 926)); escapeMap.put("Omicron", new Character((char) 927)); escapeMap.put("Pi", new Character((char) 928)); escapeMap.put("Rho", new Character((char) 929)); escapeMap.put("Sigma", new Character((char) 931)); escapeMap.put("Tau", new Character((char) 932)); escapeMap.put("Upsilon", new Character((char) 933)); escapeMap.put("Phi", new Character((char) 934)); escapeMap.put("Chi", new Character((char) 935)); escapeMap.put("Psi", new Character((char) 936)); escapeMap.put("Omega", new Character((char) 937)); escapeMap.put("alpha", new Character((char) 945)); escapeMap.put("beta", new Character((char) 946)); escapeMap.put("gamma", new Character((char) 947)); escapeMap.put("delta", new Character((char) 948)); escapeMap.put("epsilon", new Character((char) 949)); escapeMap.put("zeta", new Character((char) 950)); escapeMap.put("eta", new Character((char) 951)); escapeMap.put("theta", new Character((char) 952)); escapeMap.put("iota", new Character((char) 953)); escapeMap.put("kappa", new Character((char) 954)); escapeMap.put("lambda", new Character((char) 955)); escapeMap.put("mu", new Character((char) 956)); escapeMap.put("nu", new Character((char) 957)); escapeMap.put("xi", new Character((char) 958)); escapeMap.put("omicron", new Character((char) 959)); escapeMap.put("pi", new Character((char) 960)); escapeMap.put("rho", new Character((char) 961)); escapeMap.put("sigmaf", new Character((char) 962)); escapeMap.put("sigma", new Character((char) 963)); escapeMap.put("tau", new Character((char) 964)); escapeMap.put("upsilon", new Character((char) 965)); escapeMap.put("phi", new Character((char) 966)); escapeMap.put("chi", new Character((char) 967)); escapeMap.put("psi", new Character((char) 968)); escapeMap.put("omega", new Character((char) 969)); escapeMap.put("thetasym", new Character((char) 977)); escapeMap.put("upsih", new Character((char) 978)); escapeMap.put("piv", new Character((char) 982)); // General Punctuation escapeMap.put("bull", new Character((char) 8226)); escapeMap.put("hellip", new Character((char) 8230)); escapeMap.put("prime", new Character((char) 8242)); escapeMap.put("Prime", new Character((char) 8243)); escapeMap.put("oline", new Character((char) 8254)); escapeMap.put("frasl", new Character((char) 8260)); // Letterlike Symbols escapeMap.put("weierp", new Character((char) 8472)); escapeMap.put("image", new Character((char) 8465)); escapeMap.put("real", new Character((char) 8476)); escapeMap.put("trade", new Character((char) 8482)); escapeMap.put("alefsym", new Character((char) 8501)); // Arrows escapeMap.put("larr", new Character((char) 8592)); escapeMap.put("uarr", new Character((char) 8593)); escapeMap.put("rarr", new Character((char) 8594)); escapeMap.put("darr", new Character((char) 8595)); escapeMap.put("harr", new Character((char) 8596)); escapeMap.put("crarr", new Character((char) 8629)); escapeMap.put("lArr", new Character((char) 8656)); escapeMap.put("uArr", new Character((char) 8657)); escapeMap.put("rArr", new Character((char) 8658)); escapeMap.put("dArr", new Character((char) 8659)); escapeMap.put("hArr", new Character((char) 8660)); // Mathematical Operators escapeMap.put("forall", new Character((char) 8704)); escapeMap.put("part", new Character((char) 8706)); escapeMap.put("exist", new Character((char) 8707)); escapeMap.put("empty", new Character((char) 8709)); escapeMap.put("nabla", new Character((char) 8711)); escapeMap.put("isin", new Character((char) 8712)); escapeMap.put("notin", new Character((char) 8713)); escapeMap.put("ni", new Character((char) 8715)); escapeMap.put("prod", new Character((char) 8719)); escapeMap.put("sum", new Character((char) 8721)); escapeMap.put("minus", new Character((char) 8722)); escapeMap.put("lowast", new Character((char) 8727)); escapeMap.put("radic", new Character((char) 8730)); escapeMap.put("prop", new Character((char) 8733)); escapeMap.put("infin", new Character((char) 8734)); escapeMap.put("ang", new Character((char) 8736)); escapeMap.put("and", new Character((char) 8743)); escapeMap.put("or", new Character((char) 8744)); escapeMap.put("cap", new Character((char) 8745)); escapeMap.put("cup", new Character((char) 8746)); escapeMap.put("int", new Character((char) 8747)); escapeMap.put("there4", new Character((char) 8756)); escapeMap.put("sim", new Character((char) 8764)); escapeMap.put("cong", new Character((char) 8773)); escapeMap.put("asymp", new Character((char) 8776)); escapeMap.put("ne", new Character((char) 8800)); escapeMap.put("equiv", new Character((char) 8801)); escapeMap.put("le", new Character((char) 8804)); escapeMap.put("ge", new Character((char) 8805)); escapeMap.put("sub", new Character((char) 8834)); escapeMap.put("sup", new Character((char) 8835)); escapeMap.put("nsub", new Character((char) 8836)); escapeMap.put("sube", new Character((char) 8838)); escapeMap.put("supe", new Character((char) 8839)); escapeMap.put("oplus", new Character((char) 8853)); escapeMap.put("otimes", new Character((char) 8855)); escapeMap.put("perp", new Character((char) 8869)); escapeMap.put("sdot", new Character((char) 8901)); // Miscellaneous Technical escapeMap.put("lceil", new Character((char) 8968)); escapeMap.put("rceil", new Character((char) 8969)); escapeMap.put("lfloor", new Character((char) 8970)); escapeMap.put("rfloor", new Character((char) 8971)); escapeMap.put("lang", new Character((char) 9001)); escapeMap.put("rang", new Character((char) 9002)); // Geometric Shapes escapeMap.put("loz", new Character((char) 9674)); // Miscellaneous Symbols escapeMap.put("spades", new Character((char) 9824)); escapeMap.put("clubs", new Character((char) 9827)); escapeMap.put("hearts", new Character((char) 9829)); escapeMap.put("diams", new Character((char) 9830)); // Special characters for HTML // C0 Controls and Basic Latin escapeMap.put("quot", new Character((char) 34)); escapeMap.put("amp", new Character((char) 38)); escapeMap.put("lt", new Character((char) 60)); escapeMap.put("gt", new Character((char) 62)); escapeMap.put("apos", new Character("\"")); // Latin Extended-A escapeMap.put("OElig", new Character((char) 338)); escapeMap.put("oelig", new Character((char) 339)); escapeMap.put("Scaron", new Character((char) 352)); escapeMap.put("scaron", new Character((char) 353)); escapeMap.put("Yuml", new Character((char) 376)); // Spacing Modifier Letters escapeMap.put("circ", new Character((char) 710)); escapeMap.put("tilde", new Character((char) 732)); // General Punctuation escapeMap.put("ensp", new Character((char) 8194)); escapeMap.put("emsp", new Character((char) 8195)); escapeMap.put("thinsp", new Character((char) 8201)); escapeMap.put("zwnj", new Character((char) 8204)); escapeMap.put("zwj", new Character((char) 8205)); escapeMap.put("lrm", new Character((char) 8206)); escapeMap.put("rlm", new Character((char) 8207)); escapeMap.put("ndash", new Character((char) 8211)); escapeMap.put("mdash", new Character((char) 8212)); escapeMap.put("lsquo", new Character((char) 8216)); escapeMap.put("rsquo", new Character((char) 8217)); escapeMap.put("sbquo", new Character((char) 8218)); escapeMap.put("ldquo", new Character((char) 8220)); escapeMap.put("rdquo", new Character((char) 8221)); escapeMap.put("bdquo", new Character((char) 8222)); escapeMap.put("dagger", new Character((char) 8224)); escapeMap.put("Dagger", new Character((char) 8225)); escapeMap.put("permil", new Character((char) 8240)); escapeMap.put("lsaquo", new Character((char) 8249)); escapeMap.put("rsaquo", new Character((char) 8250)); escapeMap.put("euro", new Character((char) 8364)); } public static String unescapeString(String value) { StringBuffer unescapedString = new StringBuffer(); StringBuffer charBuf = null; for (int pos = 0; pos < value.length(); pos++) { char c = value.charAt(pos); if (c == "&") { // Process reference... c = value.charAt(++pos); boolean numeric = false; if (c == "#") { numeric = true; c = value.charAt(++pos); } if (charBuf == null) { charBuf = new StringBuffer(32); } else { charBuf.setLength(0); } while (c != ";" && pos < value.length() - 1) { charBuf.append(c); c = value.charAt(++pos); } if (numeric) { try { c = (char) Integer.parseInt(charBuf.toString(), 16); } catch (NumberFormatException nfe) { // If we can"t process it, just write out the text... unescapedString.append("&#").append( charBuf.toString()).append( ";"); } } else { Character unescapedVer = (Character) escapeMap.get(charBuf.toString()); if (unescapedVer != null) { unescapedString.append(unescapedVer); } else { unescapedString.append("&").append( charBuf.toString()).append( ";"); } } } else { unescapedString.append(c); } } return unescapedString.toString(); } public static String escapeString(String value) { StringBuffer escapedString = new StringBuffer(); for (int charCount = 0; charCount < value.length(); charCount++) { char c = value.charAt(charCount); switch (c) { case "&" : escapedString.append("&"); break; case "<" : escapedString.append("<"); break; case ">" : escapedString.append(">"); break; case "\"" : escapedString.append("""); break; case "\"" : escapedString.append("'"); break; default : escapedString.append(c); } } return escapedString.toString(); } public static String stripCRLF(String value) { StringBuffer strippedString = new StringBuffer(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!(c == "\n" || c == "\r")) { strippedString.append(c); } } return strippedString.toString(); }
}
</source>
HTML Parser
<source lang="java">
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; import java.util.ArrayList; public class HTMLParser {
FileReader reader; LineNumberReader in; String token; ArrayList attribs = new ArrayList( ); int pushC = -1; private boolean ignoreWhitespace = true; public static final int EOF = -1; public static final int TEXT = 1; public static final int DOCTYPE = 2; public static final int ELEMENT = 3; public static final int COMMENT = 4; public static final int SPECIAL_ELEMENT = 5; public static final int START_ELEMENT = 0; public static final int END_ELEMENT = 1; public static final int SINGLE_ELEMENT = 2; public HTMLParser( ) { } public void open( String fileName ) throws FileNotFoundException { reader = new FileReader( fileName ); in = new LineNumberReader( reader ); } /** * */ public void close( ) { try { in.close( ); reader.close( ); } catch ( IOException e1 ) { // Ignore } } public String getTokenText( ) { return token; } public int getElementType( ) { if ( token.startsWith( "/" ) ) //$NON-NLS-1$ return END_ELEMENT; if ( token.endsWith( "/" ) ) //$NON-NLS-1$ return SINGLE_ELEMENT; return START_ELEMENT; } public String getElement( ) { if ( token.startsWith( "/" ) ) //$NON-NLS-1$ return token.substring( 1 ); if ( token.endsWith( "/" ) ) //$NON-NLS-1$ return token.substring( 0, token.length( ) - 1 ); return token; } public ArrayList getAttribs( ) { return attribs; } public String getAttrib( String name ) { for ( int i = 0; i < attribs.size( ); i++ ) { AttribPair a = (AttribPair) attribs.get( i ); if ( a.attrib.equalsIgnoreCase( name ) ) return a.value; } return null; } private int getC( ) { if ( pushC != -1 ) { int c = pushC; pushC = -1; return c; } try { return in.read( ); } catch ( IOException e ) { return EOF; } } private void pushC( int c ) { pushC = c; } public int getToken( ) { for ( ; ; ) { int c = getC( ); switch ( c ) { case -1: return EOF; case "<": return getElement( c ); default: { parseText( c ); if ( ! ignoreWhitespace || token.trim( ).length( ) > 0 ) return TEXT; } } } } private int parseText( int c ) { StringBuffer text = new StringBuffer( ); for ( ; ; ) { if ( c == EOF ) break; if ( c == "<" ) { pushC( c ); break; } // Convert MS-Word-style quotes. if ( c == 8220 || c == 8221 ) text.append( """ ); else text.append( (char) c ); c = getC( ); } token = text.toString( ); return TEXT; } private int skipSpace( int c ) { while ( c != EOF && Character.isWhitespace( (char)c ) ) { c = getC( ); } return c; } private int getElement( int c ) { c = getC( ); // Broken element if ( c == EOF ) return EOF; if ( c == "!" ) return getSpecialElement( ); attribs.clear( ); c = skipSpace( c ); if ( c == EOF ) return EOF; StringBuffer tag = new StringBuffer( ); if ( c == "/" ) { tag.append( (char) c ); c = skipSpace( getC( ) ); while ( c != EOF && c != ">" && ! Character.isWhitespace( (char)c ) ) { tag.append( (char) c ); c = getC( ); } token = tag.toString( ); for ( ; ; ) { if ( c == ">" || c == -1 ) break; c = getC( ); } return ELEMENT; } while ( c != EOF && c != ">" && c != "/" && ! Character.isWhitespace( (char)c ) ) { tag.append( (char) c ); c = getC( ); } if ( c == EOF ) { token = tag.toString( ); return ELEMENT; } for ( ; ; ) { c = skipSpace( c ); if ( c == EOF || c == ">" || c == "/" ) break; c = getAttrib( c ); } if ( c == "/" ) { tag.append( (char) c ); for ( ; ; ) { c = getC( ); if ( c == -1 || c == ">" ) break; } } token = tag.toString( ); return ELEMENT; } private int getAttrib( int c ) { AttribPair a = new AttribPair( ); StringBuffer s = new StringBuffer( ); while ( c != EOF && c != "=" && ! Character.isWhitespace( (char)c ) ) { s.append( (char) c ); c = getC( ); } a.attrib = s.toString( ); c = skipSpace( c ); if ( c != "=" ) { attribs.add( a ); return c; } s = new StringBuffer( ); c = skipSpace( getC( ) ); if ( c == "\"" || c == """ ) { int quote = c; for ( ; ; ) { c = getC( ); if ( c == -1 ) break; if ( c == quote ) { c = getC( ); break; } if ( c == "\\" ) { c = getC( ); if ( c == EOF ) break; s.append( "\\" ); s.append( (char) c ); } else { s.append( (char) c ); } } } else { for ( ; ; ) { c = getC( ); if ( c == -1 ) break; if ( c == ">" || c == "/" || Character.isWhitespace( (char)c ) ) { c = getC( ); break; } s.append( (char) c ); } } a.value = s.toString( ); attribs.add( a ); return c; } class AttribPair { String attrib; String value; } private int getSpecialElement( ) { StringBuffer text = new StringBuffer( ); text.append( "<!" ); //$NON-NLS-1$ for ( ; ; ) { int c = getC( ); if ( c == EOF || c == ">" ) break; text.append( (char) c ); } text.append( ">" ); token = text.toString( ); if ( token.startsWith( "
Html Parse Servlet
<source lang="java">
import java.io.IOException; import java.io.PrintWriter; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.MalformedURLException; import javax.servlet.*; import javax.servlet.http.*; import javax.swing.text.html.HTMLEditorKit.ParserCallback; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.parser.ParserDelegator; public class HtmlParseServlet extends HttpServlet {
private static final String BASE_URL = "http://finance.yahoo.ru/q?d=t&s="; private ParserDelegator htmlParser = null; private MyParserCallback callback = null; private String htmlText = ""; private boolean lastTradeFlag = false; private boolean boldFlag = false; private float stockVal = 0f; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { //set the MIME type of the response, "text/html" response.setContentType("text/html"); //use a PrintWriter send text data to the client who has requested the // servlet java.io.PrintWriter out = response.getWriter(); //Begin assembling the HTML content out.println("<html><head>"); out.println("<title>Stock Price Fetcher</title></head><body>");out.println("
Please submit a new valid stock symbol
");//make sure method="post" so that the servlet service method //calls doPost in the response to this form submit out.println("<form method=\"post\" action =\"" + request.getContextPath() + "/stockservlet\" >");out.println("
"); out.println("Stock symbol: | ");
out.println("<input type=\"text\" name=\"symbol\" size=\"10\">");out.println(" |
"); out.println("<input type=\"submit\" value=\"Submit Info\"> |
out.println("</body></html>"); } //end doGet public void doPost(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException { String symbol;//this will hold the stock symbol float price; symbol = request.getParameter("symbol"); boolean isValid = (symbol == null || symbol.length() < 1) ? false : true; //set the MIME type of the response, "text/html" response.setContentType("text/html"); //use a PrintWriter send text data to the client who has requested the // servlet java.io.PrintWriter out = response.getWriter(); //Begin assembling the HTML content out.println("<html><head>"); out.println("<title>Latest stock value</title></head><body>"); if (!isValid) { out.println("
Sorry, the stock symbol parameter was either empty or null
");} else {out.println("
Here is the latest value of " + symbol + "
");price = getLatestPrice(symbol); //price < 1 ? "The symbol is probably invalid." : out.println((price == 0 ? "The symbol is probably invalid." : "" + price)); } out.println("</body></html>"); }// doPost private float getLatestPrice(String symbol) throws IOException, MalformedURLException { BufferedReader webPageStream = null; URL stockSite = new URL(BASE_URL + symbol); System.out.println(BASE_URL + symbol); webPageStream = new BufferedReader(new InputStreamReader(stockSite .openStream())); htmlParser = new ParserDelegator(); callback = new MyParserCallback(); synchronized (htmlParser) {//the code is designed to make calling // parse() thread-safe htmlParser.parse(webPageStream, callback, true); } return stockVal; }//getLatestPrice class MyParserCallback extends ParserCallback { public MyParserCallback() { if (stockVal != 0) stockVal = 0f; } public void handleStartTag(javax.swing.text.html.HTML.Tag t, MutableAttributeSet a, int pos) { if (lastTradeFlag && (t == javax.swing.text.html.HTML.Tag.B)) { boldFlag = true; } }//handleStartTag public void handleText(char[] data, int pos) { htmlText = new String(data); if (htmlText.indexOf("No such ticker symbol.") != -1) { throw new IllegalStateException( "Invalid ticker symbol in handleText() method."); } else if (htmlText.equals("Last Trade:")) { lastTradeFlag = true; } else if (boldFlag) { try { stockVal = new Float(htmlText).floatValue(); } catch (NumberFormatException ne) { try { // tease out any commas in the number using NumberFormat java.text.NumberFormat nf = java.text.NumberFormat .getInstance(); Double f = (Double) nf.parse(htmlText); stockVal = (float) f.doubleValue(); } catch (java.text.ParseException pe) { throw new IllegalStateException("The extracted text " + htmlText + " cannot be parsed as a number!"); } } lastTradeFlag = false; boldFlag = false; }//if } //handleText }//MyParserCallback
}//HttpServlet
</source>
Html utilities
<source lang="java">
import java.io.IOException; import java.io.StringWriter; import java.util.Vector; public class HtmlUtils {
public String createHtmlHeader(String title) { String htmlHeader = null; htmlHeader = "<HTML><HEAD><TITLE> " + title + " </TITLE></HEAD><BODY>"; return htmlHeader; } public String getHtmlFooter() { String htmlFooter = "</BODY></HTML>"; return htmlFooter; } public String getHead(int level, String heading) { return "<H" + level + "> " + heading + "</H" + level + ">"; } public String getTableHead(String align, int border) { String tableHeader = null;tableHeader = "
" + value + " | ";";
return TDCell; } public String getTD(int width) { String TDCell = null;TDCell = " | ";
return TDCell; } public String getTH(String align, String value) { String THCell = null;THCell = " | " + value + " | ";||||
---|---|---|---|---|---|---|---|
" + value + " | \n");
Case * |
* * |
* * |
* Table
* Extent* |
* * |
* * |
* ||
1 * |
* Cell | ** |
* * |
* * |
* * |
* * |
* * |
*
2 * |
* Cell * |
* * |
* * |
* * |
* |||
3 * |
* Cell | *||||||
4 * |
* * |
* * |
* * |
* Cell | ** |
* * |
* * |
*
5 * |
* * |
* * |
* * |
* Cell * |
* |||
6 * |
* * |
*
** |
*
** |
* * |
*
** |
*
** |
* Cell | *
* <p> * Depending on the chosen boundary conditions at the boundary locations, the following results occur: * <p>*
Case * |
* FIXED | *CLIPPING * |
* GROW * |
*
1 * |
* IllegalArgumentException * |
* null * |
* SetResult,
* table expanded* |
*
3 * |
* IllegalArgumentException | *SetResult,
* cell clipped* |
* SetResult, * table expanded | *
2 * |
* IllegalArgumentException | *SetResult, * cell clipped | *SetResult, * table expanded | *
4 * |
* SetResult * |
* SetResult * |
* SetResult | *
5 * |
* IllegalArgumentException | *SetResult, * cell clipped | *SetResult, * table expanded | *
6 * |
* IllegalArgumentException | *null * |
* SetResult, * table expanded | *
*
* @param row The logical row index
* @param col The logical column index
*
* @return A {@link SetResult} instance (or null
, see above)
*
* @see BoundaryCondition
*/
public SetResult setCell(Cell cell, int row, int col) {
if (cell == null)
throw new IllegalArgumentException("cell may not be null");
int r = row - row0; // Absolute index (row, row0 are logical)
int c = col - col0; // Absolute index (col, col0 are logical)
int rEnd = r + cell.getRowSpan() - 1; // Absolute index
int cEnd = c + cell.getColSpan() - 1; // Absolute index
int rowLimit = row0 + rowNumber - cell.getRowSpan();
int colLimit = col0 + colNumber - cell.getColSpan();
SetResult result = new SetResult(row, col); // The default
//.... Row: Case 1
if (rEnd < 0) {
switch (boundaryConditions.get(RowLocation.TOP)) {
case FIXED:
throw new IllegalArgumentException("Cell lies completely outside of the table");
case CLIPPING:
return null; // Entire contents are clipped
case GROW:
addRows(RowLocation.TOP, -r);
r = 0;
rEnd = r + cell.getRowSpan() - 1;
}
} else if (r < 0) {
//.... Row: Case 2
if (rEnd < rowNumber) {
switch (boundaryConditions.get(RowLocation.TOP)) {
case FIXED:
if (cell.getRowSpan() > rowNumber)
throw new IllegalArgumentException("Cell has too many rows. Maximum row number is " + rowNumber);
throw new IllegalArgumentException("row must be between " + row0 + " and " + rowLimit);
case CLIPPING:
r = 0;
result.setModified(true);
break;
case GROW:
addRows(RowLocation.TOP, -r);
r = 0;
rEnd = r + cell.getRowSpan() - 1;
}
} else {
//.... Row: Case 3
switch (boundaryConditions.get(RowLocation.TOP)) {
case FIXED:
throw new IllegalArgumentException("Cell has too many rows. Maximum row number is " + rowNumber);
case CLIPPING:
r = 0;
result.setModified(true);
break;
case GROW:
addRows(RowLocation.TOP, -r);
r = 0;
rEnd = r + cell.getRowSpan() - 1;
}
switch (boundaryConditions.get(RowLocation.BOTTOM)) {
case FIXED:
throw new IllegalArgumentException("Cell has too many rows. Maximum row number is " + rowNumber);
case CLIPPING:
rEnd = rowNumber - 1;
result.setModified(true);
break;
case GROW:
addRows(RowLocation.BOTTOM, rEnd - getRowEnd() + row0);
rEnd = rowNumber - 1;
}
}
} else if (r < rowNumber) {
//.... Row: Case 4
if (rEnd < rowNumber) {
//.... Row: Case 5
} else {
switch (boundaryConditions.get(RowLocation.BOTTOM)) {
case FIXED:
if (cell.getRowSpan() > rowNumber) {
throw new IllegalArgumentException("Cell has too many rows. Maximum row number is " + rowNumber);
} else {
throw new IllegalArgumentException("row must be between " + row0 + " and " + rowLimit);
}
case CLIPPING:
rEnd = rowNumber - 1;
result.setModified(true);
break;
case GROW:
addRows(RowLocation.BOTTOM, rEnd - getRowEnd() + row0);
rEnd = rowNumber - 1;
}
}
//.... Row: Case 6
} else {
switch (boundaryConditions.get(RowLocation.BOTTOM)) {
case FIXED:
throw new IllegalArgumentException("Cell lies completely outside of the table");
case CLIPPING:
return null;
case GROW:
addRows(RowLocation.BOTTOM, rEnd - getRowEnd() + row0);
rEnd = rowNumber - 1;
}
}
//.... Column: Case 1
if (cEnd < 0) {
switch (boundaryConditions.get(ColumnLocation.LEFT)) {
case FIXED:
throw new IllegalArgumentException("Cell lies completely outside of the table");
case CLIPPING:
return null; // Entire contents are clipped
case GROW:
addColumns(ColumnLocation.LEFT, -c);
c = 0;
cEnd = c + cell.getColSpan() - 1;
}
} else if (c < 0) {
//.... Column: Case 2
if (cEnd < colNumber) {
switch (boundaryConditions.get(ColumnLocation.LEFT)) {
case FIXED:
if (cell.getColSpan() > colNumber) {
throw new IllegalArgumentException("Cell has too many columns. Maximum column number is " + colNumber);
} else {
throw new IllegalArgumentException("col must be between " + col0 + " and " + colLimit);
}
case CLIPPING:
c = 0;
result.setModified(true);
break;
case GROW:
addColumns(ColumnLocation.LEFT, -c);
c = 0;
cEnd = c + cell.getColSpan() - 1;
}
} else {
//.... Column: Case 3
switch (boundaryConditions.get(ColumnLocation.LEFT)) {
case FIXED:
throw new IllegalArgumentException("Cell has too many columns. Maximum column number is " + colNumber);
case CLIPPING:
c = 0;
result.setModified(true);
break;
case GROW:
addColumns(ColumnLocation.LEFT, -c);
c = 0;
cEnd = c + cell.getColSpan() - 1;
}
switch (boundaryConditions.get(ColumnLocation.RIGHT)) {
case FIXED:
throw new IllegalArgumentException("Cell has too many columns. Maximum column number is " + colNumber);
case CLIPPING:
cEnd = colNumber - 1;
result.setModified(true);
break;
case GROW:
addColumns(ColumnLocation.RIGHT, cEnd - getColEnd() + col0);
cEnd = colNumber - 1;
}
}
} else if (c < colNumber) {
//.... Column: Case 4
if (cEnd < colNumber) {
//.... Column: Case 5
} else {
switch (boundaryConditions.get(ColumnLocation.RIGHT)) {
case FIXED:
if (cell.getColSpan() > colNumber) {
throw new IllegalArgumentException("Cell has too many columns. Maximum column number is " + colNumber);
} else {
throw new IllegalArgumentException("col must be between " + col0 + " and " + colLimit);
}
case CLIPPING:
cEnd = colNumber - 1;
result.setModified(true);
break;
case GROW:
addColumns(ColumnLocation.RIGHT, cEnd - getColEnd() + col0);
cEnd = colNumber - 1;
}
}
//.... Column: Case 6
} else {
switch (boundaryConditions.get(ColumnLocation.RIGHT)) {
case FIXED:
throw new IllegalArgumentException("Cell lies completely outside of the table");
case CLIPPING:
return null;
case GROW:
addColumns(ColumnLocation.RIGHT, cEnd - getColEnd() + col0);
cEnd = colNumber - 1;
}
}
//.... The cell may have to be modified to be displayed correctly now (CLIPPING only)
if (result.isModified()) {
cell.setRowSpan(rEnd - r + 1);
cell.setColSpan(cEnd - c + 1);
}
//.... Now actually fill the table where necessary
for (int rIndex = r; rIndex <= rEnd; rIndex++) {
for (int cIndex = c; cIndex <= cEnd; cIndex++) {
if (!def[rIndex][cIndex]) {
throw new IllegalArgumentException("Cell conflict when trying to add cell with name ""
+ cell.getName() + "" at location ("
+ rIndex + "/" + cIndex + "): already covered by cell "" + cells[rIndex][cIndex].getName() + """);
}
cells[rIndex][cIndex] = cell;
visible[rIndex][cIndex] = false;
def[rIndex][cIndex] = false;
}
}
visible[r][c] = true; // Only this one remains, all others are now hidden
result.setRow(r + row0);
result.setCol(c + col0);
result.setRowEnd(rEnd + row0);
result.setColEnd(cEnd + col0);
return result;
}
/**
* A simple HTML debug output. The table is dumped to STDOUT and the resulting file
* can directly be opened in a browser to get a rough idea of the internal table layout and
* cell structure.
*/
public void dump() {
System.out.println("<html><body>\n");
System.out.println(" (" + r + "/" + c + ")");
} else { if (visible[r][c]) {System.out.println(" | (" + r + "/" + c + ") Cell = " + cells[r][c].getName()); } else {System.out.println(" | (" + r + "/" + c + ") Cell = " + cells[r][c].getName()); } } } }System.out.println(" |
System.out.println("</body></html>\n"); } /** * Get the index of the last row in the table. * * @return The index of the last row in the table */ public int getRowEnd() { return rowEnd; } /** * Get the logical index of the last column in the table. * * @return The logical index of the last column in the table */ public int getColEnd() { return colEnd; } /** * Set the boundary condition for the given boundary location. * * @param boundaryLocation The location for which the boundary condition is to be set * @param boundaryCondition The boundary condition to establish for this location */ public void setBoundaryCondition(BoundaryLocation boundaryLocation, BoundaryCondition boundaryCondition) { if (boundaryLocation == null) { throw new IllegalArgumentException("boundaryLocation may not be null"); } if (boundaryCondition == null) { throw new IllegalArgumentException("boundaryCondition may not be null"); } boundaryConditions.put(boundaryLocation, boundaryCondition); }
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* An enum constant for the two possible boundary locations where rows are of relevance. */ enum RowLocation implements BoundaryLocation { /** * The top edge of the table */ TOP, /** * The bottom edge of the table */ BOTTOM;
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* Result information of a {@link Table#setCell(Cell, int, int)} operation. * * The information returned in an instance of this class is useful in cases where * the boundaries of the table are managed dynaically since then the cell as such may * have been clipped and thus, the starting and end indices of rows and columns may * have changed. */
class SetResult {
private int row = 0; // The logical row where the actual insert occurred private int col = 0; // The logical col where the actual insert occurred private int rowEnd = 0; // The logical index of the end row for the cell private int colEnd = 0; // The logical index of the end col for the cell private boolean modified = false; // True if rowSpan and/or colSpan had to be modified /** * Create a new instance with the given row and column information. * * @param row The logical row where the actual insert of the cell occurred * @param col The logical column where the actual insert of the cell occurred */ public SetResult(int row, int col) { this.setRow(row); this.setCol(col); } /** * Retrieve the logical index of the row where the actual insert of the cell occurred * * @return The logical index of the row where the actual insert of the cell occurred */ public int getRow() { return row; } /** * Set the logical index of the row where the actual insert of the cell occurred. Sometimes * it is necessary to modify the value established in the constructor. * * @param row The logical index of the row where the actual insert of the cell occurred */ public void setRow(int row) { this.row = row; } /** * Retrieve the logical index of the column where the actual insert of the cell occurred * * @return The logical index of the column where the actual insert of the cell occurred */ public int getCol() { return col; } /** * Set the logical index of the column where the actual insert of the cell occurred. Sometimes * it is necessary to modify the value established in the constructor. * * @param col The logical index of the column where the actual insert of the cell occurred */ public void setCol(int col) { this.col = col; } /** * Returns a boolean indicating whether the original values of the cell (row and * column number) and /or the insertion point (the arguments to the * {@link Table#setCell(Cell, int, int)} method) have been modified in the course * of the insertion process. * * @return A boolean indicating whether the original values of the cell have * been modified in the course of the insertion process */ public boolean isModified() { return modified; } /** * Set the boolean indicating whether the cell parameters have been changed in the course * of the insertion process into the table * * @param modified The desired boolean value */ public void setModified(boolean modified) { this.modified = modified; } /** * Retrieve the actual row end index of the cell in the table after the insertion process. * This value may be different from he expected value if clipping is activated at the * boundaries. * * @return The actual row end index of the cell in the table */ public int getRowEnd() { return rowEnd; } /** * Set the actual logical row end index of the cell in the table after the insertion process. * * @param rowEnd The actual logical row end index of the cell in the table */ public void setRowEnd(int rowEnd) { this.rowEnd = rowEnd; } /** * Retrieve the actual logical end column index of the cell in the table after the insertion process. * This value may be different from he expected value if clipping is activated at the * boundaries. * * @return The actual logical column end index of the cell in the table */ public int getColEnd() { return colEnd; } /** * Set the actual logical column end index of the cell in the table after the insertion process. * * @param colEnd The actual logical column end index of the cell in the table */ public void setColEnd(int colEnd) { this.colEnd = colEnd; } /** * The overridden {@link Object#toString()} method. * * @return A string representation of the instance with all relevant data */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SetResult: row = "); sb.append(row); sb.append(" / col = "); sb.append(col); sb.append(" / rowEnd = "); sb.append(rowEnd); sb.append(" / colEnd = "); sb.append(colEnd); sb.append(" / modified = "); sb.append(modified); return sb.toString(); }
}
/**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* An enum constant for the different supported boundary conditions. */
enum BoundaryCondition {
/** * Any cell location outside of the predefined area leads to an exception. * This is the default setting */ FIXED, /** * Cells are truncated when necessary */ CLIPPING, /** * The table grows when necessary to accommodate additional columns/rows */ GROW;
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* A marker interface for all locations relating to the outer boundaries of a table. */
interface BoundaryLocation extends Location {
;
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* An enum constant for internal locations of a table. This can be used to * identify whether operations on the table should apply to rows and / or * columns. */
enum InternalLocation implements Location {
/** * This location relates to all rows of the table */ ROW, /** * This location relates to all columns of the table */ COLUMN;
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* A marker interface for locations where operations or conditions apply for a table. */
interface Location {
;
} /**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* This class represents cells in the table. Cells can span more than one row and column. * Instances of this class are also used to hold all data pertaining to a cell and thus serves * as a vehicle to transport data into a Velocity template. */
class Cell {
private String name = null; private Map<String, String> properties = null; // For HTML formatting properties private int rowSpan = 1; private int colSpan = 1; private Map<String, Object> content = new HashMap<String, Object>(); private Set<String> types = new TreeSet<String>(); /** * Constructor for a simple cell with 1 row and 1 column. * * @param name The name given to the cell. This can be used as a descriptive text when * necessary */ public Cell(String name) { this(name, 1, 1); } /** * Constructor for a cell. * * @param name The name given to the cell. This can be used as a descriptive text when * necessary * @param rowSpan The number of rows that this cell spans * @param colSpan The number of columns that this cell spans */ public Cell(String name, int rowSpan, int colSpan) { this(new HashMap<String, String>(), name, rowSpan, colSpan); } /** * Constructor for a cell. * * @param properties The set of properties for this cell * @param name The name given to the cell. This can be used as a descriptive text when * necessary * @param rowSpan The number of rows that this cell spans * @param colSpan The number of columns that this cell spans */ public Cell(Map<String, String> properties, String name, int rowSpan, int colSpan) { if (properties == null) { throw new IllegalArgumentException("properties may not be null"); } if (name == null) { throw new IllegalArgumentException("name may not be null"); } if (rowSpan < 1) { throw new IllegalArgumentException("rowSpan must be larger than 0"); } if (colSpan < 1) { throw new IllegalArgumentException("colSpan must be larger than 0"); } this.setColSpan(colSpan); this.setRowSpan(rowSpan); this.properties = properties; this.name = name; } /** * Create a deep copy of the current cell. * * @return A deep copy with all properties, types and content elements. */ public Cell clone() { Cell clone = new Cell(getName(), getRowSpan(), getColSpan()); for (String key : getProperties().keySet()) { clone.setProperty(key, getProperty(key)); } for (String key : getContent().keySet()) { clone.setContent(key, getContent(key)); } for (String type : getTypes()) { clone.setType(type); } return clone; } /** * Retrieve the properties defined for this cell. * * @return The properties map for this cell */ public Map<String, String> getProperties() { return properties; } /** * Retrieve the content elements defined for this cell. * * @return The content element map for this cell */ public Map<String, Object> getContent() { return content; } /** * Retrieve the types defined for this cell. * * @return The type set for this cell */ public Set<String> getTypes() { return types; } /** * Retrieve the name of the cell. * * @return The name of the cell */ public String getName() { return name; } /** * Retrieve the number of rows that this cell spans. * * @return The number of rows that this cell spans */ public int getRowSpan() { return rowSpan; } /** * Retrieve the number of columns that this cell spans. * * @return The number of columns that this cell spans */ public int getColSpan() { return colSpan; } /** * Set a type for this cell. Types are string-valued markers, and any number of types * can be attached to a cell using this method. Inside the Velocity template, * cells can be checked for types using the {@link #isType(String)} method. This * allows the template to handle cells with different types differently (e. g. in the * layout). * * @param type The type to add for this cell */ public void setType(String type) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } types.add(type); } /** * Check whether a given type is set for this cell. This is useful inside Velocity * templates to allow for type-specific handling of cell layout. * * @param type The type to check for in this cell * * @return A boolean indicating whether the given type has been set for this cell */ public boolean isType(String type) { if (type == null) { throw new IllegalArgumentException("type may not be null"); } return types.contains(type); } /** * Retrieve a property value. * * @param key The key for this peoperty * * @return The value for the given key */ public String getProperty(String key) { if (key == null) { throw new IllegalArgumentException("key may not be null"); } if (!properties.containsKey(key)) { throw new IllegalArgumentException("Unknown property key: " + key); } return properties.get(key); } /** * Set a property value. Properties are another means to equip a cell with * configuration information or content data, and any number of key/value pairs * can be attached to a cell and used in Velocity templates when processing the cell. * * @param key The property key * @param value The property value */ public void setProperty(String key, String value) { if (key == null) { throw new IllegalArgumentException("key may not be null"); } if (value == null) { throw new IllegalArgumentException("value may not be null"); } properties.put(key, value); } /** * Retrieve the content object associated with the given key. * * @param key The key identifying the content object * * @return The content object associated with the given key */ public Object getContent(String key) { if (key == null) { throw new IllegalArgumentException("key may not be null"); } return content.get(key); } /** * Set a content object. Content objects are used to attach data to a cell * which can then be used in the template, for example to attach a picture * or a table with the results of a DB query to an HTML cell. The controller * program which sets up the table/cell structure would add such content objects * to the cells, and the Velocity template would retrieve the data using the * keys and add it to the HTML cell structure. * * @param key The key by which this content object is identified * @param value The actual content object */ public void setContent(String key, Object value) { if (key == null) { throw new IllegalArgumentException("key may not be null"); } if (value == null) { throw new IllegalArgumentException("value may not be null"); } content.put(key, value); } /** * Set the number of rows that this cell spans. The original value set in the * constructor my change when cells are clipped during insertion into the table. * * @see BoundaryCondition * * @param rowSpan The number of rows that this cell spans */ public void setRowSpan(int rowSpan) { if (rowSpan < 1) { throw new IllegalArgumentException("rowSpan must be greater than 0"); } this.rowSpan = rowSpan; } /** * Set the number of columns that this cell spans. The original value set in the * constructor my change when cells are clipped during insertion into the table. * * @see BoundaryCondition * * @param colSpan The number of columns that this cell spans */ public void setColSpan(int colSpan) { if (colSpan < 1) { throw new IllegalArgumentException("colSpan must be greater than 0"); } this.colSpan = colSpan; } /** * The overridden {@link Object#toString()} method. * * @return A string representation of the instance with all relevant data */ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Cell: name = "); sb.append(name); sb.append(" / rowSpan = "); sb.append(rowSpan); sb.append(" / colSpan = "); sb.append(colSpan); return sb.toString(); }
}
/**
* Copyright 2007 Dr. Matthias Laux * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
/**
* An enum constant for the two possible boundary locations where columns are of relevance. */ enum ColumnLocation implements BoundaryLocation { /** * The left edge of the table */ LEFT, /** * The right edge of the table */ RIGHT;
}
</source>
Normalize Post Data
<source lang="java">
/*
JSPWiki - a JSP-based WikiWiki clone. Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
import java.security.SecureRandom; import java.util.Properties; import java.util.Random; public class StringUtils {
/** * Makes sure that the POSTed data is conforms to certain rules. These * rules are:*
-
*
- The data always ends with a newline (some browsers, such * as NS4.x series, does not send a newline at the end, which makes * the diffs a bit strange sometimes. *
- The CR/LF/CRLF mess is normalized to plain CRLF. *
* * The reason why we"re using CRLF is that most browser already * return CRLF since that is the closest thing to a HTTP standard. * * @param postData The data to normalize * @return Normalized data */ public static String normalizePostData( String postData ) { StringBuffer sb = new StringBuffer(); for( int i = 0; i < postData.length(); i++ ) { switch( postData.charAt(i) ) { case 0x0a: // LF, UNIX sb.append( "\r\n" ); break; case 0x0d: // CR, either Mac or MSDOS sb.append( "\r\n" ); // If it"s MSDOS, skip the LF so that we don"t add it again. if( i < postData.length()-1 && postData.charAt(i+1) == 0x0a ) { i++; } break; default: sb.append( postData.charAt(i) ); break; } } if( sb.length() < 2 || !sb.substring( sb.length()-2 ).equals("\r\n") ) { sb.append( "\r\n" ); } return sb.toString(); }
}
</source>
Prints a conversion table of miles per gallon to kilometers per liter
<source lang="java">
/**
- Copyright (c) 2002 by Phil Hanna
- All rights reserved.
- You may study, use, modify, and distribute this
- software for any purpose provided that this
- copyright notice appears in all copies.
- This software is provided without warranty
- either expressed or implied.
- /
package com.jspcr.servlets; import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /**
- Prints a conversion table of miles per gallon
- to kilometers per liter
- /
public class K2MServlet extends HttpServlet {
/** * Numeric format used to display temperatures */ private static final DecimalFormat FMT = new DecimalFormat("#0.00"); /** * Factor to convert from km/l to mi/gal */ private static final double CONVERSION_FACTOR = 2.352145; /** * Handles a GET request */ public void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set up for creating HTML output response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Generate heading out.println ( "<html>" + "<head>" + "<title>Fuel Efficiency Conversion Chart</title>" + "</head>" + "<body>"+ "
Fuel Efficiency Conversion Chart
" + "Kilometers per Liter | " + "Miles per Gallon | " + "
---|---|
" + FMT.format(kmpl) + " | " + "" + FMT.format(mpg) + " | " + "
+ "</body>" + "</html>" ); }
}
</source>
Servlet Display Static HTML
Servlet Output HTML Demo
Servlet: Print Table
<source lang="java"> /* <servlet> <servlet-name>PrintTable</servlet-name> <servlet-class>PrintTable</servlet-class> </servlet> <servlet-mapping> <servlet-name>PrintTable</servlet-name> <url-pattern>/PrintTable</url-pattern> </servlet-mapping>
- /
import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Vector; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class PrintTable extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printTable(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printTable(request, response); } public void printTable(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HtmlUtils hu = new HtmlUtils(); out.print(hu.createHtmlHeader("Print Table")); out.print(hu.getTableHead("center", 1)); out.print(hu.getTH("center", "First Name")); out.print(hu.getTH("center", "Last Name")); out.print(hu.getTH("center", "Favorite Color")); out.print(hu.getTH("center", "Gender")); Vector av = new Vector(); av.addElement("John"); av.addElement("Sample"); av.addElement("Purple"); av.addElement("Male"); av.addElement("Joe"); av.addElement("Bloggs"); av.addElement("Green"); av.addElement("Male"); av.addElement("Fanny"); av.addElement("May"); av.addElement("Blue"); av.addElement("Female"); av.addElement("Joeline"); av.addElement("Bloggs"); av.addElement("Red"); av.addElement("Female"); out.print(hu.getTableContents("center", av, 4)); out.print(hu.getHtmlFooter()); }
} class HtmlUtils {
public String createHtmlHeader(String title) { String htmlHeader = null; htmlHeader = "<HTML><HEAD><TITLE> " + title + " </TITLE></HEAD><BODY>"; return htmlHeader; } public String getHtmlFooter() { String htmlFooter = "</BODY></HTML>"; return htmlFooter; } public String getHead(int level, String heading) { return "<H" + level + "> " + heading + "</H" + level + ">"; } public String getTableHead(String align, int border) { String tableHeader = null;tableHeader = "
" + value + " | ";";
return TDCell; } public String getTD(int width) { String TDCell = null;TDCell = " | ";
return TDCell; } public String getTH(String align, String value) { String THCell = null;THCell = " | " + value + " | ";|||
---|---|---|---|---|---|---|
" + value + " | \n");
").append(getMonth()) .append(" | ||||||
").append(days[i]).append(" | ");||||||
") .append(m_sdf.format(t).toString()).append(" | "); if (m_gc.get(Calendar.DAY_OF_MONTH) == m_gc.getActualMaximum(Calendar.DAY_OF_MONTH)) { finish = true; break; } m_gc.roll(Calendar.DAY_OF_MONTH,true); } else { sb.append(""); |
return sb.toString(); }
}
</source>