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: jones $'
11
 *     '$Date: 2002-02-02 01:14:56 -0800 (Sat, 02 Feb 2002) $'
12
 * '$Revision: 920 $'
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.Stack;
36

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

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

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

    
71
/** 
72
 * A Class that transforms XML documents utitlizing XSL style sheets
73
 */
74
public class DBTransform {
75

    
76
  private Connection	conn = null;
77
  private MetaCatUtil   util = null;
78
  private String 	configDir = null;
79
  private String	defaultStyle = null;
80

    
81
  /**
82
   * construct a DBTransform instance.
83
   *
84
   * Generally, one calls transformXMLDocument() after constructing the instance
85
   *
86
   * @param conn the database connection from which to lookup the public ids
87
   */
88
  public DBTransform( Connection conn ) 
89
                  throws IOException, 
90
                         SQLException, 
91
                         ClassNotFoundException
92
  {
93
    this.conn = conn;
94
    util = new MetaCatUtil();
95
    configDir = util.getOption("config-dir");
96
    defaultStyle = util.getOption("default-style");
97
  }
98
  
99
  /**
100
   * Transform an XML document using the stylesheet reference from the db
101
   *
102
   * @param doc the document to be transformed
103
   * @param sourcetype the document type of the source
104
   * @param targettype the target document type
105
   * @param qformat the name of the style set to use
106
   * @param pw the PrintWriter to which output is printed
107
   */
108
  public void transformXMLDocument(String doc, String sourcetype, 
109
                String targettype, String qformat, PrintWriter pw) {
110
    
111
    // Look up the stylesheet for this type combination
112
    String xsl_system_id = getStyleSystemId(qformat, sourcetype, targettype);
113

    
114
    if (xsl_system_id != null) {
115
      // Create a stylesheet from the system id that was found
116
      try {
117
        TransformerFactory tFactory = TransformerFactory.newInstance();
118
        Transformer transformer = tFactory.newTransformer(
119
                                  new StreamSource(xsl_system_id));
120
	transformer.setParameter("qformat", qformat);
121
        transformer.transform(new StreamSource(new StringReader(doc)), 
122
                              new StreamResult(pw));
123
	
124
      } catch (Exception e) {
125
        pw.println(xsl_system_id + "Error transforming document in " +
126
                   "DBTransform.transformXMLDocument: " +
127
                   e.getMessage());
128
        //e.printStackTrace();
129
      }
130
    } else {
131
      // No stylesheet registered form this document type, so just return the 
132
      // XML stream we were passed
133
      pw.print(doc);
134
    }
135
  }
136
  
137
  
138
  /**
139
   * gets the content of a tag in a given xml file with the given path
140
   * @param f the file to parse
141
   * @param path the path to get the content from
142
   */
143
  public static NodeList getPathContent(File f, String path) 
144
  {
145
    if(f == null)
146
    {
147
      return null;
148
    }
149
   
150
    DOMParser parser = new DOMParser();
151
    InputSource in;
152
    FileInputStream fs;
153
    
154
    try
155
    { 
156
      fs = new FileInputStream(f);
157
      in = new InputSource(fs);
158
    }
159
    catch(FileNotFoundException fnf)
160
    {
161
      fnf.printStackTrace();
162
      return null;
163
    }
164
    
165
    try
166
    {
167
      parser.parse(in);
168
      fs.close();
169
    }
170
    catch(Exception e1)
171
    {
172
      System.err.println("File: " + f.getPath() + " : parse threw: " + 
173
                         e1.toString());
174
      return null;
175
    }
176
    
177
    Document doc = parser.getDocument();
178
    
179
    try
180
    {
181
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
182
      return docNodeList;
183
    }
184
    catch(Exception se)
185
    {
186
      System.err.println("file: " + f.getPath() + " : parse threw: " + 
187
                         se.toString());
188
      return null;
189
    }
190
  }
191

    
192
  /**
193
   * Lookup a stylesheet reference from the db catalog
194
   *
195
   * @param qformat    the named style-set format
196
   * @param sourcetype the document type of the source
197
   * @param targettype the document type of the target
198
   */
199
  public String getStyleSystemId(String qformat, String sourcetype, 
200
                String targettype) {
201
    String systemId = null;
202

    
203
    if ((qformat == null) || (qformat.equals("html"))) {
204
      qformat = defaultStyle;
205
    }
206

    
207
    // Load the style-set map for this qformat into a DOM
208
    try {
209
      boolean breakflag = false;
210
      String filename = configDir + "/" + qformat + ".xml";       
211
      util.debugMessage("Trying style-set file: " + filename);
212
      File f = new File(filename);
213
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
214
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
215
      Node nDefault = nlDefault.item(0);
216
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
217
      
218
      for(int i=0; i<nlDoctype.getLength(); i++)
219
      { //look for the right sourcetype
220
        Node nDoctype = nlDoctype.item(i);
221
        NamedNodeMap atts = nDoctype.getAttributes();
222
        Node nAtt = atts.getNamedItem("publicid");
223
        String doctype = nAtt.getFirstChild().getNodeValue();
224
        if(doctype.equals(sourcetype))
225
        { //found the right sourcetype now we need to get the target type
226
          NodeList nlChildren = nDoctype.getChildNodes();
227
          for(int j=0; j<nlChildren.getLength(); j++)
228
          {
229
            Node nChild = nlChildren.item(j);
230
            String childName = nChild.getNodeName();
231
            if(childName.equals("target"))
232
            {
233
              NamedNodeMap childAtts = nChild.getAttributes();
234
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
235
              String target = nTargetPublicId.getFirstChild().getNodeValue();
236
              if(target.equals(targettype))
237
              { //we found the right target type
238
                NodeList nlTarget = nChild.getChildNodes();
239
                for(int k=0; k<nlTarget.getLength(); k++)
240
                {
241
                  Node nChildText = nlTarget.item(k);
242
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
243
                  { //get the text from the target node
244
                    systemId = nChildText.getNodeValue();
245
                    System.out.println("systemId: " + systemId);
246
                    breakflag = true;
247
                    break;
248
                  }
249
                }
250
              }
251
            }
252
            
253
            if(breakflag)
254
            {
255
              break;
256
            }
257
          }
258
        }
259
        
260
        if(breakflag)
261
        {
262
          break;
263
        }
264
      }
265
    }
266
    catch(Exception e)
267
    {
268
      System.out.println("Error parsing style-set file: " + e.getMessage());
269
      e.printStackTrace();
270
    }
271

    
272
    // Return the system ID for this particular source document type
273
    return systemId;
274
  }
275

    
276
  /**
277
   * Lookup a stylesheet reference from the db catalog
278
   *
279
   * @param objecttype the type of the object we want to retrieve
280
   * @param sourcetype the document type of the source
281
   * @param targettype the document type of the target
282
   */
283
  public String getSystemId(String objecttype, String sourcetype, 
284
                String targettype) {
285

    
286
    // Look up the System ID of a particular object
287
    PreparedStatement pstmt;
288
    String the_system_id = null;
289
    try {
290
      pstmt =
291
        conn.prepareStatement("SELECT system_id " +
292
                "FROM xml_catalog " +
293
                "WHERE entry_type = ? " +
294
                "AND source_doctype = ? " +
295
                "AND target_doctype = ? ");
296
      // Bind the values to the query
297
      pstmt.setString(1, objecttype);
298
      pstmt.setString(2, sourcetype);
299
      pstmt.setString(3, targettype);
300
      pstmt.execute();
301
      try {
302
        ResultSet rs = pstmt.getResultSet();
303
        try {
304
          boolean tableHasRows = rs.next();
305
          if (tableHasRows) {
306
            try {
307
              the_system_id = rs.getString(1);
308
            } catch (SQLException e) {
309
              System.out.println("Error with getString in " + 
310
                                 "DBTransform.getSystemId: " + e.getMessage());                
311
            }
312
          } else {
313
            the_system_id = null; 
314
          }
315
        } catch (SQLException e) {
316
          System.err.println("Error with next in DBTransform.getSystemId: " + 
317
                              e.getMessage());
318
          return ("Error with next: " + e.getMessage());
319
        }
320
      } catch (SQLException e) {
321
        System.err.println("Error with getrset in DBTransform.getSystemId: " + 
322
                            e.getMessage());
323
        return ("Error with getrset: " + e.getMessage());
324
      }
325
      pstmt.close();
326
    } catch (SQLException e) {
327
      System.err.println("Error getting id in DBTransform.getSystemId: " + 
328
                          e.getMessage());
329
      return ("Error getting id in DBTransform.getSystemId:: " + 
330
               e.getMessage());
331
    }
332
    return the_system_id;
333
  }
334

    
335
  /**
336
   * the main routine used to test the transform utility.
337
   *
338
   * Usage: java DBTransform
339
   */
340
  static public void main(String[] args) {
341
     
342
     if (args.length > 0)
343
     {
344
        System.err.println("Wrong number of arguments!!!");
345
        System.err.println("USAGE: java DBTransform");
346
        return;
347
     } else {
348
        try {
349
                    
350
          // Open a connection to the database
351
          MetaCatUtil   util = new MetaCatUtil();
352
          Connection dbconn = util.openDBConnection();
353

    
354
          // Create a test document
355
          StringBuffer testdoc = new StringBuffer();
356
          testdoc.append("<?xml version=\"1.0\"?>");
357
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
358
          testdoc.append("<dataset_id>DS001</dataset_id>");
359
          testdoc.append("<title>My test doc</title></eml-dataset>");
360

    
361
          // Transform the document to the new doctype
362
          DBTransform dbt = new DBTransform(dbconn);
363
          dbt.transformXMLDocument(testdoc.toString(), 
364
                                   "-//NCEAS//eml-dataset//EN", 
365
                                   "-//W3C//HTML//EN", 
366
                                   "knb",
367
                                   new PrintWriter(System.out));
368

    
369
        } catch (Exception e) {
370
          System.err.println("EXCEPTION HANDLING REQUIRED");
371
          System.err.println(e.getMessage());
372
          e.printStackTrace(System.err);
373
        }
374
     }
375
  }
376
  
377
  private void dbg(int position) {
378
    System.err.println("Debug flag: " + position);
379
  }
380

    
381
}
(18-18/40)