KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > fop > image > FopImageFactory


1 /*
2  * $Id: FopImageFactory.java,v 1.25.2.13 2003/05/10 18:29:58 jeremias Exp $
3  * ============================================================================
4  * The Apache Software License, Version 1.1
5  * ============================================================================
6  *
7  * Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without modifica-
10  * tion, are permitted provided that the following conditions are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if any, must
20  * include the following acknowledgment: "This product includes software
21  * developed by the Apache Software Foundation (http://www.apache.org/)."
22  * Alternately, this acknowledgment may appear in the software itself, if
23  * and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "FOP" and "Apache Software Foundation" must not be used to
26  * endorse or promote products derived from this software without prior
27  * written permission. For written permission, please contact
28  * apache@apache.org.
29  *
30  * 5. Products derived from this software may not be called "Apache", nor may
31  * "Apache" appear in their name, without prior written permission of the
32  * Apache Software Foundation.
33  *
34  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  * APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  * DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  * ============================================================================
45  *
46  * This software consists of voluntary contributions made by many individuals
47  * on behalf of the Apache Software Foundation and was originally created by
48  * James Tauber <jtauber@jtauber.com>. For more information on the Apache
49  * Software Foundation, please see <http://www.apache.org/>.
50  */

51 package org.apache.fop.image;
52
53 // FOP
54
import org.apache.fop.image.analyser.ImageReaderFactory;
55 import org.apache.fop.image.analyser.ImageReader;
56 import org.apache.fop.configuration.Configuration;
57 import org.apache.fop.messaging.MessageHandler;
58
59 // Java
60
import java.io.IOException JavaDoc;
61 import java.io.InputStream JavaDoc;
62 import java.net.URL JavaDoc;
63 import java.net.MalformedURLException JavaDoc;
64 import java.lang.reflect.Constructor JavaDoc;
65 import java.util.Map JavaDoc;
66
67 /**
68  * create FopImage objects (with a configuration file - not yet implemented).
69  * @author Eric SCHAEFFER
70  */

71 public class FopImageFactory {
72     // prevent instantiation
73
protected FopImageFactory() {}
74
75     private static Map JavaDoc m_urlMap = new java.util.HashMap JavaDoc();
76
77     /**
78      * The class name of the generic image handler.
79      * Will be either jimi or jai depending on what
80      * is available.
81      */

82     private static String JavaDoc m_genericImageClassName = null;
83
84     /**
85      * create an FopImage objects.
86      * @param href image URL as a String
87      * @return a new FopImage object
88      * @exception java.net.MalformedURLException bad URL
89      * @exception FopImageException an error occured during construction
90      */

91     public static synchronized FopImage Make(String JavaDoc href)
92             throws MalformedURLException JavaDoc, FopImageException {
93
94         /*
95          * According to section 5.11 a <uri-specification> is:
96          * "url(" + URI + ")"
97          * according to 7.28.7 a <uri-specification> is:
98          * URI
99          * So handle both.
100          */

101         // Get the absolute URL
102
URL JavaDoc absoluteURL = null;
103         InputStream JavaDoc imgIS = null;
104         href = href.trim();
105         if(href.startsWith("url(") && (href.indexOf(")") != -1)) {
106             href = href.substring(4, href.indexOf(")")).trim();
107             if(href.startsWith("'") && href.endsWith("'")) {
108                 href = href.substring(1, href.length() - 1);
109             } else if(href.startsWith("\"") && href.endsWith("\"")) {
110                 href = href.substring(1, href.length() - 1);
111             }
112         }
113
114         // check if already created
115
FopImage imageObject = (FopImage)m_urlMap.get(href);
116         if (imageObject != null)
117             return imageObject;
118
119         try {
120             // try url as complete first, this can cause
121
// a problem with relative uri's if there is an
122
// image relative to where fop is run and relative
123
// to the base dir of the document
124
try {
125                 absoluteURL = new URL JavaDoc(href);
126             } catch (MalformedURLException JavaDoc mue) {
127                 // if the href contains onl a path then file is assumed
128
absoluteURL = new URL JavaDoc("file:" + href);
129             }
130             imgIS = absoluteURL.openStream();
131         } catch (MalformedURLException JavaDoc e_context) {
132             throw new FopImageException("Error with image URL: "
133                                         + e_context.getMessage());
134         } catch (Exception JavaDoc e) {
135             // maybe relative
136
URL JavaDoc baseURL = Configuration.getBaseURL();
137
138             if (baseURL == null) {
139                 throw new FopImageException("Error with image URL: "
140                                              + e.getMessage()
141                                              + " and no base URL is specified");
142             }
143
144             try {
145                 /*
146                     This piece of code is based on the following statement in RFC2396 section 5.2:
147
148                     3) If the scheme component is defined, indicating that the reference
149                        starts with a scheme name, then the reference is interpreted as an
150                        absolute URI and we are done. Otherwise, the reference URI's
151                        scheme is inherited from the base URI's scheme component.
152
153                        Due to a loophole in prior specifications [RFC1630], some parsers
154                        allow the scheme name to be present in a relative URI if it is the
155                        same as the base URI scheme. Unfortunately, this can conflict
156                        with the correct parsing of non-hierarchical URI. For backwards
157                        compatibility, an implementation may work around such references
158                        by removing the scheme if it matches that of the base URI and the
159                        scheme is known to always use the <hier_part> syntax.
160
161                     The URL class does not implement this work around, so we do.
162                 */

163
164                 String JavaDoc scheme = baseURL.getProtocol() + ":";
165                 if (href.startsWith(scheme)) {
166                     href = href.substring(scheme.length());
167                 }
168                 absoluteURL = new URL JavaDoc(baseURL, href);
169             } catch (MalformedURLException JavaDoc e_context) {
170                 throw new FopImageException("Invalid Image URL - error on relative URL : "
171                                             + e_context.getMessage());
172             }
173         }
174
175         // If not, check image type
176
ImageReader imgReader = null;
177         try {
178             if (imgIS == null) {
179                 imgIS = absoluteURL.openStream();
180             }
181             imgReader = ImageReaderFactory.Make(absoluteURL.toExternalForm(),
182                                                 imgIS);
183         } catch (Exception JavaDoc e) {
184             throw new FopImageException("Error while recovering Image Informations ("
185                                         + absoluteURL.toString() + ") : "
186                                         + e.getMessage());
187         }
188         finally {
189             if (imgIS != null) {
190                 try {
191                     imgIS.close();
192                 } catch (IOException JavaDoc e) {}
193             }
194         }
195         if (imgReader == null)
196             throw new FopImageException("No ImageReader for this type of image ("
197                                         + absoluteURL.toString() + ")");
198             // Associate mime-type to FopImage class
199
String JavaDoc imgMimeType = imgReader.getMimeType();
200         String JavaDoc imgClassName = null;
201         if ("image/gif".equals(imgMimeType)) {
202             imgClassName = "org.apache.fop.image.GifImage";
203         } else if ("image/jpeg".equals(imgMimeType)) {
204             imgClassName = "org.apache.fop.image.JpegImage";
205         } else if ("image/bmp".equals(imgMimeType)) {
206             imgClassName = "org.apache.fop.image.BmpImage";
207         } else if ("image/png".equals(imgMimeType)) {
208             imgClassName = getGenericImageClassName();
209         } else if ("image/tga".equals(imgMimeType)) {
210             imgClassName = getGenericImageClassName();
211         } else if ("image/eps".equals(imgMimeType)) {
212             imgClassName = "org.apache.fop.image.EPSImage";
213         } else if ("image/tiff".equals(imgMimeType)) {
214             try {
215                 imgClassName = "org.apache.fop.image.TiffImage";
216                 Class.forName(imgClassName);
217             } catch (Throwable JavaDoc t) {
218                 imgClassName = getGenericImageClassName();
219             }
220         } else if ("image/svg+xml".equals(imgMimeType)) {
221             imgClassName = "org.apache.fop.image.SVGImage";
222         }
223         if (imgClassName == null)
224             throw new FopImageException("Unsupported image type ("
225                                         + absoluteURL.toString() + ") : "
226                                         + imgMimeType);
227
228         // load the right image class
229
// return new <FopImage implementing class>
230
Object JavaDoc imageInstance = null;
231         Class JavaDoc imageClass = null;
232         try {
233             imageClass = Class.forName(imgClassName);
234             Class JavaDoc[] imageConstructorParameters = new Class JavaDoc[2];
235             imageConstructorParameters[0] = Class.forName("java.net.URL");
236             imageConstructorParameters[1] =
237                 Class.forName("org.apache.fop.image.analyser.ImageReader");
238             Constructor JavaDoc imageConstructor =
239                 imageClass.getDeclaredConstructor(imageConstructorParameters);
240             Object JavaDoc[] initArgs = new Object JavaDoc[2];
241             initArgs[0] = absoluteURL;
242             initArgs[1] = imgReader;
243             imageInstance = imageConstructor.newInstance(initArgs);
244         } catch (java.lang.reflect.InvocationTargetException JavaDoc ex) {
245             Throwable JavaDoc t = ex.getTargetException();
246             String JavaDoc msg;
247             if (t != null) {
248                 msg = t.getMessage();
249             } else {
250                 msg = ex.getMessage();
251             }
252             throw new FopImageException("Error creating FopImage object ("
253                                         + absoluteURL.toString() + ") : "
254                                         + msg);
255         } catch (Exception JavaDoc ex) {
256             throw new FopImageException("Error creating FopImage object ("
257                                         + "Error creating FopImage object ("
258                                         + absoluteURL.toString() + ") : "
259                                         + ex.getMessage());
260         }
261         if (!(imageInstance instanceof org.apache.fop.image.FopImage)) {
262             throw new FopImageException("Error creating FopImage object ("
263                                         + absoluteURL.toString() + ") : "
264                                         + "class " + imageClass.getName()
265                                         + " doesn't implement org.apache.fop.image.FopImage interface");
266         }
267         m_urlMap.put(href, imageInstance);
268         return (FopImage)imageInstance;
269     }
270
271
272     /**
273      * Determines the class name of the generic image handler
274      * This should really come from a config file but we leave this
275      * to some future time.
276      */

277     private static String JavaDoc getGenericImageClassName() {
278
279         if (m_genericImageClassName == null) {
280             try {
281                 //this will throw a NoClassDefFoundError if JAI is not installed
282
Class.forName("org.apache.fop.image.JAIImage");
283                 m_genericImageClassName = "org.apache.fop.image.JAIImage";
284             } catch (Throwable JavaDoc t) {
285                 MessageHandler.logln("JAI support was not installed (read: not "
286                     + "present at build time). Trying to use Jimi instead");
287                 /* on any exception assume Jai is not present and use Jimi instead */
288                 m_genericImageClassName = "org.apache.fop.image.JimiImage";
289             }
290         }
291         return m_genericImageClassName;
292     }
293
294
295     /**
296      * Clear the image cache.
297      */

298     public static synchronized void resetCache() {
299         m_urlMap.clear();
300     }
301 }
302
303
Popular Tags