litesoft
@ 948
litesoft / trunk / GWT_Sandbox / FormEngine / src / com / temp / shared / utils / HtmlEntity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
package com.temp.shared.utils; public enum HtmlEntity { AMP( '&', "&" ), // LT( '<', "<" ), // GT( '>', ">" ), // QUOT( '"', """ ); private char character; private String string; private HtmlEntity( char character, String string ) { this.character = character; this.string = string; } public char getCharacter() { return character; } public String getString() { return string; } public boolean wouldMatch( String entity ) { return string.equalsIgnoreCase( entity ); } public static void append( char c, StringBuilder sb ) { switch ( c ) { case '&': sb.append( AMP.getString() ); break; case '<': sb.append( LT.getString() ); break; case '>': sb.append( GT.getString() ); break; case '"': sb.append( QUOT.getString() ); break; default: if ( (c == '\n') || ((' ' <= c) && (c <= 126)) ) { sb.append( c ); } else { sb.append( toDecimalForm( c ) ); } break; } } public static char fromStringForm( String entity ) { if ( AMP.wouldMatch( entity ) ) { return AMP.getCharacter(); } if ( LT.wouldMatch( entity ) ) { return LT.getCharacter(); } if ( GT.wouldMatch( entity ) ) { return GT.getCharacter(); } if ( QUOT.wouldMatch( entity ) ) { return QUOT.getCharacter(); } return fromDecimalForm( entity ); } public static String toDecimalForm( char c ) { return "&#" + ((int) c) + ';'; } public static char fromDecimalForm( String decimalForm ) { if ( (decimalForm != null) && (decimalForm.length() > 3) && decimalForm.startsWith( "&#" ) && decimalForm.endsWith( ";" ) ) { try { int value = Integer.parseInt( decimalForm.substring( 2, decimalForm.length() - 1 ) ); if ( (Character.MIN_VALUE <= value) && (value <= Character.MAX_VALUE) ) { return (char) value; } } catch ( NumberFormatException whatever ) { // Fall Thru } } throw new IllegalArgumentException( "Not a Html Decimal Entity: '" + decimalForm + "'" ); } public static final String NBSP = " "; } |