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
|
/*
* $Id: FOTreeBuilder.java,v 1.43 2003/03/05 21:48:01 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.fo;
// FOP
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.fop.fo.FOTreeControl;
import org.apache.fop.fo.pagination.Root;
// SAX
import org.apache.avalon.framework.logger.Logger;
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.ElementMapping.Maker;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
// Java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import org.apache.fop.apps.*;
/**
* SAX Handler that passes parsed data to the various
* FO objects, where they can be used either to build
* an FO Tree, or used by Structure Renderers to build
* other data structures.
* Now uses
* StreamRenderer to automagically render the document as
* soon as it receives a page-sequence end-tag. Also,
* calls methods to set up and shut down the renderer at
* the beginning and end of the FO document. Finally,
* supresses adding the PageSequence object to the Root,
* since it is parsed immediately.
*
* @author unascribed
* @author Mark Lillywhite mark-fop@inomial.com
*/
public class FOTreeBuilder extends DefaultHandler {
/**
* Table mapping element names to the makers of objects
* representing formatting objects.
*/
protected Map fobjTable = new java.util.HashMap();
/**
* Set of mapped namespaces.
*/
protected Set namespaces = new java.util.HashSet();
/**
* Current formatting object being handled
*/
protected FONode currentFObj = null;
/**
* The root of the formatting object tree
*/
protected Root rootFObj = null;
/**
* The class that handles formatting and rendering to a stream
* (mark-fop@inomial.com)
*/
private FOInputHandler foInputHandler;
private FOUserAgent userAgent;
public FOTreeControl foTreeControl;
/**
* Default constructor
*/
public FOTreeBuilder() {
setupDefaultMappings();
}
private Logger getLogger() {
return userAgent.getLogger();
}
/**
* Sets the user agent
* @param ua the user agent
*/
public void setUserAgent(FOUserAgent ua) {
userAgent = ua;
}
private FOUserAgent getUserAgent() {
return userAgent;
}
/**
* Sets the structure handler to receive events.
* @param foih FOInputHandler instance
*/
public void setFOInputHandler(FOInputHandler foih) {
this.foInputHandler = foih;
}
/**
* Sets all the element and property list mappings to their default values.
*
*/
private void setupDefaultMappings() {
addElementMapping("org.apache.fop.fo.FOElementMapping");
addElementMapping("org.apache.fop.svg.SVGElementMapping");
addElementMapping("org.apache.fop.fo.extensions.ExtensionElementMapping");
// add mappings from available services
Iterator providers =
Service.providers(ElementMapping.class);
if (providers != null) {
while (providers.hasNext()) {
String str = (String)providers.next();
try {
addElementMapping(str);
} catch (IllegalArgumentException e) {
getLogger().warn("Error while adding element mapping", e);
}
}
}
}
/**
* Add the given element mapping.
* An element mapping maps element names to Java classes.
*
* @param mapping the element mappingto add
*/
public void addElementMapping(ElementMapping mapping) {
this.fobjTable.put(mapping.getNamespaceURI(), mapping.getTable());
this.namespaces.add(mapping.getNamespaceURI().intern());
}
/**
* Add the element mapping with the given class name.
* @param mappingClassName the class name representing the element mapping.
* @throws IllegalArgumentException if there was not such element mapping.
*/
public void addElementMapping(String mappingClassName)
throws IllegalArgumentException {
try {
ElementMapping mapping =
(ElementMapping)Class.forName(mappingClassName).newInstance();
addElementMapping(mapping);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Could not find "
+ mappingClassName);
} catch (InstantiationException e) {
throw new IllegalArgumentException("Could not instantiate "
+ mappingClassName);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("Could not access "
+ mappingClassName);
} catch (ClassCastException e) {
throw new IllegalArgumentException(mappingClassName
+ " is not an ElementMapping");
}
}
/**
* SAX Handler for characters
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char data[], int start, int length) {
if (currentFObj != null) {
currentFObj.addCharacters(data, start, start + length);
}
}
/**
* SAX Handler for the end of an element
* @see org.xml.sax.ContentHandler#endElement(String, String, String)
*/
public void endElement(String uri, String localName, String rawName)
throws SAXException {
currentFObj.end();
currentFObj = currentFObj.getParent();
}
/**
* SAX Handler for the start of the document
* @see org.xml.sax.ContentHandler#startDocument()
*/
public void startDocument() throws SAXException {
rootFObj = null; // allows FOTreeBuilder to be reused
if (getLogger().isDebugEnabled()) {
getLogger().debug("Building formatting object tree");
}
foInputHandler.startDocument();
}
/**
* SAX Handler for the end of the document
* @see org.xml.sax.ContentHandler#endDocument()
*/
public void endDocument() throws SAXException {
rootFObj = null;
currentFObj = null;
if (getLogger().isDebugEnabled()) {
getLogger().debug("Parsing of document complete");
}
foInputHandler.endDocument();
}
/**
* SAX Handler for the start of an element
* @see org.xml.sax.ContentHandler#startElement(String, String, String, Attributes)
*/
public void startElement(String namespaceURI, String localName, String rawName,
Attributes attlist) throws SAXException {
/* the formatting object started */
FONode fobj;
/* the maker for the formatting object started */
ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName);
try {
fobj = fobjMaker.make(currentFObj);
fobj.setName(localName);
// set the user agent for resolving user agent values
fobj.setUserAgent(userAgent);
// set the structure handler so that appropriate
// elements can signal structure events
fobj.setFOInputHandler(foInputHandler);
fobj.handleAttrs(attlist);
} catch (FOPException e) {
throw new SAXException(e);
}
if (rootFObj == null) {
if (!fobj.getName().equals("fo:root")) {
throw new SAXException(new FOPException("Root element must"
+ " be fo:root, not "
+ fobj.getName()));
}
rootFObj = (Root)fobj;
rootFObj.setFOTreeControl(foTreeControl);
} else {
currentFObj.addChild(fobj);
}
currentFObj = fobj;
}
/**
* Finds the Maker used to create FO objects of a particular type
* @param namespaceURI URI for the namespace of the element
* @param localName name of the Element
* @return the ElementMapping.Maker that can create an FO object for this element
*/
public Maker findFOMaker(String namespaceURI, String localName) {
Map table = (Map)fobjTable.get(namespaceURI);
Maker fobjMaker = null;
if (table != null) {
fobjMaker = (ElementMapping.Maker)table.get(localName);
// try default
if (fobjMaker == null) {
fobjMaker = (ElementMapping.Maker)table.get(ElementMapping.DEFAULT);
}
}
if (fobjMaker == null) {
if (getLogger().isWarnEnabled()) {
getLogger().warn("Unknown formatting object " + namespaceURI + "^" + localName);
}
if (namespaces.contains(namespaceURI.intern())) {
// fall back
fobjMaker = new Unknown.Maker();
} else {
fobjMaker = new UnknownXMLObj.Maker(namespaceURI);
}
}
return fobjMaker;
}
/**
* Resets this object for another run.
*/
public void reset() {
currentFObj = null;
rootFObj = null;
foInputHandler = null;
}
/**
* Indicates if data has been processed.
* @return True if data has been processed
*/
public boolean hasData() {
return (rootFObj != null);
}
}
// code stolen from org.apache.batik.util and modified slightly
// does what sun.misc.Service probably does, but it cannot be relied on.
// hopefully will be part of standard jdk sometime.
/**
* This class loads services present in the class path.
*/
class Service {
private static Map providerMap = new java.util.Hashtable();
public static synchronized Iterator providers(Class cls) {
ClassLoader cl = cls.getClassLoader();
// null if loaded by bootstrap class loader
if (cl == null) {
cl = ClassLoader.getSystemClassLoader();
}
String serviceFile = "META-INF/services/" + cls.getName();
// getLogger().debug("File: " + serviceFile);
List lst = (List)providerMap.get(serviceFile);
if (lst != null) {
return lst.iterator();
}
lst = new java.util.Vector();
providerMap.put(serviceFile, lst);
Enumeration e;
try {
e = cl.getResources(serviceFile);
} catch (IOException ioe) {
return lst.iterator();
}
while (e.hasMoreElements()) {
try {
java.net.URL u = (java.net.URL)e.nextElement();
//getLogger().debug("URL: " + u);
InputStream is = u.openStream();
Reader r = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
while (line != null) {
try {
// First strip any comment...
int idx = line.indexOf('#');
if (idx != -1) {
line = line.substring(0, idx);
}
// Trim whitespace.
line = line.trim();
// If nothing left then loop around...
if (line.length() == 0) {
line = br.readLine();
continue;
}
// getLogger().debug("Line: " + line);
// Try and load the class
// Object obj = cl.loadClass(line).newInstance();
// stick it into our vector...
lst.add(line);
} catch (Exception ex) {
// Just try the next line
}
line = br.readLine();
}
} catch (Exception ex) {
// Just try the next file...
}
}
return lst.iterator();
}
}
|