source: MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/MDTransformer.java @ 690

Last change on this file since 690 was 690, checked in by gaba, 14 years ago

columns

File size: 10.3 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import java.io.BufferedInputStream;
4import java.io.ByteArrayInputStream;
5import java.io.ByteArrayOutputStream;
6import java.io.File;
7import java.io.FileInputStream;
8import java.io.IOException;
9import java.io.InputStream;
10import java.io.OutputStream;
11import java.io.Reader;
12import java.io.StringReader;
13import java.io.StringWriter;
14import java.net.URL;
15
16import javax.xml.parsers.DocumentBuilder;
17import javax.xml.parsers.DocumentBuilderFactory;
18import javax.xml.parsers.ParserConfigurationException;
19import javax.xml.transform.OutputKeys;
20import javax.xml.transform.Transformer;
21import javax.xml.transform.TransformerConfigurationException;
22import javax.xml.transform.TransformerException;
23import javax.xml.transform.TransformerFactory;
24import javax.xml.transform.TransformerFactoryConfigurationError;
25import javax.xml.transform.dom.DOMSource;
26import javax.xml.transform.stream.StreamResult;
27import javax.xml.transform.stream.StreamSource;
28
29import org.w3c.dom.Document;
30import org.w3c.dom.Element;
31import org.w3c.dom.Node;
32import org.w3c.dom.NodeList;
33
34/**
35 * Helper class, encapsulating the xsl-transformations handling
36 * the contract is, that the requester passes a key, which can be resolved to a xsl-script (momentary mapped in properties: Admin.getConfig())
37 * Bad things happen, if the key or the appropriate xsl-file do not exist
38 *   
39 *
40 * @author vronk
41 *
42 */
43
44public class MDTransformer {
45
46        private URL srcFile ;
47       
48               
49        private static MDTransformer singleton;
50        TransformerFactory tfactory ; 
51       
52        public MDTransformer () {               
53                tfactory = TransformerFactory.newInstance();   
54        }
55       
56        public static MDTransformer getMDTransformer () {
57                if (singleton == null) {
58                        singleton = new MDTransformer();
59                } 
60                return singleton;
61        }
62       
63       
64        public URL getSrcFile() {
65                return srcFile;
66        }
67
68        public void setSrcFile(URL srcFile) {
69                this.srcFile = srcFile;
70        }
71
72        /**
73         * get the path to the transform-xsl file from properties, based on the key
74         * @param key
75         * @return
76         */
77        private String getXSLPath (String key) {               
78                String xslpath = "";
79                String xslfilename= Admin.getConfig().getProperty("xsl." + key);
80               
81                if (xslfilename!=null) {                       
82                        xslpath =  Admin.getConfig().getProperty("scripts.path") + xslfilename;
83                } 
84                Admin.notifyUser("xslfile:" + xslpath);
85                return xslpath;
86        }
87
88        private StreamSource getXSLStreamSource (String key){           
89               
90                InputStream xslstream;
91                                       
92                //URL myURL = new URL (getXSLPath(key));
93                //xslstream = myURL.openStream();
94                String xslPath = getXSLPath(key);
95                xslstream = this.getClass().getClassLoader().getResourceAsStream(xslPath);
96                StreamSource streamSource = new StreamSource(xslstream);
97
98                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).toString());
99                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).getPath());
100               
101                streamSource.setSystemId(this.getClass().getClassLoader().getResource(xslPath).toString());
102                return streamSource ;           
103               
104        }
105
106        public Object getCols() throws TransformerConfigurationException, TransformerFactoryConfigurationError{
107               
108                String xmlString = null;
109                // create new document
110                Document doc = null;
111                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
112        DocumentBuilder docBuilder;
113                try {
114                        docBuilder = docFactory.newDocumentBuilder();
115                        doc = docBuilder.newDocument();
116                        // append root tag <col >
117                        Element root = (Element) doc.createElement("col");
118                        root.setNodeValue("Id");
119                        doc.appendChild(root);
120                       
121                        Element child = (Element) doc.createElement("col");
122                        child.setNodeValue("Name");
123                        doc.appendChild(child);
124                        //Element child = doc.createElement("col");
125                        //child.setNodeValue("Id");
126                       
127                       
128                        Transformer transformer = TransformerFactory.newInstance().newTransformer();
129                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
130
131                        //initialize StreamResult with File object to save to file
132                        StreamResult result = new StreamResult(new StringWriter());
133                        DOMSource source = new DOMSource(doc);
134                        try {
135                                transformer.transform(source, result);
136                                xmlString = result.getWriter().toString();
137                               
138                                Admin.notifyUser(xmlString);
139                        } catch (TransformerException e) {
140                                // TODO Auto-generated catch block
141                                e.printStackTrace();
142                        }
143
144                       
145
146                } catch (ParserConfigurationException e) {
147                        // TODO Auto-generated catch block
148                        e.printStackTrace();
149                }
150                //return xmlString;
151                return doc.getElementsByTagName("col").item(0);
152        }
153       
154        /**
155         * The main method for transforming, applies the appropriate (based on the transkey) stylesheet on the xml-stream
156         * and writes the result into the output stream.   
157         * @param in InpuStream with xml 
158         * @param transkey this defines the stylesheet to use and is also passed to the stylesheet as "format"-parameter
159         * @param out the stream to write the output to
160         * @throws TransformerException
161         * @throws IOException
162         */             
163        public void transformXML (InputStream in, String transkey, String cols, OutputStream out ) throws TransformerException, IOException {
164       
165                // Create a transform factory instance.
166                TransformerFactory tfactory = TransformerFactory.newInstance();
167                //OutputStream os = new ByteArrayOutputStream();
168                StreamResult stream = new StreamResult(out);
169               
170                // Create a transformer for the stylesheet.
171                        //String xslpath = getXSLPath(transkey);               
172                Transformer transformer = tfactory.newTransformer(
173                                                                        getXSLStreamSource(transkey));
174               
175                transformer.setParameter("format", transkey);
176                transformer.setParameter("cols", cols);
177               
178                if (srcFile!=null) {
179                       
180                        File f = new File(srcFile.getPath());
181                           
182                        //Admin.notifyUser("src:" + srcFile.getFile());
183                        //Admin.notifyUser("fpath:" + f.getAbsolutePath());
184                        String root_uri =  srcFile.toString();
185                        String xsrcfile =  srcFile.getFile();
186                        if  (srcFile.getProtocol().equals("file")) {
187                                root_uri = "file:///" + f.getParent().replace('\\', '/');
188                                xsrcfile = "file:///" + f.getPath().replace('\\', '/');
189                        } 
190                        Admin.notifyUser("root_uri:" +  root_uri );
191                        Admin.notifyUser("xsrcfile:" +  root_uri );
192                        transformer.setParameter("root_uri", root_uri );
193                        transformer.setParameter("src_file", xsrcfile);
194                } else {
195                        Admin.notifyUser("transformXML(): srcFile not set!!");                         
196                }
197                //
198               
199                StreamSource src =new StreamSource();                   
200                src.setInputStream(in);
201                // Transform the source XML to out-stream
202                transformer.transform(src, stream );
203            }
204       
205        /**
206         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
207         * @param xmlStream the source xml stream
208         * @param transkey
209         * @return result-stream (converted to InputStream)
210         * @throws IOException
211         * @throws InterruptedException
212         * @throws TransformerException
213         */
214        public InputStream transformXML ( InputStream xmlStream, String transkey, String cols) throws IOException, InterruptedException, TransformerException {
215               
216                ByteArrayOutputStream out = new ByteArrayOutputStream();
217                transformXML(xmlStream, transkey, cols, out);           
218            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
219            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
220            return transformedStream;
221        }
222       
223        /**
224         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
225         * @param xmlStream the source xml stream
226         * @param transkey
227         * @return result-stream (converted to InputStream)
228         * @throws IOException
229         * @throws InterruptedException
230         * @throws TransformerException
231         */
232        public InputStream transformXML ( InputStream xmlStream, String transkey) throws IOException, InterruptedException, TransformerException {
233               
234                ByteArrayOutputStream out = new ByteArrayOutputStream();
235                transformXML(xmlStream, transkey, "", out);             
236            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
237            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
238            return transformedStream;
239        }
240
241        /**
242         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
243         * @param xmlFile URL of the source-file   
244         * @param transkey
245         * @return the result-stream (already converted to an InputStream)
246         * @throws TransformerException
247         * @throws IOException
248         */
249        public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
250                srcFile= xmlFile;
251                InputStream  xmlStream =
252             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
253           
254                return transformXML ( xmlStream, transkey); 
255        }
256
257
258        /**
259         * this is for xml present as string.
260         * if xml in a file or a stream, use the other methods
261         * @param xml xml as string
262         * @param transkey
263         * @return
264         */
265        public String transformXML (String xml, String transkey ) {
266                String result="";
267                try {
268                // Create a transform factory instance.
269                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
270                TransformerFactory tfactory = TransformerFactory.newInstance();
271                OutputStream os = new ByteArrayOutputStream();
272                StreamResult stream = new StreamResult(os);
273                // Create a transformer for the stylesheet.
274                Transformer transformer = tfactory.newTransformer(
275                                                getXSLStreamSource(transkey));
276/* instead of:
277                InputStream  xslIS       =
278                    new BufferedInputStream(new FileInputStream(getXSLPath(transkey)));
279               
280                Transformer transformer =
281                    tfactory.newTransformer(new StreamSource(xslIS));
282                    */
283                transformer.setParameter("format", transkey);
284               
285                //Admin.notifyUser("transformer.parmformat" + transformer.getParameter("format"));
286
287                // Transform the source XML to System.out.
288                StreamSource src =new StreamSource();       
289                Reader reader  = new StringReader(xml);
290                src.setReader(reader);
291               
292                transformer.transform(src, stream );
293                                    //  new StreamResult(new File("Simple2.out")));
294               
295                result = os.toString(); 
296               
297                        } catch (TransformerException e) {
298                                e.printStackTrace();
299                        }
300                       
301                        return result;
302        }
303
304       
305
306}
Note: See TracBrowser for help on using the repository browser.