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: leinfelder $'
10
 * '$Date: 2008-02-25 13:07:51 -0800 (Mon, 25 Feb 2008) $'
11
 * '$Revision: 3733 $'
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 the default params (can be overridden by the passed in params)
307
        String cgiPrefix = MetaCatUtil.getOption("cgi-prefix");
308
        transformer.setParameter("cgi-prefix", cgiPrefix);
309
        transformer.setParameter("contextURL", contextURL);
310
        
311
        // Set up parameter for transformation
312
        if ( param != null) {
313
          en = param.keys();
314
          while (en.hasMoreElements()) {
315
            key = (String) en.nextElement();
316
            value = ((String[]) (param.get(key)))[0];
317
            logMetacat.info(key+" : "+value);
318
            transformer.setParameter(key, value);
319
          }
320
        }
321
        xml = new StreamSource(docContent);
322
        transformer.transform(xml,resultOutput);
323
    }
324
  }//doTransform
325

    
326

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

    
339
    DOMParser parser = new DOMParser();
340
    InputSource in;
341
    FileInputStream fs;
342

    
343
    try
344
    {
345
      fs = new FileInputStream(f);
346
      in = new InputSource(fs);
347
    }
348
    catch(FileNotFoundException fnf)
349
    {
350
      fnf.printStackTrace();
351
      return null;
352
    }
353

    
354
    try
355
    {
356
      parser.parse(in);
357
      fs.close();
358
    }
359
    catch(Exception e1)
360
    {
361
      System.err.println("File: " + f.getPath() + " : parse threw: " +
362
                         e1.toString());
363
      return null;
364
    }
365

    
366
    Document doc = parser.getDocument();
367

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

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

    
392
    if ((qformat == null) || (qformat.equals("html"))) {
393
      qformat = defaultStyle;
394
    }
395

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

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

    
441
            if(breakflag)
442
            {
443
              break;
444
            }
445
          }
446
        }
447

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

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

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

    
506
  /**
507
   * the main routine used to test the transform utility.
508
   *
509
   * Usage: java DBTransform
510
   */
511
  static public void main(String[] args) {
512

    
513
     if (args.length > 0)
514
     {
515
        System.err.println("Wrong number of arguments!!!");
516
        System.err.println("USAGE: java DBTransform");
517
        return;
518
     } else {
519
        try {
520

    
521
          // Open a connection to the database
522
          /*MetaCatUtil   util = new MetaCatUtil();
523
          Connection dbconn = util.openDBConnection();*/
524

    
525
          // Create a test document
526
          StringBuffer testdoc = new StringBuffer();
527
          testdoc.append("<?xml version=\"1.0\"?>");
528
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
529
          testdoc.append("<dataset_id>DS001</dataset_id>");
530
          testdoc.append("<title>My test doc</title></eml-dataset>");
531

    
532
          // Transform the document to the new doctype
533
          DBTransform dbt = new DBTransform();
534
          dbt.transformXMLDocument(testdoc.toString(),
535
                                   "-//NCEAS//eml-dataset//EN",
536
                                   "-//W3C//HTML//EN",
537
                                   "knb",
538
                                   new PrintWriter(System.out), null);
539

    
540
        } catch (Exception e) {
541
          System.err.println("EXCEPTION HANDLING REQUIRED");
542
          System.err.println(e.getMessage());
543
          e.printStackTrace(System.err);
544
        }
545
     }
546
  }
547

    
548
  private void dbg(int position) {
549
    System.err.println("Debug flag: " + position);
550
  }
551

    
552
}
(25-25/66)