xref: /AOO41X/main/xmerge/source/xmerge/java/org/openoffice/xmerge/converter/xml/xslt/DocumentSerializerImpl.java (revision 7a3beb322b74df1b6c96e03605837df34781c68f)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 package org.openoffice.xmerge.converter.xml.xslt;
25 
26 import org.w3c.dom.NodeList;
27 import org.w3c.dom.Node;
28 import org.w3c.dom.Element;
29 import org.w3c.dom.*;
30 
31 import java.io.IOException;
32 import java.io.ByteArrayOutputStream;
33 import java.io.ByteArrayInputStream;
34 
35 import org.openoffice.xmerge.Document;
36 import org.openoffice.xmerge.ConvertData;
37 import org.openoffice.xmerge.ConvertException;
38 import org.openoffice.xmerge.DocumentSerializer;
39 import org.openoffice.xmerge.converter.xml.xslt.GenericOfficeDocument;
40 import org.openoffice.xmerge.converter.dom.DOMDocument;
41 import org.openoffice.xmerge.util.registry.ConverterInfo;
42 import org.openoffice.xmerge.converter.xml.OfficeConstants;
43 
44 // Imported TraX classes
45 import javax.xml.transform.TransformerFactory;
46 import javax.xml.transform.Transformer;
47 import javax.xml.transform.stream.StreamSource;
48 import javax.xml.transform.stream.StreamResult;
49 import javax.xml.transform.dom.DOMSource;
50 import javax.xml.transform.TransformerException;
51 import javax.xml.transform.TransformerConfigurationException;
52 import javax.xml.transform.URIResolver;
53 import javax.xml.transform.Source;
54 
55 import javax.xml.parsers.DocumentBuilder;
56 import javax.xml.parsers.DocumentBuilderFactory;
57 
58 // Imported java classes
59 import java.io.FileNotFoundException;
60 
61 /**
62  *  <p>Xslt implementation of
63  *  org.openoffice.xmerge.DocumentSerializer
64  *  for the {@link
65  *  org.openoffice.xmerge.converter.xml.xslt.PluginFactoryImpl
66  *  PluginFactoryImpl}.</p>
67  *
68  *  <p>The <code>serialize</code> method transforms the DOM
69  *  document from the given <code>Document</code> object by
70  *  means of a supplied Xsl Stylesheet.</p>
71  *
72  *  @author      Aidan Butler
73  */
74 
75 
76 public final class DocumentSerializerImpl
77     implements DocumentSerializer,OfficeConstants,URIResolver {
78 
79 
80     /** SXW <code>Document</code> object that this converter processes. */
81     private GenericOfficeDocument sxwDoc = null;
82 
83     private PluginFactoryImpl pluginFactory = null;
84 
85     /**
86      *  Constructor.
87      *
88      *  @param  pf   A <code>PluginFactoryImpl</code>
89      *  @param  doc  A SXW <code>Document</code> to be converted.
90      */
DocumentSerializerImpl(PluginFactoryImpl pf,Document doc)91     public DocumentSerializerImpl(PluginFactoryImpl pf,Document doc) {
92     pluginFactory=pf;
93         sxwDoc = (GenericOfficeDocument) doc;
94     }
95 
96 
97     /**
98      *  Method to convert a <code>Document</code> with an xsl stylesheet.
99      *  It creates a <code>Document</code> object, which is then transformed
100      *  with the Xslt processer. A <code>ConvertData </code> object is
101      *  constructed and returned.
102      *
103      *  @return cd     A <code>ConvertData</code> object.
104      *  @throws  ConvertException  If any I/O error occurs.
105      *  @throws  IOException       If any I/O error occurs.
106      */
serialize()107     public ConvertData serialize() throws ConvertException, IOException {
108     String docName = sxwDoc.getName();
109     org.w3c.dom.Document domDoc = sxwDoc.getContentDOM();
110     org.w3c.dom.Document metaDoc = sxwDoc.getMetaDOM();
111     org.w3c.dom.Document styleDoc = sxwDoc.getStyleDOM();
112     ByteArrayOutputStream baos= new ByteArrayOutputStream();
113         ConvertData cd = new ConvertData();
114     Node offnode = (Node)domDoc.getDocumentElement();
115     if (!(offnode.getNodeName()).equals("office:document")){
116         try{
117         DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
118         DocumentBuilder builder= builderFactory.newDocumentBuilder();
119         DOMImplementation domImpl = builder.getDOMImplementation();
120         DocumentType docType =domImpl.createDocumentType("office:document","-//OpenOffice.org//DTD OfficeDocument 1.0//EN",null);
121         org.w3c.dom.Document newDoc = domImpl.createDocument("http://openoffice.org/2000/office","office:document",docType);
122 
123 
124         Element rootElement=newDoc.getDocumentElement();
125         rootElement.setAttribute("xmlns:office","http://openoffice.org/2000/office");
126         rootElement.setAttribute("xmlns:style","http://openoffice.org/2000/style" );
127         rootElement.setAttribute("xmlns:text","http://openoffice.org/2000/text");
128          rootElement.setAttribute("xmlns:table","http://openoffice.org/2000/table");
129 
130         rootElement.setAttribute("xmlns:draw","http://openoffice.org/2000/drawing");
131         rootElement.setAttribute("xmlns:fo","http://www.w3.org/1999/XSL/Format" );
132         rootElement.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink" );
133         rootElement.setAttribute("xmlns:dc","http://purl.org/dc/elements/1.1/" );
134         rootElement.setAttribute("xmlns:meta","http://openoffice.org/2000/meta" );
135         rootElement.setAttribute("xmlns:number","http://openoffice.org/2000/datastyle" );
136         rootElement.setAttribute("xmlns:svg","http://www.w3.org/2000/svg" );
137         rootElement.setAttribute("xmlns:chart","http://openoffice.org/2000/chart" );
138         rootElement.setAttribute("xmlns:dr3d","http://openoffice.org/2000/dr3d" );
139         rootElement.setAttribute("xmlns:math","http://www.w3.org/1998/Math/MathML" );
140         rootElement.setAttribute("xmlns:form","http://openoffice.org/2000/form" );
141         rootElement.setAttribute("xmlns:script","http://openoffice.org/2000/script" );
142         rootElement.setAttribute("xmlns:config","http://openoffice.org/2001/config" );
143         rootElement.setAttribute("office:class","text" );
144         rootElement.setAttribute("office:version","1.0");
145 
146 
147         NodeList nodeList;
148         Node tmpNode;
149         Node rootNode = (Node)rootElement;
150         if (metaDoc !=null){
151         nodeList= metaDoc.getElementsByTagName(TAG_OFFICE_META);
152         if (nodeList.getLength()>0){
153             tmpNode = newDoc.importNode(nodeList.item(0),true);
154             rootNode.appendChild(tmpNode);
155         }
156         } if (styleDoc !=null){
157         nodeList= styleDoc.getElementsByTagName(TAG_OFFICE_STYLES);
158         if (nodeList.getLength()>0){
159             tmpNode = newDoc.importNode(nodeList.item(0),true);
160             rootNode.appendChild(tmpNode);
161         }
162         }if (domDoc !=null){
163         nodeList= domDoc.getElementsByTagName(TAG_OFFICE_AUTOMATIC_STYLES);
164         if (nodeList.getLength()>0){
165             tmpNode = newDoc.importNode(nodeList.item(0),true);
166             rootNode.appendChild(tmpNode);
167         }
168         nodeList= domDoc.getElementsByTagName(TAG_OFFICE_BODY);
169         if (nodeList.getLength()>0){
170             tmpNode = newDoc.importNode(nodeList.item(0),true);
171             rootNode.appendChild(tmpNode);
172         }
173         }
174         domDoc=newDoc;
175         }catch(Exception e){
176         System.out.println("\nAn Exception occurred with Xslt Serializer"+e);
177         }
178 
179     }
180 
181     try{
182          baos=transform(domDoc);
183     }
184     catch (Exception e){
185         System.out.println("\n Error with Xslt\n");
186     }
187 
188     String ext = pluginFactory.getDeviceFileExtension();
189         DOMDocument resultDomDoc=(DOMDocument)pluginFactory.createDeviceDocument(docName,new ByteArrayInputStream(baos.toByteArray()));
190     cd.addDocument (resultDomDoc);
191     return cd;
192     }
193 
resolve(String href,String base)194     public Source resolve(String href,String base)
195     throws TransformerException{
196         //System.out.println("\nhref "+href+"\nbase "+base);
197         if (href !=null){
198         if(href.equals("javax.xml.transform.dom.DOMSource")|| href.equals(""))
199             return null;
200         try{
201             ConverterInfo ci = pluginFactory.getConverterInfo();
202             String newhRef ="jar:"+ci.getJarName()+"!/"+href;
203             //System.out.println("\n Looking For "+ newhRef);
204             StreamSource sheetFile= new StreamSource(newhRef);
205             return sheetFile;
206         }
207         catch (Exception e){
208             System.out.println("\nException in Xslt Resolver " +e);
209             return null;
210         }
211         }
212         else
213         return null;
214     }
215 
216 
217     /*
218      * This method performs the sxl transformation on the supplied <code>
219      * Document</code> and returns a <code>DOMResult</code> object.
220      *
221      *  Xslt transformation code
222      *
223      * @return baos A <code>ByteArrayOutputStream</code> object containing
224      *               the result of the Xslt transformation.
225      * @throws TransformerException,TransformerConfigurationException
226      *        , FileNotFoundException,IOException
227      *
228      */
229 
230 
transform(org.w3c.dom.Document domDoc)231     private ByteArrayOutputStream transform(org.w3c.dom.Document domDoc)
232        throws TransformerException,TransformerConfigurationException
233           , FileNotFoundException,IOException{
234        //System.out.println("\nTransforming...");
235        ConverterInfo ci = pluginFactory.getConverterInfo();
236        //DOMResult xmlDomResult = new DOMResult();
237        ByteArrayOutputStream baos= new ByteArrayOutputStream();
238        try{
239 
240           DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
241           dFactory.setNamespaceAware(true);
242 
243           DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
244           String teststr = ci.getXsltSerial();
245 
246           teststr= teststr.substring(0,6);
247           org.w3c.dom.Document xslDoc=null;
248               if ((teststr.equals("http:/"))||(teststr.equals("file:/"))
249                                         ||(teststr.equals("jar://"))){
250               System.out.println(ci.getXsltSerial());
251               xslDoc= dBuilder.parse(ci.getXsltSerial());
252 
253           }
254           else{
255               //System.out.println(ci.getJarName()+"!/"+ci.getXsltSerial());
256               xslDoc = dBuilder.parse(
257                   "jar:"+ci.getJarName()+"!/"+ci.getXsltSerial());
258           }
259 
260           DOMSource xslDomSource = new DOMSource(xslDoc);
261           DOMSource xmlDomSource = new DOMSource(domDoc);
262 
263           //call the tranformer using the XSL, Source and Result.
264           TransformerFactory tFactory = TransformerFactory.newInstance();
265           tFactory.setURIResolver(this);
266           Transformer transformer = tFactory.newTransformer(xslDomSource);
267 
268           transformer.transform(xmlDomSource, new StreamResult(baos));
269 
270             /*
271           transformer.transform(xmlDomSource, xmlDomResult); //Removed this impl because the DocType was not being written out
272 
273          // Serialize for output to standard out
274           Serializer serializer = SerializerFactory.getSerializer
275                                    (OutputProperties.getDefaultMethodProperties("xml"));
276               //serializer.setOutputStream(System.out);
277           serializer.setOutputStream(baos);
278           serializer.asDOMSerializer().serialize(xmlDomResult.getNode());
279           //serializer.asDOMSerializer().serialize(xmlDomSource.getNode());
280 
281 
282           //System.out.println("\n** Transform Complete ***");
283           */
284        }
285        catch(Exception e){
286               System.out.println("An error occured in the transformation : "+e);
287        }
288        return baos;
289      }
290 
291 
292 }
293 
294