Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that transforms an XML text document
4
 *             into a another type using XSL
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Matt Jones
8
 *
9
 * '$Author: daigle $'
10
 * '$Date: 2008-07-06 21:25:34 -0700 (Sun, 06 Jul 2008) $'
11
 * '$Revision: 4080 $'
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 2 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program; if not, write to the Free Software
25
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26
 */
27

    
28
package edu.ucsb.nceas.metacat;
29

    
30
import java.io.*;
31
import java.net.URL;
32
import java.net.MalformedURLException;
33
import java.sql.*;
34
import java.util.Enumeration;
35
import java.util.Hashtable;
36
import java.util.Iterator;
37
import java.util.Map;
38
import java.util.Map.Entry;
39
import java.util.Stack;
40

    
41
import javax.xml.transform.TransformerFactory;
42
import javax.xml.transform.Transformer;
43
import javax.xml.transform.stream.StreamSource;
44
import javax.xml.transform.stream.StreamResult;
45
import javax.xml.transform.TransformerException;
46
import javax.xml.transform.TransformerConfigurationException;
47

    
48
import org.apache.log4j.Logger;
49
import org.apache.xerces.parsers.DOMParser;
50
import org.w3c.dom.Attr;
51
import org.w3c.dom.NamedNodeMap;
52
import org.w3c.dom.NodeList;
53
import org.w3c.dom.Document;
54
import org.w3c.dom.Node;
55
import org.w3c.dom.DocumentType;
56
import org.xml.sax.SAXException;
57
import org.xml.sax.InputSource;
58
import org.apache.xerces.dom.DocumentTypeImpl;
59
import org.apache.xpath.XPathAPI;
60

    
61
/*
62
import oracle.xml.parser.v2.XSLStylesheet;
63
import oracle.xml.parser.v2.XSLException;
64
import oracle.xml.parser.v2.XMLParseException;
65
import oracle.xml.parser.v2.XSLProcessor;
66
import oracle.xml.parser.v2.XMLDocument;
67
import oracle.xml.parser.v2.DOMParser;
68
*/
69
import org.w3c.dom.Document;
70
import org.w3c.dom.Node;
71
import org.w3c.dom.Element;
72
import org.xml.sax.SAXException;
73

    
74
import edu.ucsb.nceas.metacat.service.PropertyService;
75
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
76
import edu.ucsb.nceas.metacat.util.SystemUtil;
77
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
78

    
79
import java.util.Properties;
80

    
81

    
82
/**
83
 * A Class that transforms XML documents utitlizing XSL style sheets
84
 */
85
public class DBTransform {
86

    
87
  //private Connection	conn = null;
88
  private MetaCatUtil   util = null;
89
  private String 	configDir = null;
90
  private String	defaultStyle = null;
91
  private Logger logMetacat = Logger.getLogger(DBTransform.class);
92
  private String httpServer = null;
93
  private String contextURL = null;
94
  private String servletURL = null;
95
  
96
  /**
97
   * construct a DBTransform instance.
98
   *
99
   * Generally, one calls transformXMLDocument() after constructing the instance
100
   *
101
   * @param conn the database connection from which to lookup the public ids
102
   */
103
  public DBTransform()
104
                  throws IOException,
105
                         SQLException,
106
                         ClassNotFoundException,
107
                         PropertyNotFoundException
108
  {
109
    configDir = SystemUtil.getStyleSkinsDir();
110
    defaultStyle = PropertyService.getProperty("application.default-style");
111
    httpServer = SystemUtil.getServerURL();
112
    contextURL = SystemUtil.getContextURL();
113
    servletURL = SystemUtil.getServletURL();
114
  }
115

    
116
  /**
117
   * @see transformXMLDocument(String doc, String sourceType,
118
   *            String targetType, String qformat, PrintWriter pw,
119
   *            String sessionid)
120
   */
121
  public void transformXMLDocument(String doc, String sourceType,
122
                String targetType, String qformat, PrintWriter pw,
123
                Hashtable param)
124
  {
125
    transformXMLDocument(doc, sourceType, targetType, qformat, pw, param, null);
126
  }
127

    
128
   /**
129
   * @see transformXMLDocument(String doc, String sourceType,
130
   *            String targetType, String qFormat, StringWriter pw
131
   *            String sessionid)
132
   */
133
  public void transformXMLDocument(String doc, String sourceType,
134
                String targetType, String qFormat, StringWriter pw)
135
  {
136
    transformXMLDocument(doc, sourceType, targetType, qFormat, pw, null);
137
  }
138

    
139

    
140
  /**
141
   * Transform an XML document using the stylesheet reference from the db
142
   *
143
   * @param doc the document to be transformed
144
   * @param sourcetype the document type of the source
145
   * @param targettype the target document type
146
   * @param qformat the name of the style set to use
147
   * @param pw the PrintWriter to which output is printed
148
   * @param params some parameters for eml2 transformation
149
   */
150
  public void transformXMLDocument(String doc, String sourceType,
151
                                   String targetType, String qformat,
152
                                   PrintWriter pw, Hashtable param,
153
                                   String sessionid)
154
 {
155

    
156
    // Look up the stylesheet for this type combination
157
    String xslSystemId = getStyleSystemId(qformat, sourceType, targetType);
158
    if (xslSystemId != null)
159
    {
160
      try
161
      {// Create a stylesheet from the system id that was found
162
        doc = removeDOCTYPE(doc);
163
        StringReader xml = new StringReader(doc);
164
        StreamResult result = new StreamResult(pw);
165
        doTransform(xml, result, xslSystemId, param, qformat, sessionid);
166

    
167
      }
168
      catch (Exception e)
169
      {
170
        pw.println(xslSystemId + ": Error transforming document in " +
171
                   "DBTransform.transformXMLDocument: " +
172
                   e.getMessage());
173

    
174
      }
175
    }
176
    else
177
    {
178
      // No stylesheet registered form this document type, so just return the
179
      // XML stream we were passed
180
      pw.print(doc);
181
    }
182
  }
183

    
184
  /**
185
   * Transform an XML document to StringWriter using the stylesheet reference
186
   * from the db
187
   * @param doc the document to be transformed
188
   * @param sourceType the document type of the source
189
   * @param targetType the target document type
190
   * @param qFormat the name of the style set to use
191
   * @param pw the StringWriter to which output will be stored
192
   */
193
  public void transformXMLDocument(String doc, String sourceType,
194
                String targetType, String qFormat, StringWriter pw,
195
                String sessionid)
196
  {
197

    
198
    // Look up the stylesheet for this type combination
199
    String xslSystemId = getStyleSystemId(qFormat, sourceType, targetType);
200
    if (xslSystemId != null)
201
    {
202
      // Create a stylesheet from the system id that was found
203
      try
204
      {
205
        doc = removeDOCTYPE(doc);
206
        StringReader xml = new StringReader(doc);
207
        StreamResult result = new StreamResult(pw);
208
        doTransform(xml, result, xslSystemId, null, qFormat, sessionid);
209
      }
210
      catch (Exception e)
211
      {
212
        logMetacat.error(xslSystemId + ": Error transforming document in " +
213
                   "DBTransform.transformXMLDocument: " +
214
                   e.getMessage());
215

    
216
      }
217
    }
218
    else
219
    {
220
      // No stylesheet registered form this document type, so just return the
221
      // XML stream we were passed
222
      pw.write(doc);
223
    }
224
  }
225

    
226
  /**
227
   * Method to do transform for a string reader
228
   * @param doc the document to be transformed
229
   * @param sourcetype the document type of the source
230
   * @param targettype the target document type
231
   * @param qformat the name of the style set to use
232
   * @param pw the PrintWriter to which output is printed
233
   * @param params some parameters for eml2 transformation
234
   */
235
   public void transformXMLDocument(StringReader docContent, String sourceType,
236
                                   String targetType, String qformat,
237
                                   PrintWriter pw, Hashtable param,
238
                                   String sessionid)
239
   {
240
     // Look up the stylesheet for this type combination
241
    String xslSystemId = getStyleSystemId(qformat, sourceType, targetType);
242
    if (xslSystemId != null)
243
    {
244
      try
245
      {// Create a stylesheet from the system id that was found
246
        StreamResult result = new StreamResult(pw);
247
        doTransform(docContent, result, xslSystemId, param, qformat, sessionid);
248

    
249
      }
250
      catch (Exception e)
251
      {
252
        pw.println(xslSystemId + ": Error transforming document in " +
253
                   "DBTransform.transformXMLDocument: " +
254
                   e.getMessage());
255

    
256
      }
257
    }
258
    else
259
    {
260
      // No stylesheet registered form this document type, so just return the
261
      // XML stream we were passed
262
      pw.print(docContent);
263
    }
264
   }
265

    
266
  /**
267
   * Reads skin's config file if it exists, and populates Transformer paramaters
268
   * with its contents.
269
   * It then adds the parameters passed to it via Hashtable param to the Transformer.
270
   * It then calls the Transformer.transform method.
271
   */
272
  private void doTransform(StringReader docContent, 
273
          StreamResult resultOutput,
274
          String xslSystemId, 
275
          Hashtable param,
276
          String qformat, 
277
          String sessionid) 
278
          throws Exception {
279
      
280
      Properties skinOptions;
281
      TransformerFactory tFactory;
282
      Transformer transformer;
283
      String key, value;
284
      StreamSource xml;
285
      Enumeration en;
286
      Iterator iterIt;
287
      Map.Entry entry;
288
      
289
      if (xslSystemId != null) {
290
        tFactory = TransformerFactory.newInstance();
291
        transformer = tFactory.newTransformer(new StreamSource(xslSystemId));
292
        
293
        transformer.setParameter("qformat", qformat);
294
        logMetacat.warn("qformat: "+qformat);
295
        
296
        if (MetaCatUtil.hasSkinConfig(qformat)) {
297
            skinOptions = MetaCatUtil.getSkinConfig(qformat);
298
		
299
            iterIt = skinOptions.entrySet().iterator();
300
            while (iterIt.hasNext()) {
301
                entry = (Entry) iterIt.next();
302
                key = (String) entry.getKey();
303
                value = (String) entry.getValue();
304
                transformer.setParameter(key, value);
305
            }
306
        }
307
        
308
        if (sessionid != null && !sessionid.equals("null")) {
309
          transformer.setParameter("sessid", sessionid);
310
        }
311
        
312
        //set up the default params (can be overridden by the passed in params)
313
        String cgiPrefix = SystemUtil.getCGI_URL();
314
        logMetacat.debug("cgi-prefix=" + cgiPrefix);
315
        logMetacat.debug("httpServer=" + httpServer);
316
        logMetacat.debug("contextURL=" + contextURL);
317
        logMetacat.debug("serletPath=" + servletURL);
318
        transformer.setParameter("cgi-prefix", cgiPrefix);
319
        transformer.setParameter("httpServer", httpServer);
320
        transformer.setParameter("contextURL", contextURL);
321
        transformer.setParameter("servletURL", servletURL);
322
        
323
        // Set up parameter for transformation
324
        if ( param != null) {
325
          en = param.keys();
326
          while (en.hasMoreElements()) {
327
            key = (String) en.nextElement();
328
            value = ((String[]) (param.get(key)))[0];
329
            logMetacat.info(key+" : "+value);
330
            transformer.setParameter(key, value);
331
          }
332
        }
333
        xml = new StreamSource(docContent);
334
        transformer.transform(xml,resultOutput);
335
    }
336
  }//doTransform
337

    
338

    
339
  /**
340
   * gets the content of a tag in a given xml file with the given path
341
   * @param f the file to parse
342
   * @param path the path to get the content from
343
   */
344
  public static NodeList getPathContent(File f, String path)
345
  {
346
    if(f == null)
347
    {
348
      return null;
349
    }
350

    
351
    DOMParser parser = new DOMParser();
352
    InputSource in;
353
    FileInputStream fs;
354

    
355
    try
356
    {
357
      fs = new FileInputStream(f);
358
      in = new InputSource(fs);
359
    }
360
    catch(FileNotFoundException fnf)
361
    {
362
      fnf.printStackTrace();
363
      return null;
364
    }
365

    
366
    try
367
    {
368
      parser.parse(in);
369
      fs.close();
370
    }
371
    catch(Exception e1)
372
    {
373
      System.err.println("File: " + f.getPath() + " : parse threw: " +
374
                         e1.toString());
375
      return null;
376
    }
377

    
378
    Document doc = parser.getDocument();
379

    
380
    try
381
    {
382
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
383
      return docNodeList;
384
    }
385
    catch(Exception se)
386
    {
387
      System.err.println("file: " + f.getPath() + " : parse threw: " +
388
                         se.toString());
389
      return null;
390
    }
391
  }
392

    
393
  /**
394
   * Lookup a stylesheet reference from the db catalog
395
   *
396
   * @param qformat    the named style-set format
397
   * @param sourcetype the document type of the source
398
   * @param targettype the document type of the target
399
   */
400
  public String getStyleSystemId(String qformat, String sourcetype,
401
                String targettype) {
402
    String systemId = null;
403

    
404
    if ((qformat == null) || (qformat.equals("html"))) {
405
      qformat = defaultStyle;
406
    }
407

    
408
    // Load the style-set map for this qformat into a DOM
409
    try {
410
      boolean breakflag = false;
411
      String filename = configDir + "/" + qformat + "/" + qformat + ".xml";
412
      logMetacat.warn("Trying style-set file: " + filename);
413
      File f = new File(filename);
414
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
415
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
416
      Node nDefault = nlDefault.item(0);
417
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
418

    
419
      for(int i=0; i<nlDoctype.getLength(); i++)
420
      { //look for the right sourcetype
421
        Node nDoctype = nlDoctype.item(i);
422
        NamedNodeMap atts = nDoctype.getAttributes();
423
        Node nAtt = atts.getNamedItem("publicid");
424
        String doctype = nAtt.getFirstChild().getNodeValue();
425
        if(doctype.equals(sourcetype))
426
        { //found the right sourcetype now we need to get the target type
427
          NodeList nlChildren = nDoctype.getChildNodes();
428
          for(int j=0; j<nlChildren.getLength(); j++)
429
          {
430
            Node nChild = nlChildren.item(j);
431
            String childName = nChild.getNodeName();
432
            if(childName.equals("target"))
433
            {
434
              NamedNodeMap childAtts = nChild.getAttributes();
435
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
436
              String target = nTargetPublicId.getFirstChild().getNodeValue();
437
              if(target.equals(targettype))
438
              { //we found the right target type
439
                NodeList nlTarget = nChild.getChildNodes();
440
                for(int k=0; k<nlTarget.getLength(); k++)
441
                {
442
                  Node nChildText = nlTarget.item(k);
443
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
444
                  { //get the text from the target node
445
                    systemId = nChildText.getNodeValue();
446
                    breakflag = true;
447
                    break;
448
                  }
449
                }
450
              }
451
            }
452

    
453
            if(breakflag)
454
            {
455
              break;
456
            }
457
          }
458
        }
459

    
460
        if(breakflag)
461
        {
462
          break;
463
        }
464
      }
465
    }
466
    catch(Exception e)
467
    {
468
      System.out.println("Error parsing style-set file: " + e.getMessage());
469
      e.printStackTrace();
470
    }
471
    
472
    //Check if the systemId is relative path, add a postfix - the contextULR to systemID. 
473
    if (systemId != null && systemId.indexOf("http://" ) == -1)
474
    {
475
    	systemId = contextURL+systemId;
476
    }
477
    // Return the system ID for this particular source document type
478
    logMetacat.info("style system id is: "+systemId);
479
    return systemId;
480
  }
481

    
482
 /* Method to modified the system id of xml input -- make sure it
483
    points to system id in xml_catalog table
484
  */
485
  private void modifiedXmlStreamSource(StreamSource xml, String publicId)
486
                                       throws Exception
487
  {
488
    // make sure the xml is not null
489
    if (xml == null || publicId == null)
490
    {
491
      return;
492
    }
493
    logMetacat.info("public id of input stream is " +publicId);
494
    // Get system id from xml_catalog table
495
    String systemId = DBEntityResolver.getDTDSystemID(publicId);
496
    logMetacat.info("system id of input stream from xml_catalog"
497
                               +"table is " +systemId);
498
    //set system id to input stream
499
    xml.setSystemId(systemId);
500
  }
501

    
502
  /*
503
   * removes the DOCTYPE element and its contents from a Sting
504
   * used to avoid problems with incorrect SystemIDs
505
   */
506
  private String removeDOCTYPE(String in) {
507
    String ret = "";
508
    int startpos = in.indexOf("<!DOCTYPE");
509
    if (startpos>-1) {
510
      int stoppos = in.indexOf(">", startpos + 8);
511
      ret = in.substring(0,startpos) + in.substring(stoppos+1,in.length());
512
    } else {
513
      return in;
514
    }
515
    return ret;
516
  }
517

    
518
  /**
519
   * the main routine used to test the transform utility.
520
   *
521
   * Usage: java DBTransform
522
   */
523
  static public void main(String[] args) {
524

    
525
     if (args.length > 0)
526
     {
527
        System.err.println("Wrong number of arguments!!!");
528
        System.err.println("USAGE: java DBTransform");
529
        return;
530
     } else {
531
        try {
532

    
533
          // Create a test document
534
          StringBuffer testdoc = new StringBuffer();
535
          testdoc.append("<?xml version=\"1.0\"?>");
536
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
537
          testdoc.append("<dataset_id>DS001</dataset_id>");
538
          testdoc.append("<title>My test doc</title></eml-dataset>");
539

    
540
          // Transform the document to the new doctype
541
          DBTransform dbt = new DBTransform();
542
          dbt.transformXMLDocument(testdoc.toString(),
543
                                   "-//NCEAS//eml-dataset//EN",
544
                                   "-//W3C//HTML//EN",
545
                                   "knb",
546
                                   new PrintWriter(System.out), null);
547

    
548
        } catch (Exception e) {
549
          System.err.println("EXCEPTION HANDLING REQUIRED");
550
          System.err.println(e.getMessage());
551
          e.printStackTrace(System.err);
552
        }
553
     }
554
  }
555

    
556
  private void dbg(int position) {
557
    System.err.println("Debug flag: " + position);
558
  }
559

    
560
}
(24-24/67)