├── AndroidMarketApi
├── .classpath
├── .project
├── .settings
│ └── org.eclipse.jdt.core.prefs
├── AndroidMarketApi.jar
├── AndroidMarketApi.jardesc
├── AndroidMarketApi.mf
├── bin
│ └── com
│ │ └── gc
│ │ └── android
│ │ └── market
│ │ └── api
│ │ ├── Base64$1.class
│ │ ├── Base64$InputStream.class
│ │ ├── Base64$OutputStream.class
│ │ ├── Base64.class
│ │ ├── Main$1.class
│ │ ├── Main.class
│ │ ├── MarketSession$Callback.class
│ │ ├── MarketSession.class
│ │ ├── Tools.class
│ │ └── model
│ │ ├── Market$1.class
│ │ ├── Market$App$Builder.class
│ │ ├── Market$App$ExtendedInfo$Builder.class
│ │ ├── Market$App$ExtendedInfo.class
│ │ ├── Market$App.class
│ │ ├── Market$AppType$1.class
│ │ ├── Market$AppType.class
│ │ ├── Market$AppsRequest$Builder.class
│ │ ├── Market$AppsRequest$OrderType$1.class
│ │ ├── Market$AppsRequest$OrderType.class
│ │ ├── Market$AppsRequest$ViewType$1.class
│ │ ├── Market$AppsRequest$ViewType.class
│ │ ├── Market$AppsRequest.class
│ │ ├── Market$AppsResponse$Builder.class
│ │ ├── Market$AppsResponse.class
│ │ ├── Market$CategoriesRequest$Builder.class
│ │ ├── Market$CategoriesRequest.class
│ │ ├── Market$CategoriesResponse$Builder.class
│ │ ├── Market$CategoriesResponse.class
│ │ ├── Market$Category$Builder.class
│ │ ├── Market$Category.class
│ │ ├── Market$Comment$Builder.class
│ │ ├── Market$Comment.class
│ │ ├── Market$CommentsRequest$Builder.class
│ │ ├── Market$CommentsRequest.class
│ │ ├── Market$CommentsResponse$Builder.class
│ │ ├── Market$CommentsResponse.class
│ │ ├── Market$Request$Builder.class
│ │ ├── Market$Request$RequestGroup$Builder.class
│ │ ├── Market$Request$RequestGroup.class
│ │ ├── Market$Request.class
│ │ ├── Market$RequestContext$Builder.class
│ │ ├── Market$RequestContext.class
│ │ ├── Market$Response$Builder.class
│ │ ├── Market$Response$ResponseGroup$Builder.class
│ │ ├── Market$Response$ResponseGroup.class
│ │ ├── Market$Response.class
│ │ ├── Market$ResponseContext$Builder.class
│ │ ├── Market$ResponseContext.class
│ │ ├── Market$SubCategoriesRequest$Builder.class
│ │ ├── Market$SubCategoriesRequest.class
│ │ ├── Market$SubCategoriesResponse$Builder.class
│ │ ├── Market$SubCategoriesResponse.class
│ │ └── Market.class
├── proto
│ ├── market.proto
│ └── protoc.exe
├── protobuf-java-2.2.0.jar
└── src
│ └── com
│ └── gc
│ └── android
│ └── market
│ └── api
│ ├── Base64.java
│ ├── LoginException.java
│ ├── Main.java
│ ├── MarketSession.java
│ ├── Tools.java
│ └── model
│ └── Market.java
└── README.md
/AndroidMarketApi/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
Encodes and decodes to and from Base64 notation.
4 | *Homepage: http://iharder.net/base64.
5 | * 6 | *Example:
7 | * 8 | *String encoded = Base64.encode( myByteArray );
9 | * byte[] myByteArray = Base64.decode( encoded );
11 | *
12 | * The options parameter, which appears in a few places, is used to pass 13 | * several pieces of information to the encoder. In the "higher level" methods such as 14 | * encodeBytes( bytes, options ) the options parameter can be used to indicate such 15 | * things as first gzipping the bytes before encoding them, not inserting linefeeds, 16 | * and encoding using the URL-safe and Ordered dialects.
17 | * 18 | *Note, according to RFC3548, 19 | * Section 2.1, implementations should not add line feeds unless explicitly told 20 | * to do so. I've got Base64 set to this behavior now, although earlier versions 21 | * broke lines by default.
22 | * 23 | *The constants defined in Base64 can be OR-ed together to combine options, so you 24 | * might make a call like this:
25 | * 26 | *String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );
27 | * to compress the data before encoding it and then making the output have newline characters.
28 | *Also...
29 | *String encoded = Base64.encodeBytes( crazyString.getBytes() );
30 | *
31 | *
32 | *
33 | * 34 | * Change Log: 35 | *
36 | *127 | * I am placing this code in the Public Domain. Do with it as you will. 128 | * This software comes with no guarantees or warranties but with 129 | * plenty of well-wishing instead! 130 | * Please visit http://iharder.net/base64 131 | * periodically to check for updates or to contribute improvements. 132 | *
133 | * 134 | * @author Robert Harder 135 | * @author rob@iharder.net 136 | * @version 2.3.3 137 | */ 138 | public class Base64 139 | { 140 | 141 | /* ******** P U B L I C F I E L D S ******** */ 142 | 143 | 144 | /** No options specified. Value is zero. */ 145 | public final static int NO_OPTIONS = 0; 146 | 147 | /** Specify encoding in first bit. Value is one. */ 148 | public final static int ENCODE = 1; 149 | 150 | 151 | /** Specify decoding in first bit. Value is zero. */ 152 | public final static int DECODE = 0; 153 | 154 | 155 | /** Specify that data should be gzip-compressed in second bit. Value is two. */ 156 | public final static int GZIP = 2; 157 | 158 | /** Specify that gzipped data should not be automatically gunzipped. */ 159 | public final static int DONT_GUNZIP = 4; 160 | 161 | 162 | /** Do break lines when encoding. Value is 8. */ 163 | public final static int DO_BREAK_LINES = 8; 164 | 165 | /** 166 | * Encode using Base64-like encoding that is URL- and Filename-safe as described 167 | * in Section 4 of RFC3548: 168 | * http://www.faqs.org/rfcs/rfc3548.html. 169 | * It is important to note that data encoded this way is not officially valid Base64, 170 | * or at the very least should not be called Base64 without also specifying that is 171 | * was encoded using the URL- and Filename-safe dialect. 172 | */ 173 | public final static int URL_SAFE = 16; 174 | 175 | 176 | /** 177 | * Encode using the special "ordered" dialect of Base64 described here: 178 | * http://www.faqs.org/qa/rfcc-1940.html. 179 | */ 180 | public final static int ORDERED = 32; 181 | 182 | 183 | /* ******** P R I V A T E F I E L D S ******** */ 184 | 185 | 186 | /** Maximum line length (76) of Base64 output. */ 187 | private final static int MAX_LINE_LENGTH = 76; 188 | 189 | 190 | /** The equals sign (=) as a byte. */ 191 | private final static byte EQUALS_SIGN = (byte)'='; 192 | 193 | 194 | /** The new line character (\n) as a byte. */ 195 | private final static byte NEW_LINE = (byte)'\n'; 196 | 197 | 198 | /** Preferred encoding. */ 199 | private final static String PREFERRED_ENCODING = "US-ASCII"; 200 | 201 | 202 | private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding 203 | private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding 204 | 205 | 206 | /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */ 207 | 208 | /** The 64 valid Base64 values. */ 209 | /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ 210 | private final static byte[] _STANDARD_ALPHABET = { 211 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 212 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 213 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 214 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 215 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 216 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 217 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 218 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 219 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 220 | (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' 221 | }; 222 | 223 | 224 | /** 225 | * Translates a Base64 value to either its 6-bit reconstruction value 226 | * or a negative number indicating some other meaning. 227 | **/ 228 | private final static byte[] _STANDARD_DECODABET = { 229 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 230 | -5,-5, // Whitespace: Tab and Linefeed 231 | -9,-9, // Decimal 11 - 12 232 | -5, // Whitespace: Carriage Return 233 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 234 | -9,-9,-9,-9,-9, // Decimal 27 - 31 235 | -5, // Whitespace: Space 236 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 237 | 62, // Plus sign at decimal 43 238 | -9,-9,-9, // Decimal 44 - 46 239 | 63, // Slash at decimal 47 240 | 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 241 | -9,-9,-9, // Decimal 58 - 60 242 | -1, // Equals sign at decimal 61 243 | -9,-9,-9, // Decimal 62 - 64 244 | 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 245 | 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 246 | -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 247 | 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 248 | 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 249 | -9,-9,-9,-9 // Decimal 123 - 126 250 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 251 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 252 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 253 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 254 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 255 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 256 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 257 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 258 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 259 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 260 | }; 261 | 262 | 263 | /* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ 264 | 265 | /** 266 | * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: 267 | * http://www.faqs.org/rfcs/rfc3548.html. 268 | * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." 269 | */ 270 | private final static byte[] _URL_SAFE_ALPHABET = { 271 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 272 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 273 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 274 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 275 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 276 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 277 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 278 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', 279 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', 280 | (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' 281 | }; 282 | 283 | /** 284 | * Used in decoding URL- and Filename-safe dialects of Base64. 285 | */ 286 | private final static byte[] _URL_SAFE_DECODABET = { 287 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 288 | -5,-5, // Whitespace: Tab and Linefeed 289 | -9,-9, // Decimal 11 - 12 290 | -5, // Whitespace: Carriage Return 291 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 292 | -9,-9,-9,-9,-9, // Decimal 27 - 31 293 | -5, // Whitespace: Space 294 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 295 | -9, // Plus sign at decimal 43 296 | -9, // Decimal 44 297 | 62, // Minus sign at decimal 45 298 | -9, // Decimal 46 299 | -9, // Slash at decimal 47 300 | 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine 301 | -9,-9,-9, // Decimal 58 - 60 302 | -1, // Equals sign at decimal 61 303 | -9,-9,-9, // Decimal 62 - 64 304 | 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 305 | 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' 306 | -9,-9,-9,-9, // Decimal 91 - 94 307 | 63, // Underscore at decimal 95 308 | -9, // Decimal 96 309 | 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 310 | 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' 311 | -9,-9,-9,-9 // Decimal 123 - 126 312 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 313 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 314 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 315 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 316 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 317 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 318 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 319 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 320 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 321 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 322 | }; 323 | 324 | 325 | 326 | /* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ 327 | 328 | /** 329 | * I don't get the point of this technique, but someone requested it, 330 | * and it is described here: 331 | * http://www.faqs.org/qa/rfcc-1940.html. 332 | */ 333 | private final static byte[] _ORDERED_ALPHABET = { 334 | (byte)'-', 335 | (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', 336 | (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', 337 | (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', 338 | (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', 339 | (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', 340 | (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', 341 | (byte)'_', 342 | (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', 343 | (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', 344 | (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', 345 | (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' 346 | }; 347 | 348 | /** 349 | * Used in decoding the "ordered" dialect of Base64. 350 | */ 351 | private final static byte[] _ORDERED_DECODABET = { 352 | -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 353 | -5,-5, // Whitespace: Tab and Linefeed 354 | -9,-9, // Decimal 11 - 12 355 | -5, // Whitespace: Carriage Return 356 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 357 | -9,-9,-9,-9,-9, // Decimal 27 - 31 358 | -5, // Whitespace: Space 359 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 360 | -9, // Plus sign at decimal 43 361 | -9, // Decimal 44 362 | 0, // Minus sign at decimal 45 363 | -9, // Decimal 46 364 | -9, // Slash at decimal 47 365 | 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine 366 | -9,-9,-9, // Decimal 58 - 60 367 | -1, // Equals sign at decimal 61 368 | -9,-9,-9, // Decimal 62 - 64 369 | 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' 370 | 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' 371 | -9,-9,-9,-9, // Decimal 91 - 94 372 | 37, // Underscore at decimal 95 373 | -9, // Decimal 96 374 | 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' 375 | 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' 376 | -9,-9,-9,-9 // Decimal 123 - 126 377 | /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 378 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 379 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 380 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 381 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 382 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 383 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 384 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 385 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 386 | -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ 387 | }; 388 | 389 | 390 | /* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ 391 | 392 | 393 | /** 394 | * Returns one of the _SOMETHING_ALPHABET byte arrays depending on 395 | * the options specified. 396 | * It's possible, though silly, to specify ORDERED and URLSAFE 397 | * in which case one of them will be picked, though there is 398 | * no guarantee as to which one will be picked. 399 | */ 400 | private final static byte[] getAlphabet( int options ) { 401 | if ((options & URL_SAFE) == URL_SAFE) { 402 | return _URL_SAFE_ALPHABET; 403 | } else if ((options & ORDERED) == ORDERED) { 404 | return _ORDERED_ALPHABET; 405 | } else { 406 | return _STANDARD_ALPHABET; 407 | } 408 | } // end getAlphabet 409 | 410 | 411 | /** 412 | * Returns one of the _SOMETHING_DECODABET byte arrays depending on 413 | * the options specified. 414 | * It's possible, though silly, to specify ORDERED and URL_SAFE 415 | * in which case one of them will be picked, though there is 416 | * no guarantee as to which one will be picked. 417 | */ 418 | private final static byte[] getDecodabet( int options ) { 419 | if( (options & URL_SAFE) == URL_SAFE) { 420 | return _URL_SAFE_DECODABET; 421 | } else if ((options & ORDERED) == ORDERED) { 422 | return _ORDERED_DECODABET; 423 | } else { 424 | return _STANDARD_DECODABET; 425 | } 426 | } // end getAlphabet 427 | 428 | 429 | 430 | /** Defeats instantiation. */ 431 | private Base64(){} 432 | 433 | 434 | 435 | 436 | /* ******** E N C O D I N G M E T H O D S ******** */ 437 | 438 | 439 | /** 440 | * Encodes up to the first three bytes of array threeBytes 441 | * and returns a four-byte array in Base64 notation. 442 | * The actual number of significant bytes in your array is 443 | * given by numSigBytes. 444 | * The array threeBytes needs only be as big as 445 | * numSigBytes. 446 | * Code can reuse a byte array by passing a four-byte array as b4. 447 | * 448 | * @param b4 A reusable byte array to reduce array instantiation 449 | * @param threeBytes the array to convert 450 | * @param numSigBytes the number of significant bytes in your array 451 | * @return four byte array in Base64 notation. 452 | * @since 1.5.1 453 | */ 454 | private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { 455 | encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); 456 | return b4; 457 | } // end encode3to4 458 | 459 | 460 | /** 461 | *Encodes up to three bytes of the array source 462 | * and writes the resulting four Base64 bytes to destination. 463 | * The source and destination arrays can be manipulated 464 | * anywhere along their length by specifying 465 | * srcOffset and destOffset. 466 | * This method does not check to make sure your arrays 467 | * are large enough to accomodate srcOffset + 3 for 468 | * the source array or destOffset + 4 for 469 | * the destination array. 470 | * The actual number of significant bytes in your array is 471 | * given by numSigBytes.
472 | *This is the lowest level of the encoding methods with 473 | * all possible parameters.
474 | * 475 | * @param source the array to convert 476 | * @param srcOffset the index where conversion begins 477 | * @param numSigBytes the number of significant bytes in your array 478 | * @param destination the array to hold the conversion 479 | * @param destOffset the index where output will be put 480 | * @return the destination array 481 | * @since 1.3 482 | */ 483 | private static byte[] encode3to4( 484 | byte[] source, int srcOffset, int numSigBytes, 485 | byte[] destination, int destOffset, int options ) { 486 | 487 | byte[] ALPHABET = getAlphabet( options ); 488 | 489 | // 1 2 3 490 | // 01234567890123456789012345678901 Bit position 491 | // --------000000001111111122222222 Array position from threeBytes 492 | // --------| || || || | Six bit groups to index ALPHABET 493 | // >>18 >>12 >> 6 >> 0 Right shift necessary 494 | // 0x3f 0x3f 0x3f Additional AND 495 | 496 | // Create buffer with zero-padding if there are only one or two 497 | // significant bytes passed in the array. 498 | // We have to shift left 24 in order to flush out the 1's that appear 499 | // when Java treats a value as negative that is cast from a byte to an int. 500 | int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) 501 | | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) 502 | | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); 503 | 504 | switch( numSigBytes ) 505 | { 506 | case 3: 507 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 508 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 509 | destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; 510 | destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; 511 | return destination; 512 | 513 | case 2: 514 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 515 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 516 | destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; 517 | destination[ destOffset + 3 ] = EQUALS_SIGN; 518 | return destination; 519 | 520 | case 1: 521 | destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; 522 | destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; 523 | destination[ destOffset + 2 ] = EQUALS_SIGN; 524 | destination[ destOffset + 3 ] = EQUALS_SIGN; 525 | return destination; 526 | 527 | default: 528 | return destination; 529 | } // end switch 530 | } // end encode3to4 531 | 532 | 533 | 534 | /** 535 | * Performs Base64 encoding on theraw
ByteBuffer,
536 | * writing it to the encoded
ByteBuffer.
537 | * This is an experimental feature. Currently it does not
538 | * pass along any options (such as {@link #DO_BREAK_LINES}
539 | * or {@link #GZIP}.
540 | *
541 | * @param raw input buffer
542 | * @param encoded output buffer
543 | * @since 2.3
544 | */
545 | public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
546 | byte[] raw3 = new byte[3];
547 | byte[] enc4 = new byte[4];
548 |
549 | while( raw.hasRemaining() ){
550 | int rem = Math.min(3,raw.remaining());
551 | raw.get(raw3,0,rem);
552 | Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
553 | encoded.put(enc4);
554 | } // end input remaining
555 | }
556 |
557 |
558 | /**
559 | * Performs Base64 encoding on the raw
ByteBuffer,
560 | * writing it to the encoded
CharBuffer.
561 | * This is an experimental feature. Currently it does not
562 | * pass along any options (such as {@link #DO_BREAK_LINES}
563 | * or {@link #GZIP}.
564 | *
565 | * @param raw input buffer
566 | * @param encoded output buffer
567 | * @since 2.3
568 | */
569 | public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
570 | byte[] raw3 = new byte[3];
571 | byte[] enc4 = new byte[4];
572 |
573 | while( raw.hasRemaining() ){
574 | int rem = Math.min(3,raw.remaining());
575 | raw.get(raw3,0,rem);
576 | Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
577 | for( int i = 0; i < 4; i++ ){
578 | encoded.put( (char)(enc4[i] & 0xFF) );
579 | }
580 | } // end input remaining
581 | }
582 |
583 |
584 |
585 |
586 | /**
587 | * Serializes an object and returns the Base64-encoded
588 | * version of that serialized object.
589 | *
590 | * As of v 2.3, if the object 591 | * cannot be serialized or there is another error, 592 | * the method will throw an java.io.IOException. This is new to v2.3! 593 | * In earlier versions, it just returned a null value, but 594 | * in retrospect that's a pretty poor way to handle it.
595 | * 596 | * The object is not GZip-compressed before being encoded. 597 | * 598 | * @param serializableObject The object to encode 599 | * @return The Base64-encoded object 600 | * @throws java.io.IOException if there is an error 601 | * @throws NullPointerException if serializedObject is null 602 | * @since 1.4 603 | */ 604 | public static String encodeObject( java.io.Serializable serializableObject ) 605 | throws java.io.IOException { 606 | return encodeObject( serializableObject, NO_OPTIONS ); 607 | } // end encodeObject 608 | 609 | 610 | 611 | /** 612 | * Serializes an object and returns the Base64-encoded 613 | * version of that serialized object. 614 | * 615 | *As of v 2.3, if the object 616 | * cannot be serialized or there is another error, 617 | * the method will throw an java.io.IOException. This is new to v2.3! 618 | * In earlier versions, it just returned a null value, but 619 | * in retrospect that's a pretty poor way to handle it.
620 | * 621 | * The object is not GZip-compressed before being encoded. 622 | *623 | * Example options:
624 | * GZIP: gzip-compresses object before encoding it. 625 | * DO_BREAK_LINES: break lines at 76 characters 626 | *627 | *
628 | * Example: encodeObject( myObj, Base64.GZIP )
or
629 | *
630 | * Example: encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )
631 | *
632 | * @param serializableObject The object to encode
633 | * @param options Specified options
634 | * @return The Base64-encoded object
635 | * @see Base64#GZIP
636 | * @see Base64#DO_BREAK_LINES
637 | * @throws java.io.IOException if there is an error
638 | * @since 2.0
639 | */
640 | public static String encodeObject( java.io.Serializable serializableObject, int options )
641 | throws java.io.IOException {
642 |
643 | if( serializableObject == null ){
644 | throw new NullPointerException( "Cannot serialize a null object." );
645 | } // end if: null
646 |
647 | // Streams
648 | java.io.ByteArrayOutputStream baos = null;
649 | java.io.OutputStream b64os = null;
650 | java.util.zip.GZIPOutputStream gzos = null;
651 | java.io.ObjectOutputStream oos = null;
652 |
653 |
654 | try {
655 | // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
656 | baos = new java.io.ByteArrayOutputStream();
657 | b64os = new Base64.OutputStream( baos, ENCODE | options );
658 | if( (options & GZIP) != 0 ){
659 | // Gzip
660 | gzos = new java.util.zip.GZIPOutputStream(b64os);
661 | oos = new java.io.ObjectOutputStream( gzos );
662 | } else {
663 | // Not gzipped
664 | oos = new java.io.ObjectOutputStream( b64os );
665 | }
666 | oos.writeObject( serializableObject );
667 | } // end try
668 | catch( java.io.IOException e ) {
669 | // Catch it and then throw it immediately so that
670 | // the finally{} block is called for cleanup.
671 | throw e;
672 | } // end catch
673 | finally {
674 | try{ oos.close(); } catch( Exception e ){}
675 | try{ gzos.close(); } catch( Exception e ){}
676 | try{ b64os.close(); } catch( Exception e ){}
677 | try{ baos.close(); } catch( Exception e ){}
678 | } // end finally
679 |
680 | // Return value according to relevant encoding.
681 | try {
682 | return new String( baos.toByteArray(), PREFERRED_ENCODING );
683 | } // end try
684 | catch (java.io.UnsupportedEncodingException uue){
685 | // Fall back to some Java default
686 | return new String( baos.toByteArray() );
687 | } // end catch
688 |
689 | } // end encode
690 |
691 |
692 |
693 | /**
694 | * Encodes a byte array into Base64 notation.
695 | * Does not GZip-compress data.
696 | *
697 | * @param source The data to convert
698 | * @return The data in Base64-encoded form
699 | * @throws NullPointerException if source array is null
700 | * @since 1.4
701 | */
702 | public static String encodeBytes( byte[] source ) {
703 | // Since we're not going to have the GZIP encoding turned on,
704 | // we're not going to have an java.io.IOException thrown, so
705 | // we should not force the user to have to catch it.
706 | String encoded = null;
707 | try {
708 | encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
709 | } catch (java.io.IOException ex) {
710 | assert false : ex.getMessage();
711 | } // end catch
712 | assert encoded != null;
713 | return encoded;
714 | } // end encodeBytes
715 |
716 |
717 |
718 | /**
719 | * Encodes a byte array into Base64 notation.
720 | *
721 | * Example options:
722 | * GZIP: gzip-compresses object before encoding it. 723 | * DO_BREAK_LINES: break lines at 76 characters 724 | * Note: Technically, this makes your encoding non-compliant. 725 | *726 | *
727 | * Example: encodeBytes( myData, Base64.GZIP )
or
728 | *
729 | * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )
730 | *
731 | *
732 | *
As of v 2.3, if there is an error with the GZIP stream, 733 | * the method will throw an java.io.IOException. This is new to v2.3! 734 | * In earlier versions, it just returned a null value, but 735 | * in retrospect that's a pretty poor way to handle it.
736 | * 737 | * 738 | * @param source The data to convert 739 | * @param options Specified options 740 | * @return The Base64-encoded data as a String 741 | * @see Base64#GZIP 742 | * @see Base64#DO_BREAK_LINES 743 | * @throws java.io.IOException if there is an error 744 | * @throws NullPointerException if source array is null 745 | * @since 2.0 746 | */ 747 | public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { 748 | return encodeBytes( source, 0, source.length, options ); 749 | } // end encodeBytes 750 | 751 | 752 | /** 753 | * Encodes a byte array into Base64 notation. 754 | * Does not GZip-compress data. 755 | * 756 | *As of v 2.3, if there is an error, 757 | * the method will throw an java.io.IOException. This is new to v2.3! 758 | * In earlier versions, it just returned a null value, but 759 | * in retrospect that's a pretty poor way to handle it.
760 | * 761 | * 762 | * @param source The data to convert 763 | * @param off Offset in array where conversion should begin 764 | * @param len Length of data to convert 765 | * @return The Base64-encoded data as a String 766 | * @throws NullPointerException if source array is null 767 | * @throws IllegalArgumentException if source array, offset, or length are invalid 768 | * @since 1.4 769 | */ 770 | public static String encodeBytes( byte[] source, int off, int len ) { 771 | // Since we're not going to have the GZIP encoding turned on, 772 | // we're not going to have an java.io.IOException thrown, so 773 | // we should not force the user to have to catch it. 774 | String encoded = null; 775 | try { 776 | encoded = encodeBytes( source, off, len, NO_OPTIONS ); 777 | } catch (java.io.IOException ex) { 778 | assert false : ex.getMessage(); 779 | } // end catch 780 | assert encoded != null; 781 | return encoded; 782 | } // end encodeBytes 783 | 784 | 785 | 786 | /** 787 | * Encodes a byte array into Base64 notation. 788 | *789 | * Example options:
790 | * GZIP: gzip-compresses object before encoding it. 791 | * DO_BREAK_LINES: break lines at 76 characters 792 | * Note: Technically, this makes your encoding non-compliant. 793 | *794 | *
795 | * Example: encodeBytes( myData, Base64.GZIP )
or
796 | *
797 | * Example: encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )
798 | *
799 | *
800 | *
As of v 2.3, if there is an error with the GZIP stream, 801 | * the method will throw an java.io.IOException. This is new to v2.3! 802 | * In earlier versions, it just returned a null value, but 803 | * in retrospect that's a pretty poor way to handle it.
804 | * 805 | * 806 | * @param source The data to convert 807 | * @param off Offset in array where conversion should begin 808 | * @param len Length of data to convert 809 | * @param options Specified options 810 | * @return The Base64-encoded data as a String 811 | * @see Base64#GZIP 812 | * @see Base64#DO_BREAK_LINES 813 | * @throws java.io.IOException if there is an error 814 | * @throws NullPointerException if source array is null 815 | * @throws IllegalArgumentException if source array, offset, or length are invalid 816 | * @since 2.0 817 | */ 818 | public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { 819 | byte[] encoded = encodeBytesToBytes( source, off, len, options ); 820 | 821 | // Return value according to relevant encoding. 822 | try { 823 | return new String( encoded, PREFERRED_ENCODING ); 824 | } // end try 825 | catch (java.io.UnsupportedEncodingException uue) { 826 | return new String( encoded ); 827 | } // end catch 828 | 829 | } // end encodeBytes 830 | 831 | 832 | 833 | 834 | /** 835 | * Similar to {@link #encodeBytes(byte[])} but returns 836 | * a byte array instead of instantiating a String. This is more efficient 837 | * if you're working with I/O streams and have large data sets to encode. 838 | * 839 | * 840 | * @param source The data to convert 841 | * @return The Base64-encoded data as a byte[] (of ASCII characters) 842 | * @throws NullPointerException if source array is null 843 | * @since 2.3.1 844 | */ 845 | public static byte[] encodeBytesToBytes( byte[] source ) { 846 | byte[] encoded = null; 847 | try { 848 | encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); 849 | } catch( java.io.IOException ex ) { 850 | assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 851 | } 852 | return encoded; 853 | } 854 | 855 | 856 | /** 857 | * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns 858 | * a byte array instead of instantiating a String. This is more efficient 859 | * if you're working with I/O streams and have large data sets to encode. 860 | * 861 | * 862 | * @param source The data to convert 863 | * @param off Offset in array where conversion should begin 864 | * @param len Length of data to convert 865 | * @param options Specified options 866 | * @return The Base64-encoded data as a String 867 | * @see Base64#GZIP 868 | * @see Base64#DO_BREAK_LINES 869 | * @throws java.io.IOException if there is an error 870 | * @throws NullPointerException if source array is null 871 | * @throws IllegalArgumentException if source array, offset, or length are invalid 872 | * @since 2.3.1 873 | */ 874 | public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { 875 | 876 | if( source == null ){ 877 | throw new NullPointerException( "Cannot serialize a null array." ); 878 | } // end if: null 879 | 880 | if( off < 0 ){ 881 | throw new IllegalArgumentException( "Cannot have negative offset: " + off ); 882 | } // end if: off < 0 883 | 884 | if( len < 0 ){ 885 | throw new IllegalArgumentException( "Cannot have length offset: " + len ); 886 | } // end if: len < 0 887 | 888 | if( off + len > source.length ){ 889 | throw new IllegalArgumentException( 890 | String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); 891 | } // end if: off < 0 892 | 893 | 894 | 895 | // Compress? 896 | if( (options & GZIP) != 0 ) { 897 | java.io.ByteArrayOutputStream baos = null; 898 | java.util.zip.GZIPOutputStream gzos = null; 899 | Base64.OutputStream b64os = null; 900 | 901 | try { 902 | // GZip -> Base64 -> ByteArray 903 | baos = new java.io.ByteArrayOutputStream(); 904 | b64os = new Base64.OutputStream( baos, ENCODE | options ); 905 | gzos = new java.util.zip.GZIPOutputStream( b64os ); 906 | 907 | gzos.write( source, off, len ); 908 | gzos.close(); 909 | } // end try 910 | catch( java.io.IOException e ) { 911 | // Catch it and then throw it immediately so that 912 | // the finally{} block is called for cleanup. 913 | throw e; 914 | } // end catch 915 | finally { 916 | try{ gzos.close(); } catch( Exception e ){} 917 | try{ b64os.close(); } catch( Exception e ){} 918 | try{ baos.close(); } catch( Exception e ){} 919 | } // end finally 920 | 921 | return baos.toByteArray(); 922 | } // end if: compress 923 | 924 | // Else, don't compress. Better not to use streams at all then. 925 | else { 926 | boolean breakLines = (options & DO_BREAK_LINES) > 0; 927 | 928 | //int len43 = len * 4 / 3; 929 | //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 930 | // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding 931 | // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines 932 | // Try to determine more precisely how big the array needs to be. 933 | // If we get it right, we don't have to do an array copy, and 934 | // we save a bunch of memory. 935 | int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding 936 | if( breakLines ){ 937 | encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters 938 | } 939 | byte[] outBuff = new byte[ encLen ]; 940 | 941 | 942 | int d = 0; 943 | int e = 0; 944 | int len2 = len - 2; 945 | int lineLength = 0; 946 | for( ; d < len2; d+=3, e+=4 ) { 947 | encode3to4( source, d+off, 3, outBuff, e, options ); 948 | 949 | lineLength += 4; 950 | if( breakLines && lineLength >= MAX_LINE_LENGTH ) 951 | { 952 | outBuff[e+4] = NEW_LINE; 953 | e++; 954 | lineLength = 0; 955 | } // end if: end of line 956 | } // en dfor: each piece of array 957 | 958 | if( d < len ) { 959 | encode3to4( source, d+off, len - d, outBuff, e, options ); 960 | e += 4; 961 | } // end if: some padding needed 962 | 963 | 964 | // Only resize array if we didn't guess it right. 965 | if( e < outBuff.length - 1 ){ 966 | byte[] finalOut = new byte[e]; 967 | System.arraycopy(outBuff,0, finalOut,0,e); 968 | //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); 969 | return finalOut; 970 | } else { 971 | //System.err.println("No need to resize array."); 972 | return outBuff; 973 | } 974 | 975 | } // end else: don't compress 976 | 977 | } // end encodeBytesToBytes 978 | 979 | 980 | 981 | 982 | 983 | /* ******** D E C O D I N G M E T H O D S ******** */ 984 | 985 | 986 | /** 987 | * Decodes four bytes from array source 988 | * and writes the resulting bytes (up to three of them) 989 | * to destination. 990 | * The source and destination arrays can be manipulated 991 | * anywhere along their length by specifying 992 | * srcOffset and destOffset. 993 | * This method does not check to make sure your arrays 994 | * are large enough to accomodate srcOffset + 4 for 995 | * the source array or destOffset + 3 for 996 | * the destination array. 997 | * This method returns the actual number of bytes that 998 | * were converted from the Base64 encoding. 999 | *This is the lowest level of the decoding methods with 1000 | * all possible parameters.
1001 | * 1002 | * 1003 | * @param source the array to convert 1004 | * @param srcOffset the index where conversion begins 1005 | * @param destination the array to hold the conversion 1006 | * @param destOffset the index where output will be put 1007 | * @param options alphabet type is pulled from this (standard, url-safe, ordered) 1008 | * @return the number of decoded bytes converted 1009 | * @throws NullPointerException if source or destination arrays are null 1010 | * @throws IllegalArgumentException if srcOffset or destOffset are invalid 1011 | * or there is not enough room in the array. 1012 | * @since 1.3 1013 | */ 1014 | private static int decode4to3( 1015 | byte[] source, int srcOffset, 1016 | byte[] destination, int destOffset, int options ) { 1017 | 1018 | // Lots of error checking and exception throwing 1019 | if( source == null ){ 1020 | throw new NullPointerException( "Source array was null." ); 1021 | } // end if 1022 | if( destination == null ){ 1023 | throw new NullPointerException( "Destination array was null." ); 1024 | } // end if 1025 | if( srcOffset < 0 || srcOffset + 3 >= source.length ){ 1026 | throw new IllegalArgumentException( String.format( 1027 | "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); 1028 | } // end if 1029 | if( destOffset < 0 || destOffset +2 >= destination.length ){ 1030 | throw new IllegalArgumentException( String.format( 1031 | "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); 1032 | } // end if 1033 | 1034 | 1035 | byte[] DECODABET = getDecodabet( options ); 1036 | 1037 | // Example: Dk== 1038 | if( source[ srcOffset + 2] == EQUALS_SIGN ) { 1039 | // Two ways to do the same thing. Don't know which way I like best. 1040 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1041 | // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); 1042 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1043 | | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); 1044 | 1045 | destination[ destOffset ] = (byte)( outBuff >>> 16 ); 1046 | return 1; 1047 | } 1048 | 1049 | // Example: DkL= 1050 | else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { 1051 | // Two ways to do the same thing. Don't know which way I like best. 1052 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1053 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1054 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); 1055 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1056 | | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 1057 | | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); 1058 | 1059 | destination[ destOffset ] = (byte)( outBuff >>> 16 ); 1060 | destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); 1061 | return 2; 1062 | } 1063 | 1064 | // Example: DkLE 1065 | else { 1066 | // Two ways to do the same thing. Don't know which way I like best. 1067 | //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) 1068 | // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) 1069 | // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) 1070 | // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); 1071 | int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) 1072 | | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) 1073 | | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) 1074 | | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); 1075 | 1076 | 1077 | destination[ destOffset ] = (byte)( outBuff >> 16 ); 1078 | destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); 1079 | destination[ destOffset + 2 ] = (byte)( outBuff ); 1080 | 1081 | return 3; 1082 | } 1083 | } // end decodeToBytes 1084 | 1085 | 1086 | 1087 | 1088 | 1089 | /** 1090 | * Low-level access to decoding ASCII characters in 1091 | * the form of a byte array. Ignores GUNZIP option, if 1092 | * it's set. This is not generally a recommended method, 1093 | * although it is used internally as part of the decoding process. 1094 | * Special case: if len = 0, an empty array is returned. Still, 1095 | * if you need more speed and reduced memory footprint (and aren't 1096 | * gzipping), consider this method. 1097 | * 1098 | * @param source The Base64 encoded data 1099 | * @return decoded data 1100 | * @since 2.3.1 1101 | */ 1102 | public static byte[] decode( byte[] source ){ 1103 | byte[] decoded = null; 1104 | try { 1105 | decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); 1106 | } catch( java.io.IOException ex ) { 1107 | assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); 1108 | } 1109 | return decoded; 1110 | } 1111 | 1112 | 1113 | 1114 | /** 1115 | * Low-level access to decoding ASCII characters in 1116 | * the form of a byte array. Ignores GUNZIP option, if 1117 | * it's set. This is not generally a recommended method, 1118 | * although it is used internally as part of the decoding process. 1119 | * Special case: if len = 0, an empty array is returned. Still, 1120 | * if you need more speed and reduced memory footprint (and aren't 1121 | * gzipping), consider this method. 1122 | * 1123 | * @param source The Base64 encoded data 1124 | * @param off The offset of where to begin decoding 1125 | * @param len The length of characters to decode 1126 | * @param options Can specify options such as alphabet type to use 1127 | * @return decoded data 1128 | * @throws java.io.IOException If bogus characters exist in source data 1129 | * @since 1.3 1130 | */ 1131 | public static byte[] decode( byte[] source, int off, int len, int options ) 1132 | throws java.io.IOException { 1133 | 1134 | // Lots of error checking and exception throwing 1135 | if( source == null ){ 1136 | throw new NullPointerException( "Cannot decode null source array." ); 1137 | } // end if 1138 | if( off < 0 || off + len > source.length ){ 1139 | throw new IllegalArgumentException( String.format( 1140 | "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); 1141 | } // end if 1142 | 1143 | if( len == 0 ){ 1144 | return new byte[0]; 1145 | }else if( len < 4 ){ 1146 | throw new IllegalArgumentException( 1147 | "Base64-encoded string must have at least four characters, but length specified was " + len ); 1148 | } // end if 1149 | 1150 | byte[] DECODABET = getDecodabet( options ); 1151 | 1152 | int len34 = len * 3 / 4; // Estimate on array size 1153 | byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output 1154 | int outBuffPosn = 0; // Keep track of where we're writing 1155 | 1156 | byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space 1157 | int b4Posn = 0; // Keep track of four byte input buffer 1158 | int i = 0; // Source array counter 1159 | byte sbiCrop = 0; // Low seven bits (ASCII) of input 1160 | byte sbiDecode = 0; // Special value from DECODABET 1161 | 1162 | for( i = off; i < off+len; i++ ) { // Loop through source 1163 | 1164 | sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits 1165 | sbiDecode = DECODABET[ sbiCrop ]; // Special value 1166 | 1167 | // White space, Equals sign, or legit Base64 character 1168 | // Note the values such as -5 and -9 in the 1169 | // DECODABETs at the top of the file. 1170 | if( sbiDecode >= WHITE_SPACE_ENC ) { 1171 | if( sbiDecode >= EQUALS_SIGN_ENC ) { 1172 | b4[ b4Posn++ ] = sbiCrop; // Save non-whitespace 1173 | if( b4Posn > 3 ) { // Time to decode? 1174 | outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); 1175 | b4Posn = 0; 1176 | 1177 | // If that was the equals sign, break out of 'for' loop 1178 | if( sbiCrop == EQUALS_SIGN ) { 1179 | break; 1180 | } // end if: equals sign 1181 | } // end if: quartet built 1182 | } // end if: equals sign or better 1183 | } // end if: white space, equals sign or better 1184 | else { 1185 | // There's a bad input character in the Base64 stream. 1186 | throw new java.io.IOException( String.format( 1187 | "Bad Base64 input character '%c' in array position %d", source[i], i ) ); 1188 | } // end else: 1189 | } // each input character 1190 | 1191 | byte[] out = new byte[ outBuffPosn ]; 1192 | System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); 1193 | return out; 1194 | } // end decode 1195 | 1196 | 1197 | 1198 | 1199 | /** 1200 | * Decodes data from Base64 notation, automatically 1201 | * detecting gzip-compressed data and decompressing it. 1202 | * 1203 | * @param s the string to decode 1204 | * @return the decoded data 1205 | * @throws java.io.IOException If there is a problem 1206 | * @since 1.4 1207 | */ 1208 | public static byte[] decode( String s ) throws java.io.IOException { 1209 | return decode( s, NO_OPTIONS ); 1210 | } 1211 | 1212 | 1213 | 1214 | /** 1215 | * Decodes data from Base64 notation, automatically 1216 | * detecting gzip-compressed data and decompressing it. 1217 | * 1218 | * @param s the string to decode 1219 | * @param options encode options such as URL_SAFE 1220 | * @return the decoded data 1221 | * @throws java.io.IOException if there is an error 1222 | * @throws NullPointerException if s is null 1223 | * @since 1.4 1224 | */ 1225 | public static byte[] decode( String s, int options ) throws java.io.IOException { 1226 | 1227 | if( s == null ){ 1228 | throw new NullPointerException( "Input string was null." ); 1229 | } // end if 1230 | 1231 | byte[] bytes; 1232 | try { 1233 | bytes = s.getBytes( PREFERRED_ENCODING ); 1234 | } // end try 1235 | catch( java.io.UnsupportedEncodingException uee ) { 1236 | bytes = s.getBytes(); 1237 | } // end catch 1238 | // 1239 | 1240 | // Decode 1241 | bytes = decode( bytes, 0, bytes.length, options ); 1242 | 1243 | // Check to see if it's gzip-compressed 1244 | // GZIP Magic Two-Byte Number: 0x8b1f (35615) 1245 | boolean dontGunzip = (options & DONT_GUNZIP) != 0; 1246 | if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { 1247 | 1248 | int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); 1249 | if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { 1250 | java.io.ByteArrayInputStream bais = null; 1251 | java.util.zip.GZIPInputStream gzis = null; 1252 | java.io.ByteArrayOutputStream baos = null; 1253 | byte[] buffer = new byte[2048]; 1254 | int length = 0; 1255 | 1256 | try { 1257 | baos = new java.io.ByteArrayOutputStream(); 1258 | bais = new java.io.ByteArrayInputStream( bytes ); 1259 | gzis = new java.util.zip.GZIPInputStream( bais ); 1260 | 1261 | while( ( length = gzis.read( buffer ) ) >= 0 ) { 1262 | baos.write(buffer,0,length); 1263 | } // end while: reading input 1264 | 1265 | // No error? Get new bytes. 1266 | bytes = baos.toByteArray(); 1267 | 1268 | } // end try 1269 | catch( java.io.IOException e ) { 1270 | e.printStackTrace(); 1271 | // Just return originally-decoded bytes 1272 | } // end catch 1273 | finally { 1274 | try{ baos.close(); } catch( Exception e ){} 1275 | try{ gzis.close(); } catch( Exception e ){} 1276 | try{ bais.close(); } catch( Exception e ){} 1277 | } // end finally 1278 | 1279 | } // end if: gzipped 1280 | } // end if: bytes.length >= 2 1281 | 1282 | return bytes; 1283 | } // end decode 1284 | 1285 | 1286 | 1287 | /** 1288 | * Attempts to decode Base64 data and deserialize a Java 1289 | * Object within. Returns null if there was an error. 1290 | * 1291 | * @param encodedObject The Base64 data to decode 1292 | * @return The decoded and deserialized object 1293 | * @throws NullPointerException if encodedObject is null 1294 | * @throws java.io.IOException if there is a general error 1295 | * @throws ClassNotFoundException if the decoded object is of a 1296 | * class that cannot be found by the JVM 1297 | * @since 1.5 1298 | */ 1299 | public static Object decodeToObject( String encodedObject ) 1300 | throws java.io.IOException, java.lang.ClassNotFoundException { 1301 | return decodeToObject(encodedObject,NO_OPTIONS,null); 1302 | } 1303 | 1304 | 1305 | /** 1306 | * Attempts to decode Base64 data and deserialize a Java 1307 | * Object within. Returns null if there was an error. 1308 | * If loader is not null, it will be the class loader 1309 | * used when deserializing. 1310 | * 1311 | * @param encodedObject The Base64 data to decode 1312 | * @param options Various parameters related to decoding 1313 | * @param loader Optional class loader to use in deserializing classes. 1314 | * @return The decoded and deserialized object 1315 | * @throws NullPointerException if encodedObject is null 1316 | * @throws java.io.IOException if there is a general error 1317 | * @throws ClassNotFoundException if the decoded object is of a 1318 | * class that cannot be found by the JVM 1319 | * @since 2.3.4 1320 | */ 1321 | public static Object decodeToObject( 1322 | String encodedObject, int options, final ClassLoader loader ) 1323 | throws java.io.IOException, java.lang.ClassNotFoundException { 1324 | 1325 | // Decode and gunzip if necessary 1326 | byte[] objBytes = decode( encodedObject, options ); 1327 | 1328 | java.io.ByteArrayInputStream bais = null; 1329 | java.io.ObjectInputStream ois = null; 1330 | Object obj = null; 1331 | 1332 | try { 1333 | bais = new java.io.ByteArrayInputStream( objBytes ); 1334 | 1335 | // If no custom class loader is provided, use Java's builtin OIS. 1336 | if( loader == null ){ 1337 | ois = new java.io.ObjectInputStream( bais ); 1338 | } // end if: no loader provided 1339 | 1340 | // Else make a customized object input stream that uses 1341 | // the provided class loader. 1342 | else { 1343 | ois = new java.io.ObjectInputStream(bais){ 1344 | @SuppressWarnings("unchecked") 1345 | @Override 1346 | public Class> resolveClass(java.io.ObjectStreamClass streamClass) 1347 | throws java.io.IOException, ClassNotFoundException { 1348 | Class c = Class.forName(streamClass.getName(), false, loader); 1349 | if( c == null ){ 1350 | return super.resolveClass(streamClass); 1351 | } else { 1352 | return c; // Class loader knows of this class. 1353 | } // end else: not null 1354 | } // end resolveClass 1355 | }; // end ois 1356 | } // end else: no custom class loader 1357 | 1358 | obj = ois.readObject(); 1359 | } // end try 1360 | catch( java.io.IOException e ) { 1361 | throw e; // Catch and throw in order to execute finally{} 1362 | } // end catch 1363 | catch( java.lang.ClassNotFoundException e ) { 1364 | throw e; // Catch and throw in order to execute finally{} 1365 | } // end catch 1366 | finally { 1367 | try{ bais.close(); } catch( Exception e ){} 1368 | try{ ois.close(); } catch( Exception e ){} 1369 | } // end finally 1370 | 1371 | return obj; 1372 | } // end decodeObject 1373 | 1374 | 1375 | 1376 | 1377 | 1378 | 1379 | 1380 | /** 1381 | * Convenience method for reading a base64-encoded 1382 | * file and decoding it. 1383 | * 1384 | *As of v 2.3, if there is a error, 1385 | * the method will throw an java.io.IOException. This is new to v2.3! 1386 | * In earlier versions, it just returned false, but 1387 | * in retrospect that's a pretty poor way to handle it.
1388 | * 1389 | * @param filename Filename for reading encoded data 1390 | * @return decoded byte array 1391 | * @throws java.io.IOException if there is an error 1392 | * @since 2.1 1393 | */ 1394 | public static byte[] decodeFromFile( String filename ) 1395 | throws java.io.IOException { 1396 | 1397 | byte[] decodedData = null; 1398 | Base64.InputStream bis = null; 1399 | try 1400 | { 1401 | // Set up some useful variables 1402 | java.io.File file = new java.io.File( filename ); 1403 | byte[] buffer = null; 1404 | int length = 0; 1405 | int numBytes = 0; 1406 | 1407 | // Check for size of file 1408 | if( file.length() > Integer.MAX_VALUE ) 1409 | { 1410 | throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); 1411 | } // end if: file too big for int index 1412 | buffer = new byte[ (int)file.length() ]; 1413 | 1414 | // Open a stream 1415 | bis = new Base64.InputStream( 1416 | new java.io.BufferedInputStream( 1417 | new java.io.FileInputStream( file ) ), Base64.DECODE ); 1418 | 1419 | // Read until done 1420 | while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { 1421 | length += numBytes; 1422 | } // end while 1423 | 1424 | // Save in a variable to return 1425 | decodedData = new byte[ length ]; 1426 | System.arraycopy( buffer, 0, decodedData, 0, length ); 1427 | 1428 | } // end try 1429 | catch( java.io.IOException e ) { 1430 | throw e; // Catch and release to execute finally{} 1431 | } // end catch: java.io.IOException 1432 | finally { 1433 | try{ bis.close(); } catch( Exception e) {} 1434 | } // end finally 1435 | 1436 | return decodedData; 1437 | } // end decodeFromFile 1438 | 1439 | 1440 | 1441 | /** 1442 | * Convenience method for reading a binary file 1443 | * and base64-encoding it. 1444 | * 1445 | *As of v 2.3, if there is a error, 1446 | * the method will throw an java.io.IOException. This is new to v2.3! 1447 | * In earlier versions, it just returned false, but 1448 | * in retrospect that's a pretty poor way to handle it.
1449 | * 1450 | * @param filename Filename for reading binary data 1451 | * @return base64-encoded string 1452 | * @throws java.io.IOException if there is an error 1453 | * @since 2.1 1454 | */ 1455 | public static String encodeFromFile( String filename ) 1456 | throws java.io.IOException { 1457 | 1458 | String encodedData = null; 1459 | Base64.InputStream bis = null; 1460 | try 1461 | { 1462 | // Set up some useful variables 1463 | java.io.File file = new java.io.File( filename ); 1464 | byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4),40) ]; // Need max() for math on small files (v2.2.1) 1465 | int length = 0; 1466 | int numBytes = 0; 1467 | 1468 | // Open a stream 1469 | bis = new Base64.InputStream( 1470 | new java.io.BufferedInputStream( 1471 | new java.io.FileInputStream( file ) ), Base64.ENCODE ); 1472 | 1473 | // Read until done 1474 | while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { 1475 | length += numBytes; 1476 | } // end while 1477 | 1478 | // Save in a variable to return 1479 | encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); 1480 | 1481 | } // end try 1482 | catch( java.io.IOException e ) { 1483 | throw e; // Catch and release to execute finally{} 1484 | } // end catch: java.io.IOException 1485 | finally { 1486 | try{ bis.close(); } catch( Exception e) {} 1487 | } // end finally 1488 | 1489 | return encodedData; 1490 | } // end encodeFromFile 1491 | 1492 | 1493 | /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ 1494 | 1495 | 1496 | 1497 | /** 1498 | * A {@link Base64.InputStream} will read data from another 1499 | * java.io.InputStream, given in the constructor, 1500 | * and encode/decode to/from Base64 notation on the fly. 1501 | * 1502 | * @see Base64 1503 | * @since 1.3 1504 | */ 1505 | public static class InputStream extends java.io.FilterInputStream { 1506 | 1507 | private boolean encode; // Encoding or decoding 1508 | private int position; // Current position in the buffer 1509 | private byte[] buffer; // Small buffer holding converted data 1510 | private int bufferLength; // Length of buffer (3 or 4) 1511 | private int numSigBytes; // Number of meaningful bytes in the buffer 1512 | private int lineLength; 1513 | private boolean breakLines; // Break lines at less than 80 characters 1514 | private int options; // Record options used to create the stream. 1515 | private byte[] decodabet; // Local copies to avoid extra method calls 1516 | 1517 | 1518 | /** 1519 | * Constructs a {@link Base64.InputStream} in DECODE mode. 1520 | * 1521 | * @param in the java.io.InputStream from which to read data. 1522 | * @since 1.3 1523 | */ 1524 | public InputStream( java.io.InputStream in ) { 1525 | this( in, DECODE ); 1526 | } // end constructor 1527 | 1528 | 1529 | /** 1530 | * Constructs a {@link Base64.InputStream} in 1531 | * either ENCODE or DECODE mode. 1532 | *1533 | * Valid options:
1534 | * ENCODE or DECODE: Encode or Decode as data is read. 1535 | * DO_BREAK_LINES: break lines at 76 characters 1536 | * (only meaningful when encoding) 1537 | *1538 | *
1539 | * Example: new Base64.InputStream( in, Base64.DECODE )
1540 | *
1541 | *
1542 | * @param in the java.io.InputStream from which to read data.
1543 | * @param options Specified options
1544 | * @see Base64#ENCODE
1545 | * @see Base64#DECODE
1546 | * @see Base64#DO_BREAK_LINES
1547 | * @since 2.0
1548 | */
1549 | public InputStream( java.io.InputStream in, int options ) {
1550 |
1551 | super( in );
1552 | this.options = options; // Record for later
1553 | this.breakLines = (options & DO_BREAK_LINES) > 0;
1554 | this.encode = (options & ENCODE) > 0;
1555 | this.bufferLength = encode ? 4 : 3;
1556 | this.buffer = new byte[ bufferLength ];
1557 | this.position = -1;
1558 | this.lineLength = 0;
1559 | this.decodabet = getDecodabet(options);
1560 | } // end constructor
1561 |
1562 | /**
1563 | * Reads enough of the input stream to convert
1564 | * to/from Base64 and returns the next byte.
1565 | *
1566 | * @return next byte
1567 | * @since 1.3
1568 | */
1569 | @Override
1570 | public int read() throws java.io.IOException {
1571 |
1572 | // Do we need to get data?
1573 | if( position < 0 ) {
1574 | if( encode ) {
1575 | byte[] b3 = new byte[3];
1576 | int numBinaryBytes = 0;
1577 | for( int i = 0; i < 3; i++ ) {
1578 | int b = in.read();
1579 |
1580 | // If end of stream, b is -1.
1581 | if( b >= 0 ) {
1582 | b3[i] = (byte)b;
1583 | numBinaryBytes++;
1584 | } else {
1585 | break; // out of for loop
1586 | } // end else: end of stream
1587 |
1588 | } // end for: each needed input byte
1589 |
1590 | if( numBinaryBytes > 0 ) {
1591 | encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
1592 | position = 0;
1593 | numSigBytes = 4;
1594 | } // end if: got data
1595 | else {
1596 | return -1; // Must be end of stream
1597 | } // end else
1598 | } // end if: encoding
1599 |
1600 | // Else decoding
1601 | else {
1602 | byte[] b4 = new byte[4];
1603 | int i = 0;
1604 | for( i = 0; i < 4; i++ ) {
1605 | // Read four "meaningful" bytes:
1606 | int b = 0;
1607 | do{ b = in.read(); }
1608 | while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
1609 |
1610 | if( b < 0 ) {
1611 | break; // Reads a -1 if end of stream
1612 | } // end if: end of stream
1613 |
1614 | b4[i] = (byte)b;
1615 | } // end for: each needed input byte
1616 |
1617 | if( i == 4 ) {
1618 | numSigBytes = decode4to3( b4, 0, buffer, 0, options );
1619 | position = 0;
1620 | } // end if: got four characters
1621 | else if( i == 0 ){
1622 | return -1;
1623 | } // end else if: also padded correctly
1624 | else {
1625 | // Must have broken out from above.
1626 | throw new java.io.IOException( "Improperly padded Base64 input." );
1627 | } // end
1628 |
1629 | } // end else: decode
1630 | } // end else: get data
1631 |
1632 | // Got data?
1633 | if( position >= 0 ) {
1634 | // End of relevant data?
1635 | if( /*!encode &&*/ position >= numSigBytes ){
1636 | return -1;
1637 | } // end if: got data
1638 |
1639 | if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
1640 | lineLength = 0;
1641 | return '\n';
1642 | } // end if
1643 | else {
1644 | lineLength++; // This isn't important when decoding
1645 | // but throwing an extra "if" seems
1646 | // just as wasteful.
1647 |
1648 | int b = buffer[ position++ ];
1649 |
1650 | if( position >= bufferLength ) {
1651 | position = -1;
1652 | } // end if: end
1653 |
1654 | return b & 0xFF; // This is how you "cast" a byte that's
1655 | // intended to be unsigned.
1656 | } // end else
1657 | } // end if: position >= 0
1658 |
1659 | // Else error
1660 | else {
1661 | throw new java.io.IOException( "Error in Base64 code reading stream." );
1662 | } // end else
1663 | } // end read
1664 |
1665 |
1666 | /**
1667 | * Calls {@link #read()} repeatedly until the end of stream
1668 | * is reached or len bytes are read.
1669 | * Returns number of bytes read into array or -1 if
1670 | * end of stream is encountered.
1671 | *
1672 | * @param dest array to hold values
1673 | * @param off offset for array
1674 | * @param len max number of bytes to read into array
1675 | * @return bytes read into array or -1 if end of stream is encountered.
1676 | * @since 1.3
1677 | */
1678 | @Override
1679 | public int read( byte[] dest, int off, int len )
1680 | throws java.io.IOException {
1681 | int i;
1682 | int b;
1683 | for( i = 0; i < len; i++ ) {
1684 | b = read();
1685 |
1686 | if( b >= 0 ) {
1687 | dest[off + i] = (byte) b;
1688 | }
1689 | else if( i == 0 ) {
1690 | return -1;
1691 | }
1692 | else {
1693 | break; // Out of 'for' loop
1694 | } // Out of 'for' loop
1695 | } // end for: each byte read
1696 | return i;
1697 | } // end read
1698 |
1699 | } // end inner class InputStream
1700 |
1701 |
1702 |
1703 |
1704 |
1705 |
1706 | /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
1707 |
1708 |
1709 |
1710 | /**
1711 | * A {@link Base64.OutputStream} will write data to another
1712 | * java.io.OutputStream, given in the constructor,
1713 | * and encode/decode to/from Base64 notation on the fly.
1714 | *
1715 | * @see Base64
1716 | * @since 1.3
1717 | */
1718 | public static class OutputStream extends java.io.FilterOutputStream {
1719 |
1720 | private boolean encode;
1721 | private int position;
1722 | private byte[] buffer;
1723 | private int bufferLength;
1724 | private int lineLength;
1725 | private boolean breakLines;
1726 | private byte[] b4; // Scratch used in a few places
1727 | private boolean suspendEncoding;
1728 | private int options; // Record for later
1729 | private byte[] decodabet; // Local copies to avoid extra method calls
1730 |
1731 | /**
1732 | * Constructs a {@link Base64.OutputStream} in ENCODE mode.
1733 | *
1734 | * @param out the java.io.OutputStream to which data will be written.
1735 | * @since 1.3
1736 | */
1737 | public OutputStream( java.io.OutputStream out ) {
1738 | this( out, ENCODE );
1739 | } // end constructor
1740 |
1741 |
1742 | /**
1743 | * Constructs a {@link Base64.OutputStream} in
1744 | * either ENCODE or DECODE mode.
1745 | *
1746 | * Valid options:
1747 | * ENCODE or DECODE: Encode or Decode as data is read. 1748 | * DO_BREAK_LINES: don't break lines at 76 characters 1749 | * (only meaningful when encoding) 1750 | *1751 | *
1752 | * Example: new Base64.OutputStream( out, Base64.ENCODE )
1753 | *
1754 | * @param out the java.io.OutputStream to which data will be written.
1755 | * @param options Specified options.
1756 | * @see Base64#ENCODE
1757 | * @see Base64#DECODE
1758 | * @see Base64#DO_BREAK_LINES
1759 | * @since 1.3
1760 | */
1761 | public OutputStream( java.io.OutputStream out, int options ) {
1762 | super( out );
1763 | this.breakLines = (options & DO_BREAK_LINES) != 0;
1764 | this.encode = (options & ENCODE) != 0;
1765 | this.bufferLength = encode ? 3 : 4;
1766 | this.buffer = new byte[ bufferLength ];
1767 | this.position = 0;
1768 | this.lineLength = 0;
1769 | this.suspendEncoding = false;
1770 | this.b4 = new byte[4];
1771 | this.options = options;
1772 | this.decodabet = getDecodabet(options);
1773 | } // end constructor
1774 |
1775 |
1776 | /**
1777 | * Writes the byte to the output stream after
1778 | * converting to/from Base64 notation.
1779 | * When encoding, bytes are buffered three
1780 | * at a time before the output stream actually
1781 | * gets a write() call.
1782 | * When decoding, bytes are buffered four
1783 | * at a time.
1784 | *
1785 | * @param theByte the byte to write
1786 | * @since 1.3
1787 | */
1788 | @Override
1789 | public void write(int theByte)
1790 | throws java.io.IOException {
1791 | // Encoding suspended?
1792 | if( suspendEncoding ) {
1793 | this.out.write( theByte );
1794 | return;
1795 | } // end if: supsended
1796 |
1797 | // Encode?
1798 | if( encode ) {
1799 | buffer[ position++ ] = (byte)theByte;
1800 | if( position >= bufferLength ) { // Enough to encode.
1801 |
1802 | this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
1803 |
1804 | lineLength += 4;
1805 | if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
1806 | this.out.write( NEW_LINE );
1807 | lineLength = 0;
1808 | } // end if: end of line
1809 |
1810 | position = 0;
1811 | } // end if: enough to output
1812 | } // end if: encoding
1813 |
1814 | // Else, Decoding
1815 | else {
1816 | // Meaningful Base64 character?
1817 | if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
1818 | buffer[ position++ ] = (byte)theByte;
1819 | if( position >= bufferLength ) { // Enough to output.
1820 |
1821 | int len = Base64.decode4to3( buffer, 0, b4, 0, options );
1822 | out.write( b4, 0, len );
1823 | position = 0;
1824 | } // end if: enough to output
1825 | } // end if: meaningful base64 character
1826 | else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
1827 | throw new java.io.IOException( "Invalid character in Base64 data." );
1828 | } // end else: not white space either
1829 | } // end else: decoding
1830 | } // end write
1831 |
1832 |
1833 |
1834 | /**
1835 | * Calls {@link #write(int)} repeatedly until len
1836 | * bytes are written.
1837 | *
1838 | * @param theBytes array from which to read bytes
1839 | * @param off offset for array
1840 | * @param len max number of bytes to read into array
1841 | * @since 1.3
1842 | */
1843 | @Override
1844 | public void write( byte[] theBytes, int off, int len )
1845 | throws java.io.IOException {
1846 | // Encoding suspended?
1847 | if( suspendEncoding ) {
1848 | this.out.write( theBytes, off, len );
1849 | return;
1850 | } // end if: supsended
1851 |
1852 | for( int i = 0; i < len; i++ ) {
1853 | write( theBytes[ off + i ] );
1854 | } // end for: each byte written
1855 |
1856 | } // end write
1857 |
1858 |
1859 |
1860 | /**
1861 | * Method added by PHIL. [Thanks, PHIL. -Rob]
1862 | * This pads the buffer without closing the stream.
1863 | * @throws java.io.IOException if there's an error.
1864 | */
1865 | public void flushBase64() throws java.io.IOException {
1866 | if( position > 0 ) {
1867 | if( encode ) {
1868 | out.write( encode3to4( b4, buffer, position, options ) );
1869 | position = 0;
1870 | } // end if: encoding
1871 | else {
1872 | throw new java.io.IOException( "Base64 input not properly padded." );
1873 | } // end else: decoding
1874 | } // end if: buffer partially full
1875 |
1876 | } // end flush
1877 |
1878 |
1879 | /**
1880 | * Flushes and closes (I think, in the superclass) the stream.
1881 | *
1882 | * @since 1.3
1883 | */
1884 | @Override
1885 | public void close() throws java.io.IOException {
1886 | // 1. Ensure that pending characters are written
1887 | flushBase64();
1888 |
1889 | // 2. Actually close the stream
1890 | // Base class both flushes and closes.
1891 | super.close();
1892 |
1893 | buffer = null;
1894 | out = null;
1895 | } // end close
1896 |
1897 |
1898 |
1899 | /**
1900 | * Suspends encoding of the stream.
1901 | * May be helpful if you need to embed a piece of
1902 | * base64-encoded data in a stream.
1903 | *
1904 | * @throws java.io.IOException if there's an error flushing
1905 | * @since 1.5.1
1906 | */
1907 | public void suspendEncoding() throws java.io.IOException {
1908 | flushBase64();
1909 | this.suspendEncoding = true;
1910 | } // end suspendEncoding
1911 |
1912 |
1913 | /**
1914 | * Resumes encoding of the stream.
1915 | * May be helpful if you need to embed a piece of
1916 | * base64-encoded data in a stream.
1917 | *
1918 | * @since 1.5.1
1919 | */
1920 | public void resumeEncoding() {
1921 | this.suspendEncoding = false;
1922 | } // end resumeEncoding
1923 |
1924 |
1925 |
1926 | } // end inner class OutputStream
1927 |
1928 |
1929 | } // end class Base64
1930 |
--------------------------------------------------------------------------------
/AndroidMarketApi/src/com/gc/android/market/api/LoginException.java:
--------------------------------------------------------------------------------
1 | package com.gc.android.market.api;
2 |
3 | public class LoginException extends RuntimeException {
4 |
5 | public static final String ERROR_BAD_AUTHENTICATION = "BadAuthentication";
6 | public static final String ERROR_NOT_VERIFIED = "NotVerified";
7 | public static final String ERROR_TERMS_NOT_AGREED = "TermsNotAgreed";
8 | public static final String ERROR_CAPTCHA_REQUIRED = "CaptchaRequired";
9 | public static final String ERROR_UNKNOWN = "Unknown";
10 | public static final String ERROR_ACCOUNT_DELETED = "AccountDeleted";
11 | public static final String ERROR_ACCOUNT_DISABLED = "AccountDisabled";
12 | public static final String ERROR_SERVICE_DISABLED = "ServiceDisabled";
13 | public static final String ERROR_SERVICE_UNAVAILABLE = "ServiceUnavailable";
14 |
15 | private String googleErrorCode;
16 |
17 | public LoginException(String googleErrorCode) {
18 | super(getErrorMessage(googleErrorCode).isEmpty() ? googleErrorCode : getErrorMessage(googleErrorCode));
19 | this.googleErrorCode = googleErrorCode;
20 | }
21 |
22 | public String getErrorCode() {
23 | return googleErrorCode;
24 | }
25 |
26 | private static String getErrorMessage(String errorCode) {
27 | // from http://code.google.com/intl/fr-FR/apis/accounts/docs/AuthForInstalledApps.html
28 | if(errorCode.equals(ERROR_BAD_AUTHENTICATION))
29 | return "The login request used a username or password that is not recognized.";
30 | if(errorCode.equals(ERROR_NOT_VERIFIED))
31 | return "The account email address has not been verified. The user will need to access their Google account directly to resolve the issue before logging in using a non-Google application.";
32 | if(errorCode.equals(ERROR_TERMS_NOT_AGREED))
33 | return "The user has not agreed to terms. The user will need to access their Google account directly to resolve the issue before logging in using a non-Google application.";
34 | if(errorCode.equals(ERROR_CAPTCHA_REQUIRED))
35 | return "A CAPTCHA is required. (A response with this error code will also contain an image URL and a CAPTCHA token.)";
36 | if(errorCode.equals(ERROR_UNKNOWN))
37 | return "The error is unknown or unspecified; the request contained invalid input or was malformed.";
38 | if(errorCode.equals(ERROR_ACCOUNT_DELETED))
39 | return "The user account has been deleted.";
40 | if(errorCode.equals(ERROR_ACCOUNT_DISABLED))
41 | return "The user account has been disabled.";
42 | if(errorCode.equals(ERROR_SERVICE_DISABLED))
43 | return "The user's access to the specified service has been disabled. (The user account may still be valid.)";
44 | if(errorCode.equals(ERROR_SERVICE_UNAVAILABLE))
45 | return "The service is not available; try again later.";
46 | return "";
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/AndroidMarketApi/src/com/gc/android/market/api/Main.java:
--------------------------------------------------------------------------------
1 | package com.gc.android.market.api;
2 |
3 | import java.io.FileOutputStream;
4 |
5 | import com.gc.android.market.api.MarketSession.Callback;
6 | import com.gc.android.market.api.model.Market.AppsRequest;
7 | import com.gc.android.market.api.model.Market.CommentsRequest;
8 | import com.gc.android.market.api.model.Market.GetImageRequest;
9 | import com.gc.android.market.api.model.Market.GetImageResponse;
10 | import com.gc.android.market.api.model.Market.ResponseContext;
11 | import com.gc.android.market.api.model.Market.GetImageRequest.AppImageUsage;
12 |
13 | public class Main {
14 |
15 | /**
16 | * @param args
17 | */
18 | public static void main(String[] args) {
19 | try {
20 | if(args.length < 2) {
21 | System.out.println("Usage :\n" +
22 | "market email password query");
23 | return;
24 | }
25 |
26 |
27 | String login = args[0];
28 | String password = args[1];
29 | String query = args.length > 2 ? args[2] : "Test";
30 |
31 | MarketSession session = new MarketSession();
32 | System.out.println("Login...");
33 | session.login(login,password);
34 | System.out.println("Login done");
35 |
36 | AppsRequest appsRequest = AppsRequest.newBuilder()
37 | .setQuery(query)
38 | .setStartIndex(2).setEntriesCount(10)
39 | .setWithExtendedInfo(true)
40 | .build();
41 |
42 | CommentsRequest commentsRequest = CommentsRequest.newBuilder()
43 | .setAppId("7065399193137006744")
44 | .setStartIndex(0)
45 | .setEntriesCount(10)
46 | .build();
47 |
48 | //
49 |
50 | GetImageRequest imgReq = GetImageRequest.newBuilder().setAppId("-7934792861962808905")
51 | .setImageUsage(AppImageUsage.SCREENSHOT)
52 | .setImageId("1")
53 | .build();
54 |
55 | MarketSession.Callback callback = new MarketSession.Callback() {
56 |
57 | @Override
58 | public void onResult(ResponseContext context, Object response) {
59 | System.out.println("Response : " + response);
60 | }
61 |
62 | };
63 | session.append(appsRequest, callback);
64 | session.flush();
65 | session.append(imgReq, new Callback