KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > serialization > FOPSerializer


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.serialization;
17
18 import java.io.File JavaDoc;
19 import java.io.OutputStream JavaDoc;
20 import java.io.Serializable JavaDoc;
21 import java.net.MalformedURLException JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.HashMap JavaDoc;
24
25 import org.apache.avalon.framework.CascadingRuntimeException;
26 import org.apache.avalon.framework.configuration.Configurable;
27 import org.apache.avalon.framework.configuration.Configuration;
28 import org.apache.avalon.framework.configuration.ConfigurationException;
29 import org.apache.avalon.framework.logger.Logger;
30 import org.apache.avalon.framework.service.ServiceException;
31 import org.apache.avalon.framework.service.ServiceManager;
32 import org.apache.avalon.framework.service.Serviceable;
33 import org.apache.cocoon.caching.CacheableProcessingComponent;
34 import org.apache.cocoon.components.renderer.ExtendableRendererFactory;
35 import org.apache.cocoon.components.renderer.RendererFactory;
36 import org.apache.cocoon.components.source.SourceUtil;
37 import org.apache.cocoon.util.ClassUtils;
38 import org.apache.excalibur.source.Source;
39 import org.apache.excalibur.source.SourceResolver;
40 import org.apache.excalibur.source.SourceValidity;
41 import org.apache.excalibur.source.impl.validity.NOPValidity;
42 import org.apache.fop.apps.Driver;
43 import org.apache.fop.apps.Options;
44 import org.apache.fop.configuration.ConfigurationParser;
45 import org.apache.fop.messaging.MessageHandler;
46 import org.apache.fop.render.Renderer;
47
48 /**
49  * @author ?
50  * @author <a HREF="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
51  * @version CVS $Id: FOPSerializer.java 123903 2005-01-02 21:26:59Z antonio $
52  */

53 public class FOPSerializer extends AbstractSerializer implements
54   Configurable, CacheableProcessingComponent, Serviceable/*, Disposable */{
55
56     //protected SourceResolver resolver;
57

58     /**
59      * The Renderer Factory to use
60      */

61     protected final static RendererFactory factory = ExtendableRendererFactory.getRendererFactoryImplementation();
62
63     /**
64      * The <code>Driver</code> which is FOP.
65      */

66     protected Driver driver;
67
68     /**
69      * The current <code>Renderer</code>.
70      */

71     protected Renderer renderer;
72
73     /**
74      * The current <code>mime-type</code>.
75      */

76     protected String JavaDoc mimetype;
77
78     /**
79      * The renderer name if configured
80      */

81     protected String JavaDoc rendererName;
82
83     /**
84      * Should we set the content length ?
85      */

86     protected boolean setContentLength = true;
87
88     /**
89      * This logger is used for FOP
90      */

91     protected Logger logger;
92
93     /**
94      * It is used to make sure that default Options loaded only once.
95      */

96     private static boolean configured = false;
97
98     /**
99      * Manager to get URLFactory from.
100      */

101     protected ServiceManager manager;
102
103     /**
104      * Set the component manager for this serializer.
105      */

106     public void service(ServiceManager manager) throws ServiceException {
107         this.manager = manager;
108         //this.resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
109
}
110 /*
111     public void dispose() {
112         this.manager.release(this.resolver);
113     }
114 */

115     /**
116      * Set the configurations for this serializer.
117      */

118     public void configure(Configuration conf) throws ConfigurationException {
119
120         this.logger = getLogger().getChildLogger("fop");
121         MessageHandler.setScreenLogger(this.logger);
122
123         // FIXME: VG: Initialize static FOP configuration with defaults, only once.
124
// FOP has static config, but that's going to change in the near future.
125
// Then this code should be reviewed.
126
synchronized (FOPSerializer.class) {
127             if (!configured) {
128                 try {
129                     if (getLogger().isDebugEnabled()) {
130                         getLogger().debug("Loading default configuration");
131                     }
132                     new Options();
133                 } catch (Exception JavaDoc e) {
134                     getLogger().error("Cannot load default configuration. Proceeding.", e);
135                 }
136                 configured = true;
137             }
138         }
139
140         this.setContentLength = conf.getChild("set-content-length").getValueAsBoolean(true);
141
142         // Old syntax: Attribute src of element user-config contains file
143
String JavaDoc configUrl = conf.getChild("user-config").getAttribute("src", null);
144         if (configUrl != null) {
145             getLogger().warn("Attribute src of user-config element is deprecated. "
146                              + "Provide Cocoon URI as value of the element instead");
147             try {
148                 // VG: Old version of serializer supported only files
149
configUrl = new File JavaDoc(configUrl).toURL().toExternalForm();
150             } catch (MalformedURLException JavaDoc e) {
151                 getLogger().warn("Can not load config file " + configUrl, e);
152                 configUrl = null;
153             }
154         } else {
155             // New syntax: Element user-config contains URL
156
configUrl = conf.getChild("user-config").getValue(null);
157         }
158
159         if (configUrl != null) {
160             Source configSource = null;
161             SourceResolver resolver = null;
162             try {
163                 resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
164                 configSource = resolver.resolveURI(configUrl);
165                 if (getLogger().isDebugEnabled()) {
166                     getLogger().debug("Loading configuration from " + configSource.getURI());
167                 }
168                 SourceUtil.toSAX(configSource, new ConfigurationParser());
169             } catch (Exception JavaDoc e) {
170                 getLogger().warn("Cannot load configuration from " + configUrl);
171                 throw new ConfigurationException("Cannot load configuration from " + configUrl, e);
172             } finally {
173                 if (resolver != null) {
174                     resolver.release(configSource);
175                     manager.release(resolver);
176                 }
177             }
178         }
179
180         // Get the mime type.
181
this.mimetype = conf.getAttribute("mime-type");
182
183         // Iterate through the parameters, looking for a renderer reference
184
Configuration[] parameters = conf.getChildren("parameter");
185         for (int i = 0; i < parameters.length; i++) {
186             String JavaDoc name = parameters[i].getAttribute("name");
187             if ("renderer".equals(name)) {
188                 this.rendererName = parameters[i].getAttribute("value");
189                 try {
190                     this.renderer = (Renderer)ClassUtils.newInstance(rendererName);
191                 } catch (Exception JavaDoc ex) {
192                     getLogger().error("Cannot load class " + rendererName, ex);
193                     throw new ConfigurationException("Cannot load class " + rendererName, ex);
194                 }
195             }
196         }
197         if (this.renderer == null) {
198             // Using the Renderer Factory, get the default renderer
199
// for this MIME type.
200
this.renderer = factory.createRenderer(mimetype);
201         }
202
203         // Do we have a renderer yet?
204
if (this.renderer == null ) {
205             throw new ConfigurationException(
206                 "Could not autodetect renderer for FOPSerializer and "
207                 + "no renderer was specified in the sitemap configuration."
208             );
209         }
210
211         Configuration confRenderer = conf.getChild("renderer-config");
212         if (confRenderer != null) {
213             parameters = confRenderer.getChildren("parameter");
214             if (parameters.length > 0) {
215                 Map JavaDoc rendererOptions = new HashMap JavaDoc();
216                 for (int i = 0; i < parameters.length; i++) {
217                     String JavaDoc name = parameters[i].getAttribute("name");
218                     String JavaDoc value = parameters[i].getAttribute("value");
219                 
220                     if (getLogger().isDebugEnabled()) {
221                         getLogger().debug("renderer " + String.valueOf(name) + " = " + String.valueOf(value));
222                     }
223                     rendererOptions.put(name,value);
224                 }
225                 this.renderer.setOptions(rendererOptions);
226             }
227         }
228     }
229
230     /**
231      * Return the MIME type.
232      */

233     public String JavaDoc getMimeType() {
234         return mimetype;
235     }
236
237     /**
238      * Create the FOP driver
239      * Set the <code>OutputStream</code> where the XML should be serialized.
240      */

241     public void setOutputStream(OutputStream JavaDoc out) {
242         
243         // Give the source resolver to Batik which is used by FOP
244
//SourceProtocolHandler.setup(this.resolver);
245

246         // load the fop driver
247
this.driver = new Driver();
248         this.driver.setLogger(this.logger);
249         if (this.rendererName == null) {
250             this.renderer = factory.createRenderer(mimetype);
251         } else {
252             try {
253                 this.renderer = (Renderer)ClassUtils.newInstance(this.rendererName);
254             } catch (Exception JavaDoc e) {
255                 if (getLogger().isWarnEnabled()) {
256                     getLogger().warn("Cannot load class " + this.rendererName, e);
257                 }
258                 throw new CascadingRuntimeException("Cannot load class " + this.rendererName, e);
259             }
260         }
261         this.driver.setRenderer(this.renderer);
262         this.driver.setOutputStream(out);
263         setContentHandler(this.driver.getContentHandler());
264     }
265
266     /**
267      * Generate the unique key.
268      * This key must be unique inside the space of this component.
269      * This method must be invoked before the generateValidity() method.
270      *
271      * @return The generated key or <code>0</code> if the component
272      * is currently not cacheable.
273      */

274     public Serializable JavaDoc getKey() {
275         return "1";
276     }
277
278     /**
279      * Generate the validity object.
280      * Before this method can be invoked the generateKey() method
281      * must be invoked.
282      *
283      * @return The generated validity object or <code>null</code> if the
284      * component is currently not cacheable.
285      */

286     public SourceValidity getValidity() {
287         return NOPValidity.SHARED_INSTANCE;
288     }
289
290     /**
291      * Recycle serializer by removing references
292      */

293     public void recycle() {
294         super.recycle();
295         this.driver = null;
296         this.renderer = null;
297     }
298
299     /**
300      * Test if the component wants to set the content length
301      */

302     public boolean shouldSetContentLength() {
303         return this.setContentLength;
304     }
305
306 }
307
Popular Tags