Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements org.xml.sax.EntityResolver interface
4
 *             for resolving external entities
5
 *  Copyright: 2000 Regents of the University of California and the
6
 *             National Center for Ecological Analysis and Synthesis
7
 *    Authors: Jivka Bojilova, Matt Jones
8
 *    Release: @release@
9
 *
10
 *   '$Author: tao $'
11
 *     '$Date: 2002-05-23 20:48:20 -0700 (Thu, 23 May 2002) $'
12
 * '$Revision: 1131 $'
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 org.xml.sax.*;
32
import org.xml.sax.helpers.DefaultHandler;
33

    
34
import java.sql.*;
35
import java.io.File;
36
import java.io.Reader;
37
import java.io.BufferedReader;
38
import java.io.BufferedInputStream;
39
import java.io.FileWriter;
40
import java.io.BufferedWriter;
41
import java.io.InputStream;
42
import java.io.IOException;
43
import java.net.URL;
44
import java.net.URLConnection;
45
import java.net.MalformedURLException;
46

    
47
/** 
48
 * A database aware Class implementing EntityResolver interface for the SAX 
49
 * parser to call when processing the XML stream and intercepting any 
50
 * external entities (including the external DTD subset and external 
51
 * parameter entities, if any) before including them.
52
 */
53
public class DBEntityResolver implements EntityResolver
54
{
55
  //private Connection conn = null;
56
  private DefaultHandler handler = null;
57
  private String docname = null;
58
  private String doctype = null;
59
  private String systemid = null;
60
  private Reader dtdtext = null;
61

    
62
  /** 
63
   * Construct an instance of the DBEntityResolver class
64
   *
65
   * @param conn the JDBC connection to which information is written
66
   */
67
  public DBEntityResolver()
68
  {
69
    //this.conn = conn;
70
  }
71
  /** 
72
   * Construct an instance of the DBEntityResolver class
73
   *
74
   * @param conn the JDBC connection to which information is written
75
   * @param handler the SAX handler to determine parsing context
76
   * @param dtd Reader of new dtd to be uploaded on server's file system
77
   */
78
  public DBEntityResolver(DefaultHandler handler, Reader dtd)
79
  {
80
    //this.conn = conn;
81
    this.handler = handler;
82
    this.dtdtext = dtd;
83
  }
84
   
85
  /** 
86
   * The Parser call this method before opening any external entity 
87
   * except the top-level document entity (including the external DTD subset,
88
   * external entities referenced within the DTD, and external entities 
89
   * referenced within the document element)
90
   */
91
  public InputSource resolveEntity (String publicId, String systemId)
92
                     throws SAXException
93
  {
94
    String dbSystemID;
95
    String doctype = null;
96
    
97
    // Won't have a handler under all cases
98
    if ( handler != null ) {
99
      if ( handler instanceof DBSAXHandler ) {
100
        DBSAXHandler dhandler = null;
101
        dhandler = (DBSAXHandler)handler;
102
        if ( dhandler.processingDTD() ) {
103
          // public ID is doctype
104
          if (publicId != null) {   
105
            doctype = publicId;
106
          // assume public ID (doctype) is docname
107
          } else if (systemId != null) {
108
            doctype = dhandler.getDocname();
109
          }
110
        }
111
      } else if ( handler instanceof AccessControlList ) {
112
        AccessControlList ahandler = null;
113
        ahandler = (AccessControlList)handler;
114
        //if ( ahandler.processingDTD() ) {
115
          // public ID is doctype
116
          if (publicId != null) {   
117
            doctype = publicId;
118
          // assume public ID (doctype) is docname
119
          } else if (systemId != null) {
120
            doctype = ahandler.getDocname();
121
          }
122
        //}
123
      }
124
    }
125

    
126
    // get System ID for doctype
127
    if (doctype != null) {
128
      // look at db XML Catalog for System ID 
129
      dbSystemID = getDTDSystemID(doctype);
130
      boolean doctypeIsInDB = true;
131
      // no System ID found in db XML Catalog
132
      if (dbSystemID == null) {
133
        doctypeIsInDB = false;
134
        // use the provided System ID
135
        if (systemId != null) {
136
          dbSystemID = systemId;
137
        }
138
      }
139

    
140
      // there are dtd text provided; try to upload on Metacat
141
      if ( dtdtext != null ) {
142
        dbSystemID = uploadDTD(dbSystemID);
143
      }
144

    
145
      // open URLConnection to check first
146
      InputStream istream = checkURLConnection(dbSystemID);
147

    
148
      // need to register System ID in db XML Catalog if not yet
149
      if ( !doctypeIsInDB ) {
150
        // new DTD from outside URL location; try to upload on Metacat
151
        if ( dtdtext == null ) {
152
          dbSystemID = uploadDTDFromURL(istream, dbSystemID);
153
        }
154
        registerDTD(doctype, dbSystemID);
155
      }
156
      
157
      // return a byte-input stream for use
158
      InputSource is = new InputSource(dbSystemID); 
159

    
160
      // close and open URLConnection again
161
      try {
162
        istream.close();
163
      } catch (IOException e) {
164
        throw new SAXException 
165
        ("DBEntityResolver.resolveEntity(): " + e.getMessage());
166
      }    
167
      istream = checkURLConnection(dbSystemID);
168
      is.setByteStream(istream);
169
      return is;
170

    
171
    } else {
172
      // use provided systemId for the other cases
173
      InputStream istream = checkURLConnection(systemId);
174
      return null;
175
      
176
    }
177
    
178
  }
179

    
180
  /** 
181
   * Look at db XML Catalog to get System ID (if any) for @doctype.
182
   * Return null if there are no System ID found for @doctype
183
   */
184
  private String getDTDSystemID( String doctype )
185
                 throws SAXException
186
  {
187
    String systemid = null;
188
    Statement stmt = null;
189
    DBConnection conn = null;
190
    int serialNumber = -1;
191
    try {
192
      //check out DBConnection
193
      conn=DBConnectionPool.getDBConnection("DBEntityResolver.getDTDSystemID");
194
      serialNumber=conn.getCheckOutSerialNumber();
195
      
196
      stmt = conn.createStatement();
197
      stmt.execute("SELECT system_id FROM xml_catalog " + 
198
                   "WHERE entry_type = 'DTD' AND public_id = '" +
199
                   doctype + "'");
200
      ResultSet rs = stmt.getResultSet();
201
      boolean tableHasRows = rs.next();
202
      if (tableHasRows) {
203
        systemid = rs.getString(1);
204
      }
205
      stmt.close();
206
    } catch (SQLException e) {
207
      throw new SAXException
208
      ("DBEntityResolver.getDTDSystemID(): " + e.getMessage());
209
    }
210
    finally
211
    {
212
      DBConnectionPool.returnDBConnection(conn, serialNumber);
213
    }//finally
214

    
215
    // return the selected System ID
216
    return systemid;
217
  }
218

    
219
  /** 
220
   * Register new DTD identified by @systemId in Metacat XML Catalog 
221
   * . make a reference with @systemId for @doctype in Metacat DB
222
   */
223
  private void registerDTD ( String doctype, String systemId )
224
                 throws SAXException
225
  {
226
    DBConnection conn = null;
227
    int serialNumber = -1;
228
    // make a reference in db catalog table with @systemId for @doctype
229
    try {
230
      //check out DBConnection
231
      conn=DBConnectionPool.getDBConnection("DBEntityResolver.registerDTD");
232
      serialNumber=conn.getCheckOutSerialNumber();
233
      
234
      PreparedStatement pstmt;
235
      pstmt = conn.prepareStatement(
236
             "INSERT INTO xml_catalog " +
237
             "(catalog_id, entry_type, public_id, system_id) " +
238
             "VALUES (null, 'DTD', ?, ?)");
239
      // Bind the values to the query
240
      pstmt.setString(1, doctype);
241
      pstmt.setString(2, systemId);
242
      // Do the insertion
243
      pstmt.execute();
244
      pstmt.close();
245
    } catch (SQLException e) {
246
      throw new SAXException
247
      ("DBEntityResolver.registerDTD(): " + e.getMessage());
248
    }
249
    finally
250
    {
251
      DBConnectionPool.returnDBConnection(conn, serialNumber);
252
    }
253
  }
254

    
255
  /** 
256
   * Upload new DTD text identified by @systemId to Metacat file system
257
   */
258
  private String uploadDTD ( String systemId )
259
                 throws SAXException
260
  {
261
    MetaCatUtil util = new MetaCatUtil();
262
    String dtdPath = util.getOption("dtdPath");
263
    String dtdURL = util.getOption("dtdURL");
264
    
265
    // get filename from systemId
266
    String filename = systemId;
267
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
268
    if ( slash > -1 ) {
269
      filename = filename.substring(slash + 1);
270
    }
271

    
272
    // writing dtd text on Metacat file system as filename
273
    try {
274
      // create a buffering character-input stream
275
      // that uses a default-sized input buffer
276
      BufferedReader in = new BufferedReader(dtdtext);
277

    
278
      // open file writer to write the input into it
279
      //String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
280
      File f = new File(dtdPath, filename);
281
     synchronized (f) { 
282
      try {
283
        if ( f.exists() ) {
284
          throw new IOException("File already exist: " + f.getCanonicalFile());
285
        //if ( f.exists() && !f.canWrite() ) {
286
        //  throw new IOException("Not writable: " + f.getCanonicalFile());
287
        }
288
      } catch (SecurityException se) {
289
        // if a security manager exists,
290
        // its checkRead method is called for f.exist()
291
        // or checkWrite method is called for f.canWrite()
292
        throw se;
293
      }
294
      // create a buffered character-output stream
295
      // that uses a default-sized output buffer
296
      FileWriter fw = new FileWriter(f);
297
      BufferedWriter out = new BufferedWriter(fw);
298

    
299
      // read the input and write into the file writer
300
	    String inputLine;
301
	    while ( (inputLine = in.readLine()) != null ) {
302
	      out.write(inputLine, 0, inputLine.length());
303
  	    out.newLine(); //instead of out.write('\r\n');
304
	    }
305

    
306
      // the input and the output streams must be closed
307
	    in.close();
308
	    out.flush();
309
	    out.close();
310
	    fw.close();
311
     } // end of synchronized      
312
    } catch (MalformedURLException e) {
313
      throw new SAXException
314
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
315
    } catch (IOException e) {
316
      throw new SAXException
317
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
318
    } catch (SecurityException e) {
319
      throw new SAXException
320
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
321
    }
322
    
323
    //String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
324
    return  dtdURL + filename;
325
  }
326

    
327

    
328
  /** 
329
   * Upload new DTD located at outside URL to Metacat file system
330
   */
331
  private String uploadDTDFromURL(InputStream istream, String systemId)
332
                 throws SAXException
333
  {
334
    MetaCatUtil util = new MetaCatUtil();
335
    String dtdPath = util.getOption("dtdPath");
336
    String dtdURL = util.getOption("dtdURL");
337
    
338
    // get filename from systemId
339
    String filename = systemId;
340
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
341
    if ( slash > -1 ) {
342
      filename = filename.substring(slash + 1);
343
    }
344

    
345
    // writing dtd text on Metacat file system as filename
346
    try {
347
      // create a buffering character-input stream
348
      // that uses a default-sized input buffer
349
      BufferedInputStream in = new BufferedInputStream(istream);
350

    
351
      // open file writer to write the input into it
352
      //String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
353
      File f = new File(dtdPath, filename);
354
     synchronized (f) { 
355
      try {
356
        if ( f.exists() ) {
357
          throw new IOException("File already exist: " + f.getCanonicalFile());
358
        //if ( f.exists() && !f.canWrite() ) {
359
        //  throw new IOException("Not writable: " + f.getCanonicalFile());
360
        }
361
      } catch (SecurityException se) {
362
        // if a security manager exists,
363
        // its checkRead method is called for f.exist()
364
        // or checkWrite method is called for f.canWrite()
365
        throw se;
366
      }
367
      // create a buffered character-output stream
368
      // that uses a default-sized output buffer
369
      FileWriter fw = new FileWriter(f);
370
      BufferedWriter out = new BufferedWriter(fw);
371

    
372
      // read the input and write into the file writer
373
	    int inputByte;
374
	    while ( (inputByte = in.read()) != -1 ) {
375
	      out.write(inputByte);
376
  	    //out.newLine(); //instead of out.write('\r\n');
377
	    }
378

    
379
      // the input and the output streams must be closed
380
	    in.close();
381
	    out.flush();
382
	    out.close();
383
	    fw.close();
384
     } // end of synchronized
385
    } catch (MalformedURLException e) {
386
      throw new SAXException
387
      ("DBEntityResolver.uploadDTDFromURL(): " + e.getMessage());
388
    } catch (IOException e) {
389
      throw new SAXException
390
      ("DBEntityResolver.uploadDTDFromURL(): " + e.getMessage());
391
    } catch (SecurityException e) {
392
      throw new SAXException
393
      ("DBEntityResolver.uploadDTDFromURL(): " + e.getMessage());
394
    }
395
    
396
    //String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
397
    return  dtdURL + filename;
398
  }
399

    
400
  /** 
401
   * Check URL Connection for @systemId, and return an InputStream
402
   * that can be used to read from the systemId URL.  The parser ends
403
   * up using this via the InputSource to read the DTD.
404
   *
405
   * @param systemId a URI (in practice URL) to be checked and opened
406
   */
407
  private InputStream checkURLConnection (String systemId)
408
                      throws SAXException
409
  {
410
    try {
411

    
412
      return (new URL(systemId).openStream());
413

    
414
    } catch (MalformedURLException e) {
415
      throw new SAXException
416
      ("DBEntityResolver.checkURLConnection(): " + e.getMessage());
417
    } catch (IOException e) {
418
      throw new SAXException
419
      ("DBEntityResolver.checkURLConnection(): " + e.getMessage());
420
    }    
421
  }   
422
}
(16-16/43)