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: tao $'
10
 *     '$Date: 2016-09-02 18:20:44 -0700 (Fri, 02 Sep 2016) $'
11
 * '$Revision: 9916 $'
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.accesscontrol.AccessControlList;
35
import edu.ucsb.nceas.metacat.database.DBConnection;
36
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
37
import edu.ucsb.nceas.metacat.util.SystemUtil;
38
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
39

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

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

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

    
105
    // Won't have a handler under all cases
106
    if ( handler != null ) {
107
      if ( handler instanceof DBSAXHandler ) {
108
        DBSAXHandler dhandler = null;
109
        dhandler = (DBSAXHandler)handler;
110
        if ( dhandler.processingDTD() ) {
111
         
112
          // public ID is doctype
113
          if (publicId != null) {
114
            doctype = publicId;
115
            logMetacat.debug("DBEntityResolver.resolveEntity - the publicId is not null, so the publicId is the doctype. The doctype is: "
116
                                     + doctype);
117
          // assume public ID (doctype) is docname
118
          } else {
119
            doctype = dhandler.getDocname();
120
            logMetacat.debug("DBEntityResolver.resolveEntity - the publicId is null and we treat the doc name(the root element name) as the doc type. The doctype is: "
121
                    + doctype);
122
          }
123
        }
124
      } else if ( handler instanceof AccessControlList ) {
125
        AccessControlList ahandler = null;
126
        ahandler = (AccessControlList)handler;
127
        if ( ahandler.processingDTD() ) {
128
          // public ID is doctype
129
          if (publicId != null) {
130
            doctype = publicId;
131
          // assume public ID (doctype) is docname
132
          } else {
133
            doctype = ahandler.getDocname();
134
          }
135
        }
136
      }
137
    } else {
138
        logMetacat.debug("DBEntityResolver.resolveEntity - the xml handler is null. So we can't find the doctype.");
139
    }
140

    
141
    // get System ID for doctype
142
    if (doctype != null) {
143
      // look at db XML Catalog for System ID
144
      logMetacat.info("DBEntityResolver.resolveEntity - get systemId from doctype: " + doctype);
145
      dbSystemID = getDTDSystemID(doctype);
146
      logMetacat.info("DBEntityResolver.resolveEntity - The Systemid from xml_catalog table is: " + dbSystemID);
147
      if(dbSystemID == null) {
148
          logMetacat.error("DBEntityResolver.resolveEntity - "+"The doctype: "+doctype+" , which was defined by a DTD document, isn't registered in Metacat. Please contact the operator of the Metacat");
149
          throw new SAXException("The doctype: "+doctype+" , which was defined by a DTD document, isn't registered in Metacat. Please contact the operator of the Metacat");
150
      }
151
      // check that it is accessible on our system before getting too far
152
      try {
153
    	  InputStream in = checkURLConnection(dbSystemID);
154
    	  dtdSource = new InputSource(in);
155
	  } catch (SAXException se) {
156
	      se.printStackTrace();
157
	      throw se;
158
		  // after an upgrade, the dtd will not exist on disk, but it is in xml catalog.  The db system id may be pointing 
159
		  // back at this system  Try and download it from the original system id and see if we still have a problem
160
		  // checking the URL connection.
161
		  /*logMetacat.warn("DBEntityResolver.resolveEntity - Problem when checking URL Connection: " + se.getMessage());
162
		  logMetacat.warn("DBEntityResolver.resolveEntity - Probably, dtd for doc type " + doctype + " existed in xml catalog, but not on disk.  Uploading from: " + systemId);
163
		  InputStream istream = checkURLConnection(systemId);
164
		  uploadDTDFromURL(istream, systemId);
165
		  try {
166
			  Thread.currentThread().sleep(6000);
167
			  checkURLConnection(dbSystemID);
168
		  } catch (Exception e2) {
169
			  logMetacat.error("DBEntityResolver.resolveEntity - still could not find dtd for doc type " + doctype + " at " 
170
					  + dbSystemID + " : " + e2.getMessage());
171
			  dbSystemID = null;
172
		  }*/
173
	  } 
174
      /*boolean doctypeIsInDB = true;
175
      // no System ID found in db XML Catalog
176
      if (dbSystemID == null) {
177
        doctypeIsInDB = false;
178
        // use the provided System ID
179
        if (systemId != null) {
180
          dbSystemID = systemId;
181
        }
182
        logMetacat.info("DBEntityResolver.resolveEntity - If above Systemid is null, then get "
183
                                 + "system id from file: " + dbSystemID);
184
      }
185
      // there are dtd text provided; try to upload on Metacat
186
      if ( dtdtext != null ) {
187
        dbSystemID = uploadDTD(dbSystemID);
188
      }
189

    
190
      // open URLConnection to check first
191
      InputStream istream = checkURLConnection(dbSystemID);
192

    
193
      // need to register System ID in db XML Catalog if not yet
194
      if ( !doctypeIsInDB ) {
195
        // new DTD from outside URL location; try to upload on Metacat
196
        if ( dtdtext == null ) {
197
          dbSystemID = uploadDTDFromURL(istream, dbSystemID);
198
        }
199
        registerDTD(doctype, dbSystemID);
200
      }
201
      // return a byte-input stream for use
202
      InputSource is = new InputSource(dbSystemID);
203

    
204
      // close and open URLConnection again
205
      try {
206
        istream.close();
207
      } catch (IOException e) {
208
        throw new SAXException
209
        ("DBEntityResolver.resolveEntity - I/O issue when resolving entity: " + e.getMessage());
210
      }
211
      istream = checkURLConnection(dbSystemID);
212
      is.setByteStream(istream);
213
      return is;*/
214
    } else {
215
      //we can't determine the public id or the name of the root element in for this dtd defined xml document
216
      String message = "Metacat can't determine the public id or the name of the root element of the document, so the validation can't be imposed and the document is rejected";
217
      logMetacat.error("DBEntityResolver.resolveEntity - "+message);
218
      throw new SAXException(message);
219
      //InputStream istream = checkURLConnection(systemId);
220
      //return null;
221
    }
222
    return dtdSource;
223

    
224
  }
225

    
226
  /**
227
   * Look at db XML Catalog to get System ID (if any) for @doctype.
228
   * Return null if there are no System ID found for @doctype
229
   */
230
  public static String getDTDSystemID( String doctype )
231
                 throws SAXException
232
  {
233
    String systemid = null;
234
    PreparedStatement pstmt = null;
235
    DBConnection conn = null;
236
    int serialNumber = -1;
237
    ResultSet rs = null;
238
    try {
239
      //check out DBConnection
240
      conn=DBConnectionPool.getDBConnection("DBEntityResolver.getDTDSystemID");
241
      serialNumber=conn.getCheckOutSerialNumber();
242

    
243
      String sql = "SELECT system_id FROM xml_catalog " +
244
      "WHERE entry_type = 'DTD' AND public_id = ?";
245
      
246
      pstmt = conn.prepareStatement(sql);
247
      pstmt.setString(1, doctype);
248
      
249
      pstmt.execute();
250
      rs = pstmt.getResultSet();
251
      boolean tableHasRows = rs.next();
252
      if (tableHasRows) {
253
        systemid = rs.getString(1);
254
        // system id may not have server url on front.  Add it if not.
255
        if (!systemid.startsWith("http://")) {
256
        	systemid = SystemUtil.getContextURL() + systemid;
257
        }
258
      }
259
      //pstmt.close();
260
    } catch (SQLException e) {
261
      throw new SAXException
262
      ("DBEntityResolver.getDTDSystemID - SQL error when getting DTD system ID: " + e.getMessage());
263
    } catch (PropertyNotFoundException pnfe) {
264
        throw new SAXException
265
        ("DBEntityResolver.getDTDSystemID - Property error when getting DTD system ID:  " + pnfe.getMessage());
266
      }
267
    finally
268
    {
269
      try
270
      {
271
          if(rs != null) {
272
              rs.close();
273
          }
274
          if(pstmt != null) {
275
              pstmt.close();
276
          }
277
        
278
      }//try
279
      catch (SQLException sqlE)
280
      {
281
        logMetacat.error("DBEntityResolver.getDTDSystemId - SQL error: " + sqlE.getMessage());
282
      }//catch
283
      finally
284
      {
285
        DBConnectionPool.returnDBConnection(conn, serialNumber);
286
      }//finally
287
    }//finally
288

    
289
    // return the selected System ID
290
    return systemid;
291
  }
292

    
293
  /**
294
   * Register new DTD identified by @systemId in Metacat XML Catalog
295
   * . make a reference with @systemId for @doctype in Metacat DB
296
   */
297
  private void registerDTD ( String doctype, String systemId )
298
                 throws SAXException
299
  {
300
	  String existingSystemId = getDTDSystemID(doctype);
301
	  if (existingSystemId != null && existingSystemId.equals(systemId)) {
302
		  logMetacat.warn("DBEntityResolver.registerDTD - doctype/systemId already registered in DB: " + doctype);
303
		  return;
304
	  }
305
    //DBConnection conn = null;
306
    //int serialNumber = -1;
307
    PreparedStatement pstmt = null;
308
    // make a reference in db catalog table with @systemId for @doctype
309
    try {
310
      //check out DBConnection
311
      //conn=DBConnectionPool.getDBConnection("DBEntityResolver.registerDTD");
312
      //serialNumber=conn.getCheckOutSerialNumber();
313

    
314

    
315
      pstmt = connection.prepareStatement(
316
             "INSERT INTO xml_catalog " +
317
             "(entry_type, public_id, system_id) " +
318
             "VALUES ('DTD', ?, ?)");
319
      // Increase usage count
320
      connection.increaseUsageCount(1);
321
      // Bind the values to the query
322
      pstmt.setString(1, doctype);
323
      pstmt.setString(2, systemId);
324
      // Do the insertion
325
      pstmt.execute();
326
      int updateCnt = pstmt.getUpdateCount();
327
      logMetacat.debug("DBEntityReolver.registerDTD - DTDs registered: " + updateCnt);
328
      pstmt.close();
329
    } catch (SQLException e) {
330
      throw new SAXException
331
      ("DBEntityResolver.registerDTD - SQL issue when registering DTD: " + e.getMessage());
332
    }
333
    finally
334
    {
335
      try
336
      {
337
        pstmt.close();
338
      }//try
339
      catch (SQLException sqlE)
340
      {
341
        logMetacat.error("DBEntityResolver.registerDTD - SQL error: " + sqlE.getMessage());
342
      }//catch
343
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
344
    }//finally
345

    
346
  }
347

    
348
  /**
349
	 * Upload new DTD text identified by
350
	 * 
351
	 * @systemId to Metacat file system
352
	 */
353
	private String uploadDTD(String systemId) throws SAXException {
354
		String dtdPath = null;
355
		String dtdURL = null;
356
		try {
357
			dtdPath = SystemUtil.getContextDir() + "/dtd/";
358
			dtdURL = SystemUtil.getContextURL() + "/dtd/";
359
		} catch (PropertyNotFoundException pnfe) {
360
			throw new SAXException("DBEntityResolver.uploadDTD: " + pnfe.getMessage());
361
		}
362

    
363
		// get filename from systemId
364
		String filename = systemId;
365
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
366
		if (slash > -1) {
367
			filename = filename.substring(slash + 1);
368
		}
369

    
370
		// writing dtd text on Metacat file system as filename
371
		try {
372
			// create a buffering character-input stream
373
			// that uses a default-sized input buffer
374
			BufferedReader in = new BufferedReader(dtdtext);
375

    
376
			// open file writer to write the input into it
377
			// String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
378
			File f = new File(dtdPath, filename);
379
			synchronized (f) {
380
				try {
381
					if (f.exists()) {
382
						throw new IOException("File already exist: "
383
								+ f.getCanonicalFile());
384
						// if ( f.exists() && !f.canWrite() ) {
385
						// throw new IOException("Not writable: " +
386
						// f.getCanonicalFile());
387
					}
388
				} catch (SecurityException se) {
389
					// if a security manager exists,
390
					// its checkRead method is called for f.exist()
391
					// or checkWrite method is called for f.canWrite()
392
					throw se;
393
				}
394
				// create a buffered character-output stream
395
				// that uses a default-sized output buffer
396
				FileWriter fw = new FileWriter(f);
397
				BufferedWriter out = new BufferedWriter(fw);
398

    
399
				// read the input and write into the file writer
400
				String inputLine;
401
				while ((inputLine = in.readLine()) != null) {
402
					out.write(inputLine, 0, inputLine.length());
403
					out.newLine(); // instead of out.write('\r\n');
404
				}
405

    
406
				// the input and the output streams must be closed
407
				in.close();
408
				out.flush();
409
				out.close();
410
				fw.close();
411
			} // end of synchronized
412
		} catch (MalformedURLException e) {
413
			throw new SAXException("DBEntityResolver.uploadDTD() - Malformed URL when uploading DTD: " + e.getMessage());
414
		} catch (IOException e) {
415
			throw new SAXException("DBEntityResolver.uploadDTD - I/O issue when uploading DTD: " + e.getMessage());
416
		} catch (SecurityException e) {
417
			throw new SAXException("DBEntityResolver.uploadDTD() - Security issue when uploading DTD: " + e.getMessage());
418
		}
419

    
420
		// String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
421
		return dtdURL + filename;
422
	}
423

    
424

    
425
  /**
426
	 * Upload new DTD located at outside URL to Metacat file system
427
	 */
428
	private String uploadDTDFromURL(InputStream istream, String systemId)
429
			throws SAXException {
430
		String dtdPath = null;
431
		String dtdURL = null;
432
		try {
433
			dtdPath = SystemUtil.getContextDir() + "/dtd/";
434
			dtdURL = SystemUtil.getContextURL() + "/dtd/";
435
		} catch (PropertyNotFoundException pnfe) {
436
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Property issue when uploading DTD from URL: "
437
					+ pnfe.getMessage());
438
		}
439

    
440
		// get filename from systemId
441
		String filename = systemId;
442
		int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
443
		if (slash > -1) {
444
			filename = filename.substring(slash + 1);
445
		}
446

    
447
		// writing dtd text on Metacat file system as filename
448
		try {
449
			// create a buffering character-input stream
450
			// that uses a default-sized input buffer
451
			BufferedInputStream in = new BufferedInputStream(istream);
452

    
453
			// open file writer to write the input into it
454
			//String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
455
			File f = new File(dtdPath, filename);
456
			synchronized (f) {
457
				try {
458
					if (f.exists()) {
459
						logMetacat.warn("DBEntityResolver.uploadDTDFromURL - File already exists: " + f.getCanonicalFile());
460
						//return dtdURL + filename;
461
						//throw new IOException("File already exist: "
462
						//		+ f.getCanonicalFile());
463
						//if ( f.exists() && !f.canWrite() ) {
464
						//  throw new IOException("Not writable: " + f.getCanonicalFile());
465
					}
466
				} catch (SecurityException se) {
467
					// if a security manager exists,
468
					// its checkRead method is called for f.exist()
469
					// or checkWrite method is called for f.canWrite()
470
					throw se;
471
				}
472
				// create a buffered character-output stream
473
				// that uses a default-sized output buffer
474
				FileWriter fw = new FileWriter(f);
475
				BufferedWriter out = new BufferedWriter(fw);
476

    
477
				// read the input and write into the file writer
478
				int inputByte;
479
				while ((inputByte = in.read()) != -1) {
480
					out.write(inputByte);
481
					//out.newLine(); //instead of out.write('\r\n');
482
				}
483

    
484
				// the input and the output streams must be closed
485
				in.close();
486
				out.flush();
487
				out.close();
488
				fw.close();
489
			} // end of synchronized
490
		} catch (MalformedURLException e) {
491
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Malformed URL when uploading DTD from URL: "
492
					+ e.getMessage());
493
		} catch (IOException e) {
494
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - I/O issue when uploading DTD from URL:  "
495
					+ e.getMessage());
496
		} catch (SecurityException e) {
497
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Security issue when uploading DTD from URL:  "
498
					+ e.getMessage());
499
		}
500

    
501
		//String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
502
		return dtdURL + filename;
503
	}
504

    
505
	/**
506
	 * Check URL Connection for @systemId, and return an InputStream
507
	 * that can be used to read from the systemId URL.  The parser ends
508
	 * up using this via the InputSource to read the DTD.
509
	 *
510
	 * @param systemId a URI (in practice URL) to be checked and opened
511
	 */
512
	public static InputStream checkURLConnection(String systemId) throws SAXException {
513
		try {
514
			return (new URL(systemId).openStream());
515

    
516
		} catch (MalformedURLException e) {
517
			throw new SAXException("DBEntityResolver.checkURLConnection - Malformed URL when checking URL Connection: "
518
					+ e.getMessage());
519
		} catch (IOException e) {
520
			throw new SAXException("DBEntityResolver.checkURLConnection - I/O issue when checking URL Connection: "
521
					+ e.getMessage());
522
		}
523
	}
524
}
(16-16/64)