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

import java.net.HttpURLConnection;

// There are quite a number of classes imported from this package
import java.util.concurrent.*;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

import Torello.Java.Additional.Ret2;

// Download an Image to a java.awt.image.BufferedImage instance
class DownloadImage
{
    // Has one method inside ImageScraper - namely Shut-Down Time-Out Threads...
    static final ExecutorService executor = Executors.newCachedThreadPool();

    // Used Internally only / private
    private static final Lock lock = new ReentrantLock();

    static Ret2<BufferedImage, IF> run(RECORD r) throws ImageScraperException
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Do the "Skipping URL" Lambda-Target right now (if the user's Request-Instance has one)
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        if (r.request.skipURL != null)
        {
            try 
            {
                if (r.request.skipURL.test(r.url))
                {
                    // This *ISN'T* Exception-Case Code, it is a situation where the user has
                    // intentionally asked that this URL be skipped.
        
                    if (r.logLevelEQ1) r.append("x ");
    
                    if (r.logLevelGTEQ2)
                        r.appendI4("URL Skip-Predicate requests this URL be skipped.\n");
    
                    r.results.skippedURL(r.url);
                    return null;
                }
            }

            catch (Exception e)
            {
                // This call either returns null, or throws an ImageScraperException 
                // Depending upon the boolean 'r.request.skipOnUserLambdaException'
                //
                // NOTE: This **DOESN'T** return (for now).  This is actually a non-fatal exception
                //       and progress can actually continue

                r.reportEx(
                    r.request.skipOnUserLambdaException,
                    "Exception Thrown by User-Provided Lambda-Target 'Request.skipURL'",
                    "Invoke User 'Request.skipURL' Lambda-Target",
                    e
                );
            } 
        }
        

        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build a Monitor Thread Instance
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        Callable<BufferedImage> threadDownloader = new Callable<BufferedImage>()
        {
            public BufferedImage call() throws ImageScraperException
            { return downloadImageCallable(r); }
        };


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Run the Monitor Thread, return the result... Or Handle the Exception (if there was one)
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        lock.lock();
        Future<BufferedImage> future = executor.submit(threadDownloader);
        lock.unlock();

        try
        {
            BufferedImage bi = future.get(r.request.maxDownloadWaitTime, r.request.waitTimeUnits);

            return (bi == null)
                ? null
                : new Ret2<>(bi, IF.getGuess(r.url.toString()));
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // TimeoutException: Web-Server took longer 'Request.maxDownloadWaitTime'
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        catch (TimeoutException e)
        {
            // This call either returns null, or throws an ImageScraperException 
            // Depending upon the boolean 'r.request.skipOnTimeOutException'

            return r.reportEx(
                r.request.skipOnTimeOutException,
                "Waited: " + r.request.maxDownloadWaitTime + " " +
                    r.request.waitTimeUnits.toString(),
                "HTTP Image-Download",
                e
            );

            // OLD MESSAGE:
            // "The download source-code seems to have waited the maximum amount of time, as " +
            // "specified by the 'maxDownloadWaitTime' configuration parameters:\n" + msg
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // ExecutionException: An "Exception Wrapper" for internal-exceptions
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        //
        // Thrown if there were any exceptions while running the 'Callable' that was created above.
        // Since the Callable's 'call()' method catches its exceptions, and wraps them inside an
        // ImageScraperException, THEORETICALLY, the 'cause'-Throwable for this 'e' should
        // **ALWAYS** be an ImageScraperException
        //
        // NOTE: If there is an ImageScraperException, make sure not to report it a second time!!!

        catch (ExecutionException e)
        {
            Throwable cause = e.getCause();

            if (ImageScraperException.class.isAssignableFrom(cause.getClass()))
                throw (ImageScraperException) cause;

            // This call either returns null, or throws an ImageScraperException 
            // Depending upon the boolean 'r.request.skipOnDownloadException'

            return r.reportEx(
                r.request.skipOnDownloadException,
                "Exception throw by Java Image-Download Code",
                "HTTP Image-Download",
                e
            );
        }


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // InterruptedException: I THINK THIS IS UNREACHABLE - UNLESS USER IS INTERRUPTING THINGS!
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // 
        // This should mostly be unreachable, unless the end user is 'playing games' with Java's
        // Thread Mechanism.  According to the JavaDoc Pgae for 'InterruptedException' - this is
        // only thrown if the Thread is interrupte, which certainly won't happen on account of
        // anything in this tool's code!

        catch (InterruptedException e)
        {
            // This call either returns null, or throws an ImageScraperException 
            // Depending upon the boolean 'r.request.skipOnDownloadException'

            return r.reportEx(
                r.request.skipOnDownloadException,
                "Image Download Code Thread was Interrupted",
                "HTTP Image-Download",
                e
            );
        }
    }

    private static BufferedImage downloadImageCallable(RECORD r) throws ImageScraperException
    {
        BufferedImage       image   = null;
        HttpURLConnection   con     = null;
        Exception           ex      = null;

        try
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // FIRST DOWNLOAD ATTEMPT
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            if (r.request.alwaysUseUserAgent)
            {
                con = (HttpURLConnection) r.url.openConnection();
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", r.request.userAgent);

                image = ImageIO.read(con.getInputStream());
            }

            else image = ImageIO.read(r.url);


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // First Download-Attempt Was Possibly Successfull
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            if (image != null) return image;


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // IF NULL-IMAGE && NO-RETRY: Then either return null or throw ImageScraperException
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            else if (r.request.alwaysUseUserAgent || (! r.request.retryWithUserAgent))
            {
                // This call either returns null, or throws an ImageScraperException 
                // Depending upon the boolean 'r.request.skipOnNullImageException'

                return r.reportEx(
                    r.request.skipOnNullImageException,
                    "Downloaded Empty / Null Image",
                    "HTTP Image-Download",
                    (NullImageException) new NullImageException
                        ("The Image Failed to Download Properly").fillInStackTrace()
                );
            }    
        }

        catch (ImageScraperException e) { throw e; }

        catch (Exception e) // (IOException | IIOException e)
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // EXCEPTION WAS THROWN: So **Possibly** Still need to retry with the User-Agent
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            if (r.request.retryWithUserAgent && (! r.request.alwaysUseUserAgent))
            {
                if (r.logLevelGTEQ2) r.appendI4(
                    "Image Download Failed - Re-attempting Download with / via User-Agent: " +
                        r.request.userAgent + '\n'
                    );
            }

            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // NO RETRY: Either Skip to next image (return null), or throw ImageScraperException
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            else
            {
                // This call either returns null, or throws an ImageScraperException 
                // Depending upon the boolean 'r.request.skipOnDownloadException'

                return r.reportEx(
                    r.request.skipOnDownloadException,
                    "Java HTTP Image Downloader javax.imageio.ImageIO.read(...) threw Exception",
                    "HTTP Image-Download",
                    e
                );
            }
        }

        try
        {
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // SECOND DOWNLOAD ATTEMPT
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            con = (HttpURLConnection) r.url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("User-Agent", r.request.userAgent);

            image = ImageIO.read(con.getInputStream());


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // Second Download-Attempt Was Possibly Successfull
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

            if (image != null) return image;


            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            // IF NULL-IMAGE: Then either return null or throw ImageScraperException
            // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
            //
            // This call either returns null, or throws an ImageScraperException 
            // Depending upon the boolean 'r.request.skipOnNullImageException'

            return r.reportEx(
                r.request.skipOnNullImageException,
                "Downloaded Empty / Null Image",
                "HTTP Image-Download",
                (NullImageException) new NullImageException
                    ("The Image Failed to Download Properly").fillInStackTrace()
            );
        }

        catch (ImageScraperException e) { throw e; }

        catch (Exception e)
        {
            // This call either returns null, or throws an ImageScraperException 
            // Depending upon the boolean 'r.request.skipOnNullskipOnDownloadExceptionImageException'

            return r.reportEx(
                r.request.skipOnDownloadException,
                "Java HTTP Image Downloader javax.imageio.ImageIO.read(...) threw Exception",
                "HTTP Image-Download",
                e
            );
        }
    }
}