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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 | package Torello.Java; import Torello.Java.StrIndent; import static Torello.Java.C.*; import java.util.*; import java.io.*; import java.util.zip.*; import com.google.cloud.storage.*; import com.google.auth.oauth2.*; /** * <B><CODE>Load File Exception Catch</CODE></B> provides an eloquent way for printing standardized * <I>(consistent-looking)</I> error messages to terminal if a data-file fails to load from the * file-system, and subsequently halting the JVM - immediately. * * <EMBED CLASS='external-html' DATA-FILE-ID=LFEC> */ @Torello.JavaDoc.StaticFunctional public class LFEC { private LFEC() { } // ******************************************************************************************** // ******************************************************************************************** // These are error-printing methods. // ******************************************************************************************** // ******************************************************************************************** /** * This prints a message and a location and halts the current thread immediately. (Halts the * program) The entire rational behind the {@code class LFEC} is to facilitate loading * data-files, and forcing an immediate program halt if this operation fails. Generally, * during development and debugging, failing to read from a data-file is serious enough to * warrant stopping the software until the issue is fixed. "Hobbling along without reading * the data-files" makes little sense. * * <BR /><BR />When the software is being released or distributed, the philosophy turns to * loading mission critical data out of data-files in a java jar-file. If the jar-file is * corrupted and those files are not present, generally <I>this situation would <B>also * warrant</B> halting the program execution immediately until the jar file is fixed.</I> * * @param t An exception, error or other {@code Throwable} that generated a problem when * attempting to read a data-file. * * @param message This is an internally generated message explaining what has occurred. */ protected static void ERROR_EXIT(Throwable t, String message) { System.out.println( '\n' + "There was an error loading a data-file, and program-execution is being halted " + "immediately.\n" + "Problem Encountered With:\n" + StrIndent.indent(message, 4) + "\n" + "Exception or Error Message:\n" + EXCC.toString(t) + "\n\n" + "Exiting Program, Fatal Error Loading Critical Data File." ); System.exit(1); } /** * This prints a message and a location and halts the current thread immediately. (Halts the * program) The entire rational behind the {@code class LFEC} is to facilitate loading * data-files, and forcing an immediate program halt if this operation fails. Generally, * during development and debugging, failing to read from a data-file is serious enough to * warrant stopping the software until the issue is fixed. "Hobbling along without reading * the data-files" makes little sense. * * <BR /><BR />When the software is being released or distributed, the philosophy turns to * loading mission critical data out of data-files in a java jar-file. If the jar-file is * corrupted and those files are not present, generally <I>this situation would <B>also * warrant</B> halting the program execution immediately until the jar file is fixed.</I> * * @param message This is an internally generated message explaining what has occurred. */ protected static void ERROR_EXIT(String message) { System.out.println( '\n' + "There was an error loading a data-file, and program-execution is being halted " + "immediately.\n" + "Problem Encountered With:\n" + message + "\n\n" + "Exiting Program, Fatal Error Loading Critical Data File." ); System.exit(1); } // ******************************************************************************************** // ******************************************************************************************** // These are the data-loading methods. // ******************************************************************************************** // ******************************************************************************************** /** * Loads a file directly into a java-{@code String.} If this file fails to load, it halts the * run-time environment. * * @param f This is a {@code java.lang.String} that contains the filename. * * @return The returned {@code String} contains the entire contents of the file. * * @see FileRW#loadFileToString(String) * @see #ERROR_EXIT(Throwable, String) */ public static String loadFile(String f) { try { return FileRW.loadFileToString(f); } catch (Throwable t) { ERROR_EXIT(t, "FileRW.loadFileToString(\"" + f + "\")"); } throw new UnreachableError(); // Should not be possible to reach this statement } /** * Loads a file directory to a string <I>from a java jar-file</I>. It halts the program, and * prints a detailed message if any {@code Error's} or {@code Exception's} were thrown. The * directory inside the jar-file where this file may be located identified by parameter * {@code class 'classLoaderClass'}. * * @param classLoaderClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CLASS_LOAD_C> * <EMBED CLASS='external-html' DATA-FILE-ID=RAWTYPES> * * @param f This is a {@code String} that contains the filename of the data-file that needs * to be loaded. It is a 'relative file-name' that is relative to the jar-file / directory pair * location that the class loader identifies using the {@code Class} from parameter * {@code 'classLoaderClass'} * * @return The returned string contains the entire contents of the file. * * @see #ERROR_EXIT(Throwable, String) */ public static String loadFile_JAR(Class<?> classLoaderClass, String f) { // These are 'java.lang.AutoCloseable', and java handles them automatically // if there is an exception try ( InputStream is = classLoaderClass.getResourceAsStream(f); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ) { String s = ""; StringBuffer sb = new StringBuffer(); while ((s = br.readLine()) != null) sb.append(s + "\n"); return sb.toString(); } catch (Throwable t) { ERROR_EXIT( t, "Error loading text-file [" + f + "] from jar-file.\n" + "Class loader attempted to use information in class " + "[" + classLoaderClass.getCanonicalName() + "], but failed." ); } throw new UnreachableError(); // Should NOT be possible to reach this statement... } /** * Loads a file <I>from a java jar-file</I> using an {@code InputStream} and copies that file, * byte-for-byte, to {@code 'targetFileName'}. A detailed message is printed if any * {@code Error's} or {@code Exception's} were thrown. The directory inside the jar-file * where this file may be located identified by parameter {@code class 'classLoaderClass'}. * * @param classLoaderClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CLASS_LOAD_C> * <EMBED CLASS='external-html' DATA-FILE-ID=RAWTYPES> * * @param fileName This is a {@code String} that contains the filename of the data-file that * needs to be copied. It is a 'relative file-name' that is relative to the jar-file / * directory pair location that the class loader identifies using the {@code Class} from * parameter {@code 'classLoaderClass'}. * * @param targetFileName This is the file and directory that contains the target location * (as a {@code String}) to where the file should be copied. * * @see #ERROR_EXIT(Throwable, String) */ public static void copyFile_JAR (Class<?> classLoaderClass, String fileName, String targetFileName) { // These are 'java.lang.AutoCloseable', and java handles them automatically // if there is an exception try ( InputStream is = classLoaderClass.getResourceAsStream(fileName); FileOutputStream fos = new FileOutputStream(targetFileName); ) { byte[] b = new byte[5000]; int result = 0; while ((result = is.read(b)) != -1) fos.write(b, 0, result); } catch (Throwable t) { ERROR_EXIT( t, "Error copying file [" + fileName + "] from jar-file to " + "[" + targetFileName + "].\n" + "Class loader attempted to use information in class " + "[" + classLoaderClass.getCanonicalName() + "]." ); } } /** * This loads a file to a {@code Vector} of {@code String's}. It halts the program, and prints * a detailed message if any errors or exceptions occur. * * @param f The name of the file to load * * @param includeNewLine States whether the {@code '\n'} (new-line) character should be appended * to each element of the returned {@code Vector<String>}. * * @return a {@code Vector} of {@code String's}, where each element in the {@code Vector} is a * line retrieved from the text-file. * * @see #ERROR_EXIT(Throwable, String) */ public static Vector<String> loadFileToVector(String f, boolean includeNewLine) { try { return FileRW.loadFileToVector(f, includeNewLine); } catch (Throwable t) { ERROR_EXIT( t, "Attempting to Invoke this Load-Method with these Arguments:\n" + "FileRW.loadFileToVector(\"" + f + "\", " + includeNewLine + ");" ); } throw new UnreachableError(); // Should NOT be possible to reach this statement... } /** * This loads a file to a {@code Vector} of {@code String's}. It halts the program, and prints * a detailed message if any {@code Error's} or {@code Exception's} occur. The directory inside * the jar-file where this file may be located identified by parameter * {@code 'classLoaderClass'}. * * @param classLoaderClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CLASS_LOAD_C> * <EMBED CLASS='external-html' DATA-FILE-ID=RAWTYPES> * * @param f This is a {@code String} that contains the filename of the data-file that needs to * be loaded. It is a 'relative file-name' that is relative to the jar-file / directory pair * location that the class loader identifies using the {@code Class} from parameter * {@code 'classLoaderClass'}. * * @param includeNewLine States whether the {@code '\n'} (newline) character should be appended * to each element of the {@code Vector}. * * @return a {@code Vector} of {@code String's}, where each element in the {@code Vector} is a * line retrieved from the text-file. * * @see #ERROR_EXIT(Throwable, String) */ public static Vector<String> loadFileToVector_JAR (Class<?> classLoaderClass, String f, boolean includeNewLine) { // These are 'java.lang.AutoCloseable', and java handles them automatically // if there is an exception try ( InputStream is = classLoaderClass.getResourceAsStream(f); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ) { String s = ""; Vector<String> ret = new Vector<>(); if (includeNewLine) while ((s = br.readLine()) != null) ret.addElement(s + '\n'); else while ((s = br.readLine()) != null) ret.addElement(s); return ret; } catch (Throwable t) { ERROR_EXIT( t, "Error loading text-file [" + f + "] from jar-file.\n" + "Parameter includeNewLine was: " + includeNewLine + "\n" + "Class loader attempted to use information in class " + "[" + classLoaderClass.getCanonicalName() + "], but failed." ); } throw new UnreachableError(); // Should NOT be possible to reach this statement... } /** * This loads a {@code java.lang.Object} from a data-file. * <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CONTAINER> * * @param f The name of the file containing a serialized {@code java.lang.Object} to load * * @param zip This should be <I>TRUE</I> if, when serialized, the {@code Object} was compressed * too, and <I>FALSE</I> if compression was not used. * * @param returnClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_RET_CLASS> * * @param <T> This type parameter is simply provided for convenience, to allow the user to * specify the return class, without having to cast the object and suppress warnings, or catch * exceptions. * * @return A de-serialized {@code java.lang.Object} present in the data-file passed by-name * through file-name parameter {@code 'f'}, and cast to the type denoted by parameter * {@code returnClass}. * * @see FileRW#readObjectFromFile(String, boolean) * @see #ERROR_EXIT(Throwable, String) */ public static <T> T readObjectFromFile(String f, boolean zip, Class<T> returnClass) { try { Object ret = FileRW.readObjectFromFile(f, zip); if (! returnClass.isInstance(ret)) ERROR_EXIT( "Serialized Object from file: " + f + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" + "Didn't have an object with class-name: [" + returnClass + "]\n" + "but rather with class-name: [" + ret.getClass().getName() + "]" ); return returnClass.cast(ret); } catch (Throwable t) { ERROR_EXIT( t, "Exception reading Serialized Object from file: " + f + "\n" + "With intended read class-name of: " + returnClass + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" ); } throw new UnreachableError(); // Should NOT be possible to reach this statement... } /** * This loads a {@code java.lang.Object} from a data-file located in a JAR File. * <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CONTAINER> * * @param classLoaderClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_CLASS_LOAD_C> * <EMBED CLASS='external-html' DATA-FILE-ID=RAWTYPES> * * @param f The name of the file containing a serialized {@code java.lang.Object} to load * * @param zip This should be <I>TRUE</I> if, when serialized, the {@code Object} was compressed * too, and <I>FALSE</I> if compression was not used. * * @param returnClass <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_RET_CLASS> * * @param <T> This type parameter is simply provided for convenience, to allow the user to * specify the return class, without having to cast the object and suppress warnings, or catch * exceptions. * * @return a de-serialized {@code java.lang.Object} present in the data-file passed by-name * through file-name parameter {@code 'f'}, and cast to the type denoted by parameter * {@code 'returnClass'}. * * @see #ERROR_EXIT(Throwable, String) */ public static <T> T readObjectFromFile_JAR (Class<?> classLoaderClass, String f, boolean zip, Class<T> returnClass) { // These are 'java.lang.AutoCloseable', and java handles them automatically // if there is an exception try ( InputStream is = classLoaderClass.getResourceAsStream(f); // The user may or may not have asked for reading a *COMPRESSED* file ObjectInputStream ois = zip ? new ObjectInputStream(new GZIPInputStream(is)) : new ObjectInputStream(is); ) { Object ret = ois.readObject(); if (! returnClass.isInstance(ret)) ERROR_EXIT( "Serialized Object from jar-file loading-using class: " + classLoaderClass.getCanonicalName() + "\n" + "Looking for data-file named: " + f + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" + "Didn't have an object with class-name: [" + returnClass + "]\n" + "but rather with class-name: [" + ret.getClass().getName() + "]" ); return returnClass.cast(ret); } catch (Throwable t) { ERROR_EXIT( t, "Exception reading Serialized Object from jar-file, loading-using class: " + classLoaderClass.getCanonicalName() + "\n" + "Looking for data-file named: " + f + "\n" + "And attempting to retrieve an object having class-name: " + returnClass + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" ); throw new UnreachableError(); // Should NOT be possible to reach this statement... } } // ******************************************************************************************** // ******************************************************************************************** // Google Cloud Server - Public Static Inner Class // ******************************************************************************************** // ******************************************************************************************** /** * The Google Cloud Server Storage Bucket extension of "Load File Exception Catch" does the * work that <CODE>LFEC</CODE> does, but for GCS Storage Buckets, rather than operating * system files. * * <EMBED CLASS='external-html' DATA-FILE-ID=LFEC_GCSSB> */ @Torello.JavaDoc.StaticFunctional public static class GCSSB { private GCSSB() { } /** * This will read a Java Serialized {@code java.lang.Object} from a location in a Google * Cloud Server {@code Storage Bucket}. * * @param storage <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_STORAGE> * * @param bucket The {@code bucket} name of the {@code bucket} from a Google Cloud Server * account. * * @param completeFileName <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_CMPL_FNAME> * * @param zip <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_ZIP> * * @param returnClass This is the type expected to be found by Java in the Serialized * {@code Object} Data-File. If an {@code Object} is read from this location, but it does * not have the type indicated by this parameter, the program will also halt, and an * explanatory exception message will be printed to the console/terminal. * * @param <T> This type parameter is simply provided for convenience, to allow the user * to specify the return class, without having to cast the object and suppress warnings, * or catch exceptions. * * @return A de-serialized java {@code java.lang.Object} that has been read from a GCS * {@code Storage Bucket}, and cast to the type denoted by parameter * {@code 'returnClass'}. * * @see FileRW#readObjectFromFile(String, boolean) * @see FileRW#readObjectFromFileNOCNFE(String, boolean) * @see #readObjectFromFile(String, boolean, Class) * @see #ERROR_EXIT(String) */ public static <T> T readObjectFromFile( Storage storage, String bucket, String completeFileName, boolean zip, Class<T> returnClass ) { try { // Read Storage Bucket Data into a byte[] array byte[] bArr = storage.get(bucket, completeFileName).getContent(); // Build an Input Stream, using that byte[] array as input ByteArrayInputStream bis = new ByteArrayInputStream(bArr); // Build an Object Input Stream, using the byte-array input-stream as input ObjectInputStream ois = zip ? new ObjectInputStream(new GZIPInputStream(bis)) : new ObjectInputStream(bis); // Use Java's Object Serialization method to read the Object Object ret = ois.readObject(); if (! returnClass.isInstance(ret)) ERROR_EXIT( "Serialized Object read from GCS Storage Bucket: " + bucket + "\n" + "And file-name: " + completeFileName + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" + "Didn't have an object with class-name: " + returnClass + "\n" + "But rather with className: " + ret.getClass().getName() ); ois.close(); bis.close(); return returnClass.cast(ret); } catch (Throwable t) { ERROR_EXIT( t, "Serialized Object read from GCS Storage Bucket: " + bucket + "\n" + "And file-name: " + completeFileName + "\n" + "Using expected (" + (zip ? "zip-compression" : "no-compression") + ")\n" + "And Expected class-name: " + returnClass + "\n" ); throw new UnreachableError(); // Cannot reach this statement } } /** * This merely loads a text-file from Google's Storage Bucket infrastructure into a * {@code String.} Make sure to check that the file you are loading does indeed have * text-content. * * @param storage <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_STORAGE> * * @param bucket The {@code bucket} name of the {@code bucket} from a Google Cloud Server * account. * * @param completeFileName <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_CMPL_FNAME> * * @return The text file on Google Cloud Server's Storage Bucket file/directory returned as * a {@code java.lang.String} */ public static String loadFileToString (Storage storage, String bucket, String completeFileName) { return new String(storage.get(bucket, completeFileName).getContent()); } /** * This merely loads a text-file from Google's Storage Bucket infrastructure into a * {@code String}. Make sure to check that the file you are loading does indeed have * text-content. * * @param storage <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_STORAGE> * * @param bucket The {@code bucket} name of the {@code bucket} from a Google Cloud Server * account. * * @param completeFileName <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_CMPL_FNAME> * * @param includeNewLine This tells the method to include, or not-include, a {@code '\n'} * (newline) character to each {@code String}. * * @return The text file on Google Cloud Server's {@code Storage Bucket} file/directory * stuff as a {@code Vector} of {@code String's}. * * @see #loadFileToString(Storage, String, String) */ public static Vector<String> loadFileToVector (Storage storage, String bucket, String completeFileName, boolean includeNewLine) { String s = loadFileToString(storage, bucket, completeFileName); Vector<String> ret = new Vector<>(); int pos = 0; int delta = includeNewLine ? 1 : 0; int lastPos = 0; while ((pos = s.indexOf('\n')) != -1) { ret.add(s.substring(lastPos, pos + delta)); lastPos = pos + 1; } if (lastPos < s.length()) ret.add(s.substring(lastPos)); return ret; } /** * This will write the contents of a java {@code 'CharSequence'} - includes * {@code String, StringBuffer & StringBuilder} to a * file on Google Cloud Server's storage bucket system. * * @param storage <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_STORAGE> * * @param bucket The {@code bucket} name of the {@code bucket} from a Google Cloud Server * account. * @param completeFileName <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_CMPL_FNAME> * * @param ASCIIorUTF8 When writing java {@code String's} the file-system, it is generally * not to important to worry about whether java has stored an {@code 'ASCII'} encoded * {@code String}, or a {@code String} encoded using {@code 'UTF-8'}. Most * foreign-language news-sites require the latter ({@code 'UTF-8'}), but any site that is * strictly English can get by with plain old ASCII. * * <BR /><BR /><B><SPAN STYLE="color: red">IMPORTANT:</B></SPAN> When this boolean is * {@code TRUE}, this method will attempt to presume the character-sequence you have passed * is in ASCII, and write it that way. When this boolean is set to {@code FALSE}, * this method will attempt to write the {@code String} of {@code byte's} as a * {@code 'UTF-8'} encoded character-set. * * <BR /><BR /><B>ALSO:</B> I have not made any allowance for Unicode or Unicode little * endian, because I have never used them with either the Chinese or Spanish sites I * scrape. UTF-8 has been the only other character set I encounter. */ public static void writeFile( CharSequence fileAsStr, Storage storage, String bucket, String completeFileName, boolean ASCIIorUTF8 ) { BlobInfo blobInfo = BlobInfo.newBuilder (BlobId.of(bucket, completeFileName)).setContentType("text/plain").build(); byte[] file = ASCIIorUTF8 ? fileAsStr.toString().getBytes() : fileAsStr.toString().getBytes(java.nio.charset.Charset.forName("UTF-8")); Blob blob = storage.create(blobInfo, file); } /** * This will write a Java {@code Serializable Object} to a location in a Google Cloud * Server Storage Bucket. * * @param storage <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_STORAGE> * * @param o This may be any {@code Serializable Java Object}. {@code Serializable Java * Objects} are ones which implement the {@code interface java.io.Serializable}. * * @param bucket The {@code bucket} name of the {@code bucket} from a Google Cloud Server * account. * * @param completeFileName <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_CMPL_FNAME> * * @param zip <EMBED CLASS='external-html' DATA-FILE-ID=GCSSB_ZIP> */ public static void writeObjectToFile( Object o, Storage storage, String bucket, String completeFileName, boolean zip ) throws IOException { // Retrieves a file-name object using a GCS BUCKET-NAME, and the FILE-NAME (in // the bucket) BlobId blobId = BlobId.of(bucket, completeFileName); // This BlobInfo is GCS version of "java.io.File". It points to a specific file // inside a GCS Bucket (which was specified earlier) BlobInfo blobInfo = BlobInfo .newBuilder(blobId) // .setContentType("text/plain") .build(); // This will save the Serialized Object Data to a Stream (and eventually an array) ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This stream writes serialized Java-Objects to the Storage Bucket ObjectOutputStream oos = zip ? new ObjectOutputStream(new GZIPOutputStream(baos)) : new ObjectOutputStream(baos); oos.writeObject(o); oos.flush(); baos.flush(); oos.close(); // Convert that BAOS to a Byte-Array byte[] bArr = baos.toByteArray(); // Write the BYTE-ARRAY to the GCS Bucket and file using the "BlobInfo" that was built // a few lines ago. Blob blob = storage.create(blobInfo, bArr); } } } |