1 17 18 package org.apache.tomcat.util.buf; 19 20 import java.io.CharArrayWriter ; 21 import java.io.IOException ; 22 import java.io.Writer ; 23 import java.util.BitSet ; 24 25 35 public final class UEncoder { 36 37 private static org.apache.commons.logging.Log log= 38 org.apache.commons.logging.LogFactory.getLog(UEncoder.class ); 39 40 private BitSet safeChars=null; 43 private C2BConverter c2b=null; 44 private ByteChunk bb=null; 45 46 private String encoding="UTF8"; 47 private static final int debug=0; 48 49 public UEncoder() { 50 initSafeChars(); 51 } 52 53 public void setEncoding( String s ) { 54 encoding=s; 55 } 56 57 public void addSafeCharacter( char c ) { 58 safeChars.set( c ); 59 } 60 61 62 68 public void urlEncode( Writer buf, String s ) 69 throws IOException 70 { 71 if( c2b==null ) { 72 bb=new ByteChunk(16); c2b=new C2BConverter( bb, encoding ); 74 } 75 76 for (int i = 0; i < s.length(); i++) { 77 int c = (int) s.charAt(i); 78 if( safeChars.get( c ) ) { 79 if( debug > 0 ) log("Safe: " + (char)c); 80 buf.write((char)c); 81 } else { 82 if( debug > 0 ) log("Unsafe: " + (char)c); 83 c2b.convert( (char)c ); 84 85 if (c >= 0xD800 && c <= 0xDBFF) { 88 if ( (i+1) < s.length()) { 89 int d = (int) s.charAt(i+1); 90 if (d >= 0xDC00 && d <= 0xDFFF) { 91 if( debug > 0 ) log("Unsafe: " + c); 92 c2b.convert( (char)d); 93 i++; 94 } 95 } 96 } 97 98 c2b.flushBuffer(); 99 100 urlEncode( buf, bb.getBuffer(), bb.getOffset(), 101 bb.getLength() ); 102 bb.recycle(); 103 } 104 } 105 } 106 107 109 public void urlEncode( Writer buf, byte bytes[], int off, int len) 110 throws IOException 111 { 112 for( int j=off; j< len; j++ ) { 113 buf.write( '%' ); 114 char ch = Character.forDigit((bytes[j] >> 4) & 0xF, 16); 115 if( debug > 0 ) log("Encode: " + ch); 116 buf.write(ch); 117 ch = Character.forDigit(bytes[j] & 0xF, 16); 118 if( debug > 0 ) log("Encode: " + ch); 119 buf.write(ch); 120 } 121 } 122 123 128 public String encodeURL(String uri) { 129 String outUri=null; 130 try { 131 CharArrayWriter out = new CharArrayWriter (); 133 urlEncode(out, uri); 134 outUri=out.toString(); 135 } catch (IOException iex) { 136 } 137 return outUri; 138 } 139 140 141 143 private void init() { 145 146 } 147 148 private void initSafeChars() { 149 safeChars=new BitSet (128); 150 int i; 151 for (i = 'a'; i <= 'z'; i++) { 152 safeChars.set(i); 153 } 154 for (i = 'A'; i <= 'Z'; i++) { 155 safeChars.set(i); 156 } 157 for (i = '0'; i <= '9'; i++) { 158 safeChars.set(i); 159 } 160 safeChars.set('$'); 162 safeChars.set('-'); 163 safeChars.set('_'); 164 safeChars.set('.'); 165 166 safeChars.set('!'); 171 safeChars.set('*'); 172 safeChars.set('\''); 173 safeChars.set('('); 174 safeChars.set(')'); 175 safeChars.set(','); 176 } 177 178 private static void log( String s ) { 179 if (log.isDebugEnabled()) 180 log.debug("Encoder: " + s ); 181 } 182 } 183 | Popular Tags |