001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one
003     * or more contributor license agreements. See the NOTICE file
004     * distributed with this work for additional information
005     * regarding copyright ownership. The ASF licenses this file
006     * to you under the Apache License, Version 2.0 (the  "License");
007     * you may not use this file except in compliance with the License.
008     * You may obtain a copy of the License at
009     *
010     *     http://www.apache.org/licenses/LICENSE-2.0
011     *
012     * Unless required by applicable law or agreed to in writing, software
013     * distributed under the License is distributed on an "AS IS" BASIS,
014     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015     * See the License for the specific language governing permissions and
016     * limitations under the License.
017     */
018    /*
019     * $Id: Transform.java 468647 2006-10-28 06:59:33Z minchau $
020     */
021    
022    package org.apache.xalan.xsltc.cmdline;
023    
024    import java.io.FileNotFoundException;
025    import java.net.MalformedURLException;
026    import java.net.UnknownHostException;
027    import java.util.Vector;
028    
029    import javax.xml.parsers.SAXParser;
030    import javax.xml.parsers.SAXParserFactory;
031    import javax.xml.transform.sax.SAXSource;
032    
033    import org.apache.xalan.xsltc.TransletException;
034    import org.apache.xalan.xsltc.compiler.util.ErrorMsg;
035    import org.apache.xalan.xsltc.DOMEnhancedForDTM;
036    import org.apache.xalan.xsltc.dom.XSLTCDTMManager;
037    import org.apache.xalan.xsltc.runtime.AbstractTranslet;
038    import org.apache.xalan.xsltc.runtime.Constants;
039    import org.apache.xalan.xsltc.runtime.Parameter;
040    import org.apache.xalan.xsltc.runtime.output.TransletOutputHandlerFactory;
041    import org.apache.xml.serializer.SerializationHandler;
042    
043    import org.xml.sax.InputSource;
044    import org.xml.sax.SAXException;
045    import org.xml.sax.XMLReader;
046    
047    import org.apache.xalan.xsltc.StripFilter;
048    import org.apache.xml.dtm.DTMWSFilter;
049    import org.apache.xalan.xsltc.dom.DOMWSFilter;
050    
051    /**
052     * @author Jacek Ambroziak
053     * @author Santiago Pericas-Geertsen
054     * @author G. Todd Miller
055     * @author Morten Jorgensen
056     */
057    final public class Transform {
058    
059        private SerializationHandler _handler;
060    
061        private String  _fileName;
062        private String  _className;
063        private String  _jarFileSrc;
064        private boolean _isJarFileSpecified = false;
065        private Vector  _params = null;
066        private boolean _uri, _debug;
067        private int     _iterations;
068    
069        public Transform(String className, String fileName,
070                         boolean uri, boolean debug, int iterations) {
071            _fileName = fileName;
072            _className = className;
073            _uri = uri;
074            _debug = debug;
075            _iterations = iterations;
076      }
077      
078       public String getFileName(){return _fileName;}
079       public String getClassName(){return _className;}
080    
081        public void setParameters(Vector params) {
082            _params = params;
083        }
084    
085        private void setJarFileInputSrc(boolean flag,  String jarFile) {
086            // TODO: at this time we do not do anything with this
087            // information, attempts to add the jarfile to the CLASSPATH
088            // were successful via System.setProperty, but the effects
089            // were not visible to the running JVM. For now we add jarfile
090            // to CLASSPATH in the wrapper script that calls this program. 
091            _isJarFileSpecified = flag;
092            // TODO verify jarFile exists...
093            _jarFileSrc = jarFile;  
094        }
095    
096        private void doTransform() {
097            try {
098                final Class clazz = ObjectFactory.findProviderClass(
099                    _className, ObjectFactory.findClassLoader(), true);
100                final AbstractTranslet translet = (AbstractTranslet)clazz.newInstance();
101                translet.postInitialization();
102    
103                // Create a SAX parser and get the XMLReader object it uses
104                final SAXParserFactory factory = SAXParserFactory.newInstance();
105                try {
106                    factory.setFeature(Constants.NAMESPACE_FEATURE,true);
107                }
108                catch (Exception e) {
109                    factory.setNamespaceAware(true);
110                }
111                final SAXParser parser = factory.newSAXParser();
112                final XMLReader reader = parser.getXMLReader();
113    
114                // Set the DOM's DOM builder as the XMLReader's SAX2 content handler
115                XSLTCDTMManager dtmManager =
116                    (XSLTCDTMManager)XSLTCDTMManager.getDTMManagerClass()
117                                                    .newInstance();
118    
119                DTMWSFilter wsfilter;
120                if (translet != null && translet instanceof StripFilter) {
121                    wsfilter = new DOMWSFilter(translet);
122                } else {
123                    wsfilter = null;
124                }
125    
126                final DOMEnhancedForDTM dom =
127                       (DOMEnhancedForDTM)dtmManager.getDTM(
128                                new SAXSource(reader, new InputSource(_fileName)),
129                                false, wsfilter, true, false, translet.hasIdCall());
130    
131                dom.setDocumentURI(_fileName);
132                translet.prepassDocument(dom);
133    
134                // Pass global parameters
135                int n = _params.size();
136                for (int i = 0; i < n; i++) {
137                    Parameter param = (Parameter) _params.elementAt(i);
138                    translet.addParameter(param._name, param._value);
139                }
140    
141                // Transform the document
142                TransletOutputHandlerFactory tohFactory = 
143                    TransletOutputHandlerFactory.newInstance();
144                tohFactory.setOutputType(TransletOutputHandlerFactory.STREAM);
145                tohFactory.setEncoding(translet._encoding);
146                tohFactory.setOutputMethod(translet._method);
147    
148                if (_iterations == -1) {
149                    translet.transform(dom, tohFactory.getSerializationHandler());
150                }
151                else if (_iterations > 0) {
152                    long mm = System.currentTimeMillis();
153                    for (int i = 0; i < _iterations; i++) {
154                        translet.transform(dom,
155                                           tohFactory.getSerializationHandler());
156                    }
157                    mm = System.currentTimeMillis() - mm;
158    
159                    System.err.println("\n<!--");
160                    System.err.println("  transform  = "
161                                       + (((double) mm) / ((double) _iterations))
162                                       + " ms");
163                    System.err.println("  throughput = "
164                                       + (1000.0 / (((double) mm)
165                                                     / ((double) _iterations)))
166                                       + " tps");
167                    System.err.println("-->");
168                }
169            }
170            catch (TransletException e) {
171                if (_debug) e.printStackTrace();
172                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
173                       e.getMessage());         
174            }
175            catch (RuntimeException e) {
176                if (_debug) e.printStackTrace();
177                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
178                                   e.getMessage());
179            }
180            catch (FileNotFoundException e) {
181                if (_debug) e.printStackTrace();
182                ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_NOT_FOUND_ERR, _fileName);
183                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
184                                   err.toString());
185            }
186            catch (MalformedURLException e) {
187                if (_debug) e.printStackTrace();
188                ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, _fileName);
189                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
190                                   err.toString());
191            }
192            catch (ClassNotFoundException e) {
193                if (_debug) e.printStackTrace();
194                ErrorMsg err= new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR,_className);
195                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
196                                   err.toString());
197            }
198            catch (UnknownHostException e) {
199                if (_debug) e.printStackTrace();
200                ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_URI_ERR, _fileName);
201                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
202                                   err.toString());
203            }
204            catch (SAXException e) {
205                Exception ex = e.getException();
206                if (_debug) {
207                    if (ex != null) ex.printStackTrace();
208                    e.printStackTrace();
209                }
210                System.err.print(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY));
211                if (ex != null)
212                    System.err.println(ex.getMessage());
213                else
214                    System.err.println(e.getMessage());
215            }
216            catch (Exception e) {
217                if (_debug) e.printStackTrace();
218                System.err.println(new ErrorMsg(ErrorMsg.RUNTIME_ERROR_KEY)+
219                                   e.getMessage());
220            }
221        }
222    
223        public static void printUsage() {
224            System.err.println(new ErrorMsg(ErrorMsg.TRANSFORM_USAGE_STR));
225        }
226    
227        public static void main(String[] args) {
228            try {
229                if (args.length > 0) {
230                    int i;
231                    int iterations = -1;
232                    boolean uri = false, debug = false;
233                    boolean isJarFileSpecified = false;
234                    String  jarFile = null;
235    
236                    // Parse options starting with '-'
237                    for (i = 0; i < args.length && args[i].charAt(0) == '-'; i++) {
238                        if (args[i].equals("-u")) {
239                            uri = true;
240                        }
241                        else if (args[i].equals("-x")) {
242                            debug = true;
243                        }
244                        else if (args[i].equals("-j")) {
245                            isJarFileSpecified = true;      
246                            jarFile = args[++i];
247                        }
248                        else if (args[i].equals("-n")) {
249                            try {
250                                iterations = Integer.parseInt(args[++i]);
251                            }
252                            catch (NumberFormatException e) {
253                                // ignore
254                            }
255                        }
256                        else {
257                            printUsage();
258                        }
259                    }
260    
261                    // Enough arguments left ?
262                    if (args.length - i < 2) printUsage();
263    
264                    // Get document file and class name
265                    Transform handler = new Transform(args[i+1], args[i], uri,
266                        debug, iterations);
267                    handler.setJarFileInputSrc(isJarFileSpecified,  jarFile);
268    
269                    // Parse stylesheet parameters
270                    Vector params = new Vector();
271                    for (i += 2; i < args.length; i++) {
272                        final int equal = args[i].indexOf('=');
273                        if (equal > 0) {
274                            final String name  = args[i].substring(0, equal);
275                            final String value = args[i].substring(equal+1);
276                            params.addElement(new Parameter(name, value));
277                        }
278                        else {
279                            printUsage();
280                        }
281                    }
282    
283                    if (i == args.length) {
284                        handler.setParameters(params);
285                        handler.doTransform();
286                    }
287                } else {
288                    printUsage();
289                }
290            }
291            catch (Exception e) {
292                e.printStackTrace();
293            }
294        }
295    }