Ignore:
Timestamp:
08/25/11 20:21:23 (13 years ago)
Author:
vronk
Message:

started cleaning up code, adding inline-documentation;
also changes to output method in xsl (xhtml)

File:
1 edited

Legend:

Unmodified
Added
Removed
  • MDService2/trunk/MDService2/src/eu/clarin/cmdi/mdservice/action/MDTransformer.java

    r1488 r1495  
    5252
    5353/**
    54  * Helper class, encapsulating the xsl-transformations handling
    55  * the contract is, that the requester passes a key, which can be resolved to a xsl-script (momentary mapped in properties: Admin.getConfig())
    56  * Bad things happen, if the key or the appropriate xsl-file do not exist
     54 * Helper class, encapsulating the xsl-transformations handling.
     55 * The contract is, that the requester passes a key, which can be resolved to a xsl-script (momentary mapped in properties: Admin.getConfig())
     56 *
     57 * Bad things happen, if the key or the appropriate xsl-file do not exist - well the client gets a diagnostic message.
    5758 *   
    5859 *
     
    6667        private HashMap<String,String> params;
    6768               
    68         private MDTransformer singleton;
     69        // don't use singleton!! Bad things happen
     70        // private MDTransformer singleton;
    6971        TransformerFactory tfactory ;
    7072       
     
    7375        }
    7476       
    75         /*
    76         public static MDTransformer getMDTransformer () {
    77                 if (singleton == null) {
    78                         singleton = new MDTransformer();
    79                 }
    80                 return singleton;
    81         }
    82         */
    8377       
    8478        public URL getSrcFile() {
     
    9084        }
    9185
     86        /**
     87         * This serves the caller (mainly GenericProxyAction.prepare())
     88         * to provide/fill the request parameters.
     89         * They then get translated to stylesheet-parameters (in SetTransformerParameters()).
     90         * @return
     91         */
    9292        public void setParams(HashMap<String,String> params){
    9393                this.params = params;
    9494        }
    9595       
     96       
    9697        public HashMap<String,String> getParams(){
    9798                return this.params;
    9899        }
    99100        /**
    100          * get the path to the transform-xsl file from properties, based on the key
     101         * get the path to the transform-xsl file from properties, based on the key (aka format-parameter)
    101102         * @param key
    102103         * @return
     
    116117        }
    117118
     119        /**
     120         * Tries to load the stylesheet based on the key.
     121         * This is done in two steps:
     122         * 1. try to resolve the key to a path
     123         * 2. get the xsl-file as a stream (and establish it as StreamSource)
     124         *
     125         * @param key The key identifying the stylesheet for the transformation as passed by GenericProxyAction.
     126         * @return the stylesheet to be applied (as StreamSource)
     127         * @throws NoStylesheetException If the stylesheet could not be located
     128         */
    118129        private StreamSource getXSLStreamSource (String key) throws NoStylesheetException{             
    119130               
     
    126137                StreamSource streamSource = new StreamSource(xslstream);
    127138
    128                 //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).toString());
    129                 //Admin.notifyUser(this.getClass().getClassLoader().getResource(xslPath).getPath());
    130                
    131                
    132139                streamSource.setSystemId(this.getClass().getClassLoader().getResource(xslPath).toString());
    133                 return streamSource ;           
    134                
    135         }
    136 
    137         public Object getCols() throws TransformerConfigurationException, TransformerFactoryConfigurationError{
    138                
    139                 String xmlString = null;
    140                 // create new document
    141                 Document doc = null;
    142                 DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    143         DocumentBuilder docBuilder;
    144                 try {
    145                         docBuilder = docFactory.newDocumentBuilder();
    146                         doc = docBuilder.newDocument();
    147                         // append root tag <col >
    148                         Element root = (Element) doc.createElement("root");
    149                         doc.appendChild(root);
    150                        
    151                         Element child1 = (Element) doc.createElement("col");
    152                         child1.setTextContent("Id");
    153                         root.appendChild(child1);                       
    154                         Element child = (Element) doc.createElement("col");
    155                         child.setTextContent("Name");
    156                         root.appendChild(child);
    157                         //Element child = doc.createElement("col");
    158                         //child.setNodeValue("Id");
    159                        
    160                        
    161                         Transformer transformer = TransformerFactory.newInstance().newTransformer();
    162                         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    163 
    164                         //initialize StreamResult with File object to save to file
    165                         StreamResult result = new StreamResult(new StringWriter());
    166                         DOMSource source = new DOMSource(doc);
    167                         try {
    168                                 transformer.transform(source, result);
    169                                 xmlString = result.getWriter().toString();
    170                                
    171                                 Admin.notifyUser(xmlString);
    172                         } catch (TransformerException e) {
    173                                 // TODO Auto-generated catch block
    174                                 e.printStackTrace();
    175                         }
    176 
    177                        
    178 
    179                 } catch (ParserConfigurationException e) {
    180                         // TODO Auto-generated catch block
    181                         e.printStackTrace();
    182                 }
    183                 //return xmlString;
    184                 //return doc.getElementsByTagName("col").item(0);
    185                 return doc.getDocumentElement();
     140                return streamSource ;   
     141               
    186142        }
    187143       
     
    189145                return params.get("format");
    190146        }
    191        
     147
     148        /**
     149         * Makes the request-parameters available in the stylesheets
     150         * by translating them to stylesheet-parameters
     151         * @param transformer
     152         */
    192153        public void SetTransformerParameters(Transformer transformer){
    193154               
     
    231192                me.setWriter(w);
    232193               ((net.sf.saxon.Controller)transformer).setMessageEmitter(me);//new net.sf.saxon.event.MessageWarner());
     194
    233195               
    234 /*              transformer.setParameter("q", q);
    235                 transformer.setParameter("lang", lang);
    236                 transformer.setParameter("format", transkey);
    237                 transformer.setParameter("cols", cols);
    238                 if ((startRecord != null) && (maximumRecords != null)) {
    239 
    240                         transformer.setParameter("startRecord", startRecord);
    241                         transformer.setParameter("maximumRecords", maximumRecords);
    242                 }
    243                 if (repositoryURI != null) {
    244 
    245                         transformer.setParameter("repository_uri", repositoryURI);
    246                 }
    247                 */
    248                 /*       transformer.setParameter("cols", "<col label='id'>Id</col>" +
    249                                                                                  "<col label='id'>idno</col>" +
    250                                                                                  "<col label='name'>Name</col>" +
    251                                                                                  "<col label='title'>Title</col>" +
    252                                                                                  "<col label='title'>title</col>"); */
    253                
    254196                if (srcFile!=null) {
    255197                       
     
    288230                writeXslMessages(w);
    289231                ///Admin.notifyUser(w.getBuffer().toString());         
    290             }
    291        
     232   }
     233       
     234
     235        /**
     236         * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
     237         * @param xmlStream the source xml stream
     238         * @param transkey
     239         * @return result-stream (converted to InputStream)
     240         * @throws IOException
     241         * @throws InterruptedException
     242         * @throws TransformerException
     243         * @throws NoStylesheetException
     244         */
     245        public InputStream transformXML ( InputStream xmlStream) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
     246        //public InputStream transformXML ( InputStream xmlStream, String transkey, String cols, String startRecord, String maximumRecords, String lang, String q, String repositoryURI) throws IOException, InterruptedException, TransformerException {
     247               
     248                ByteArrayOutputStream out = new ByteArrayOutputStream();
     249                transformXML(xmlStream, out);           
     250            InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
     251            return transformedStream;
     252        }
     253       
     254        /**
     255         * another wrapper for the main method allowing to directly pass a URL to the source-xml   
     256         * @param xmlFile URL of the source-file   
     257         * @param transkey
     258         * @return the result-stream (already converted to an InputStream)
     259         * @throws TransformerException
     260         * @throws IOException
     261         * @throws NoStylesheetException
     262         */
     263        public InputStream transformXML (URL xmlFile ) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
     264        //public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
     265                srcFile= xmlFile;
     266                InputStream  xmlStream =
     267             new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
     268           
     269                return transformXML ( xmlStream);
     270        }
     271
     272
     273        /**
     274         * this is for xml-data present as string (primarily the query string present as XCQL).
     275         * if xml in a file or a stream, use the other methods
     276         * @param xml xml-data as string
     277         * @param transkey
     278         * @return
     279         * @throws NoStylesheetException
     280         * @throws IOException
     281         */
     282        public String transformXML (String xml) throws NoStylesheetException {
     283        //public String transformXML (String xml, String transkey ) {
     284                String result="";
     285                try {
     286                // Create a transform factory instance.
     287                        System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
     288                        //System.setProperty("javax.xml.transform.TransformerFactory", "com.icl.saxon.TransformerFactoryImpl");
     289                TransformerFactory tfactory = TransformerFactory.newInstance();
     290                OutputStream os = new ByteArrayOutputStream();
     291                StreamResult stream = new StreamResult(os);
     292                // Create a transformer for the stylesheet.
     293                Transformer transformer = tfactory.newTransformer(
     294                                                getXSLStreamSource(getTranskey()));
     295
     296                MessageEmitter me = new net.sf.saxon.event.MessageEmitter();
     297                StringWriter w = new StringWriter();
     298                me.setWriter(w);
     299                ((net.sf.saxon.Controller)transformer).setMessageEmitter(me);//new net.sf.saxon.event.MessageWarner());
     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             // Write <xsl:message>
     309                writeXslMessages(w);
     310                 
     311                result = os.toString();
     312               
     313                        } catch (TransformerException e) {
     314                                e.printStackTrace();
     315                        }
     316                       
     317                        return result;
     318        }
     319
    292320        private void writeXslMessages(StringWriter w){
    293321       
     
    304332                        e.printStackTrace();
    305333                }
    306 
    307         }
    308         /**
    309          * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
    310          * @param xmlStream the source xml stream
    311          * @param transkey
    312          * @return result-stream (converted to InputStream)
    313          * @throws IOException
    314          * @throws InterruptedException
    315          * @throws TransformerException
    316          * @throws NoStylesheetException
    317          */
    318         public InputStream transformXML ( InputStream xmlStream) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
    319         //public InputStream transformXML ( InputStream xmlStream, String transkey, String cols, String startRecord, String maximumRecords, String lang, String q, String repositoryURI) throws IOException, InterruptedException, TransformerException {
    320                
    321                 ByteArrayOutputStream out = new ByteArrayOutputStream();
    322                 transformXML(xmlStream, out);
    323                 //transformXML(xmlStream, transkey, cols, startRecord, maximumRecords, lang, q, repositoryURI, out);           
    324             InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
    325             //Admin.notifyUser("transformedStream:" + transformedStream.toString());
    326             return transformedStream;
    327         }
    328        
    329         /**
    330          * just a wrapper for the main method translating the output-stream into a input-stream (expected by the Controller-Actions to return as response)
    331          * @param xmlStream the source xml stream
    332          * @param transkey
    333          * @return result-stream (converted to InputStream)
    334          * @throws IOException
    335          * @throws InterruptedException
    336          * @throws TransformerException
    337          */
    338         /*
    339         public InputStream transformXML ( InputStream xmlStream, String transkey) throws IOException, InterruptedException, TransformerException {
    340                
    341                 ByteArrayOutputStream out = new ByteArrayOutputStream();
    342                 transformXML(xmlStream, transkey, "", "", "","","", "", out);           
    343             InputStream transformedStream = new ByteArrayInputStream(out.toByteArray());
    344             //Admin.notifyUser("transformedStream:" + transformedStream.toString());
    345             return transformedStream;
    346         }
    347 */
    348         /**
    349          * another wrapper for the main method allowing to directly pass a URL to the source-xml   
    350          * @param xmlFile URL of the source-file   
    351          * @param transkey
    352          * @return the result-stream (already converted to an InputStream)
    353          * @throws TransformerException
    354          * @throws IOException
    355          * @throws NoStylesheetException
    356          */
    357         public InputStream transformXML (URL xmlFile ) throws IOException, InterruptedException, TransformerException, NoStylesheetException {
    358         //public InputStream transformXML (URL xmlFile, String transkey ) throws IOException, InterruptedException, TransformerException {
    359                 srcFile= xmlFile;
    360                 InputStream  xmlStream =
    361              new BufferedInputStream(new FileInputStream(xmlFile.getPath()));
    362            
    363                 return transformXML ( xmlStream);
    364         }
    365 
    366 
    367         /**
    368          * this is for xml present as string.
    369          * if xml in a file or a stream, use the other methods
    370          * @param xml xml as string
    371          * @param transkey
    372          * @return
    373          * @throws NoStylesheetException
    374          * @throws IOException
    375          */
    376         public String transformXML (String xml) throws NoStylesheetException {
    377         //public String transformXML (String xml, String transkey ) {
    378                 String result="";
    379                 try {
    380                 // Create a transform factory instance.
    381                         System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    382                         //System.setProperty("javax.xml.transform.TransformerFactory", "com.icl.saxon.TransformerFactoryImpl");
    383                 TransformerFactory tfactory = TransformerFactory.newInstance();
    384                 OutputStream os = new ByteArrayOutputStream();
    385                 StreamResult stream = new StreamResult(os);
    386                 // Create a transformer for the stylesheet.
    387                 Transformer transformer = tfactory.newTransformer(
    388                                                 getXSLStreamSource(getTranskey()));
    389 /* instead of:
    390                 InputStream  xslIS       =
    391                     new BufferedInputStream(new FileInputStream(getXSLPath(transkey)));
    392                
    393                 Transformer transformer =
    394                     tfactory.newTransformer(new StreamSource(xslIS));
    395                     */
    396                 ////////////////////
    397                 MessageEmitter me = new net.sf.saxon.event.MessageEmitter();
    398                 StringWriter w = new StringWriter();
    399                 me.setWriter(w);
    400                 ((net.sf.saxon.Controller)transformer).setMessageEmitter(me);//new net.sf.saxon.event.MessageWarner());
    401 
    402                 // Transform the source XML to System.out.
    403                 StreamSource src =new StreamSource();       
    404                 Reader reader  = new StringReader(xml);
    405                 src.setReader(reader);
    406                
    407                 transformer.transform(src, stream );
    408                                     //  new StreamResult(new File("Simple2.out")));
    409              // Write <xsl:message>
    410                 writeXslMessages(w);
    411                  
    412                 result = os.toString();
    413                
    414                         } catch (TransformerException e) {
    415                                 e.printStackTrace();
    416                         }
    417                        
    418                         return result;
    419         }
    420 
     334        }
    421335       
    422336        public static HashMap<String,String> createParamsMap(String transkey){
Note: See TracChangeset for help on using the changeset viewer.