1 16 17 package org.apache.jetspeed.util; 18 19 20 28 public class URIEncoder { 29 30 31 43 public static final String [] INVALID_CHARACTERS = { "\\", 44 "/", 45 ":", 46 "*", 47 "\"", 48 "<", 49 ">", 50 "|", 51 "+", 52 "?" }; 53 public static final String [] CODED_CHARACTERS = { "#" + (int)'\\' + ";", 54 "#" + (int)'/' + ";", 55 "#" + (int)':' + ";", 56 "#" + (int)'*' + ";", 57 "#" + (int)'"' + ";", 58 "#" + (int)'<' + ";", 59 "#" + (int)'>' + ";", 60 "#" + (int)'|' + ";", 61 "#" + (int)'+' + ";", 62 "#" + (int)'?' + ";" 63 }; 64 65 68 public static String encode( String uri ) { 69 70 if ( uri == null ) { 71 throw new IllegalArgumentException ( "URI may not be null. " ); 72 } 73 74 89 90 StringBuffer buffer = new StringBuffer ( uri ); 91 StringUtils.replaceAll( buffer, "_", "__" ); 92 StringUtils.replaceAll( buffer, "://", "_" ); 93 StringUtils.replaceAll( buffer, "/", "_" ); 94 StringUtils.replaceAll( buffer, ":", "___" ); 95 96 97 encodeQueryData( buffer ); 100 101 102 return buffer.toString(); 103 } 104 105 106 109 public static String decode( String uri ) { 110 111 if ( uri == null ) { 112 throw new IllegalArgumentException ( "URI may not be null. " ); 113 } 114 115 String newURI = ""; 116 117 int start = uri.indexOf("_"); 118 119 String protocol = null; 120 121 if( uri.charAt( start + 1 ) == '_' ) { 123 start = -1; 124 } 125 126 if ( start > -1 ) { 127 protocol = uri.substring( 0, start ); 128 } 129 130 newURI = uri.substring( start + 1, uri.length() ); 131 StringBuffer buffer = new StringBuffer ( newURI ); 132 133 StringUtils.replaceAll( buffer, "___", ":" ); 134 135 StringUtils.replaceAll( buffer, "_", "/" ); 136 StringUtils.replaceAll( buffer, "_", "/" ); 137 138 StringUtils.replaceAll( buffer, "//", "_" ); 140 141 if ( protocol != null ) { 142 buffer.replace( 0, 0, "://" ); buffer.replace( 0, 0, protocol ); } 145 146 decodeQueryData( buffer ); 147 148 return buffer.toString(); 149 } 150 151 163 private static StringBuffer encodeQueryData( StringBuffer data ) { 164 165 for (int i = 0; i < INVALID_CHARACTERS.length; ++i ) { 166 167 String source = INVALID_CHARACTERS[i]; 168 169 String coded = CODED_CHARACTERS[i]; 170 171 data = StringUtils.replaceAll( data, source, coded ); 172 173 } 174 175 return data; 176 } 177 178 190 private static StringBuffer decodeQueryData( StringBuffer data ) { 191 192 for (int i = 0; i < INVALID_CHARACTERS.length; ++i ) { 193 194 String source = INVALID_CHARACTERS[i]; 195 196 String coded = CODED_CHARACTERS[i]; 197 198 data = StringUtils.replaceAll( data, coded, source ); 199 200 } 201 202 return data; 203 } 204 205 206 } 207 | Popular Tags |