source: MDUTILS/src/eu/clarin/cmdi/mdservice/internal/MDTransformer.java @ 1622

Last change on this file since 1622 was 1622, checked in by gaba, 13 years ago
File size: 12.4 KB
Line 
1package eu.clarin.cmdi.mdservice.internal;
2
3import java.io.BufferedInputStream;
4import java.io.BufferedReader;
5import java.io.ByteArrayInputStream;
6import java.io.ByteArrayOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.io.OutputStream;
13import java.io.Reader;
14import java.io.StringReader;
15import java.io.StringWriter;
16import java.net.URL;
17import java.util.HashMap;
18import java.util.Iterator;
19import java.util.Map;
20import java.util.Properties;
21import java.util.Set;
22import java.util.Map.Entry;
23
24import javax.xml.transform.Transformer;
25import javax.xml.transform.TransformerException;
26import javax.xml.transform.TransformerFactory;
27import javax.xml.transform.stream.StreamResult;
28import javax.xml.transform.stream.StreamSource;
29
30import org.apache.log4j.Logger;
31
32import net.sf.saxon.event.MessageEmitter;
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: Utils.getConfig())
37 *
38 * Bad things happen, if the key or the appropriate xsl-file do not exist - well the client gets a diagnostic message.
39 *   
40 *
41 * @author vronk
42 *
43 */
44
45public class MDTransformer {
46       
47        private static Logger log = Logger.getLogger("MDTransformer");
48
49        private String transkey;
50        private URL srcFile ;
51        private Map<String, String[]> params;
52       
53        private Properties config;
54        private ClassLoader loader = null;
55       
56               
57        // don't use singleton!! Bad things happen
58        // private MDTransformer singleton;
59        //TransformerFactory tfactory ;
60       
61        //public MDTransformer () {             
62        //      tfactory = TransformerFactory.newInstance();   
63        //}
64       
65        public ClassLoader getLoader(){
66                if (loader == null){
67                        return Utils.class.getClassLoader();
68                }
69                return loader;
70        }
71        public void configure(String configPath){
72                config = Utils.createConfig(configPath, null);
73        }
74        public void configure(Properties _config, ClassLoader _loader){
75                config = _config;
76                loader = _loader;
77        }
78       
79        public URL getSrcFile() {
80                return srcFile;
81        }
82
83        public void setSrcFile(URL srcFile) {
84                this.srcFile = srcFile;
85        }
86
87        /**
88         * This serves the caller (mainly GenericProxyAction.prepare())
89         * to provide/fill the request parameters.
90         * They then get translated to stylesheet-parameters (in SetTransformerParameters()).
91         * @return
92         */
93        public void setParams(Map<String, String[]> map){
94                this.params = map;
95        }
96       
97       
98        public Map<String,String[]> getParams(){
99                return this.params;
100        }
101
102        public Properties getConfig(){
103                if (config == null){
104                         return Utils.getConfig();
105                }
106                return config;
107        }
108        /**
109         * Get the path to the xsl file from properties, based on the key (aka format-parameter)
110         * @param key
111         * @return
112         * @throws NoStylesheetException - if no matching entry in properties could be found
113         */
114        private String getXSLPath (String key) throws NoStylesheetException {           
115                String xslpath = "";
116                String xslfilename= getConfig().getProperty("xsl." + key);
117               
118                if (xslfilename!=null) {                       
119                        xslpath =  getConfig().getProperty("scripts.path") + xslfilename;
120                } else {
121                        throw new NoStylesheetException("No Stylesheet found for format-key: " + key);
122                }
123                log.debug("xslfile:" + xslpath);
124                return xslpath;
125        }
126        /**
127         * Tries to load the stylesheet based on the key.
128         * This is done in two steps:
129         * 1. try to resolve the key to a path
130         * 2. get the xsl-file as a stream (and establish it as StreamSource)
131         *
132         * @param key The key identifying the stylesheet for the transformation as passed by GenericProxyAction.
133         * @return the stylesheet to be applied (as StreamSource)
134         * @throws NoStylesheetException If the stylesheet could not be located
135         */
136       
137        private StreamSource getXSLStreamSource (String key) throws NoStylesheetException{             
138               
139                InputStream xslstream;
140                       
141                //URL myURL = new URL (getXSLPath(key));
142                //xslstream = myURL.openStream();
143                String xslPath = getXSLPath(key);
144                xslstream = getLoader().getResourceAsStream(xslPath);
145                StreamSource streamSource = new StreamSource(xslstream);
146
147                streamSource.setSystemId(getLoader().getResource(xslPath).toString());
148                return streamSource ;   
149               
150        }
151
152        public void setTranskey(String key){
153                transkey = key;
154        }
155       
156        public String getTranskey(){
157                //return params.get("x-cmd-format")[0];
158                if (transkey == null & params.containsKey("fullformat")) {
159                        transkey = params.get("fullformat")[0] ;
160                }
161                if (transkey.equals("") & params.containsKey("fullformat")) {
162                        transkey = params.get("fullformat")[0] ;       
163                }
164                return transkey;
165        }
166
167        /**
168         * The main method for transforming, applies the appropriate (based on the transkey) stylesheet on the xml-stream
169         * and writes the result into the output stream.   
170         * @param in InpuStream with xml 
171         * @param transkey this defines the stylesheet to use and is also passed to the stylesheet as "format"-parameter
172         * @param out the stream to write the output to
173         * @throws TransformerException
174         * @throws IOException
175         * @throws NoStylesheetException
176         */
177        public void transformXML (InputStream in, OutputStream out ) throws TransformerException, IOException, NoStylesheetException {
178        //public void transformXML (InputStream in, String transkey, String cols, String startRecord, String maximumRecords, String lang, String q, String repositoryURI, OutputStream out ) throws TransformerException, IOException {
179       
180                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
181                // Create a transform factory instance.
182                TransformerFactory tfactory = TransformerFactory.newInstance();
183                //OutputStream os = new ByteArrayOutputStream();
184                StreamResult stream = new StreamResult(out);
185               
186                // Create a transformer for the stylesheet.
187                        //String xslpath = getXSLPath(transkey);               
188                Transformer transformer = tfactory.newTransformer(
189                                                                        getXSLStreamSource(getTranskey()));
190                SetTransformerParameters(transformer);
191               
192                //MessageWarner gg = new net.sf.saxon.event.MessageWarner();
193                MessageEmitter me = new net.sf.saxon.event.MessageEmitter();
194                StringWriter w = new StringWriter();
195                me.setWriter(w);
196               ((net.sf.saxon.Controller)transformer).setMessageEmitter(me);//new net.sf.saxon.event.MessageWarner());
197
198               
199                if (srcFile!=null) {
200                       
201                        File f = new File(srcFile.getPath());
202                           
203                        //log.debug("src:" + srcFile.getFile());
204                        //log.debug("fpath:" + f.getAbsolutePath());
205                        String root_uri =  srcFile.toString();
206                        String xsrcfile =  srcFile.getFile();
207                        if  (srcFile.getProtocol().equals("file")) {
208                                root_uri = "file:///" + f.getParent().replace('\\', '/');
209                                xsrcfile = "file:///" + f.getPath().replace('\\', '/');
210                        } 
211                        // TODO repository-path -removed, bad formating
212                        String[] xsrcfiles = xsrcfile.split("&repository=");
213                        String[] root_uris = root_uri.split("&repository=");
214                        xsrcfile = xsrcfiles[0];
215                        root_uri = root_uris[0];
216                        ///
217                       
218                        log.debug("root_uri:" +  root_uri );
219                        log.debug("xsrcfile:" +  xsrcfile );
220                       
221                        transformer.setParameter("root_uri", root_uri );
222                        transformer.setParameter("src_file", xsrcfile);
223                } else {
224                        log.error("transformXML(): srcFile not set!!");                         
225                }
226                //
227                StreamSource src =new StreamSource();                   
228                src.setInputStream(in);
229                // Transform the source XML to out-stream
230                transformer.transform(src, stream );
231               
232                // Write <xsl:message>
233                writeXslMessages(w);
234                ///log.debug(w.getBuffer().toString());         
235   }
236       
237
238        /**
239         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
240         * @param xmlStream the source xml stream
241         * @param transkey
242         * @return result-stream (converted to InputStream)
243         * @throws IOException
244         * @throws InterruptedException
245         * @throws TransformerException
246         * @throws NoStylesheetException
247         */
248        public InputStream transformXML ( InputStream xmlStream) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
249        //public InputStream transformXML ( InputStream xmlStream, String transkey, String cols, String startRecord, String maximumRecords, String lang, String q, String repositoryURI) throws IOException, InterruptedException, TransformerException {
250               
251                ByteArrayOutputStream out = new ByteArrayOutputStream();
252                transformXML(xmlStream, out);           
253            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
254            return transformedStream;
255        }
256       
257        /**
258         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
259         * @param xmlFile URL of the source-file   
260         * @param transkey
261         * @return the result-stream (already converted to an InputStream)
262         * @throws TransformerException
263         * @throws IOException
264         * @throws NoStylesheetException
265         */
266        public InputStream transformXML (URL xmlFile ) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
267        //public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
268                srcFile= xmlFile;
269                InputStream  xmlStream =
270             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
271           
272                return transformXML ( xmlStream); 
273        }
274
275        /**
276         * this is for xml-data present as string (primarily the query string present as XCQL).
277         * if xml in a file or a stream, use the other methods
278         * @param xml xml-data as string
279         * @param transkey
280         * @return
281         * @throws NoStylesheetException
282         * @throws IOException
283         */
284        public String transformXML (String xml) throws NoStylesheetException {
285        //public String transformXML (String xml, String transkey ) {
286                String result="";
287                try {
288                // Create a transform factory instance.
289                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
290                        //System.setProperty("javax.xml.transform.TransformerFactory", "com.icl.saxon.TransformerFactoryImpl");
291                TransformerFactory tfactory = TransformerFactory.newInstance();
292                OutputStream os = new ByteArrayOutputStream();
293                StreamResult stream = new StreamResult(os);
294                // Create a transformer for the stylesheet.
295                Transformer transformer = tfactory.newTransformer(
296                                                getXSLStreamSource(getTranskey()));
297
298                MessageEmitter me = new net.sf.saxon.event.MessageEmitter();
299                StringWriter w = new StringWriter();
300                me.setWriter(w);
301                ((net.sf.saxon.Controller)transformer).setMessageEmitter(me);//new net.sf.saxon.event.MessageWarner());
302
303                // Transform the source XML to System.out.
304                StreamSource src =new StreamSource();       
305                Reader reader  = new StringReader(xml);
306                src.setReader(reader);
307               
308                transformer.transform(src, stream );
309                                    //  new StreamResult(new File("Simple2.out")));
310             // Write <xsl:message>
311                writeXslMessages(w);
312                 
313                result = os.toString(); 
314               
315                        } catch (TransformerException e) {
316                                e.printStackTrace();
317                        }
318                       
319                        return result;
320        }
321
322        private void writeXslMessages(StringWriter w){
323       
324        byte[] bytes = w.getBuffer().toString().getBytes();
325        InputStream is =  new ByteArrayInputStream(bytes);
326        BufferedReader br = new BufferedReader(new InputStreamReader(is));
327        String s;
328                try {
329                        while ((s = br.readLine()) != null){
330                        log.debug(s);
331                }
332                } catch (IOException e) {
333                        log.error(Utils.errorMessage(e));
334                }
335        }
336
337        /**
338         * Makes the request-parameters available in the stylesheets
339         * by translating them to stylesheet-parameters
340         * @param transformer
341         */
342        public void SetTransformerParameters(Transformer transformer){
343               
344                Set<Entry<String, String[]>> set = params.entrySet();
345                Iterator<Entry<String, String[]>> i = set.iterator();
346
347            while(i.hasNext()){
348              Map.Entry<String,String[]> e = (Map.Entry<String,String[]>)i.next();
349              transformer.setParameter((String)e.getKey(), (String)e.getValue()[0]);
350            }
351        }
352
353       
354        public static HashMap<String,String[]> createParamsMap(String key){
355                HashMap<String,String[]> hm = new HashMap<String,String[]>();
356               
357            if (key != null){
358                String[] arrkey = new String[1];
359                arrkey[0] = key;
360                        hm.put("fullformat", arrkey);                   
361            }
362            return hm;
363        }
364       
365}
Note: See TracBrowser for help on using the repository browser.