aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/image/ImageFactory.java
blob: 62a46f7f4fd3036153dc6fd87d3b9a566626845c (plain)
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
/*
 * $Id: ImageFactory.java,v 1.15 2003/03/06 21:25:44 jeremias Exp $
 * ============================================================================
 *                    The Apache Software License, Version 1.1
 * ============================================================================
 *
 * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modifica-
 * tion, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. The end-user documentation included with the redistribution, if any, must
 *    include the following acknowledgment: "This product includes software
 *    developed by the Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself, if
 *    and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "FOP" and "Apache Software Foundation" must not be used to
 *    endorse or promote products derived from this software without prior
 *    written permission. For written permission, please contact
 *    apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache", nor may
 *    "Apache" appear in their name, without prior written permission of the
 *    Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
 * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ============================================================================
 *
 * This software consists of voluntary contributions made by many individuals
 * on behalf of the Apache Software Foundation and was originally created by
 * James Tauber <jtauber@jtauber.com>. For more information on the Apache
 * Software Foundation, please see <http://www.apache.org/>.
 */
package org.apache.fop.image;

// Java
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Set;
import java.util.Collections;
import java.util.Iterator;

// Avalon
import org.apache.avalon.framework.logger.Logger;

// FOP
import org.apache.fop.image.analyser.ImageReaderFactory;
import org.apache.fop.apps.FOUserAgent;


/**
 * Create FopImage objects (with a configuration file - not yet implemented).
 * @author Eric SCHAEFFER
 */
public class ImageFactory {

    private static ImageFactory factory = new ImageFactory();

    private ImageCache cache = new ContextImageCache(true);

    private ImageFactory() {
    }

    /**
     * Get static image factory instance.
     *
     * @return the image factory instance
     */
    public static ImageFactory getInstance() {
        return factory;
    }

    /**
     * Get the url string from a wrapped url.
     *
     * @param href the input wrapped url
     * @return the raw url
     */
    public static String getURL(String href) {
        /*
         * According to section 5.11 a <uri-specification> is:
         * "url(" + URI + ")"
         * according to 7.28.7 a <uri-specification> is:
         * URI
         * So handle both.
         */
        href = href.trim();
        if (href.startsWith("url(") && (href.indexOf(")") != -1)) {
            href = href.substring(4, href.indexOf(")")).trim();
            if (href.startsWith("'") && href.endsWith("'")) {
                href = href.substring(1, href.length() - 1);
            } else if (href.startsWith("\"") && href.endsWith("\"")) {
                href = href.substring(1, href.length() - 1);
            }
        } else {
            // warn
        }
        return href;
    }

    /**
     * Get the image from the cache or load.
     * If this returns null then the image could not be loaded
     * due to an error. Messages should be logged.
     * Before calling this the getURL(url) must be used.
     *
     * @param url the url for the image
     * @param context the user agent context
     * @return the fop image instance
     */
    public FopImage getImage(String url, FOUserAgent context) {
        return cache.getImage(url, context);
    }

    /**
     * Release an image from the cache.
     * This can be used if the renderer has its own cache of
     * the image.
     * The image should then be put into the weak cache.
     *
     * @param url the url for the image
     * @param context the user agent context
     */
    public void releaseImage(String url, FOUserAgent context) {
        cache.releaseImage(url, context);
    }

    /**
     * Release the context and all images in the context.
     *
     * @param context the context to remove
     */
    public void removeContext(FOUserAgent context) {
        cache.removeContext(context);
    }

    /**
     * Create an FopImage objects.
     * @param href the url for the image
     * @param ua the user agent context
     * @return the fop image instance
     */
    public static FopImage loadImage(String href, FOUserAgent ua) {
        Logger log = ua.getLogger();

        InputStream in = openStream(href, ua);

        if (in == null) {
            return null;
        }

        // If not, check image type
        FopImage.ImageInfo imgInfo = null;
        try {
            imgInfo = ImageReaderFactory.make(
                          href, in, ua);
        } catch (Exception e) {
            log.error("Error while recovering image information ("
                    + href + ") : " + e.getMessage(), e);
            return null;
        }
        if (imgInfo == null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
                log.debug("Error closing the InputStream for the image", e);
            }
            log.error("No ImageReader for this type of image ("
                    + href + ")");
            return null;
        }
        // Associate mime-type to FopImage class
        String imgMimeType = imgInfo.mimeType;
        String imgClassName = getImageClassName(imgMimeType);
        if (imgClassName == null) {
            log.error("Unsupported image type ("
                    + href + "): " + imgMimeType);
            return null;
        }

        // load the right image class
        // return new <FopImage implementing class>
        Object imageInstance = null;
        Class imageClass = null;
        try {
            imageClass = Class.forName(imgClassName);
            Class[] imageConstructorParameters = new Class[1];
            imageConstructorParameters[0] = org.apache.fop.image.FopImage.ImageInfo.class;
            Constructor imageConstructor =
              imageClass.getDeclaredConstructor(
                imageConstructorParameters);
            Object[] initArgs = new Object[1];
            initArgs[0] = imgInfo;
            imageInstance = imageConstructor.newInstance(initArgs);
        } catch (java.lang.reflect.InvocationTargetException ex) {
            Throwable t = ex.getTargetException();
            String msg;
            if (t != null) {
                msg = t.getMessage();
            } else {
                msg = ex.getMessage();
            }
            log.error("Error creating FopImage object ("
                    + href + "): " + msg, (t == null) ? ex : t);
            return null;
        } catch (Exception ex) {
            log.error("Error creating FopImage object ("
                    + href + "): " + ex.getMessage(), ex);
            return null;
        }
        if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
            log.error("Error creating FopImage object ("
                    + href + "): " + "class "
                    + imageClass.getName()
                    + " doesn't implement org.apache.fop.image.FopImage interface");
            return null;
        }
        return (FopImage) imageInstance;
    }

    /**
     * Create an FopImage objects.
     * @param href image URL as a String
     * @param ua user agent
     * @return a new FopImage object
     */
    protected static InputStream openStream(String href, FOUserAgent ua) {
        Logger log = ua.getLogger();
        // Get the absolute URL
        URL absoluteURL = null;
        InputStream in = null;
        try {
            in = ua.getStream(href);
        } catch (IOException ioe) {
            log.error("Error while opening stream for ("
                    + href + "): " + ioe.getMessage(), ioe);
            return null;
        }
        if (in == null) {
            try {
                // try url as complete first, this can cause
                // a problem with relative uri's if there is an
                // image relative to where fop is run and relative
                // to the base dir of the document
                try {
                    absoluteURL = new URL(href);
                } catch (MalformedURLException mue) {
                    // if the href contains only a path then file is assumed
                    absoluteURL = new URL("file:" + href);
                }
                in = absoluteURL.openStream();
            } catch (MalformedURLException mfue) {
                log.error("Error with image URL: " + mfue.getMessage(), mfue);
                return null;
            } catch (Exception e) {
                // maybe relative
                if (ua.getBaseURL() == null) {
                    log.error("Error with image URL: " + e.getMessage()
                            + " and no base URL is specified", e);
                    return null;
                }
                try {
                    absoluteURL = new URL(ua.getBaseURL() + absoluteURL.getFile());
                } catch (MalformedURLException e_context) {
                    // pb context url
                    log.error("Invalid Image URL - error on relative URL: "
                            + e_context.getMessage(), e_context);
                    return null;
                }
            }
        } /* if (in == null) */

        try {
            if (in == null && absoluteURL != null) {
                in = absoluteURL.openStream();
            }
            if (in == null) {
                log.error("Could not resolve URI for image: " + href);
                return null;
            }

            //Decorate the InputStream with a BufferedInputStream
            return new java.io.BufferedInputStream(in);
        } catch (Exception e) {
            log.error("Error while opening stream for ("
                    + href + "): " + e.getMessage(), e);
            return null;
        }
    }

    private static String getImageClassName(String imgMimeType) {
        String imgClassName = null;
        if ("image/gif".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.GifImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/jpeg".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.JpegImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/bmp".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.BmpImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/eps".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.EPSImage";
        } else if ("image/png".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.JimiImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/tga".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.JimiImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/tiff".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.JimiImage";
            // imgClassName = "org.apache.fop.image.JAIImage";
        } else if ("image/svg+xml".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.XMLImage";
        } else if ("text/xml".equals(imgMimeType)) {
            imgClassName = "org.apache.fop.image.XMLImage";
        }
        return imgClassName;
    }
}

/**
 * Basic image cache.
 * This keeps track of invalid images.
 */
class BasicImageCache implements ImageCache {

    private Set invalid = Collections.synchronizedSet(new java.util.HashSet());
    private Map contextStore = Collections.synchronizedMap(new java.util.HashMap());

    public FopImage getImage(String url, FOUserAgent context) {
        if (invalid.contains(url)) {
            return null;
        }
        return null;
    }

    public void releaseImage(String url, FOUserAgent context) {
        // do nothing
    }

    public void invalidateImage(String url, FOUserAgent context) {
        // cap size of invalid list
        if (invalid.size() > 100) {
            invalid.clear();
        }
        invalid.add(url);
    }

    public void removeContext(FOUserAgent context) {
        // do nothing
    }
}

/**
 * This is the context image cache.
 * This caches images on the basis of the given context.
 * Common images in different contexts are currently not handled.
 * There are two possiblities, each context handles its own images
 * and renderers can cache information or images are shared and
 * all information is retained.
 * Once a context is removed then all images are placed into a
 * weak hashmap so they may be garbage collected.
 */
class ContextImageCache implements ImageCache {

    // if this cache is collective then images can be shared
    // among contexts, this implies that the base directory
    // is either the same or does not effect the images being
    // loaded
    private boolean collective;
    private Map contextStore = Collections.synchronizedMap(new java.util.HashMap());
    private Set invalid = null;
    private Map weakStore = null;

    public ContextImageCache(boolean col) {
        collective = col;
        if (collective) {
            weakStore = Collections.synchronizedMap(new java.util.WeakHashMap());
            invalid = Collections.synchronizedSet(new java.util.HashSet());
        }
    }

    // sync around lookups and puts
    // another sync around load for a particular image
    public FopImage getImage(String url, FOUserAgent context) {
        ImageLoader im = null;
        // this protects the finding or creating of a new
        // ImageLoader for multi threads
        synchronized (this) {
            if (collective && invalid.contains(url)) {
                return null;
            }
            Context con = (Context) contextStore.get(context);
            if (con == null) {
                con = new Context(context, collective);
                contextStore.put(context, con);
            } else {
                if (con.invalid(url)) {
                    return null;
                }
                im = con.getImage(url);
            }
            if (im == null && collective) {
                Iterator i = contextStore.values().iterator();
                while (i.hasNext()) {
                    Context c = (Context)i.next();
                    if (c != con) {
                        im = c.getImage(url);
                        if (im != null) {
                            break;
                        }
                    }
                }
                if (im == null) {
                    im = (ImageLoader) weakStore.get(url);
                }
            }

            if (im != null) {
                con.putImage(url, im);
            } else {
                im = con.getImage(url, this);
            }
        }

        // the ImageLoader is synchronized so images with the
        // same url will not be loaded at the same time
        if (im != null) {
            return im.loadImage();
        }
        return null;
    }

    public void releaseImage(String url, FOUserAgent context) {
        Context con = (Context) contextStore.get(context);
        if (con != null) {
            if (collective) {
                ImageLoader im = con.getImage(url);
                weakStore.put(url, im);
            }
            con.releaseImage(url);
        }
    }

    public void invalidateImage(String url, FOUserAgent context) {
        if (collective) {
            // cap size of invalid list
            if (invalid.size() > 100) {
                invalid.clear();
            }
            invalid.add(url);
        }
        Context con = (Context) contextStore.get(context);
        if (con != null) {
            con.invalidateImage(url);
        }
    }

    public void removeContext(FOUserAgent context) {
        Context con = (Context) contextStore.get(context);
        if (con != null) {
            if (collective) {
                Map images = con.getImages();
                weakStore.putAll(images);
            }
            contextStore.remove(context);
        }
    }

    class Context {
        private Map images = Collections.synchronizedMap(new java.util.HashMap());
        private Set invalid = null;
        private FOUserAgent userAgent;

        public Context(FOUserAgent ua, boolean inv) {
            userAgent = ua;
            if (inv) {
                invalid = Collections.synchronizedSet(new java.util.HashSet());
            }
        }

        public ImageLoader getImage(String url, ImageCache c) {
            if (images.containsKey(url)) {
                return (ImageLoader) images.get(url);
            }
            ImageLoader loader = new ImageLoader(url, c, userAgent);
            images.put(url, loader);
            return loader;
        }

        public void putImage(String url, ImageLoader image) {
            images.put(url, image);
        }

        public ImageLoader getImage(String url) {
            return (ImageLoader) images.get(url);
        }

        public void releaseImage(String url) {
            images.remove(url);
        }

        public Map getImages() {
            return images;
        }

        public void invalidateImage(String url) {
            invalid.add(url);
        }

        public boolean invalid(String url) {
            return invalid.contains(url);
        }

    }

}