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

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

rework components resolution - now based on @ComponentID not @filename

File size: 7.6 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               
39        private static MDTransformer singleton;
40        TransformerFactory tfactory ; 
41       
42        public MDTransformer () {               
43                tfactory = TransformerFactory.newInstance();   
44        }
45       
46        public static MDTransformer getMDTransformer () {
47                if (singleton == null) {
48                        singleton = new MDTransformer();
49                } 
50                return singleton;
51        }
52       
53       
54        public URL getSrcFile() {
55                return srcFile;
56        }
57
58        public void setSrcFile(URL srcFile) {
59                this.srcFile = srcFile;
60        }
61
62        /**
63         * get the path to the transform-xsl file from properties, based on the key
64         * @param key
65         * @return
66         */
67        private String getXSLPath (String key) {               
68                String xslpath = "";
69                String xslfilename= Admin.getConfig().getProperty("xsl." + key);
70               
71                if (xslfilename!=null) {                       
72                        xslpath =  Admin.getConfig().getProperty("scripts.path") + xslfilename;
73                } 
74                Admin.notifyUser("xslfile:" + xslpath);
75                return xslpath;
76        }
77
78        private StreamSource getXSLStreamSource (String key){           
79               
80                InputStream xslstream;
81                                       
82                //URL myURL = new URL (getXSLPath(key));
83                //xslstream = myURL.openStream();
84                String xslPath = getXSLPath(key);
85                xslstream = this.getClass().getClassLoader().getResourceAsStream(xslPath);
86                StreamSource streamSource = new StreamSource(xslstream);
87
88                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).toString());
89                //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).getPath());
90               
91                streamSource.setSystemId(this.getClass().getClassLoader().getResource(xslPath).toString());
92                return streamSource ;           
93               
94        }
95
96        /**
97         * The main method for transforming, applies the appropriate (based on the transkey) stylesheet on the xml-stream
98         * and writes the result into the output stream.   
99         * @param in InpuStream with xml 
100         * @param transkey this defines the stylesheet to use and is also passed to the stylesheet as "format"-parameter
101         * @param out the stream to write the output to
102         * @throws TransformerException
103         * @throws IOException
104         */             
105        public void transformXML (InputStream in, String transkey, OutputStream out ) throws TransformerException, IOException {
106       
107                // Create a transform factory instance.
108                TransformerFactory tfactory = TransformerFactory.newInstance();
109                //OutputStream os = new ByteArrayOutputStream();
110                StreamResult stream = new StreamResult(out);
111               
112                // Create a transformer for the stylesheet.
113                        //String xslpath = getXSLPath(transkey);               
114                Transformer transformer = tfactory.newTransformer(
115                                                                        getXSLStreamSource(transkey));
116                       
117                transformer.setParameter("format", transkey);
118               
119                if (srcFile!=null) {
120                        File f = new File(srcFile.getPath());
121                       
122                        //Admin.notifyUser("src:" + srcFile.getFile());
123                        //Admin.notifyUser("fpath:" + f.getAbsolutePath());
124                        String root_uri =  srcFile.toString();
125                        String xsrcfile =  srcFile.getFile();
126                        if  (srcFile.getProtocol().equals("file")) {
127                                root_uri = "file:///" + f.getParent().replace('\\', '/');
128                                xsrcfile = "file:///" + f.getPath().replace('\\', '/');
129                        } 
130                        Admin.notifyUser("root_uri:" +  root_uri );
131                        transformer.setParameter("root_uri", root_uri );
132                        transformer.setParameter("src_file", xsrcfile);
133                } else {
134                        Admin.notifyUser("transformXML(): srcFile not set!!");                         
135                }
136                //
137               
138                StreamSource src =new StreamSource();                   
139                src.setInputStream(in);
140               
141                // Transform the source XML to out-stream
142                transformer.transform(src, stream );
143            }
144       
145        /**
146         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
147         * @param xmlStream the source xml stream
148         * @param transkey
149         * @return result-stream (converted to InputStream)
150         * @throws IOException
151         * @throws InterruptedException
152         * @throws TransformerException
153         */
154        public InputStream transformXML ( InputStream xmlStream, String transkey) throws IOException, InterruptedException, TransformerException {
155               
156                ByteArrayOutputStream out = new ByteArrayOutputStream();
157                transformXML(xmlStream, transkey, out);         
158            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
159            //Admin.notifyUser("transformedStream:" + transformedStream.toString());
160            return transformedStream;
161        }
162
163        /**
164         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
165         * @param xmlFile URL of the source-file   
166         * @param transkey
167         * @return the result-stream (already converted to an InputStream)
168         * @throws TransformerException
169         * @throws IOException
170         */
171        public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
172                srcFile= xmlFile;
173                InputStream  xmlStream =
174             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
175           
176                return transformXML ( xmlStream, transkey); 
177        }
178
179
180        /**
181         * this is for xml present as string.
182         * if xml in a file or a stream, use the other methods
183         * @param xml xml as string
184         * @param transkey
185         * @return
186         */
187        public String transformXML (String xml, String transkey ) {
188                String result="";
189                try {
190                // Create a transform factory instance.
191                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
192                TransformerFactory tfactory = TransformerFactory.newInstance();
193                OutputStream os = new ByteArrayOutputStream();
194                StreamResult stream = new StreamResult(os);
195                // Create a transformer for the stylesheet.
196                Transformer transformer = tfactory.newTransformer(
197                                                getXSLStreamSource(transkey));
198/* instead of:
199                InputStream  xslIS       =
200                    new BufferedInputStream(new FileInputStream(getXSLPath(transkey)));
201               
202                Transformer transformer =
203                    tfactory.newTransformer(new StreamSource(xslIS));
204                    */
205                transformer.setParameter("format", transkey);
206                //Admin.notifyUser("transformer.parmformat" + transformer.getParameter("format"));
207
208                // Transform the source XML to System.out.
209                StreamSource src =new StreamSource();       
210                Reader reader  = new StringReader(xml);
211                src.setReader(reader);
212               
213                transformer.transform(src, stream );
214                                    //  new StreamResult(new File("Simple2.out")));
215               
216                result = os.toString(); 
217               
218                        } catch (TransformerException e) {
219                                e.printStackTrace();
220                        }
221                       
222                        return result;
223        }
224
225}
Note: See TracBrowser for help on using the repository browser.