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
package Torello.HTML.Tools.Images;

import Torello.Java.*;

// Needed for a JavaDoc Comment {@link ...}
import Torello.HTML.TagNode;

import java.net.URL;
import java.io.Serializable;
import java.util.Arrays;

/**
 * After downloading all of the user's requested images, the class {@link ImageScraper} returns an
 * instance of this class.
 * 
 * <BR /><BR />When a download request has completed, this class will be instantiated and returned.
 * Care has been taken to ensure this class does not freeze nor fail when a particular image fails
 * to download.  This level of control is customizable, so if the programmer would prefer download 
 * execution to halt immediately upon exception, there is are several settings for this in the
 * class {@link Request}.
 * 
 * <BR /><BR />The link below contains the output of invoking the {@link #toString} method on a
 * {@code 'Results'} instance after downloading all of the HTML {@code <IMG SRC=...>} tags that
 * were scraped from the Web-Server {@code news.yahoo.com}.
 * 
 * <BR /><BR /><B><CODE><A HREF='doc-files/results.txt'>results.txt</A></CODE></B>
 *
 * <BR /><BR /><B CLASS=JDDescLabel>Initializations:</B>
 * 
 * <BR />Many of the values in the arrays for class {@code 'Results'} (this class) may contain
 * null-values, or a {@code '-1'}.  This happens if an exceptions is thrown while downloading or
 * saving any one particular image, which prevents the process from running to completion.
 * 
 * <BR /><BR />To view the exact initialization-value for elements of any of these array, simply
 * click on the <B><CODE><A HREF='hilite-files/Results.java.html'>HiLited Source-Code</A></CODE>
 * </B> link, and scroll down to the <B>Package-Private</B> <CODE>Results</CODE> class constructor.
 *
 * <BR /><BR /><B CLASS=JDDescLabel>The 'skipped' Array:</B>
 * 
 * <BR />There is an easy way to check which {@code URL's} have failed or were skipped (due
 * to user-request), and which {@code URL's} were successfully obtained.  One of several arrays
 * that are {@code public} in this class is the {@link #skipped} {@code boolean[]}-array.
 * 
 * <BR /><BR /> Whenever a particular {@code URL}-index corresponds to a {@code skipped}-index that
 * contains a {@code FALSE} boolean-value, it indicates that that particular {@code URL} ultimately
 * was not properly saved or re-transmitted.
 * 
 * @see ImageScraper
 */
@Torello.JavaDoc.JDHeaderBackgroundImg(EmbedTagFileID="IMAGE_SCRAPER_CLASS")
public class Results implements Serializable, Cloneable
{
    /** <EMBED CLASS='external-html' DATA-FILE-ID=SVUID> */
    public static final long serialVersionUID = 1;


    // ********************************************************************************************
    // ********************************************************************************************
    // Public Array Fields: User may inspect these fields when an instance of 'Results' is returned
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * This will contain a complete list of the {@code URL's} that were retrieved (or generated-
     * <I>if partially-resolved 'relative' {@code URL's} were provided</I>) from the
     * {@link Request}-instances {@code static}-builder.  Every image downloaded (or attempted for
     * download) will have its {@code URL} saved here, in this array.
     *
     * <BR /><BR /><B CLASS=JDDescLabel>Null's in the {@code urls} Array</B>
     * 
     * <BR />An array-element of the {@code urls}-array will contain null under the following
     * two circumstances:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * 
     * <LI> No image-{@code URL} was provided, becasue the picture was a Base-64 Encoded Image, and
     *      instead was a {@code String} that had been retrieved from a {@link TagNode}'s
     *      {@code SRC}-Attribute.
     *      <BR /><BR />
     *      </LI>
     *
     * <LI> The user provided a {@code String} to the {@link Request} Class builder, but that 
     *      {@code String} caused a {@code MalformedURLException}, and no {@code URL}-instance
     *      was ever built.  (Note that in this scenario, the {@link #exceptions} array would be
     *      storing the {@code URL}-Exception that was thrown).
     *      <BR /><BR />
     *      </LI>
     * 
     * </UL>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final URL[] urls;

    /**
     * When constructing an {@link ImageScraper}'s {@link Request} object, one of the options for
     * building the instance is to pass a list of HTML {@link TagNode} instances containing HTML
     * {@code '<IMG SRC=...>'} tags.
     * 
     * <BR /><BR />HTML {@code TagNode} elements will sometimes / occasionally have a variant of an
     * image source known as the <B STYLE='color: red;'>Base-64 Encoded Image</B>.  These are
     * images where the actual pictures fully stored &amp; encoded inside the {@code SRC}-Attribute
     * of the HTML {@link TagNode}'s {@code SRC}-Attribute.
     * 
     * <BR /><BR />Base-64 Images are just pictures that have been converted into actual character
     * data, in the form of a simple {@code String}, and saved into the {@code <IMG>} tag's
     * {@code SRC}-URL - <I>instead of an actual HTTP {@code URL} being saved there</I>.  Note that
     * this practice is generally used for much smaller pictures, thumbnails or logo signs (images
     * that wouldn't use up a lot of data).
     * 
     * <BR /><BR />A full explanation of HTML's {@code Base-64} Image-Encoding is beyone the scope
     * of this Java-Doc Comment.
     * 
     * <BR /><BR />If any image was "converted" from a B-64 Image-Encoding (rather than downloaded
     * from a {@code URL}), then the boolean for the image's index will be {@code TRUE} rather than
     * {@code FALSE}.  The default value for all elements of this array is {@code FALSE}.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */    
    public final boolean[] b64EncodedImg;

    /**
     * An images {@code Results}-data in this particular paralell-array will be {@code TRUE} under
     * any of the following circumstances:
     * 
     * <BR /><BR /><UL CLASS=JDUL>
     * 
     * <LI> If the user provided a {@link Request#skipURL}-Predicate, and that predicate rejected
     *      the image (telling the downloader not to download the picture).
     *      <BR /><BR />
     *      </LI>
     * 
     * <LI> If the user provided a {@link Request#keeperPredicate}, and that predicate, after
     *      image-downloade complettion, rejected the image (telling the downloader not save the 
     *      picture to disk the picture).
     *      <BR /><BR />
     *      </LI>
     * 
     * <LI> If there were any exceptions thrown while downloading the image that forced the
     *      downloader-logic to abandon the image (and either throw the exception, or
     *      skip-and-move-on to the next image).
     *      <BR /><BR />
     *      </LI>
     *
     * <LI> If the original {@code Iterable} that was provided to the {@link Request}-instance
     *      had entries that had caused {@code exceptions} to be thrown while building the
     *      {@link Request}-instance.
     *      </LI>
     * 
     * </UL>
     * 
     * <BR /><B STYLE='color: red;'><I>Under any / all other circumstances, if an image was
     * successfully downloaded and written to disk, then the corresponding element in this array
     * will contain {@code FALSE}!</I></B>
     *
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final boolean[] skipped;

    /**
     * The names of the files that were retrieved and/or stored will be in this array.
     * If this image were skipped or an exception occurred, the array position for that
     * {@code URL} would contain 'null'.
     * 
     * <BR /><BR />It is important to note that if an element of this array contains a valid,
     * non-null, file-name - <I><B>it does not guarantee that the image was properly saved</B></I>.
     * The value stored in the corresponding (parallel) {@link #skipped}-array index is the only
     * way to ascertain whether an image was ultimately written to disk (or transmitted to a 
     * User-Provided {@link Request#imageReceiver}).
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final String[] fileNames;

    /**
     * The location of the file-name saved directory, if an image did not successfully save to
     * the file system, or if an {@code imageReceiver} were used, then the array-location would
     * contain {@code 'null'}.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final String[] saveDirectories;

    /**
     * The image type of the files that were retrieved will be stored in this array.
     * 
     * <EMBED CLASS='external-html' DATA-DEFVAL=null DATA-SPEC="image-format"
     *      DATA-FILE-ID=REQ_SKIPPED_NOTE>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final IF[] imageFormats;

    /**
     * If any stage of the image download, conversion or disk-write fails, then this array will
     * store a record the exception that was thrown.
     *
     * <BR /><BR />If the download succeeded, then the {@code 'exceptions'}-array element at that
     * index would contain 'null.'  Any {@code exceptions}-array index that contains a non-null 
     * {@code Exception} will be an index for which the {@link #skipped}-array contains a
     * {@code TRUE}-value stored at the same location.
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final Exception[] exceptions;

    /**
     * This will contain a list of long-integers, each of which will have the file-size of the
     * downloaded image.  
     * 
     * <EMBED CLASS='external-html' DATA-DEFVAL="-1" DATA-SPEC=size DATA-FILE-ID=REQ_SKIPPED_NOTE>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final long[] sizes;

    /**
     * This will contain a list of integers, each of which shall have the image-widths of the 
     * downloaded images.
     * 
     * <EMBED CLASS='external-html' DATA-DEFVAL="-1" DATA-SPEC=width DATA-FILE-ID=REQ_SKIPPED_NOTE>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final int[] widths;

    /**
     * This shall contain a list of integers, each of which shall have the image-heights of 
     * the downloaded images.
     * 
     * <EMBED CLASS='external-html' DATA-DEFVAL="-1" DATA-SPEC=height
     *      DATA-FILE-ID=REQ_SKIPPED_NOTE>
     * 
     * <EMBED CLASS='external-html' DATA-FILE-ID=REQ_PARALLEL_NOTE>
     */
    public final int[] heights;


    // ********************************************************************************************
    // ********************************************************************************************
    // Some Package-Private Fields, Used here and by class ImageScraper
    // ********************************************************************************************
    // ********************************************************************************************


    // next result received array position.
    int pos = 0;

    // number of successfully saved images.
    int successCounter = 0;


    // ********************************************************************************************
    // ********************************************************************************************
    // Package-Private Constructor
    // ********************************************************************************************
    // ********************************************************************************************


    Results(int size)
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Create each of these arrays
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        urls                = new URL[size];
        b64EncodedImg       = new boolean[size];
        skipped             = new boolean[size];
        fileNames           = new String[size];
        saveDirectories     = new String[size];
        imageFormats        = new IF[size];
        exceptions          = new Exception[size];
        sizes               = new long[size];
        widths              = new int[size];
        heights             = new int[size];


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Initialize each element of the above arrays
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        for (int i=0; i < size; i++)
        {
            urls[i]             = null;
            b64EncodedImg[i]    = false;
            skipped[i]          = false;
            fileNames[i]        = null;
            saveDirectories[i]  = null;
            imageFormats[i]     = null;
            exceptions[i]       = null;
            sizes[i]            = -1;
            widths[i]           = -1;
            heights[i]          = -1;
        }
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // No Image Downloaded
    // ********************************************************************************************
    // ********************************************************************************************


    // Request static-builder generated an "Exception URL"
    // Called From: ImageScraper.loopBody(RECORD)

    void tagNodeSRCError(Exception e)
    {
        skipped[pos]    = true;
        exceptions[pos] = e;

        pos++;
    }

    // User-Provided "Predicate<URL> skipURL"
    // Called From: ImageScraper.downloadImage(RECORD)

    void skippedURL(URL url)
    {
        urls[pos]       = url;
        skipped[pos]    = true;

        pos++;
    }

    // User-Provided "boolean skipBase64EncodedImages"
    // Called From: ImageScraper.convertB64Image(RECORD)

    void skipB64()
    {
        b64EncodedImg[pos]  = true;
        skipped[pos]        = true;

        pos++;
    }

    // Called from many places.  This method is the biggest of the Results-Reporters 
    //   * Exception-thrown
    //   * 'ImageInfo' instance hasn't been constructed yet

    void exceptionFail(URL url, Exception e)
    {
        urls[pos]           = url;
        b64EncodedImg[pos]  = (url == null);
        skipped[pos]        = true;
        exceptions[pos]     = e;

        pos++;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // "ImageInfo" instance available now: Image Successfully Downloaded and Converted to Array.
    // ********************************************************************************************
    // ********************************************************************************************


    // There are 3 different User-Provided Lambda-Target's that might throw exceptions
    // This is called from within "ImageScraper.RECORD.userLambdaEx(...)"

    void userLambdaException(ImageInfo imageInfo, Exception e)
    {
        skipped[pos]    = true;
        exceptions[pos] = e;

        copyImageInfo(imageInfo);
    }

    // The User Keep/Reject Predicate rejected this image
    // Called From: ImageScraper.handleImageByteArray(RECORD)

    void predicateReject(ImageInfo imageInfo)
    {
        skipped[pos] = true;
        copyImageInfo(imageInfo);
    }

    // Image was written to disk somewhere, or accepted by the Request.imageReceiver
    // Called From: ImageScraper.writeOrTransmit(RECORD)

    void success(ImageInfo imageInfo, String targetDirectory)
    {
        // Directory where the image was saved, if called by "ImageReceiver", this will be null
        saveDirectories[pos] = targetDirectory;

        copyImageInfo(imageInfo);

        // Only time this is ever incremented
        successCounter++;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // SMALL HELPER
    // ********************************************************************************************
    // ********************************************************************************************


    // Private Method, used in all 5 previous methods directly above here
    private void copyImageInfo(ImageInfo imageInfo)
    {
        urls[pos]           = imageInfo.url;
        b64EncodedImg[pos]  = imageInfo.isB64EncodedImage;
        imageFormats[pos]   = imageInfo.actualExtension;
        sizes[pos]          = imageInfo.imgByteArr.length;
        widths[pos]         = imageInfo.width;
        heights[pos]        = imageInfo.height;
        fileNames[pos]      = imageInfo.fileName() + '.' + imageInfo.actualExtension;

        pos++;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // interface java.lang.Cloneable
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Generates a <B STYLE='color: red;'>Deep Copy</B> of {@code 'this'} instance.  This means
     * all internal arrays are also cloned / copied
     * 
     * @return A duplicate instance of this class, with all arrays having been copied.
     */
    public Results clone()
    { return new Results(this); }

    // Private Constructor, used only for the 'clone()' method
    private Results(Results r)
    {
        this.urls               = r.urls.clone();
        this.b64EncodedImg      = r.b64EncodedImg.clone();
        this.skipped            = r.skipped.clone();
        this.fileNames          = r.fileNames.clone();
        this.saveDirectories    = r.saveDirectories.clone();
        this.imageFormats       = r.imageFormats.clone();
        this.exceptions         = r.exceptions.clone();
        this.sizes              = r.sizes.clone();
        this.widths             = r.widths.clone();
        this.heights            = r.heights.clone();

        this.pos                = r.pos;
        this.successCounter     = r.successCounter;
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // java.lang.Object
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Checks whether {@code 'this'} instance is equal to another instance of class
     * {@code Results}.  This method performs a <B STYLE='color: red;'>Deep Equals</B> comparison
     * using the {@code equals(...)} method suite found in class' {@code java.util.Arrays}.
     * 
     * @param other This may be any Java Object, but only an instance class {@code 'Results'} has
     * any chance of being marked as <B STYLE='color: red;'>equal</B> to this instance.
     * 
     * @return {@code TRUE} if and only if {@code 'o'} has a type that's assignable to
     * {@code Results} - and if each of the internal arrays in this instance are equal to the
     * arrays in parameter {@code 'o'}.
     */
    public boolean equals(Object other)
    {
        if (other == null) return false;

        if (! Results.class.isAssignableFrom(other.getClass())) return false;

        Results r = (Results) other;


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // NOTE: These arrays cannot ever be null, that is an "Unreachable Situation"
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return 
                Arrays.equals(this.urls,            r.urls)
            &&  Arrays.equals(this.b64EncodedImg,   r.b64EncodedImg)
            &&  Arrays.equals(this.skipped,         r.skipped)
            &&  Arrays.equals(this.fileNames,       r.fileNames)
            &&  Arrays.equals(this.saveDirectories, r.saveDirectories)
            &&  Arrays.equals(this.imageFormats,    r.imageFormats)
            &&  Arrays.equals(this.exceptions,      r.exceptions)
            &&  Arrays.equals(this.sizes,           r.sizes)
            &&  Arrays.equals(this.widths,          r.widths)
            &&  Arrays.equals(this.heights,         r.heights);
    }

    // Used in the above toString() method
    private static final String COMMA = ", ";

    /**
     * Returns a {@code java.lang.String} representation of {@code 'this'} instance
     * 
     * @return A Java {@code String} containing the data inside this class.
     */
    public String toString()
    {
        StringBuilder sb = new StringBuilder();


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // NOTE: These arrays, themselves can never be null - BUT THEIR CONTENTS ARE OFTEN NULL
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        for (int i=0; i < urls.length; i++)
        {
            if (b64EncodedImg[i]) sb.append("Base 64 Encoded Image\n");

            else sb.append(
                "URL: " + ((urls[i] == null)
                    ? "null"
                    : StrPrint.abbrev(urls[i].toString(), 50, true, " ... ", 100)) +
                '\n'
            );

            boolean comma = false;

            if (skipped[i] == true)
            {
                sb.append("    SKIPPED");
                comma = true;
            }

            if (imageFormats[i] != null)
            {
                sb.append(comma ? COMMA : "    ");
                sb.append("Format: " + imageFormats[i]);
                comma = true;
            }

            if (sizes[i] > 0)
            {
                sb.append(comma ? COMMA : "    ");
                sb.append("Size: " + StringParse.commas(sizes[i]));
                comma = true;
            }

            if (widths[i] > 0)
            {
                sb.append(comma ? COMMA : "    ");
                sb.append("W: " + StringParse.commas(widths[i]));
                comma = true;
            }

            if (heights[i] > 0)
            {
                sb.append(comma ? COMMA : "    ");
                sb.append("H: " + StringParse.commas(heights[i]));
                comma = true;
            }

            if (comma) sb.append('\n');

            comma = false;

            if (fileNames[i] != null)
            {
                sb.append("    FileName: [" + fileNames[i] + ']');
                comma = true;
            }

            if (saveDirectories[i] != null)
            {
                sb.append(comma ? COMMA : "    ");
                sb.append("Dir: [" + StrPrint.abbrev(saveDirectories[i], 30, true, null, 60) + ']');
                comma = true;
            }

            if (comma) sb.append('\n');

            if (exceptions[i] != null)
                sb.append("    Thrown: " + exceptions[i].getClass().getName() + '\n');

            if (i < (urls.length - 1)) sb.append('\n');
        }

        return sb.toString();
    }

    /**
     * Java's hash-code requirement.  The code is computed by summing the first 10 {@link #sizes}
     * array elements.
     * 
     * @return A hash-code that may be used when storing this node in a java sorted-collection.
     */
    public int hashCode()
    {
       int sum = 0;

       for (int i=0; (i < 10) && (i < sizes.length); i++) sum += sizes[i];

       return sum;
    }
}