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

Last change on this file since 789 was 789, checked in by vronk, 14 years ago

finalization of terms2view.xsl (autocomplete), @id, @path..;
adding lang-param (mainly for DCR)

File size: 11.1 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               
102                streamSource.setSystemId(this.getClass().getClassLoader().getResource(xslPath).toString());
103                return streamSource ;           
104               
105        }
106
107        public Object getCols() throws TransformerConfigurationException, TransformerFactoryConfigurationError{
108               
109                String xmlString = null;
110                // create new document
111                Document doc = null;
112                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
113        DocumentBuilder docBuilder;
114                try {
115                        docBuilder = docFactory.newDocumentBuilder();
116                        doc = docBuilder.newDocument();
117                        // append root tag <col >
118                        Element root = (Element) doc.createElement("root");
119                        doc.appendChild(root);
120                       
121                        Element child1 = (Element) doc.createElement("col");
122                        child1.setTextContent("Id");
123                        root.appendChild(child1);                       
124                        Element child = (Element) doc.createElement("col");
125                        child.setTextContent("Name");
126                        root.appendChild(child);
127                        //Element child = doc.createElement("col");
128                        //child.setNodeValue("Id");
129                       
130                       
131                        Transformer transformer = TransformerFactory.newInstance().newTransformer();
132                        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
133
134                        //initialize StreamResult with File object to save to file
135                        StreamResult result = new StreamResult(new StringWriter());
136                        DOMSource source = new DOMSource(doc);
137                        try {
138                                transformer.transform(source, result);
139                                xmlString = result.getWriter().toString();
140                               
141                                Admin.notifyUser(xmlString);
142                        } catch (TransformerException e) {
143                                // TODO Auto-generated catch block
144                                e.printStackTrace();
145                        }
146
147                       
148
149                } catch (ParserConfigurationException e) {
150                        // TODO Auto-generated catch block
151                        e.printStackTrace();
152                }
153                //return xmlString;
154                //return doc.getElementsByTagName("col").item(0);
155                return doc.getDocumentElement();
156        }
157       
158        /**
159         * The main method for transforming, applies the appropriate (based on the transkey) stylesheet on the xml-stream
160         * and writes the result into the output stream.   
161         * @param in InpuStream with xml 
162         * @param transkey this defines the stylesheet to use and is also passed to the stylesheet as "format"-parameter
163         * @param out the stream to write the output to
164         * @throws TransformerException
165         * @throws IOException
166         */             
167        public void transformXML (InputStream in, String transkey, String cols, String startRecord, String maximumRecords, String lang, OutputStream out ) throws TransformerException, IOException {
168       
169                // Create a transform factory instance.
170                TransformerFactory tfactory = TransformerFactory.newInstance();
171                //OutputStream os = new ByteArrayOutputStream();
172                StreamResult stream = new StreamResult(out);
173               
174                // Create a transformer for the stylesheet.
175                        //String xslpath = getXSLPath(transkey);               
176                Transformer transformer = tfactory.newTransformer(
177                                                                        getXSLStreamSource(transkey));
178               
179                transformer.setParameter("lang", lang);
180                transformer.setParameter("format", transkey);
181                transformer.setParameter("cols", cols);
182                if ((startRecord != null) && (maximumRecords != null)) {
183
184                        transformer.setParameter("startRecord", startRecord);
185                        transformer.setParameter("maximumRecords", maximumRecords);
186                }
187                /*       transformer.setParameter("cols", "<col label='id'>Id</col>" +
188                                                                                 "<col label='id'>idno</col>" +
189                                                                                 "<col label='name'>Name</col>" +
190                                                                                 "<col label='title'>Title</col>" +
191                                                                                 "<col label='title'>title</col>"); */
192               
193                if (srcFile!=null) {
194                       
195                        File f = new File(srcFile.getPath());
196                           
197                        //Admin.notifyUser("src:" + srcFile.getFile());
198                        //Admin.notifyUser("fpath:" + f.getAbsolutePath());
199                        String root_uri =  srcFile.toString();
200                        String xsrcfile =  srcFile.getFile();
201                        if  (srcFile.getProtocol().equals("file")) {
202                                root_uri = "file:///" + f.getParent().replace('\\', '/');
203                                xsrcfile = "file:///" + f.getPath().replace('\\', '/');
204                        } 
205                        Admin.notifyUser("root_uri:" +  root_uri );
206                        Admin.notifyUser("xsrcfile:" +  root_uri );
207                        transformer.setParameter("root_uri", root_uri );
208                        transformer.setParameter("src_file", xsrcfile);
209                } else {
210                        Admin.notifyUser("transformXML(): srcFile not set!!");                         
211                }
212                //
213                StreamSource src =new StreamSource();                   
214                src.setInputStream(in);
215                // Transform the source XML to out-stream
216                transformer.transform(src, stream );
217            }
218       
219        /**
220         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
221         * @param xmlStream the source xml stream
222         * @param transkey
223         * @return result-stream (converted to InputStream)
224         * @throws IOException
225         * @throws InterruptedException
226         * @throws TransformerException
227         */
228        public InputStream transformXML ( InputStream xmlStream, String transkey, String cols, String startRecord, String maximumRecords, String lang) throws IOException, InterruptedException, TransformerException {
229               
230                ByteArrayOutputStream out = new ByteArrayOutputStream();
231                transformXML(xmlStream, transkey, cols, startRecord, maximumRecords, lang, out);               
232            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
233            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
234            return transformedStream;
235        }
236       
237        /**
238         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
239         * @param xmlStream the source xml stream
240         * @param transkey
241         * @return result-stream (converted to InputStream)
242         * @throws IOException
243         * @throws InterruptedException
244         * @throws TransformerException
245         */
246        public InputStream transformXML ( InputStream xmlStream, String transkey) throws IOException, InterruptedException, TransformerException {
247               
248                ByteArrayOutputStream out = new ByteArrayOutputStream();
249                transformXML(xmlStream, transkey, "", "", "","", out);         
250            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
251            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
252            return transformedStream;
253        }
254
255        /**
256         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
257         * @param xmlFile URL of the source-file   
258         * @param transkey
259         * @return the result-stream (already converted to an InputStream)
260         * @throws TransformerException
261         * @throws IOException
262         */
263        public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
264                srcFile= xmlFile;
265                InputStream  xmlStream =
266             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
267           
268                return transformXML ( xmlStream, transkey); 
269        }
270
271
272        /**
273         * this is for xml present as string.
274         * if xml in a file or a stream, use the other methods
275         * @param xml xml as string
276         * @param transkey
277         * @return
278         */
279        public String transformXML (String xml, String transkey ) {
280                String result="";
281                try {
282                // Create a transform factory instance.
283                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
284                TransformerFactory tfactory = TransformerFactory.newInstance();
285                OutputStream os = new ByteArrayOutputStream();
286                StreamResult stream = new StreamResult(os);
287                // Create a transformer for the stylesheet.
288                Transformer transformer = tfactory.newTransformer(
289                                                getXSLStreamSource(transkey));
290/* instead of:
291                InputStream  xslIS       =
292                    new BufferedInputStream(new FileInputStream(getXSLPath(transkey)));
293               
294                Transformer transformer =
295                    tfactory.newTransformer(new StreamSource(xslIS));
296                    */
297                transformer.setParameter("format", transkey);
298               
299                //Admin.notifyUser("transformer.parmformat" + transformer.getParameter("format"));
300
301                // Transform the source XML to System.out.
302                StreamSource src =new StreamSource();       
303                Reader reader  = new StringReader(xml);
304                src.setReader(reader);
305               
306                transformer.transform(src, stream );
307                                    //  new StreamResult(new File("Simple2.out")));
308               
309                result = os.toString(); 
310               
311                        } catch (TransformerException e) {
312                                e.printStackTrace();
313                        }
314                       
315                        return result;
316        }
317
318       
319
320}
Note: See TracBrowser for help on using the repository browser.