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: jones $'
10
 * '$Date: 2006-11-10 10:25:38 -0800 (Fri, 10 Nov 2006) $'
11
 * '$Revision: 3077 $'
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.Stack;
37

    
38
import javax.xml.transform.TransformerFactory;
39
import javax.xml.transform.Transformer;
40
import javax.xml.transform.stream.StreamSource;
41
import javax.xml.transform.stream.StreamResult;
42
import javax.xml.transform.TransformerException;
43
import javax.xml.transform.TransformerConfigurationException;
44

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

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

    
73
import java.util.Properties;
74

    
75

    
76
/**
77
 * A Class that transforms XML documents utitlizing XSL style sheets
78
 */
79
public class DBTransform {
80

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

    
105
  /**
106
   * @see transformXMLDocument(String doc, String sourceType,
107
   *            String targetType, String qformat, PrintWriter pw,
108
   *            String sessionid)
109
   */
110
  public void transformXMLDocument(String doc, String sourceType,
111
                String targetType, String qformat, PrintWriter pw,
112
                Hashtable param)
113
  {
114
    transformXMLDocument(doc, sourceType, targetType, qformat, pw, param, null);
115
  }
116

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

    
128

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

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

    
156
      }
157
      catch (Exception e)
158
      {
159
        pw.println(xslSystemId + "Error transforming document in " +
160
                   "DBTransform.transformXMLDocument: " +
161
                   e.getMessage());
162

    
163
      }
164
    }
165
    else
166
    {
167
      // No stylesheet registered form this document type, so just return the
168
      // XML stream we were passed
169
      pw.print(doc);
170
    }
171
  }
172

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

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

    
205
      }
206
    }
207
    else
208
    {
209
      // No stylesheet registered form this document type, so just return the
210
      // XML stream we were passed
211
      pw.write(doc);
212
    }
213
  }
214

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

    
238
      }
239
      catch (Exception e)
240
      {
241
        pw.println(xslSystemId + "Error transforming document in " +
242
                   "DBTransform.transformXMLDocument: " +
243
                   e.getMessage());
244

    
245
      }
246
    }
247
    else
248
    {
249
      // No stylesheet registered form this document type, so just return the
250
      // XML stream we were passed
251
      pw.print(docContent);
252
    }
253
   }
254

    
255
  /*
256
   * Method to do transfer
257
   */
258
  private void doTransform(StringReader docContent, StreamResult resultOutput,
259
                           String xslSystemId, Hashtable param,
260
                           String qformat, String sessionid)
261
                          throws Exception
262
  {
263
    if (xslSystemId != null)
264
    {
265
        TransformerFactory tFactory = TransformerFactory.newInstance();
266
        Transformer transformer = tFactory.newTransformer(
267
                                  new StreamSource(xslSystemId));
268
        transformer.setParameter("qformat", qformat);
269
        logMetacat.warn("qformat: "+qformat);
270
        
271
        if (MetaCatUtil.skinconfigs.containsKey(qformat)){
272
        	Properties skinOptions = (Properties)MetaCatUtil.skinconfigs.get(qformat);
273
		
274
			if(skinOptions.getProperty("lsidauthority") != null){
275
        		transformer.setParameter("lsidauthority", skinOptions.getProperty("lsidauthority"));
276
			}
277
			
278
			if(skinOptions.getProperty("registryurl") != null){
279
           		transformer.setParameter("registryurl", skinOptions.getProperty("registryurl"));
280
			}
281
			
282
			if(skinOptions.getProperty("registryname") != null){
283
           		transformer.setParameter("registryname", skinOptions.getProperty("registryname"));
284
      		}	
285
		}
286
        
287
        if(sessionid != null)
288
        {
289
          transformer.setParameter("sessid", sessionid);
290
        }
291
        // Set up parameter for transformation
292
        if ( param != null)
293
        {
294
          Enumeration en = param.keys();
295
          while (en.hasMoreElements())
296
          {
297
            String key =(String)en.nextElement();
298
            String value = ((String[])(param.get(key)))[0];
299
            logMetacat.info(key+" : "+value);
300
            transformer.setParameter(key, value);
301
          }
302
        }
303
        StreamSource xml = new StreamSource(docContent);
304
        transformer.transform(xml,resultOutput);
305
    }
306
  }//doTransform
307

    
308

    
309
  /**
310
   * gets the content of a tag in a given xml file with the given path
311
   * @param f the file to parse
312
   * @param path the path to get the content from
313
   */
314
  public static NodeList getPathContent(File f, String path)
315
  {
316
    if(f == null)
317
    {
318
      return null;
319
    }
320

    
321
    DOMParser parser = new DOMParser();
322
    InputSource in;
323
    FileInputStream fs;
324

    
325
    try
326
    {
327
      fs = new FileInputStream(f);
328
      in = new InputSource(fs);
329
    }
330
    catch(FileNotFoundException fnf)
331
    {
332
      fnf.printStackTrace();
333
      return null;
334
    }
335

    
336
    try
337
    {
338
      parser.parse(in);
339
      fs.close();
340
    }
341
    catch(Exception e1)
342
    {
343
      System.err.println("File: " + f.getPath() + " : parse threw: " +
344
                         e1.toString());
345
      return null;
346
    }
347

    
348
    Document doc = parser.getDocument();
349

    
350
    try
351
    {
352
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
353
      return docNodeList;
354
    }
355
    catch(Exception se)
356
    {
357
      System.err.println("file: " + f.getPath() + " : parse threw: " +
358
                         se.toString());
359
      return null;
360
    }
361
  }
362

    
363
  /**
364
   * Lookup a stylesheet reference from the db catalog
365
   *
366
   * @param qformat    the named style-set format
367
   * @param sourcetype the document type of the source
368
   * @param targettype the document type of the target
369
   */
370
  public String getStyleSystemId(String qformat, String sourcetype,
371
                String targettype) {
372
    String systemId = null;
373

    
374
    if ((qformat == null) || (qformat.equals("html"))) {
375
      qformat = defaultStyle;
376
    }
377

    
378
    // Load the style-set map for this qformat into a DOM
379
    try {
380
      boolean breakflag = false;
381
      String filename = configDir + "/" + qformat + "/" + qformat + ".xml";
382
      logMetacat.warn("Trying style-set file: " + filename);
383
      File f = new File(filename);
384
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
385
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
386
      Node nDefault = nlDefault.item(0);
387
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
388

    
389
      for(int i=0; i<nlDoctype.getLength(); i++)
390
      { //look for the right sourcetype
391
        Node nDoctype = nlDoctype.item(i);
392
        NamedNodeMap atts = nDoctype.getAttributes();
393
        Node nAtt = atts.getNamedItem("publicid");
394
        String doctype = nAtt.getFirstChild().getNodeValue();
395
        if(doctype.equals(sourcetype))
396
        { //found the right sourcetype now we need to get the target type
397
          NodeList nlChildren = nDoctype.getChildNodes();
398
          for(int j=0; j<nlChildren.getLength(); j++)
399
          {
400
            Node nChild = nlChildren.item(j);
401
            String childName = nChild.getNodeName();
402
            if(childName.equals("target"))
403
            {
404
              NamedNodeMap childAtts = nChild.getAttributes();
405
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
406
              String target = nTargetPublicId.getFirstChild().getNodeValue();
407
              if(target.equals(targettype))
408
              { //we found the right target type
409
                NodeList nlTarget = nChild.getChildNodes();
410
                for(int k=0; k<nlTarget.getLength(); k++)
411
                {
412
                  Node nChildText = nlTarget.item(k);
413
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
414
                  { //get the text from the target node
415
                    systemId = nChildText.getNodeValue();
416
                    breakflag = true;
417
                    break;
418
                  }
419
                }
420
              }
421
            }
422

    
423
            if(breakflag)
424
            {
425
              break;
426
            }
427
          }
428
        }
429

    
430
        if(breakflag)
431
        {
432
          break;
433
        }
434
      }
435
    }
436
    catch(Exception e)
437
    {
438
      System.out.println("Error parsing style-set file: " + e.getMessage());
439
      e.printStackTrace();
440
    }
441

    
442
    // Return the system ID for this particular source document type
443
    logMetacat.info("style system id is: "+systemId);
444
    return systemId;
445
  }
446

    
447
 /* Method to modified the system id of xml input -- make sure it
448
    points to system id in xml_catalog table
449
  */
450
  private void modifiedXmlStreamSource(StreamSource xml, String publicId)
451
                                       throws Exception
452
  {
453
    // make sure the xml is not null
454
    if (xml == null || publicId == null)
455
    {
456
      return;
457
    }
458
    logMetacat.info("public id of input stream is " +publicId);
459
    // Get system id from xml_catalog table
460
    String systemId = DBEntityResolver.getDTDSystemID(publicId);
461
    logMetacat.info("system id of input stream from xml_catalog"
462
                               +"table is " +systemId);
463
    //set system id to input stream
464
    xml.setSystemId(systemId);
465
  }
466

    
467
  /*
468
   * removes the DOCTYPE element and its contents from a Sting
469
   * used to avoid problems with incorrect SystemIDs
470
   */
471
  private String removeDOCTYPE(String in) {
472
    String ret = "";
473
    int startpos = in.indexOf("<!DOCTYPE");
474
    if (startpos>-1) {
475
      int stoppos = in.indexOf(">", startpos + 8);
476
      ret = in.substring(0,startpos) + in.substring(stoppos+1,in.length());
477
    } else {
478
      return in;
479
    }
480
    return ret;
481
  }
482

    
483
  /**
484
   * the main routine used to test the transform utility.
485
   *
486
   * Usage: java DBTransform
487
   */
488
  static public void main(String[] args) {
489

    
490
     if (args.length > 0)
491
     {
492
        System.err.println("Wrong number of arguments!!!");
493
        System.err.println("USAGE: java DBTransform");
494
        return;
495
     } else {
496
        try {
497

    
498
          // Open a connection to the database
499
          /*MetaCatUtil   util = new MetaCatUtil();
500
          Connection dbconn = util.openDBConnection();*/
501

    
502
          // Create a test document
503
          StringBuffer testdoc = new StringBuffer();
504
          testdoc.append("<?xml version=\"1.0\"?>");
505
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
506
          testdoc.append("<dataset_id>DS001</dataset_id>");
507
          testdoc.append("<title>My test doc</title></eml-dataset>");
508

    
509
          // Transform the document to the new doctype
510
          DBTransform dbt = new DBTransform();
511
          dbt.transformXMLDocument(testdoc.toString(),
512
                                   "-//NCEAS//eml-dataset//EN",
513
                                   "-//W3C//HTML//EN",
514
                                   "knb",
515
                                   new PrintWriter(System.out), null);
516

    
517
        } catch (Exception e) {
518
          System.err.println("EXCEPTION HANDLING REQUIRED");
519
          System.err.println(e.getMessage());
520
          e.printStackTrace(System.err);
521
        }
522
     }
523
  }
524

    
525
  private void dbg(int position) {
526
    System.err.println("Debug flag: " + position);
527
  }
528

    
529
}
(25-25/66)