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: tao $'
10
 * '$Date: 2008-02-20 19:38:44 -0800 (Wed, 20 Feb 2008) $'
11
 * '$Revision: 3725 $'
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.NodeList;
56
import org.w3c.dom.DocumentType;
57
import org.xml.sax.SAXException;
58
import org.xml.sax.InputSource;
59
import org.apache.xerces.dom.DocumentTypeImpl;
60
import org.apache.xpath.XPathAPI;
61
import org.w3c.dom.NamedNodeMap;
62

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

    
76
import java.util.Properties;
77

    
78

    
79
/**
80
 * A Class that transforms XML documents utitlizing XSL style sheets
81
 */
82
public class DBTransform {
83

    
84
  //private Connection	conn = null;
85
  private MetaCatUtil   util = null;
86
  private String 	configDir = null;
87
  private String	defaultStyle = null;
88
  private Logger logMetacat = Logger.getLogger(DBTransform.class);
89
  private String contextURL = null;
90
  
91
  /**
92
   * construct a DBTransform instance.
93
   *
94
   * Generally, one calls transformXMLDocument() after constructing the instance
95
   *
96
   * @param conn the database connection from which to lookup the public ids
97
   */
98
  public DBTransform()
99
                  throws IOException,
100
                         SQLException,
101
                         ClassNotFoundException
102
  {
103
    //this.conn = conn;
104
    util = new MetaCatUtil();
105
    configDir = util.getOption("config-dir");
106
    defaultStyle = util.getOption("default-style");
107
    contextURL = util.getOption("httpserver")+"/"+util.getOption("context")+"/";
108
  }
109

    
110
  /**
111
   * @see transformXMLDocument(String doc, String sourceType,
112
   *            String targetType, String qformat, PrintWriter pw,
113
   *            String sessionid)
114
   */
115
  public void transformXMLDocument(String doc, String sourceType,
116
                String targetType, String qformat, PrintWriter pw,
117
                Hashtable param)
118
  {
119
    transformXMLDocument(doc, sourceType, targetType, qformat, pw, param, null);
120
  }
121

    
122
   /**
123
   * @see transformXMLDocument(String doc, String sourceType,
124
   *            String targetType, String qFormat, StringWriter pw
125
   *            String sessionid)
126
   */
127
  public void transformXMLDocument(String doc, String sourceType,
128
                String targetType, String qFormat, StringWriter pw)
129
  {
130
    transformXMLDocument(doc, sourceType, targetType, qFormat, pw, null);
131
  }
132

    
133

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

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

    
161
      }
162
      catch (Exception e)
163
      {
164
        pw.println(xslSystemId + "Error transforming document in " +
165
                   "DBTransform.transformXMLDocument: " +
166
                   e.getMessage());
167

    
168
      }
169
    }
170
    else
171
    {
172
      // No stylesheet registered form this document type, so just return the
173
      // XML stream we were passed
174
      pw.print(doc);
175
    }
176
  }
177

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

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

    
210
      }
211
    }
212
    else
213
    {
214
      // No stylesheet registered form this document type, so just return the
215
      // XML stream we were passed
216
      pw.write(doc);
217
    }
218
  }
219

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

    
243
      }
244
      catch (Exception e)
245
      {
246
        pw.println(xslSystemId + "Error transforming document in " +
247
                   "DBTransform.transformXMLDocument: " +
248
                   e.getMessage());
249

    
250
      }
251
    }
252
    else
253
    {
254
      // No stylesheet registered form this document type, so just return the
255
      // XML stream we were passed
256
      pw.print(docContent);
257
    }
258
   }
259

    
260
  /**
261
   * Reads skin's config file if it exists, and populates Transformer paramaters
262
   * with its contents.
263
   * It then adds the parameters passed to it via Hashtable param to the Transformer.
264
   * It then calls the Transformer.transform method.
265
   */
266
  private void doTransform(StringReader docContent, 
267
          StreamResult resultOutput,
268
          String xslSystemId, 
269
          Hashtable param,
270
          String qformat, 
271
          String sessionid) 
272
          throws Exception {
273
      
274
      Properties skinOptions;
275
      TransformerFactory tFactory;
276
      Transformer transformer;
277
      String key, value;
278
      StreamSource xml;
279
      Enumeration en;
280
      Iterator iterIt;
281
      Map.Entry entry;
282
      
283
      if (xslSystemId != null) {
284
        tFactory = TransformerFactory.newInstance();
285
        transformer = tFactory.newTransformer(new StreamSource(xslSystemId));
286
        
287
        transformer.setParameter("qformat", qformat);
288
        logMetacat.warn("qformat: "+qformat);
289
        
290
        if (MetaCatUtil.hasSkinConfig(qformat)) {
291
            skinOptions = MetaCatUtil.getSkinConfig(qformat);
292
		
293
            iterIt = skinOptions.entrySet().iterator();
294
            while (iterIt.hasNext()) {
295
                entry = (Entry) iterIt.next();
296
                key = (String) entry.getKey();
297
                value = (String) entry.getValue();
298
                transformer.setParameter(key, value);
299
            }
300
        }
301
        
302
        if (sessionid != null && !sessionid.equals("null")) {
303
          transformer.setParameter("sessid", sessionid);
304
        }
305
        
306
        // Set up parameter for transformation
307
        if ( param != null) {
308
          en = param.keys();
309
          while (en.hasMoreElements()) {
310
            key = (String) en.nextElement();
311
            value = ((String[]) (param.get(key)))[0];
312
            logMetacat.info(key+" : "+value);
313
            transformer.setParameter(key, value);
314
          }
315
        }
316
        xml = new StreamSource(docContent);
317
        transformer.transform(xml,resultOutput);
318
    }
319
  }//doTransform
320

    
321

    
322
  /**
323
   * gets the content of a tag in a given xml file with the given path
324
   * @param f the file to parse
325
   * @param path the path to get the content from
326
   */
327
  public static NodeList getPathContent(File f, String path)
328
  {
329
    if(f == null)
330
    {
331
      return null;
332
    }
333

    
334
    DOMParser parser = new DOMParser();
335
    InputSource in;
336
    FileInputStream fs;
337

    
338
    try
339
    {
340
      fs = new FileInputStream(f);
341
      in = new InputSource(fs);
342
    }
343
    catch(FileNotFoundException fnf)
344
    {
345
      fnf.printStackTrace();
346
      return null;
347
    }
348

    
349
    try
350
    {
351
      parser.parse(in);
352
      fs.close();
353
    }
354
    catch(Exception e1)
355
    {
356
      System.err.println("File: " + f.getPath() + " : parse threw: " +
357
                         e1.toString());
358
      return null;
359
    }
360

    
361
    Document doc = parser.getDocument();
362

    
363
    try
364
    {
365
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
366
      return docNodeList;
367
    }
368
    catch(Exception se)
369
    {
370
      System.err.println("file: " + f.getPath() + " : parse threw: " +
371
                         se.toString());
372
      return null;
373
    }
374
  }
375

    
376
  /**
377
   * Lookup a stylesheet reference from the db catalog
378
   *
379
   * @param qformat    the named style-set format
380
   * @param sourcetype the document type of the source
381
   * @param targettype the document type of the target
382
   */
383
  public String getStyleSystemId(String qformat, String sourcetype,
384
                String targettype) {
385
    String systemId = null;
386

    
387
    if ((qformat == null) || (qformat.equals("html"))) {
388
      qformat = defaultStyle;
389
    }
390

    
391
    // Load the style-set map for this qformat into a DOM
392
    try {
393
      boolean breakflag = false;
394
      String filename = configDir + "/" + qformat + "/" + qformat + ".xml";
395
      logMetacat.warn("Trying style-set file: " + filename);
396
      File f = new File(filename);
397
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
398
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
399
      Node nDefault = nlDefault.item(0);
400
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
401

    
402
      for(int i=0; i<nlDoctype.getLength(); i++)
403
      { //look for the right sourcetype
404
        Node nDoctype = nlDoctype.item(i);
405
        NamedNodeMap atts = nDoctype.getAttributes();
406
        Node nAtt = atts.getNamedItem("publicid");
407
        String doctype = nAtt.getFirstChild().getNodeValue();
408
        if(doctype.equals(sourcetype))
409
        { //found the right sourcetype now we need to get the target type
410
          NodeList nlChildren = nDoctype.getChildNodes();
411
          for(int j=0; j<nlChildren.getLength(); j++)
412
          {
413
            Node nChild = nlChildren.item(j);
414
            String childName = nChild.getNodeName();
415
            if(childName.equals("target"))
416
            {
417
              NamedNodeMap childAtts = nChild.getAttributes();
418
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
419
              String target = nTargetPublicId.getFirstChild().getNodeValue();
420
              if(target.equals(targettype))
421
              { //we found the right target type
422
                NodeList nlTarget = nChild.getChildNodes();
423
                for(int k=0; k<nlTarget.getLength(); k++)
424
                {
425
                  Node nChildText = nlTarget.item(k);
426
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
427
                  { //get the text from the target node
428
                    systemId = nChildText.getNodeValue();
429
                    breakflag = true;
430
                    break;
431
                  }
432
                }
433
              }
434
            }
435

    
436
            if(breakflag)
437
            {
438
              break;
439
            }
440
          }
441
        }
442

    
443
        if(breakflag)
444
        {
445
          break;
446
        }
447
      }
448
    }
449
    catch(Exception e)
450
    {
451
      System.out.println("Error parsing style-set file: " + e.getMessage());
452
      e.printStackTrace();
453
    }
454
    
455
    //Check if the systemId is relative path, add a postfix - the contextULR to systemID. 
456
    if (systemId != null && systemId.indexOf("http://" ) == -1)
457
    {
458
    	systemId = contextURL+systemId;
459
    }
460
    // Return the system ID for this particular source document type
461
    logMetacat.info("style system id is: "+systemId);
462
    return systemId;
463
  }
464

    
465
 /* Method to modified the system id of xml input -- make sure it
466
    points to system id in xml_catalog table
467
  */
468
  private void modifiedXmlStreamSource(StreamSource xml, String publicId)
469
                                       throws Exception
470
  {
471
    // make sure the xml is not null
472
    if (xml == null || publicId == null)
473
    {
474
      return;
475
    }
476
    logMetacat.info("public id of input stream is " +publicId);
477
    // Get system id from xml_catalog table
478
    String systemId = DBEntityResolver.getDTDSystemID(publicId);
479
    logMetacat.info("system id of input stream from xml_catalog"
480
                               +"table is " +systemId);
481
    //set system id to input stream
482
    xml.setSystemId(systemId);
483
  }
484

    
485
  /*
486
   * removes the DOCTYPE element and its contents from a Sting
487
   * used to avoid problems with incorrect SystemIDs
488
   */
489
  private String removeDOCTYPE(String in) {
490
    String ret = "";
491
    int startpos = in.indexOf("<!DOCTYPE");
492
    if (startpos>-1) {
493
      int stoppos = in.indexOf(">", startpos + 8);
494
      ret = in.substring(0,startpos) + in.substring(stoppos+1,in.length());
495
    } else {
496
      return in;
497
    }
498
    return ret;
499
  }
500

    
501
  /**
502
   * the main routine used to test the transform utility.
503
   *
504
   * Usage: java DBTransform
505
   */
506
  static public void main(String[] args) {
507

    
508
     if (args.length > 0)
509
     {
510
        System.err.println("Wrong number of arguments!!!");
511
        System.err.println("USAGE: java DBTransform");
512
        return;
513
     } else {
514
        try {
515

    
516
          // Open a connection to the database
517
          /*MetaCatUtil   util = new MetaCatUtil();
518
          Connection dbconn = util.openDBConnection();*/
519

    
520
          // Create a test document
521
          StringBuffer testdoc = new StringBuffer();
522
          testdoc.append("<?xml version=\"1.0\"?>");
523
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
524
          testdoc.append("<dataset_id>DS001</dataset_id>");
525
          testdoc.append("<title>My test doc</title></eml-dataset>");
526

    
527
          // Transform the document to the new doctype
528
          DBTransform dbt = new DBTransform();
529
          dbt.transformXMLDocument(testdoc.toString(),
530
                                   "-//NCEAS//eml-dataset//EN",
531
                                   "-//W3C//HTML//EN",
532
                                   "knb",
533
                                   new PrintWriter(System.out), null);
534

    
535
        } catch (Exception e) {
536
          System.err.println("EXCEPTION HANDLING REQUIRED");
537
          System.err.println(e.getMessage());
538
          e.printStackTrace(System.err);
539
        }
540
     }
541
  }
542

    
543
  private void dbg(int position) {
544
    System.err.println("Debug flag: " + position);
545
  }
546

    
547
}
(25-25/66)