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

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

initial import

File size: 7.4 KB
Line 
1package eu.clarin.cmdi.mdservice.action;
2
3import eu.clarin.cmdi.mdservice.action.Helpers;
4import java.io.BufferedInputStream;
5import java.io.ByteArrayInputStream;
6import java.io.ByteArrayOutputStream;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileNotFoundException;
10import java.io.IOException;
11import java.io.InputStream;
12import java.io.OutputStream;
13import java.io.Reader;
14import java.io.StringReader;
15import java.net.MalformedURLException;
16import java.net.URL;
17
18import javax.xml.transform.Transformer;
19import javax.xml.transform.TransformerException;
20import javax.xml.transform.TransformerFactory;
21import javax.xml.transform.stream.StreamResult;
22import javax.xml.transform.stream.StreamSource;
23
24/**
25 * Helper class, encapsulating the xsl-transformations handling
26 * the contract is, that the requester passes a key, which can be resolved to a xsl-script (momentary mapped in properties: Admin.getConfig())
27 * Bad things happen, if the key or the appropriate xsl-file do not exist
28 *   
29 *
30 * @author vronk
31 *
32 */
33
34public class MDTransformer {
35
36        private URL srcFile ;
37               
38        private static MDTransformer singleton;
39        TransformerFactory tfactory ; 
40       
41        public MDTransformer () {               
42                tfactory = TransformerFactory.newInstance();   
43        }
44       
45        public static MDTransformer getMDTransformer () {
46                if (singleton == null) {
47                        singleton = new MDTransformer();
48                } 
49                return singleton;
50        }
51       
52        /**
53         * get the path to the transform-xsl file from properties, based on the key
54         * @param key
55         * @return
56         */
57        private String getXSLPath (String key) {               
58                String xslpath = "";
59                String xslfilename= Admin.getConfig().getProperty("xsl." + key);
60               
61                if (xslfilename!=null) {                       
62                        xslpath =  Admin.getConfig().getProperty("scripts.path") + xslfilename;
63                } 
64                Admin.notifyUser("xslfile:" + xslpath);
65                return xslpath;
66        }
67
68        private StreamSource getXSLStreamSource (String key){           
69               
70                InputStream xslstream;
71                                       
72                //URL myURL = new URL (getXSLPath(key));
73                //xslstream = myURL.openStream();
74                String xslPath = getXSLPath(key);
75                xslstream = this.getClass().getClassLoader().getResourceAsStream(xslPath);
76                StreamSource streamSource = new StreamSource(xslstream);
77
78                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).toString());
79                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).getPath());
80               
81                streamSource.setSystemId(this.getClass().getClassLoader().getResource(xslPath).toString());
82                return streamSource ;           
83               
84        }
85
86        /**
87         * The main method for transforming, applies the appropriate (based on the transkey) stylesheet on the xml-stream
88         * and writes the result into the output stream.   
89         * @param in InpuStream with xml 
90         * @param transkey this defines the stylesheet to use and is also passed to the stylesheet as "format"-parameter
91         * @param out the stream to write the output to
92         * @throws TransformerException
93         * @throws IOException
94         */             
95        public void transformXML (InputStream in, String transkey, OutputStream out ) throws TransformerException, IOException {
96       
97                // Create a transform factory instance.
98                TransformerFactory tfactory = TransformerFactory.newInstance();
99                //OutputStream os = new ByteArrayOutputStream();
100                StreamResult stream = new StreamResult(out);
101               
102                // Create a transformer for the stylesheet.
103                        //String xslpath = getXSLPath(transkey);               
104                Transformer transformer = tfactory.newTransformer(
105                                                                        getXSLStreamSource(transkey));
106                       
107                transformer.setParameter("format", transkey);
108               
109                if (srcFile!=null) {
110                        File f = new File(srcFile.getPath());
111                       
112                        //Admin.notifyUser("src:" + srcFile.getFile());
113                        //Admin.notifyUser("fpath:" + f.getAbsolutePath());
114                        String root_uri =  srcFile.getFile();
115                        String xsrcfile =  srcFile.getFile();
116                        if  (srcFile.getProtocol().equals("file")) {
117                                root_uri = "file:///" + f.getParent().replace('\\', '/');
118                                xsrcfile = "file:///" + f.getPath().replace('\\', '/');
119                        } 
120                        Admin.notifyUser("root_uri:" +  root_uri );
121                        transformer.setParameter("root_uri", root_uri );
122                        transformer.setParameter("src_file", xsrcfile);
123                }
124                // Admin.notifyUser("transformer.parmformat" + transformer.getParameter("format"));
125               
126                StreamSource src =new StreamSource();                   
127                src.setInputStream(in);
128               
129                // Transform the source XML to out-stream
130                transformer.transform(src, stream );
131            }
132       
133        /**
134         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
135         * @param xmlStream the source xml stream
136         * @param transkey
137         * @return result-stream (converted to InputStream)
138         * @throws IOException
139         * @throws InterruptedException
140         * @throws TransformerException
141         */
142        public InputStream transformXML ( InputStream xmlStream, String transkey) throws IOException, InterruptedException, TransformerException {
143               
144                ByteArrayOutputStream out = new ByteArrayOutputStream();
145                transformXML(xmlStream, transkey, out);         
146            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
147            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
148            return transformedStream;
149        }
150
151        /**
152         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
153         * @param xmlFile URL of the source-file   
154         * @param transkey
155         * @return the result-stream (already converted to an InputStream)
156         * @throws TransformerException
157         * @throws IOException
158         */
159        public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
160                srcFile= xmlFile;
161                InputStream  xmlStream =
162             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
163           
164                return transformXML ( xmlStream, transkey); 
165        }
166
167
168        /**
169         * this is for xml present as string.
170         * if xml in a file or a stream, use the other methods
171         * @param xml xml as string
172         * @param transkey
173         * @return
174         */
175        public String transformXML (String xml, String transkey ) {
176                String result="";
177                try {
178                // Create a transform factory instance.
179                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
180                TransformerFactory tfactory = TransformerFactory.newInstance();
181                OutputStream os = new ByteArrayOutputStream();
182                StreamResult stream = new StreamResult(os);
183                // Create a transformer for the stylesheet.
184                InputStream  xslIS       =
185                    new BufferedInputStream(new FileInputStream(getXSLPath(transkey)));
186               
187                Transformer transformer =
188                    tfactory.newTransformer(new StreamSource(xslIS));
189                transformer.setParameter("format", transkey);
190                //Admin.notifyUser("transformer.parmformat" + transformer.getParameter("format"));
191
192                // Transform the source XML to System.out.
193                StreamSource src =new StreamSource();       
194                Reader reader  = new StringReader(xml);
195                src.setReader(reader);
196               
197                transformer.transform(src, stream );
198                                    //  new StreamResult(new File("Simple2.out")));
199               
200                result = os.toString(); 
201               
202                        } catch (TransformerException e) {
203                                e.printStackTrace();
204                        } catch (FileNotFoundException e) {
205                                // TODO Auto-generated catch block
206                                e.printStackTrace();
207                        }
208                       
209                        return result;
210        }
211
212}
Note: See TracBrowser for help on using the repository browser.