1 20 21 package org.apache.directory.ldapstudio.browser.core.utils; 22 23 24 import java.io.UnsupportedEncodingException ; 25 import java.net.URLEncoder ; 26 27 import org.apache.commons.codec.binary.Base64; 28 import org.apache.commons.codec.binary.Hex; 29 import org.apache.directory.ldapstudio.browser.core.BrowserCoreConstants; 30 import org.apache.directory.ldapstudio.browser.core.model.IValue; 31 32 33 39 public class LdifUtils 40 { 41 42 43 50 public static byte[] utf8encode( String s ) 51 { 52 try 53 { 54 return s.getBytes( "UTF-8" ); 55 } 56 catch ( UnsupportedEncodingException e ) 57 { 58 return s.getBytes(); 59 } 60 } 61 62 63 70 public static String urlEncode( String s ) 71 { 72 try 73 { 74 return URLEncoder.encode( s, "UTF-8" ); 75 } 76 catch ( UnsupportedEncodingException e ) 77 { 78 return s; 79 } 80 } 81 82 83 90 public static String base64encode( byte[] b ) 91 { 92 return utf8decode( Base64.encodeBase64( b ) ); 93 } 94 95 96 103 public static String hexEncode( byte[] data ) 104 { 105 if ( data == null ) 106 return null; 107 108 char[] c = Hex.encodeHex( data ); 109 String s = new String ( c ); 110 return s; 111 112 } 124 125 126 133 public static String utf8decode( byte[] b ) 134 { 135 try 136 { 137 return new String ( b, "UTF-8" ); 138 } 139 catch ( UnsupportedEncodingException e ) 140 { 141 return new String ( b ); 142 } 143 } 144 145 146 154 public static byte[] base64decodeToByteArray( String s ) 155 { 156 return Base64.decodeBase64( utf8encode( s ) ); 157 } 158 159 160 167 public static boolean mustEncodeDN( String dn ) 168 { 169 return mustEncode( dn ); 170 } 171 172 173 181 public static boolean mustEncode( String value ) 182 { 183 if ( value == null || value.length() < 1 ) 184 { 185 return false; 186 } 187 188 if ( value.startsWith( " " ) || value.startsWith( ":" ) || value.startsWith( "<" ) ) 189 { 190 return true; 191 } 192 if ( value.endsWith( " " ) ) 193 { 194 return true; 195 } 196 197 for ( int i = 0; i < value.length(); i++ ) 198 { 199 if ( value.charAt( i ) == '\r' || value.charAt( i ) == '\n' || value.charAt( i ) == '\u0000' 200 || value.charAt( i ) > '\u007F' ) 201 { 202 return true; 203 } 204 } 205 206 return false; 207 } 208 209 210 220 public static String getStringValue( IValue value, int binaryEncoding ) 221 { 222 String s = value.getStringValue(); 223 if ( value.isBinary() && LdifUtils.mustEncode( s ) ) 224 { 225 byte[] binary = value.getBinaryValue(); 226 if ( binaryEncoding == BrowserCoreConstants.BINARYENCODING_BASE64 ) 227 { 228 s = LdifUtils.base64encode( binary ); 229 } 230 else if ( binaryEncoding == BrowserCoreConstants.BINARYENCODING_HEX ) 231 { 232 s = LdifUtils.hexEncode( binary ); 233 } 234 else 235 { 236 s = BrowserCoreConstants.BINARY; 237 } 238 } 239 return s; 240 } 241 242 } 243 | Popular Tags |