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
 *    Release: @release@
9
 *
10
 *   '$Author: tao $'
11
 *     '$Date: 2003-11-17 15:17:56 -0800 (Mon, 17 Nov 2003) $'
12
 * '$Revision: 1896 $'
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 2 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program; if not, write to the Free Software
26
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
 */
28

    
29
package edu.ucsb.nceas.metacat;
30

    
31
import java.io.*;
32
import java.net.URL;
33
import java.net.MalformedURLException;
34
import java.sql.*;
35
import java.util.Enumeration;
36
import java.util.Hashtable;
37
import java.util.Stack;
38

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

    
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
/**
74
 * A Class that transforms XML documents utitlizing XSL style sheets
75
 */
76
public class DBTransform {
77

    
78
  //private Connection	conn = null;
79
  private MetaCatUtil   util = null;
80
  private String 	configDir = null;
81
  private String	defaultStyle = null;
82

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

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

    
113
  /**
114
   * Transform an XML document using the stylesheet reference from the db
115
   *
116
   * @param doc the document to be transformed
117
   * @param sourcetype the document type of the source
118
   * @param targettype the target document type
119
   * @param qformat the name of the style set to use
120
   * @param pw the PrintWriter to which output is printed
121
   * @param params some parameters for eml2 transformation
122
   */
123
  public void transformXMLDocument(String doc, String sourceType,
124
                                   String targetType, String qformat,
125
                                   PrintWriter pw, Hashtable param,
126
                                   String sessionid)
127
 {
128

    
129
    // Look up the stylesheet for this type combination
130
    String xslSystemId = getStyleSystemId(qformat, sourceType, targetType);
131

    
132
    if (xslSystemId != null) {
133
      // Create a stylesheet from the system id that was found
134
      try {
135
        TransformerFactory tFactory = TransformerFactory.newInstance();
136
        Transformer transformer = tFactory.newTransformer(
137
                                  new StreamSource(xslSystemId));
138
        //transformer.setParameter("qformat", qformat);
139
        //MetaCatUtil.debugMessage("qformat: "+qformat, 30);
140

    
141
        if(sessionid != null)
142
        {
143
          transformer.setParameter("sessid", sessionid);
144
        }
145

    
146
        // Set up parameter for transformation
147
        if ( param != null)
148
        {
149
          Enumeration en = param.keys();
150
          while (en.hasMoreElements())
151
          {
152
            String key =(String)en.nextElement();
153
            String value = ((String[])(param.get(key)))[0];
154
            MetaCatUtil.debugMessage(key+" : "+value, 30);
155
            transformer.setParameter(key, value);
156
          }
157
        }
158
        
159
       
160
        StreamSource xml = new StreamSource(new StringReader(doc));
161
        //modify the system id for dtd
162
        modifiedXmlStreamSource(xml, sourceType);
163
        transformer.transform(xml, new StreamResult(pw));
164
      } catch (Exception e) {
165
        pw.println(xslSystemId + "Error transforming document in " +
166
                   "DBTransform.transformXMLDocument: " +
167
                   e.getMessage());
168

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

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

    
190
    // Look up the stylesheet for this type combination
191
    String xslSystemId = getStyleSystemId(qFormat, sourceType, targetType);
192

    
193
    if (xslSystemId != null) {
194
      // Create a stylesheet from the system id that was found
195
      try {
196
        TransformerFactory tFactory = TransformerFactory.newInstance();
197
        Transformer transformer = tFactory.newTransformer(
198
                                  new StreamSource(xslSystemId));
199
        if(sessionid != null)
200
        {
201
          transformer.setParameter("sessid", sessionid);
202
        }
203
        transformer.setParameter("qFormat", qFormat);
204
        StreamSource xml = new StreamSource(new StringReader(doc));
205
        //modify the system id for dtd
206
        modifiedXmlStreamSource(xml, sourceType);
207
        transformer.transform(xml, new StreamResult(pw));
208
      } catch (Exception e) {
209
        util.debugMessage(xslSystemId + "Error transforming document in " +
210
                   "DBTransform.transformXMLDocument: " +
211
                   e.getMessage(), 30);
212

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

    
221
  /**
222
   * @see transformXMLDocument(String doc, String sourceType,
223
   *            String targetType, String qFormat, StringWriter pw
224
   *            String sessionid)
225
   */
226
  public void transformXMLDocument(String doc, String sourceType,
227
                String targetType, String qFormat, StringWriter pw)
228
  {
229
    transformXMLDocument(doc, sourceType, targetType, qFormat, pw, null);
230
  }
231

    
232
  /**
233
   * gets the content of a tag in a given xml file with the given path
234
   * @param f the file to parse
235
   * @param path the path to get the content from
236
   */
237
  public static NodeList getPathContent(File f, String path)
238
  {
239
    if(f == null)
240
    {
241
      return null;
242
    }
243

    
244
    DOMParser parser = new DOMParser();
245
    InputSource in;
246
    FileInputStream fs;
247

    
248
    try
249
    {
250
      fs = new FileInputStream(f);
251
      in = new InputSource(fs);
252
    }
253
    catch(FileNotFoundException fnf)
254
    {
255
      fnf.printStackTrace();
256
      return null;
257
    }
258

    
259
    try
260
    {
261
      parser.parse(in);
262
      fs.close();
263
    }
264
    catch(Exception e1)
265
    {
266
      System.err.println("File: " + f.getPath() + " : parse threw: " +
267
                         e1.toString());
268
      return null;
269
    }
270

    
271
    Document doc = parser.getDocument();
272

    
273
    try
274
    {
275
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
276
      return docNodeList;
277
    }
278
    catch(Exception se)
279
    {
280
      System.err.println("file: " + f.getPath() + " : parse threw: " +
281
                         se.toString());
282
      return null;
283
    }
284
  }
285

    
286
  /**
287
   * Lookup a stylesheet reference from the db catalog
288
   *
289
   * @param qformat    the named style-set format
290
   * @param sourcetype the document type of the source
291
   * @param targettype the document type of the target
292
   */
293
  public String getStyleSystemId(String qformat, String sourcetype,
294
                String targettype) {
295
    String systemId = null;
296

    
297
    if ((qformat == null) || (qformat.equals("html"))) {
298
      qformat = defaultStyle;
299
    }
300

    
301
    // Load the style-set map for this qformat into a DOM
302
    try {
303
      boolean breakflag = false;
304
      String filename = configDir + "/" + qformat + ".xml";
305
      util.debugMessage("Trying style-set file: " + filename, 30);
306
      File f = new File(filename);
307
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
308
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
309
      Node nDefault = nlDefault.item(0);
310
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
311

    
312
      for(int i=0; i<nlDoctype.getLength(); i++)
313
      { //look for the right sourcetype
314
        Node nDoctype = nlDoctype.item(i);
315
        NamedNodeMap atts = nDoctype.getAttributes();
316
        Node nAtt = atts.getNamedItem("publicid");
317
        String doctype = nAtt.getFirstChild().getNodeValue();
318
        if(doctype.equals(sourcetype))
319
        { //found the right sourcetype now we need to get the target type
320
          NodeList nlChildren = nDoctype.getChildNodes();
321
          for(int j=0; j<nlChildren.getLength(); j++)
322
          {
323
            Node nChild = nlChildren.item(j);
324
            String childName = nChild.getNodeName();
325
            if(childName.equals("target"))
326
            {
327
              NamedNodeMap childAtts = nChild.getAttributes();
328
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
329
              String target = nTargetPublicId.getFirstChild().getNodeValue();
330
              if(target.equals(targettype))
331
              { //we found the right target type
332
                NodeList nlTarget = nChild.getChildNodes();
333
                for(int k=0; k<nlTarget.getLength(); k++)
334
                {
335
                  Node nChildText = nlTarget.item(k);
336
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
337
                  { //get the text from the target node
338
                    systemId = nChildText.getNodeValue();
339
                    breakflag = true;
340
                    break;
341
                  }
342
                }
343
              }
344
            }
345

    
346
            if(breakflag)
347
            {
348
              break;
349
            }
350
          }
351
        }
352

    
353
        if(breakflag)
354
        {
355
          break;
356
        }
357
      }
358
    }
359
    catch(Exception e)
360
    {
361
      System.out.println("Error parsing style-set file: " + e.getMessage());
362
      e.printStackTrace();
363
    }
364

    
365
    // Return the system ID for this particular source document type
366
    MetaCatUtil.debugMessage("style system id is: "+systemId, 30);
367
    return systemId;
368
  }
369

    
370
 /* Method to modified the system id of xml input -- make sure it
371
    points to system id in xml_catalog table
372
  */
373
  private void modifiedXmlStreamSource(StreamSource xml, String publicId)   
374
                                       throws Exception
375
  {
376
    // make sure the xml is not null
377
    if (xml == null || publicId == null)
378
    {
379
      return;
380
    }
381
    MetaCatUtil.debugMessage("public id of input stream is " +publicId, 25);
382
    // Get system id from xml_catalog table
383
    String systemId = DBEntityResolver.getDTDSystemID(publicId);
384
    MetaCatUtil.debugMessage("system id of input stream from xml_catalog"
385
                               +"table is " +systemId, 25);
386
    //set system id to input stream
387
    xml.setSystemId(systemId);
388
  }
389

    
390
  /**
391
   * the main routine used to test the transform utility.
392
   *
393
   * Usage: java DBTransform
394
   */
395
  static public void main(String[] args) {
396

    
397
     if (args.length > 0)
398
     {
399
        System.err.println("Wrong number of arguments!!!");
400
        System.err.println("USAGE: java DBTransform");
401
        return;
402
     } else {
403
        try {
404

    
405
          // Open a connection to the database
406
          /*MetaCatUtil   util = new MetaCatUtil();
407
          Connection dbconn = util.openDBConnection();*/
408

    
409
          // Create a test document
410
          StringBuffer testdoc = new StringBuffer();
411
          testdoc.append("<?xml version=\"1.0\"?>");
412
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
413
          testdoc.append("<dataset_id>DS001</dataset_id>");
414
          testdoc.append("<title>My test doc</title></eml-dataset>");
415

    
416
          // Transform the document to the new doctype
417
          DBTransform dbt = new DBTransform();
418
          dbt.transformXMLDocument(testdoc.toString(),
419
                                   "-//NCEAS//eml-dataset//EN",
420
                                   "-//W3C//HTML//EN",
421
                                   "knb",
422
                                   new PrintWriter(System.out), null);
423

    
424
        } catch (Exception e) {
425
          System.err.println("EXCEPTION HANDLING REQUIRED");
426
          System.err.println(e.getMessage());
427
          e.printStackTrace(System.err);
428
        }
429
     }
430
  }
431

    
432
  private void dbg(int position) {
433
    System.err.println("Debug flag: " + position);
434
  }
435

    
436
}
(26-26/58)