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
 *
9
 *   '$Author: leinfelder $'
10
 *     '$Date: 2009-02-11 17:40:48 -0800 (Wed, 11 Feb 2009) $'
11
 * '$Revision: 4803 $'
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 org.apache.log4j.Logger;
31
import org.xml.sax.*;
32
import org.xml.sax.helpers.DefaultHandler;
33

    
34
import edu.ucsb.nceas.metacat.util.SystemUtil;
35
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
36

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

    
50
/**
51
 * A database aware Class implementing EntityResolver interface for the SAX
52
 * parser to call when processing the XML stream and intercepting any
53
 * external entities (including the external DTD subset and external
54
 * parameter entities, if any) before including them.
55
 */
56
public class DBEntityResolver implements EntityResolver
57
{
58
  private DBConnection connection = null;
59
  private DefaultHandler handler = null;
60
  private String docname = null;
61
  private String doctype = null;
62
  private String systemid = null;
63
  private Reader dtdtext = null;
64
  private static Logger logMetacat = Logger.getLogger(DBEntityResolver.class);
65
  
66
  /**
67
   * Construct an instance of the DBEntityResolver class
68
   *
69
   * @param conn the JDBC connection to which information is written
70
   */
71
  public DBEntityResolver(DBConnection conn)
72
  {
73
    this.connection= conn;
74
  }
75
  /**
76
   * Construct an instance of the DBEntityResolver class
77
   *
78
   * @param conn the JDBC connection to which information is written
79
   * @param handler the SAX handler to determine parsing context
80
   * @param dtd Reader of new dtd to be uploaded on server's file system
81
   */
82
  public DBEntityResolver(DBConnection conn, DefaultHandler handler, Reader dtd)
83
  {
84
    this.connection = conn;
85
    this.handler = handler;
86
    this.dtdtext = dtd;
87
  }
88

    
89
  /**
90
   * The Parser call this method before opening any external entity
91
   * except the top-level document entity (including the external DTD subset,
92
   * external entities referenced within the DTD, and external entities
93
   * referenced within the document element)
94
   */
95
  public InputSource resolveEntity (String publicId, String systemId)
96
                     throws SAXException
97
  {
98
    logMetacat.debug("in DBEntityResolver.resolveEntity");
99
    String dbSystemID;
100
    String doctype = null;
101

    
102
    // Won't have a handler under all cases
103
    if ( handler != null ) {
104
      if ( handler instanceof DBSAXHandler ) {
105
        DBSAXHandler dhandler = null;
106
        dhandler = (DBSAXHandler)handler;
107
        if ( dhandler.processingDTD() ) {
108
         
109
          // public ID is doctype
110
          if (publicId != null) {
111
            doctype = publicId;
112
            logMetacat.info("in get type from publicId and doctype is: "
113
                                     +doctype);
114
          // assume public ID (doctype) is docname
115
          } else if (systemId != null) {
116
            doctype = dhandler.getDocname();
117
          }
118
        }
119
      } else if ( handler instanceof AccessControlList ) {
120
        AccessControlList ahandler = null;
121
        ahandler = (AccessControlList)handler;
122
        //if ( ahandler.processingDTD() ) {
123
          // public ID is doctype
124
          if (publicId != null) {
125
            doctype = publicId;
126
          // assume public ID (doctype) is docname
127
          } else if (systemId != null) {
128
            doctype = ahandler.getDocname();
129
          }
130
        //}
131
      }
132
    }
133

    
134
    // get System ID for doctype
135
    if (doctype != null) {
136
      // look at db XML Catalog for System ID
137
      logMetacat.info("get systemId from doctype: "+doctype);
138
      dbSystemID = getDTDSystemID(doctype);
139
      logMetacat.info("The Systemid is: "+dbSystemID);
140
      // check that it is accessible on our system before getting too far
141
      try {
142
    	  InputStream in = checkURLConnection(dbSystemID);
143
	  }
144
      catch (Exception e) {
145
    	  dbSystemID = null;
146
	  }
147
      boolean doctypeIsInDB = true;
148
      // no System ID found in db XML Catalog
149
      if (dbSystemID == null) {
150
        doctypeIsInDB = false;
151
        // use the provided System ID
152
        if (systemId != null) {
153
          dbSystemID = systemId;
154
        }
155
        logMetacat.info("If above Systemid is null and then get "
156
                                 +" system id from file" + dbSystemID);
157
      }
158
      // there are dtd text provided; try to upload on Metacat
159
      if ( dtdtext != null ) {
160
        dbSystemID = uploadDTD(dbSystemID);
161
      }
162

    
163
      // open URLConnection to check first
164
      InputStream istream = checkURLConnection(dbSystemID);
165

    
166
      // need to register System ID in db XML Catalog if not yet
167
      if ( !doctypeIsInDB ) {
168
        // new DTD from outside URL location; try to upload on Metacat
169
        if ( dtdtext == null ) {
170
          dbSystemID = uploadDTDFromURL(istream, dbSystemID);
171
        }
172
        registerDTD(doctype, dbSystemID);
173
      }
174
      // return a byte-input stream for use
175
      InputSource is = new InputSource(dbSystemID);
176

    
177
      // close and open URLConnection again
178
      try {
179
        istream.close();
180
      } catch (IOException e) {
181
        throw new SAXException
182
        ("DBEntityResolver.resolveEntity(): " + e.getMessage());
183
      }
184
      istream = checkURLConnection(dbSystemID);
185
      is.setByteStream(istream);
186
      return is;
187
    } else {
188
      // use provided systemId for the other cases
189
      logMetacat.info("doctype is null and using system id from file");
190
      InputStream istream = checkURLConnection(systemId);
191
      return null;
192

    
193
    }
194

    
195
  }
196

    
197
  /**
198
   * Look at db XML Catalog to get System ID (if any) for @doctype.
199
   * Return null if there are no System ID found for @doctype
200
   */
201
  public static String getDTDSystemID( String doctype )
202
                 throws SAXException
203
  {
204
    String systemid = null;
205
    Statement stmt = null;
206
    DBConnection conn = null;
207
    int serialNumber = -1;
208
    try {
209
      //check out DBConnection
210
      conn=DBConnectionPool.getDBConnection("DBEntityResolver.getDTDSystemID");
211
      serialNumber=conn.getCheckOutSerialNumber();
212

    
213
      stmt = conn.createStatement();
214
      stmt.execute("SELECT system_id FROM xml_catalog " +
215
                   "WHERE entry_type = 'DTD' AND public_id = '" +
216
                   doctype + "'");
217
      ResultSet rs = stmt.getResultSet();
218
      boolean tableHasRows = rs.next();
219
      if (tableHasRows) {
220
        systemid = rs.getString(1);
221
        // system id may not have server url on front.  Add it if not.
222
        if (!systemid.startsWith("http://")) {
223
        	systemid = SystemUtil.getContextURL() + systemid;
224
        }
225
      }
226
      stmt.close();
227
    } catch (SQLException e) {
228
      throw new SAXException
229
      ("DBEntityResolver.getDTDSystemID(): " + e.getMessage());
230
    } catch (PropertyNotFoundException pnfe) {
231
        throw new SAXException
232
        ("DBEntityResolver.getDTDSystemID(): " + pnfe.getMessage());
233
      }
234
    finally
235
    {
236
      try
237
      {
238
        stmt.close();
239
      }//try
240
      catch (SQLException sqlE)
241
      {
242
        logMetacat.error("Error in DBEntityReolver.getDTDSystemId: "
243
                                  +sqlE.getMessage());
244
      }//catch
245
      finally
246
      {
247
        DBConnectionPool.returnDBConnection(conn, serialNumber);
248
      }//finally
249
    }//finally
250

    
251
    // return the selected System ID
252
    return systemid;
253
  }
254

    
255
  /**
256
   * Register new DTD identified by @systemId in Metacat XML Catalog
257
   * . make a reference with @systemId for @doctype in Metacat DB
258
   */
259
  private void registerDTD ( String doctype, String systemId )
260
                 throws SAXException
261
  {
262
	  String existingSystemId = getDTDSystemID(doctype);
263
	  if (existingSystemId != null && existingSystemId.equals(systemId)) {
264
		  logMetacat.warn("doctype/systemId already registered in DB: " + doctype);
265
		  return;
266
	  }
267
    //DBConnection conn = null;
268
    //int serialNumber = -1;
269
    PreparedStatement pstmt = null;
270
    // make a reference in db catalog table with @systemId for @doctype
271
    try {
272
      //check out DBConnection
273
      //conn=DBConnectionPool.getDBConnection("DBEntityResolver.registerDTD");
274
      //serialNumber=conn.getCheckOutSerialNumber();
275

    
276

    
277
      pstmt = connection.prepareStatement(
278
             "INSERT INTO xml_catalog " +
279
             "(entry_type, public_id, system_id) " +
280
             "VALUES ('DTD', ?, ?)");
281
      // Increase usage count
282
      connection.increaseUsageCount(1);
283
      // Bind the values to the query
284
      pstmt.setString(1, doctype);
285
      pstmt.setString(2, systemId);
286
      // Do the insertion
287
      pstmt.execute();
288
      int updateCnt = pstmt.getUpdateCount();
289
      logMetacat.debug("DBEntityReolver.registerDTD: DTDs registered: " + updateCnt);
290
      pstmt.close();
291
    } catch (SQLException e) {
292
      throw new SAXException
293
      ("DBEntityResolver.registerDTD(): " + e.getMessage());
294
    }
295
    finally
296
    {
297
      try
298
      {
299
        pstmt.close();
300
      }//try
301
      catch (SQLException sqlE)
302
      {
303
        logMetacat.error("Error in DBEntityReolver.registerDTD: "
304
                                    +sqlE.getMessage());
305
      }//catch
306
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
307
    }//finally
308

    
309
  }
310

    
311
  /**
312
	 * Upload new DTD text identified by
313
	 * 
314
	 * @systemId to Metacat file system
315
	 */
316
	private String uploadDTD(String systemId) throws SAXException {
317
		String dtdPath = null;
318
		String dtdURL = null;
319
		try {
320
			dtdPath = SystemUtil.getContextDir() + "/dtd/";
321
			dtdURL = SystemUtil.getContextURL() + "/dtd/";
322
		} catch (PropertyNotFoundException pnfe) {
323
			throw new SAXException("DBEntityResolver.uploadDTD: " + pnfe.getMessage());
324
		}
325

    
326
		// get filename from systemId
327
		String filename = systemId;
328
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
329
		if (slash > -1) {
330
			filename = filename.substring(slash + 1);
331
		}
332

    
333
		// writing dtd text on Metacat file system as filename
334
		try {
335
			// create a buffering character-input stream
336
			// that uses a default-sized input buffer
337
			BufferedReader in = new BufferedReader(dtdtext);
338

    
339
			// open file writer to write the input into it
340
			// String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
341
			File f = new File(dtdPath, filename);
342
			synchronized (f) {
343
				try {
344
					if (f.exists()) {
345
						throw new IOException("File already exist: "
346
								+ f.getCanonicalFile());
347
						// if ( f.exists() && !f.canWrite() ) {
348
						// throw new IOException("Not writable: " +
349
						// f.getCanonicalFile());
350
					}
351
				} catch (SecurityException se) {
352
					// if a security manager exists,
353
					// its checkRead method is called for f.exist()
354
					// or checkWrite method is called for f.canWrite()
355
					throw se;
356
				}
357
				// create a buffered character-output stream
358
				// that uses a default-sized output buffer
359
				FileWriter fw = new FileWriter(f);
360
				BufferedWriter out = new BufferedWriter(fw);
361

    
362
				// read the input and write into the file writer
363
				String inputLine;
364
				while ((inputLine = in.readLine()) != null) {
365
					out.write(inputLine, 0, inputLine.length());
366
					out.newLine(); // instead of out.write('\r\n');
367
				}
368

    
369
				// the input and the output streams must be closed
370
				in.close();
371
				out.flush();
372
				out.close();
373
				fw.close();
374
			} // end of synchronized
375
		} catch (MalformedURLException e) {
376
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
377
		} catch (IOException e) {
378
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
379
		} catch (SecurityException e) {
380
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
381
		}
382

    
383
		// String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
384
		return dtdURL + filename;
385
	}
386

    
387

    
388
  /**
389
	 * Upload new DTD located at outside URL to Metacat file system
390
	 */
391
	private String uploadDTDFromURL(InputStream istream, String systemId)
392
			throws SAXException {
393
		String dtdPath = null;
394
		String dtdURL = null;
395
		try {
396
			dtdPath = SystemUtil.getContextDir() + "/dtd/";
397
			dtdURL = SystemUtil.getContextURL() + "/dtd/";
398
		} catch (PropertyNotFoundException pnfe) {
399
			throw new SAXException("DBEntityResolver.uploadDTDFromURL: "
400
					+ pnfe.getMessage());
401
		}
402

    
403
		// get filename from systemId
404
		String filename = systemId;
405
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
406
		if (slash > -1) {
407
			filename = filename.substring(slash + 1);
408
		}
409

    
410
		// writing dtd text on Metacat file system as filename
411
		try {
412
			// create a buffering character-input stream
413
			// that uses a default-sized input buffer
414
			BufferedInputStream in = new BufferedInputStream(istream);
415

    
416
			// open file writer to write the input into it
417
			//String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
418
			File f = new File(dtdPath, filename);
419
			synchronized (f) {
420
				try {
421
					if (f.exists()) {
422
						logMetacat.warn("File already exist, overwriting: "
423
								+ f.getCanonicalFile());
424
						//return dtdURL + filename;
425
						//throw new IOException("File already exist: "
426
						//		+ f.getCanonicalFile());
427
						//if ( f.exists() && !f.canWrite() ) {
428
						//  throw new IOException("Not writable: " + f.getCanonicalFile());
429
					}
430
				} catch (SecurityException se) {
431
					// if a security manager exists,
432
					// its checkRead method is called for f.exist()
433
					// or checkWrite method is called for f.canWrite()
434
					throw se;
435
				}
436
				// create a buffered character-output stream
437
				// that uses a default-sized output buffer
438
				FileWriter fw = new FileWriter(f);
439
				BufferedWriter out = new BufferedWriter(fw);
440

    
441
				// read the input and write into the file writer
442
				int inputByte;
443
				while ((inputByte = in.read()) != -1) {
444
					out.write(inputByte);
445
					//out.newLine(); //instead of out.write('\r\n');
446
				}
447

    
448
				// the input and the output streams must be closed
449
				in.close();
450
				out.flush();
451
				out.close();
452
				fw.close();
453
			} // end of synchronized
454
		} catch (MalformedURLException e) {
455
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
456
					+ e.getMessage());
457
		} catch (IOException e) {
458
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
459
					+ e.getMessage());
460
		} catch (SecurityException e) {
461
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
462
					+ e.getMessage());
463
		}
464

    
465
		//String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
466
		return dtdURL + filename;
467
	}
468

    
469
	/**
470
	 * Check URL Connection for @systemId, and return an InputStream
471
	 * that can be used to read from the systemId URL.  The parser ends
472
	 * up using this via the InputSource to read the DTD.
473
	 *
474
	 * @param systemId a URI (in practice URL) to be checked and opened
475
	 */
476
	public static InputStream checkURLConnection(String systemId) throws SAXException {
477
		try {
478
			return (new URL(systemId).openStream());
479

    
480
		} catch (MalformedURLException e) {
481
			throw new SAXException("DBEntityResolver.checkURLConnection(): "
482
					+ e.getMessage());
483
		} catch (IOException e) {
484
			throw new SAXException("DBEntityResolver.checkURLConnection(): "
485
					+ e.getMessage());
486
		}
487
	}
488
}
(20-20/69)