Project

General

Profile

1 87 jones
/**
2 203 jones
 *  '$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 87 jones
 *
9 1929 brooke
 * '$Author$'
10
 * '$Date$'
11 203 jones
 * '$Revision$'
12 669 jones
 *
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 87 jones
 */
27
28
package edu.ucsb.nceas.metacat;
29
30 5752 leinfelder
import java.io.File;
31
import java.io.FileInputStream;
32
import java.io.FileNotFoundException;
33
import java.io.IOException;
34
import java.io.OutputStreamWriter;
35
import java.io.StringReader;
36
import java.io.Writer;
37
import java.sql.SQLException;
38 1688 tao
import java.util.Enumeration;
39 1664 tao
import java.util.Hashtable;
40 3675 barteau
import java.util.Iterator;
41
import java.util.Map;
42 87 jones
43 906 berkley
import javax.xml.transform.TransformerFactory;
44
import javax.xml.transform.Transformer;
45
import javax.xml.transform.stream.StreamSource;
46
import javax.xml.transform.stream.StreamResult;
47
48 2663 sgarg
import org.apache.log4j.Logger;
49 906 berkley
import org.apache.xerces.parsers.DOMParser;
50
import org.w3c.dom.NamedNodeMap;
51
import org.w3c.dom.NodeList;
52
import org.w3c.dom.Document;
53
import org.w3c.dom.Node;
54
import org.xml.sax.InputSource;
55
import org.apache.xpath.XPathAPI;
56
57 5030 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
58
import edu.ucsb.nceas.metacat.properties.SkinPropertyService;
59 4080 daigle
import edu.ucsb.nceas.metacat.util.SystemUtil;
60
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
61 4327 leinfelder
import edu.ucsb.nceas.utilities.SortedProperties;
62 4080 daigle
63 1716 berkley
/**
64 87 jones
 * A Class that transforms XML documents utitlizing XSL style sheets
65
 */
66
public class DBTransform {
67
68 7859 leinfelder
69 832 jones
  private String 	configDir = null;
70
  private String	defaultStyle = null;
71 2663 sgarg
  private Logger logMetacat = Logger.getLogger(DBTransform.class);
72 3780 daigle
  private String httpServer = null;
73 3725 tao
  private String contextURL = null;
74 3780 daigle
  private String servletURL = null;
75 8664 tao
  private String userManagementURL = null;
76 2663 sgarg
77 87 jones
  /**
78
   * construct a DBTransform instance.
79
   *
80
   * Generally, one calls transformXMLDocument() after constructing the instance
81
   *
82
   * @param conn the database connection from which to lookup the public ids
83
   */
84 1716 berkley
  public DBTransform()
85
                  throws IOException,
86
                         SQLException,
87 4080 daigle
                         ClassNotFoundException,
88
                         PropertyNotFoundException
89 87 jones
  {
90 4080 daigle
    configDir = SystemUtil.getStyleSkinsDir();
91
    defaultStyle = PropertyService.getProperty("application.default-style");
92 9391 leinfelder
    httpServer = SystemUtil.getServerURL();
93
    contextURL = SystemUtil.getContextURL();
94 4080 daigle
    servletURL = SystemUtil.getServletURL();
95 8664 tao
    userManagementURL = PropertyService.getProperty("auth.userManagementUrl");
96 87 jones
  }
97 1716 berkley
98 87 jones
  /**
99
   * Transform an XML document using the stylesheet reference from the db
100
   *
101
   * @param doc the document to be transformed
102
   * @param sourcetype the document type of the source
103
   * @param targettype the target document type
104 832 jones
   * @param qformat the name of the style set to use
105
   * @param pw the PrintWriter to which output is printed
106 1664 tao
   * @param params some parameters for eml2 transformation
107 87 jones
   */
108 1716 berkley
  public void transformXMLDocument(String doc, String sourceType,
109
                                   String targetType, String qformat,
110 5752 leinfelder
                                   Writer w, Hashtable<String, String[]> param,
111 1716 berkley
                                   String sessionid)
112 1664 tao
 {
113 1716 berkley
114 5752 leinfelder
	  String xslSystemId = getStyleSystemId(qformat, sourceType, targetType);
115
	  try {
116
		  // Look up the stylesheet for this type combination
117
		  if (xslSystemId != null) {
118
			// Create a stylesheet from the system id that was found
119
			doc = removeDOCTYPE(doc);
120 7860 leinfelder
			StreamSource xml = new StreamSource(new StringReader(doc));
121 5752 leinfelder
			StreamResult result = new StreamResult(w);
122
			doTransform(xml, result, xslSystemId, param, qformat, sessionid);
123
		  }
124
		  else {
125
			  // No stylesheet registered form this document type, so just return the
126
			  // XML stream we were passed
127
			  w.write(doc);
128
		  }
129 2088 tao
      }
130
      catch (Exception e)
131
      {
132 5752 leinfelder
    	  try {
133 7258 leinfelder
    		  String msg = xslSystemId + ": Error transforming document in " +
134
	           "DBTransform.transformXMLDocument: " +
135
	           e.getMessage();
136
    		  w.write(msg);
137
    		  w.flush();
138
    		  logMetacat.error(msg, e);
139 5752 leinfelder
		} catch (IOException e1) {
140
			logMetacat.error(e1.getMessage(), e1);
141
		}
142 1716 berkley
143 87 jones
      }
144 5752 leinfelder
145 87 jones
  }
146 941 tao
147 1716 berkley
148 3675 barteau
  /**
149
   * Reads skin's config file if it exists, and populates Transformer paramaters
150
   * with its contents.
151
   * It then adds the parameters passed to it via Hashtable param to the Transformer.
152
   * It then calls the Transformer.transform method.
153 2088 tao
   */
154 7860 leinfelder
  private void doTransform(StreamSource xml,
155 3675 barteau
          StreamResult resultOutput,
156
          String xslSystemId,
157 5025 daigle
          Hashtable<String, String[]> param,
158 3675 barteau
          String qformat,
159
          String sessionid)
160
          throws Exception {
161
162 4327 leinfelder
      SortedProperties skinOptions;
163 3675 barteau
      TransformerFactory tFactory;
164
      Transformer transformer;
165
      String key, value;
166 5025 daigle
      Enumeration<String> en;
167
      Iterator<Map.Entry<String, String>> iterIt;
168
      Map.Entry<String, String> entry;
169 3675 barteau
170
      if (xslSystemId != null) {
171
        tFactory = TransformerFactory.newInstance();
172
        transformer = tFactory.newTransformer(new StreamSource(xslSystemId));
173
174 2088 tao
        transformer.setParameter("qformat", qformat);
175 5167 daigle
        logMetacat.info("DBTransform.doTransform - qformat: " + qformat);
176 2893 sgarg
177 4327 leinfelder
        skinOptions = SkinPropertyService.getProperties(qformat);
178
        if (skinOptions != null) {
179
            iterIt = skinOptions.getProperties().entrySet().iterator();
180 3675 barteau
            while (iterIt.hasNext()) {
181 5025 daigle
                entry = iterIt.next();
182
                key = entry.getKey();
183
                value = entry.getValue();
184 4327 leinfelder
                //only include the plain properties
185
                if (key.indexOf('.') == -1) {
186
                	transformer.setParameter(key, value);
187
                }
188 3675 barteau
            }
189
        }
190 2893 sgarg
191 3675 barteau
        if (sessionid != null && !sessionid.equals("null")) {
192 2088 tao
          transformer.setParameter("sessid", sessionid);
193
        }
194 3675 barteau
195 3733 leinfelder
        //set up the default params (can be overridden by the passed in params)
196 4080 daigle
        String cgiPrefix = SystemUtil.getCGI_URL();
197 5167 daigle
        logMetacat.debug("DBTransform.doTransform - cgi-prefix: " + cgiPrefix);
198
        logMetacat.debug("DBTransform.doTransform - httpServer: " + httpServer);
199
        logMetacat.debug("DBTransform.doTransform - contextURL: " + contextURL);
200
        logMetacat.debug("DBTransform.doTransform - serletURL: " + servletURL);
201 8664 tao
        logMetacat.debug("DBTransform.doTransform - userManagementURL: " + userManagementURL);
202 3733 leinfelder
        transformer.setParameter("cgi-prefix", cgiPrefix);
203 3780 daigle
        transformer.setParameter("httpServer", httpServer);
204 3733 leinfelder
        transformer.setParameter("contextURL", contextURL);
205 3780 daigle
        transformer.setParameter("servletURL", servletURL);
206 8664 tao
        transformer.setParameter("userManagementURL", userManagementURL);
207 2088 tao
        // Set up parameter for transformation
208 3675 barteau
        if ( param != null) {
209
          en = param.keys();
210
          while (en.hasMoreElements()) {
211 5025 daigle
            key = en.nextElement();
212
            value = (param.get(key))[0];
213 5167 daigle
            logMetacat.info("DBTransform.doTransform - param: " + key + " -- " + value);
214 2088 tao
            transformer.setParameter(key, value);
215
          }
216
        }
217 7860 leinfelder
        transformer.transform(xml, resultOutput);
218 2088 tao
    }
219
  }//doTransform
220
221
222 1716 berkley
  /**
223 906 berkley
   * gets the content of a tag in a given xml file with the given path
224
   * @param f the file to parse
225
   * @param path the path to get the content from
226
   */
227 1716 berkley
  public static NodeList getPathContent(File f, String path)
228 906 berkley
  {
229
    if(f == null)
230
    {
231
      return null;
232
    }
233 1716 berkley
234 906 berkley
    DOMParser parser = new DOMParser();
235
    InputSource in;
236
    FileInputStream fs;
237 1716 berkley
238 906 berkley
    try
239 1716 berkley
    {
240 906 berkley
      fs = new FileInputStream(f);
241
      in = new InputSource(fs);
242
    }
243
    catch(FileNotFoundException fnf)
244
    {
245
      fnf.printStackTrace();
246
      return null;
247
    }
248 1716 berkley
249 906 berkley
    try
250
    {
251
      parser.parse(in);
252
      fs.close();
253
    }
254
    catch(Exception e1)
255
    {
256 1716 berkley
      System.err.println("File: " + f.getPath() + " : parse threw: " +
257 906 berkley
                         e1.toString());
258
      return null;
259
    }
260 1716 berkley
261 906 berkley
    Document doc = parser.getDocument();
262 1716 berkley
263 906 berkley
    try
264
    {
265
      NodeList docNodeList = XPathAPI.selectNodeList(doc, path);
266
      return docNodeList;
267
    }
268
    catch(Exception se)
269
    {
270 1716 berkley
      System.err.println("file: " + f.getPath() + " : parse threw: " +
271 906 berkley
                         se.toString());
272
      return null;
273
    }
274
  }
275 87 jones
276
  /**
277
   * Lookup a stylesheet reference from the db catalog
278
   *
279 832 jones
   * @param qformat    the named style-set format
280
   * @param sourcetype the document type of the source
281
   * @param targettype the document type of the target
282
   */
283 1716 berkley
  public String getStyleSystemId(String qformat, String sourcetype,
284 832 jones
                String targettype) {
285
    String systemId = null;
286
287
    if ((qformat == null) || (qformat.equals("html"))) {
288
      qformat = defaultStyle;
289
    }
290
291
    // Load the style-set map for this qformat into a DOM
292
    try {
293 906 berkley
      boolean breakflag = false;
294 1929 brooke
      String filename = configDir + "/" + qformat + "/" + qformat + ".xml";
295 5167 daigle
      logMetacat.info("DBTransform.getStyleSystemId - Trying style-set file: " + filename);
296 906 berkley
      File f = new File(filename);
297
      NodeList nlDoctype = getPathContent(f, "/style-set/doctype");
298
      NodeList nlDefault = getPathContent(f, "/style-set/default-style");
299
      Node nDefault = nlDefault.item(0);
300
      systemId = nDefault.getFirstChild().getNodeValue(); //set the default
301 1716 berkley
302 906 berkley
      for(int i=0; i<nlDoctype.getLength(); i++)
303
      { //look for the right sourcetype
304
        Node nDoctype = nlDoctype.item(i);
305
        NamedNodeMap atts = nDoctype.getAttributes();
306
        Node nAtt = atts.getNamedItem("publicid");
307
        String doctype = nAtt.getFirstChild().getNodeValue();
308
        if(doctype.equals(sourcetype))
309
        { //found the right sourcetype now we need to get the target type
310
          NodeList nlChildren = nDoctype.getChildNodes();
311
          for(int j=0; j<nlChildren.getLength(); j++)
312
          {
313
            Node nChild = nlChildren.item(j);
314
            String childName = nChild.getNodeName();
315
            if(childName.equals("target"))
316
            {
317
              NamedNodeMap childAtts = nChild.getAttributes();
318
              Node nTargetPublicId = childAtts.getNamedItem("publicid");
319
              String target = nTargetPublicId.getFirstChild().getNodeValue();
320
              if(target.equals(targettype))
321
              { //we found the right target type
322
                NodeList nlTarget = nChild.getChildNodes();
323
                for(int k=0; k<nlTarget.getLength(); k++)
324
                {
325
                  Node nChildText = nlTarget.item(k);
326
                  if(nChildText.getNodeType() == Node.TEXT_NODE)
327
                  { //get the text from the target node
328
                    systemId = nChildText.getNodeValue();
329
                    breakflag = true;
330
                    break;
331
                  }
332
                }
333 832 jones
              }
334
            }
335 1716 berkley
336 906 berkley
            if(breakflag)
337
            {
338
              break;
339
            }
340 832 jones
          }
341
        }
342 1716 berkley
343 906 berkley
        if(breakflag)
344
        {
345
          break;
346
        }
347 832 jones
      }
348
    }
349 906 berkley
    catch(Exception e)
350
    {
351
      System.out.println("Error parsing style-set file: " + e.getMessage());
352
      e.printStackTrace();
353
    }
354 3725 tao
355
    //Check if the systemId is relative path, add a postfix - the contextULR to systemID.
356 9161 leinfelder
    if (systemId != null && !systemId.startsWith("http"))
357 3725 tao
    {
358
    	systemId = contextURL+systemId;
359
    }
360 832 jones
    // Return the system ID for this particular source document type
361 5167 daigle
    logMetacat.info("DBTransform.getStyleSystemId - style system id is: " + systemId);
362 832 jones
    return systemId;
363
  }
364
365 5025 daigle
// /* Method to modified the system id of xml input -- make sure it
366
//    points to system id in xml_catalog table
367
//  */
368
//  private void modifiedXmlStreamSource(StreamSource xml, String publicId)
369
//                                       throws Exception
370
//  {
371
//    // make sure the xml is not null
372
//    if (xml == null || publicId == null)
373
//    {
374
//      return;
375
//    }
376
//    logMetacat.info("public id of input stream is " +publicId);
377
//    // Get system id from xml_catalog table
378
//    String systemId = DBEntityResolver.getDTDSystemID(publicId);
379
//    logMetacat.info("system id of input stream from xml_catalog"
380
//                               +"table is " +systemId);
381
//    //set system id to input stream
382
//    xml.setSystemId(systemId);
383
//  }
384 2088 tao
385 1903 tao
  /*
386
   * removes the DOCTYPE element and its contents from a Sting
387 2088 tao
   * used to avoid problems with incorrect SystemIDs
388 1903 tao
   */
389 2088 tao
  private String removeDOCTYPE(String in) {
390 1903 tao
    String ret = "";
391
    int startpos = in.indexOf("<!DOCTYPE");
392
    if (startpos>-1) {
393 2088 tao
      int stoppos = in.indexOf(">", startpos + 8);
394 1903 tao
      ret = in.substring(0,startpos) + in.substring(stoppos+1,in.length());
395
    } else {
396
      return in;
397
    }
398 2088 tao
    return ret;
399 1903 tao
  }
400 99 jones
401
  /**
402
   * the main routine used to test the transform utility.
403
   *
404 184 jones
   * Usage: java DBTransform
405 99 jones
   */
406
  static public void main(String[] args) {
407 1716 berkley
408 184 jones
     if (args.length > 0)
409 99 jones
     {
410
        System.err.println("Wrong number of arguments!!!");
411 184 jones
        System.err.println("USAGE: java DBTransform");
412 99 jones
        return;
413
     } else {
414
        try {
415 1716 berkley
416 99 jones
          // Create a test document
417
          StringBuffer testdoc = new StringBuffer();
418 5752 leinfelder
          String encoding = "UTF-8";
419
          testdoc.append("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
420 99 jones
          testdoc.append("<eml-dataset><metafile_id>NCEAS-0001</metafile_id>");
421
          testdoc.append("<dataset_id>DS001</dataset_id>");
422
          testdoc.append("<title>My test doc</title></eml-dataset>");
423
424
          // Transform the document to the new doctype
425 5752 leinfelder
          Writer w = new OutputStreamWriter(System.out, encoding);
426 1217 tao
          DBTransform dbt = new DBTransform();
427 1716 berkley
          dbt.transformXMLDocument(testdoc.toString(),
428
                                   "-//NCEAS//eml-dataset//EN",
429
                                   "-//W3C//HTML//EN",
430 832 jones
                                   "knb",
431 5752 leinfelder
                                   w, null, null);
432 99 jones
433
        } catch (Exception e) {
434
          System.err.println("EXCEPTION HANDLING REQUIRED");
435
          System.err.println(e.getMessage());
436
          e.printStackTrace(System.err);
437
        }
438
     }
439
  }
440 1716 berkley
441 5025 daigle
//  private void dbg(int position) {
442
//    System.err.println("Debug flag: " + position);
443
//  }
444 99 jones
445 87 jones
}