Project

General

Profile

« Previous | Next » 

Revision 598

Added by bojilova almost 24 years ago

DBEntityResolver:
- added new parameter dtd for upload on Metacat file system; optional; Reader
- new routines to upload dtd if provided
- systemID of metadata document is used to exctract the filename of new dtd;
- the new dtd is uploaded on Metacat file system as specified by dtdPath property;
- dtdURL property value is return after upload to the parser as a new systemID for metadata doc;
- the doctype of metadata document is used for registering of the new dtd;
- <doctype, dtdURL> is registered in db xml_catalog
AccessControlList:
- changes to use DBEntityResolver as a EntityResolver
DocumentImpl, MetaCatServlet:
- changes related to DTD upload - new servlet parameter dtdtext(optional) for the text of the new DTD;
- dtdtext parameter is expected on INSERT or UPDATE actions

View differences:

src/edu/ucsb/nceas/metacat/MetaCatServlet.java
72 72
 * qformat=html -- display resultset from query in HTML<br>
73 73
 * docid=34 -- display the document with the document ID number 34<br>
74 74
 * doctext -- XML text of the document to load into the database<br>
75
 * acl - xml access file for a document to load into the database<br>
75
 * acltext -- XML access text for a document to load into the database<br>
76
 * dtdtext -- XML DTD text for a new DTD to load into Metacat XML Catalog<br>
76 77
 * query -- actual query text (to go with 'action=query' or 'action=squery')<br>
77 78
 * valtext -- XML text to be validated<br>
78 79
 * action=getdatadoc -- retreive a stored datadocument<br>
......
124 125
      executescript = util.getOption("executescript"); 
125 126
      servletpath = util.getOption("servletpath");
126 127
      htmlpath = util.getOption("htmlpath");
127
/*
128
      try {
129
        // Open a pool of db connections
130
        connectionPool = util.getConnectionPool();
131
      } catch (Exception e) {
132
        System.err.println("Error creating pool of database connections");
133
        System.err.println(e.getMessage());
134
      }
135
*/
128

  
129
//      try {
130
//        // Open a pool of db connections
131
//        connectionPool = util.getConnectionPool();
132
//      } catch (Exception e) {
133
//        System.err.println("Error creating pool of database connections");
134
//        System.err.println(e.getMessage());
135
//      }
136 136
    } catch ( ServletException ex ) {
137 137
      throw ex;
138 138
    }
......
175 175
    if ( util == null ) {
176 176
        util = new MetaCatUtil(); 
177 177
    }
178
    if ( connectionPool == null ) {
178
    if ( connectionPool.isEmpty() ) {
179 179
      try {
180 180
        // Open a pool of db connections
181 181
        connectionPool = util.getConnectionPool();
......
884 884
               HttpServletResponse response) 
885 885
               throws ClassNotFoundException, IOException, SQLException 
886 886
  {
887
//    out.println(((String[])params.get("docid"))[0]);
887
    //out.println(((String[])params.get("docid"))[0]);
888 888
    try {
889 889
      //MetacatURL murl = new MetacatURL(((String[])params.get("docid"))[0]);
890 890
      URL murl = new URL(((String[])params.get("docid"))[0]);
......
963 963
    try {
964 964
      // Get the document indicated
965 965
      String[] doctext = (String[])params.get("doctext");
966
      String[] acltext = null;
967 966

  
968 967
      StringReader acl = null;
969
      if(params.contains("acl"))
968
      if(params.contains("acltext"))
970 969
      {
971
        acltext = (String[])params.get("acl");
970
        String[] acltext = (String[])params.get("acltext");
972 971
        try {
973 972
          acl = new StringReader(acltext[0]);
974 973
        } catch (NullPointerException npe) {}
975 974
      }
975
      StringReader dtd = null;
976
      if(params.contains("dtdtext"))
977
      {
978
        String[] dtdtext = (String[])params.get("dtdtext");
979
        try {
980
          dtd = new StringReader(dtdtext[0]);
981
        } catch (NullPointerException npe) {}
982
      }
976 983
      
977 984
      StringReader xml = null;
978 985
      try {
......
999 1006
                if (accNumber.equals("")) {
1000 1007
                    accNumber = null;
1001 1008
                }
1002
                newdocid = DocumentImpl.write(conn, xml, acl, doAction,
1009
                newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1003 1010
                                              accNumber, user, group);
1004 1011
                
1005 1012
            } catch (NullPointerException npe) {
1006
              newdocid = DocumentImpl.write(conn, xml, acl, doAction,
1013
              newdocid = DocumentImpl.write(conn, xml, acl, dtd, doAction,
1007 1014
                                            null, user, group);
1008 1015
            }
1009 1016
//        } catch (Exception e) {
src/edu/ucsb/nceas/metacat/DocumentImpl.java
589 589

  
590 590
    } catch (SQLException sqle) {
591 591
      throw sqle;
592
//    } catch (AccessionNumberException ane) {
593
//      MetaCatUtil.debugMessage("Invalid accession number.");
594
//      MetaCatUtil.debugMessage(ane.getMessage());
595
//      throw ane;
596 592
    } catch (Exception e) {
597 593
      throw e;
598 594
    }
......
633 629
  }
634 630

  
635 631
  /**
636
   * Look up the title of the first child element named "title"
637
   * and record it as the document title
638
   */
639
/*   NOT NEEDED ANY MORE
640
  public void setTitleFromChildElement() {
641
    String title = null;
642
    long assigned_id=0;
643
    PreparedStatement pstmt;
644
    try {
645
      pstmt = conn.prepareStatement(
646
              "SELECT nodedata FROM xml_nodes " +
647
              "WHERE nodetype = 'TEXT' " +
648
              "AND rootnodeid = ? " +
649
              "AND parentnodeid IN " +
650
              "  (SELECT nodeid FROM xml_nodes " +
651
              "  WHERE nodename = 'title' " +
652
              "  AND nodetype =  'ELEMENT' " +
653
              "  AND rootnodeid = ? ) " +
654
              "ORDER BY nodeid");
655
*/
656
      // The above query might be slow, and probably will be because
657
      // it gets ALL of the title elements while searching for one
658
      // title in a small subtree but it avoids the problem of using
659
      // Oracle's Hierarchical Query syntax which is not portable --
660
      // the commented out SQL that follows shows an equivalent query
661
      // using Oracle-specific hierarchical query
662
      /*
663
      pstmt = conn.prepareStatement(
664
              "SELECT nodedata FROM xml_nodes " +
665
              "WHERE nodetype = 'TEXT' " +
666
              "AND parentnodeid IN " +
667
              "(SELECT nodeid FROM xml_nodes " +
668
              "WHERE nodename = 'title' " +
669
              "START WITH nodeid = ? " +
670
              "CONNECT BY PRIOR nodeid = parentnodeid)");
671
      */
672
/*
673
      // Bind the values to the query
674
      pstmt.setLong(1, rootnodeid);
675
      pstmt.setLong(2, rootnodeid);
676

  
677
      pstmt.execute();
678
      ResultSet rs = pstmt.getResultSet();
679
      boolean tableHasRows = rs.next();
680
      if (tableHasRows) {
681
        title = rs.getString(1);
682
      }
683
      pstmt.close();
684
    } catch (SQLException e) {
685
      System.out.println("Error getting title: " + e.getMessage());
686
    }
687

  
688
    // assign the new title
689
    this.setTitle(title);
690
  }
691
*/
692

  
693
  /**
694 632
   * Write an XML file to the database, given a filename
695 633
   *
696 634
   * @param conn the JDBC connection to the database
......
698 636
   * @param action the action to be performed (INSERT OR UPDATE)
699 637
   * @param docid the docid to use for the INSERT OR UPDATE
700 638
   */
701
  public static String write( Connection conn, String filename,
702
                              String aclfilename, String action, String docid,
703
                              String user, String group )
639
  public static String write(Connection conn,String filename,
640
                             String aclfilename,String dtdfilename,
641
                             String action, String docid, String user,
642
                             String group )
704 643
                throws Exception {
644
                  
645
    Reader acl = null;
646
    if ( aclfilename != null ) {
647
      acl = new FileReader(new File(aclfilename).toString());
648
    }
649
    Reader dtd = null;
650
    if ( dtdfilename != null ) {
651
      dtd = new FileReader(new File(dtdfilename).toString());
652
    }
705 653
    return write ( conn, new FileReader(new File(filename).toString()),
706
                   new FileReader(new File(aclfilename).toString()),
707
                   action, docid, user, group);
654
                   acl, dtd, action, docid, user, group);
708 655
  }
709
  
710
  public static String write( Connection conn, Reader xml, Reader acl, 
711
                              String action, String docid, String user,
712
                              String group )
656

  
657
  public static String write(Connection conn,Reader xml,Reader acl,Reader dtd,
658
                             String action, String docid, String user,
659
                             String group )
713 660
                throws Exception {
661
    return write ( conn, xml, acl, dtd, action, docid, user, group, 1, false);
662
  }
663

  
664
  public static String write(Connection conn,Reader xml,Reader acl,
665
                             String action, String docid, String user,
666
                             String group )
667
                throws Exception {
714 668
    if(action.equals("UPDATE"))
715 669
    {//if the document is being updated then use the servercode from the 
716 670
     //originally inserted document.
717 671
      DocumentImpl doc = new DocumentImpl(conn, docid);
718 672
      int servercode = doc.getServerlocation();
719
      return write(conn, xml, acl, action, docid, user, group, servercode);
673
      return write(conn,xml,acl,action,docid,user,group,servercode);
720 674
    }
721 675
    else
722 676
    {//if the file is being inserted then the servercode is always 1
......
727 681
  public static String write( Connection conn, Reader xml,
728 682
                              String action, String docid, String user,
729 683
                              String group, int serverCode )
730
                              throws Exception
684
                throws Exception
731 685
  {
732
    return write(conn, xml, null, action, docid, user, group, serverCode); 
686
    return write(conn,xml,null,action,docid,user,group,serverCode);
733 687
  }
734 688
  
735
  public static String write( Connection conn, Reader xml, Reader acl,
689
  public static String write( Connection conn,Reader xml,Reader acl,
736 690
                              String action, String docid, String user,
737
                              String group, int serverCode) throws Exception
691
                              String group, int serverCode) 
692
                throws Exception
738 693
  {
739
    return write(conn, xml, acl, action, docid, user, group, serverCode, false);
694
    return write(conn,xml,acl,null,action,docid,user,group,serverCode,false);
740 695
  }
741 696
  
742 697
  /**
......
757 712
   *        update will be locked and version checked.
758 713
   */
759 714

  
760
  public static String write( Connection conn, Reader xml, Reader acl,
715
  public static String write( Connection conn,Reader xml,Reader acl,Reader dtd,
761 716
                              String action, String docid, String user,
762 717
                              String group, int serverCode, boolean override)
763
                              throws Exception 
718
                throws Exception
764 719
  {
765 720
    MetaCatUtil util = new MetaCatUtil();
766 721
        // Determine if the docid is OK for INSERT or UPDATE
......
794 749
        {
795 750
          MetacatReplication.replLog("lock granted for " + docid + " from " +
796 751
                                      server);
797
          XMLReader parser = initializeParser(conn,action,newdocid,user,
798
                                              serverCode);
752
          XMLReader parser = initializeParser(conn, action, newdocid, user,
753
                                              serverCode, dtd);
799 754
          conn.setAutoCommit(false);
800 755
          parser.parse(new InputSource(xml));
801 756
          conn.commit();
......
866 821

  
867 822
    try 
868 823
    {
869
      XMLReader parser = initializeParser(conn,action,newdocid,user,serverCode);
824
      XMLReader parser=initializeParser(conn,action,newdocid,user,serverCode,dtd);
870 825
      conn.setAutoCommit(false);
871 826
      parser.parse(new InputSource(xml));
872 827
      conn.commit();
......
967 922
  /**
968 923
   * Set up the parser handlers for writing the document to the database
969 924
   */
970
  private static XMLReader initializeParser(Connection conn,
971
                           String action, String docid, String user, int serverCode) 
972
                           throws Exception {
925
  private static XMLReader initializeParser(Connection conn, String action,
926
                                            String docid, String user,
927
                                            int serverCode, Reader dtd) 
928
                           throws Exception 
929
  {
973 930
    XMLReader parser = null;
974 931
    //
975 932
    // Set up the SAX document handlers for parsing
976 933
    //
977 934
    try {
978
      ContentHandler chandler   = new DBSAXHandler(conn, action, docid, user, serverCode);
979
      EntityResolver dbresolver = new DBEntityResolver(conn, 
980
                                      (DBSAXHandler)chandler);
981
      DTDHandler dtdhandler     = new DBDTDHandler(conn);
935
      ContentHandler chandler = new DBSAXHandler(conn,action,docid,user,serverCode);
936
      EntityResolver eresolver= new DBEntityResolver(conn,(DBSAXHandler)chandler,dtd);
937
      DTDHandler dtdhandler   = new DBDTDHandler(conn);
982 938

  
983 939
      // Get an instance of the parser
984 940
      MetaCatUtil util = new MetaCatUtil();
......
994 950
      parser.setProperty("http://xml.org/sax/properties/lexical-handler",
995 951
                         chandler);
996 952
      parser.setContentHandler((ContentHandler)chandler);
997
      parser.setEntityResolver((EntityResolver)dbresolver);
953
      parser.setEntityResolver((EntityResolver)eresolver);
998 954
      parser.setDTDHandler((DTDHandler)dtdhandler);
999 955
      parser.setErrorHandler((ErrorHandler)chandler);
1000 956

  
......
1043 999
    try {
1044 1000
      String filename    = null;
1045 1001
      String aclfilename = null;
1002
      String dtdfilename = null;
1046 1003
      String action      = null;
1047 1004
      String docid       = null;
1048 1005
      boolean showRuntime = false;
......
1054 1011
          filename =  args[++i];
1055 1012
        } else if ( args[i].equals( "-c" ) ) {
1056 1013
          aclfilename =  args[++i];
1014
        } else if ( args[i].equals( "-r" ) ) {
1015
          dtdfilename =  args[++i];
1057 1016
        } else if ( args[i].equals( "-a" ) ) {
1058 1017
          action =  args[++i];
1059 1018
        } else if ( args[i].equals( "-d" ) ) {
......
1094 1053
      if (!argsAreValid) {
1095 1054
        System.err.println("Wrong number of arguments!!!");
1096 1055
        System.err.println(
1097
          "USAGE: java DocumentImpl [-t] <-a INSERT> [-d docid] <-f filename> [-c aclfilename]");
1056
          "USAGE: java DocumentImpl [-t] <-a INSERT> [-d docid] <-f filename> "+
1057
          "[-c aclfilename] [-r dtdfilename]");
1098 1058
        System.err.println(
1099
          "   OR: java DocumentImpl [-t] <-a UPDATE -d docid -f filename> [-c aclfilename]");
1059
          "   OR: java DocumentImpl [-t] <-a UPDATE -d docid -f filename> " +
1060
          "[-c aclfilename] [-r dtdfilename]");
1100 1061
        System.err.println(
1101 1062
          "   OR: java DocumentImpl [-t] <-a DELETE -d docid>");
1102 1063
        System.err.println(
......
1125 1086
        System.out.println("Document deleted: " + docid);
1126 1087
      } else {
1127 1088
        String newdocid = DocumentImpl.write(dbconn, filename, aclfilename,
1128
                                             action, docid, null, null);
1089
                                             dtdfilename, action, docid,
1090
                                             null, null);
1129 1091
        if ((docid != null) && (!docid.equals(newdocid))) {
1130 1092
          if (action.equals("INSERT")) {
1131 1093
            System.out.println("New document ID generated!!! ");
src/edu/ucsb/nceas/metacat/DBEntityResolver.java
15 15
package edu.ucsb.nceas.metacat;
16 16

  
17 17
import org.xml.sax.*;
18
import org.xml.sax.helpers.DefaultHandler;
18 19

  
19 20
import java.sql.*;
20 21
import java.io.File;
21
import java.io.FileReader;
22
import java.io.Reader;
23
import java.io.BufferedReader;
24
import java.io.FileWriter;
25
import java.io.BufferedWriter;
22 26
import java.io.InputStream;
23 27
import java.io.IOException;
24 28
import java.net.URL;
25 29
import java.net.URLConnection;
26 30
import java.net.MalformedURLException;
27
import java.util.Stack;
28
import java.util.EmptyStackException;
29 31

  
30 32
/** 
31 33
 * A database aware Class implementing EntityResolver interface for the SAX 
......
35 37
 */
36 38
public class DBEntityResolver implements EntityResolver
37 39
{
38
   private Connection conn = null;
39
   private DBSAXHandler handler = null;
40
  private Connection conn = null;
41
  private DefaultHandler handler = null;
42
  private String docname = null;
43
  private String doctype = null;
44
  private String systemid = null;
45
  private Reader dtdtext = null;
40 46

  
41
   /** 
42
    * Construct an instance of the DBEntityResolver class
43
    *
44
    * @param conn the JDBC connection to which information is written
45
    */
46
   public DBEntityResolver(Connection conn)
47
   {
48
      this.conn = conn;
49
   }
50

  
51
   /** 
52
    * Construct an instance of the DBEntityResolver class
53
    *
54
    * @param conn the JDBC connection to which information is written
55
    * @param handler the SAX handler to determine parsing context
56
    */
57
   public DBEntityResolver(Connection conn, DBSAXHandler handler)
58
   {
59
      this(conn);
60
      this.handler = handler;
61
   }
47
  /** 
48
   * Construct an instance of the DBEntityResolver class
49
   *
50
   * @param conn the JDBC connection to which information is written
51
   * @param handler the SAX handler to determine parsing context
52
   * @param dtd Reader of new dtd to be uploaded on server's file system
53
   */
54
  public DBEntityResolver(Connection conn, DefaultHandler handler, Reader dtd)
55
  {
56
    this.conn = conn;
57
    this.handler = handler;
58
    this.dtdtext = dtd;
59
  }
62 60
   
63
   /** 
64
    * The Parser call this method before opening any external entity 
65
    * except the top-level document entity (including the external DTD subset,
66
    * external entities referenced within the DTD, and external entities 
67
    * referenced within the document element)
68
    */
69
   public InputSource resolveEntity (String publicId, String systemId)
70
                throws SAXException, IOException
71
   {
72
     String dbSystemId;
73
     String doctype = null;
74
     
75
     if (publicId != null) {       // If we have a public ID, use it
76
       doctype = publicId;
77
       MetaCatUtil.debugMessage("DOCTYPE-c: " + doctype);
78
     } else if (systemId != null) {  // Otherwise, use system id if we can
79
       if (handler != null) {        // Won't have a handler under all cases
80
         if (handler.processingDTD()) {  // Assume the public ID is the docname
81
           doctype = handler.getDocname();
82
           MetaCatUtil.debugMessage("DOCTYPE-d: " + doctype);
83
         }
84
       }
85
     }    
86

  
87
     // look at the db XML Catalog and get dbSystemId for this doctype
88
     if (doctype != null) {
89
       dbSystemId = getDTDSystemID (conn, doctype);
90
       if (dbSystemId == null) {
91
         MetaCatUtil.debugMessage("  RESOLVED NOTHING");
92
         // if it is not found in the database, then
93
         // register publicId in db and use the provided systemId
94
         if (systemId != null) {
95
           InputStream istream = checkURLConnection(systemId);
96
           if (handler != null) {    // Won't have a handler under all cases
97
             if (handler.processingDTD()) {
98
               registerDTDSystemID (conn, doctype, doctype, systemId);
99
             }
100
           }
101
           return null;
102
         }
103
       } else {
104
         MetaCatUtil.debugMessage("  RESOLVED SYSTEMID: " + dbSystemId);
105
         // If it is in the database, return the systemid from the database
106
         InputStream istream = checkURLConnection(dbSystemId);
107
         InputSource is = new InputSource(dbSystemId);
108
         is.setByteStream(istream);
109
         MetaCatUtil.debugMessage("  INPUTSOURCE SYSTEMID: " 
110
                                      + is.getSystemId());
111
         return is;
112
       } 
113
     }
61
  /** 
62
   * The Parser call this method before opening any external entity 
63
   * except the top-level document entity (including the external DTD subset,
64
   * external entities referenced within the DTD, and external entities 
65
   * referenced within the document element)
66
   */
67
  public InputSource resolveEntity (String publicId, String systemId)
68
                     throws SAXException
69
  {
70
    String dbSystemID;
71
    String doctype = null;
114 72
    
115
     // use the provided systemID for other cases
116
     InputStream istream = checkURLConnection(systemId);
117
     return null;
118
   }
119

  
120
   /** 
121
    * Look at db XML Catalog to get System ID (if any) for that doctype.
122
    * Return empty string if there are not 
123
    */
124
   private String getDTDSystemID (Connection conn, String doctype)  {
125
        String system_id = null;
126
        Statement stmt;
127
        try {
128
          stmt = conn.createStatement();
129
          stmt.execute("SELECT system_id FROM xml_catalog " + 
130
                       "WHERE entry_type = 'DTD' AND public_id = '" + 
131
                       doctype + "'");
132
          try {
133
            ResultSet rs = stmt.getResultSet();
134
            try {
135
              boolean tableHasRows = rs.next();
136
              if (tableHasRows) {
137
                try {
138
                  system_id = rs.getString(1);
139
                } catch (SQLException e) {
140
                  System.out.println("DBEntityResolver.getDTDSystemID() " +
141
                             "- Error with getString: " + e.getMessage());
142
                }
143
              }
144
            } catch (SQLException e) {
145
              System.out.println("DBEntityResolver.getDTDSystemID() " +
146
                             "- Error with next: " + e.getMessage());
147
            }
148
          } catch (SQLException e) {
149
            System.out.println("DBEntityResolver.getDTDSystemID() " +
150
                             "- Error with getrset: " + e.getMessage());
73
    // Won't have a handler under all cases
74
    if ( handler != null ) {
75
      if ( handler instanceof DBSAXHandler ) {
76
        DBSAXHandler dhandler = null;
77
        dhandler = (DBSAXHandler)handler;
78
        if ( dhandler.processingDTD() ) {
79
          // public ID is doctype
80
          if (publicId != null) {   
81
            doctype = publicId;
82
          // assume public ID (doctype) is docname
83
          } else if (systemId != null) {
84
            doctype = dhandler.getDocname();
151 85
          }
152
          stmt.close();
153
        } catch (SQLException e) {
154
          System.out.println("DBEntityResolver.getDTDSystemID() " +
155
                             "- Error getting id: " + e.getMessage());
156 86
        }
87
      } else if ( handler instanceof AccessControlList ) {
88
        AccessControlList ahandler = null;
89
        ahandler = (AccessControlList)handler;
90
        //if ( ahandler.processingDTD() ) {
91
          // public ID is doctype
92
          if (publicId != null) {   
93
            doctype = publicId;
94
          // assume public ID (doctype) is docname
95
          } else if (systemId != null) {
96
            doctype = ahandler.getDocname();
97
          }
98
        //}
99
      }
100
    }
157 101

  
158
        // return the selected System ID
159
        return system_id;
160
   }
102
    // get System ID for doctype
103
    if (doctype != null) {
104
      // look at db XML Catalog for System ID 
105
      dbSystemID = getDTDSystemID(doctype);
106
      boolean doctypeIsInDB = true;
107
      // no System ID found in db XML Catalog
108
      if (dbSystemID == null) {
109
        doctypeIsInDB = false;
110
        // use the provided System ID
111
        if (systemId != null) {
112
          dbSystemID = systemId;
113
        }
114
      }
161 115

  
162
   /** 
163
    * Register DTD System ID in db XML Catalog 
164
    */
165
   private void registerDTDSystemID (Connection conn, String doctype, 
166
                                     String publicId, String systemId)
167
   {
168
     try {
169
       PreparedStatement pstmt;
170
       pstmt = conn.prepareStatement(
116
      // there are dtd text provided; try to upload on Metacat
117
      if ( dtdtext != null ) {
118
        dbSystemID = uploadDTD(dbSystemID);
119
      }
120

  
121
      // check URLConnection first
122
      InputStream istream = checkURLConnection(dbSystemID);
123

  
124
      // need to register System ID in db XML Catalog if not yet
125
      if ( !doctypeIsInDB ) {
126
        registerDTD(doctype, dbSystemID);
127
      }
128
      
129
      // return a byte-input stream for use
130
      InputSource is = new InputSource(dbSystemID); 
131
      //is.setPublicId(doctype);
132
      //is.setSystemId(dbSystemID);
133
      is.setByteStream(istream);
134
      return is;
135

  
136
    } else {
137
      // use the provided systemId for other cases
138
      InputStream istream = checkURLConnection(systemId);
139
      return null;
140
      
141
    }
142
    
143
  }
144

  
145
  /** 
146
   * Look at db XML Catalog to get System ID (if any) for @doctype.
147
   * Return null if there are no System ID found for @doctype
148
   */
149
  private String getDTDSystemID( String doctype )
150
                 throws SAXException
151
  {
152
    String systemid = null;
153
    Statement stmt;
154
    try {
155
      stmt = conn.createStatement();
156
      stmt.execute("SELECT system_id FROM xml_catalog " + 
157
                   "WHERE entry_type = 'DTD' AND public_id = '" +
158
                   doctype + "'");
159
      ResultSet rs = stmt.getResultSet();
160
      boolean tableHasRows = rs.next();
161
      if (tableHasRows) {
162
        systemid = rs.getString(1);
163
      }
164
      stmt.close();
165
    } catch (SQLException e) {
166
      throw new SAXException
167
      ("DBEntityResolver.getDTDSystemID(): " + e.getMessage());
168
    }
169

  
170
    // return the selected System ID
171
    return systemid;
172
  }
173

  
174
  /** 
175
   * Register new DTD identified by @systemId in Metacat XML Catalog 
176
   * . make a reference with @systemId for @doctype in Metacat DB
177
   */
178
  private void registerDTD ( String doctype, String systemId )
179
                 throws SAXException
180
  {
181
    // make a reference in db catalog table with @systemId for @doctype
182
    try {
183
      PreparedStatement pstmt;
184
      pstmt = conn.prepareStatement(
171 185
             "INSERT INTO xml_catalog " +
172
             "(catalog_id, entry_type, source_doctype, " +
173
             "public_id, system_id) " +
174
             "VALUES (null, 'DTD', ?, ?, ?)");
175
       // Bind the values to the query
176
       pstmt.setString(1, doctype);
177
       pstmt.setString(2, publicId);
178
       pstmt.setString(3, systemId);
179
       // Do the insertion
180
       pstmt.execute();
181
       pstmt.close();
182
     } catch (SQLException e) {
183
       System.out.println(e.getMessage());
184
     }
185
   }
186
             "(catalog_id, entry_type, public_id, system_id) " +
187
             "VALUES (null, 'DTD', ?, ?)");
188
      // Bind the values to the query
189
      pstmt.setString(1, doctype);
190
      pstmt.setString(2, systemId);
191
      // Do the insertion
192
      pstmt.execute();
193
      pstmt.close();
194
    } catch (SQLException e) {
195
      throw new SAXException
196
      ("DBEntityResolver.registerDTD(): " + e.getMessage());
197
    }
198
  }
186 199

  
187
   /** 
188
    * Check URL Connection for systemId, and return an InputStream
189
    * that can be used to read from the systemId URL.  The parser ends
190
    * up using this via the InputSource to read the DTD.
191
    *
192
    * @param systemID a URI (in practice URL) to be checked and opened
193
    */
194
   private InputStream checkURLConnection (String systemId)
195
                throws MalformedURLException, IOException
196
   {
197
     try {
200
  /** 
201
   * Upload new DTD text identified by @systemId on Metacat file system
202
   */
203
  private String uploadDTD ( String systemId )
204
                 throws SAXException
205
  {
206
    MetaCatUtil util = new MetaCatUtil();
207
    String dtdPath = util.getOption("dtdPath");
208
    String dtdURL = util.getOption("dtdURL");
209
    
210
    // get filename from systemId
211
    String filename = systemId;
212
    int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
213
    if ( slash > -1 ) {
214
      filename = filename.substring(slash + 1);
215
    }
198 216

  
199
       return (new URL(systemId).openStream());
217
    // writing dtd text on Metacat file system as filename
218
    try {
219
      // create a buffering character-input stream
220
      // that uses a default-sized input buffer
221
      BufferedReader in = new BufferedReader(dtdtext);
200 222

  
201
     } catch (MalformedURLException e) {
202
       System.out.println("from checkURLConnection(): " + e.getMessage());
203
       throw e;
204
     } catch (IOException e) {
205
       System.out.println("from checkURLConnection(): " + e.getMessage());
206
       throw e;
207
     }    
208
   }   
223
      // open file writer to write the input into it
224
      //String dtdPath = "/opt/tomcat/webapps/bojilova/dtd/";
225
      File f = new File(dtdPath, filename);
226
      try {
227
        if ( f.exists() && !f.canWrite() ) {
228
          throw new IOException("Not writable: " + f.getCanonicalFile());
229
        }
230
      } catch (SecurityException se) {
231
        // if a security manager exists,
232
        // its checkRead method is called for f.exist()
233
        // or checkWrite method is called for f.canWrite()
234
        throw se;
235
      }
236
      // create a buffered character-output stream
237
      // that uses a default-sized output buffer
238
      FileWriter fw = new FileWriter(f);
239
      BufferedWriter out = new BufferedWriter(fw);
240

  
241
      // read the input and write into the file writer
242
	    String inputLine;
243
	    while ( (inputLine = in.readLine()) != null ) {
244
	      out.write(inputLine, 0, inputLine.length());
245
  	    out.newLine(); //instead of out.write('\r\n');
246
	    }
247

  
248
      // the input and the output streams must be closed
249
	    in.close();
250
	    out.flush();
251
	    out.close();
252
	    fw.close();
253
      
254
    } catch (MalformedURLException e) {
255
      throw new SAXException
256
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
257
    } catch (IOException e) {
258
      throw new SAXException
259
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
260
    } catch (SecurityException e) {
261
      throw new SAXException
262
      ("DBEntityResolver.uploadDTD(): " + e.getMessage());
263
    }
264
    
265
    //String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
266
    return  dtdURL + filename;
267
  }
268

  
269
  /** 
270
   * Check URL Connection for @systemId, and return an InputStream
271
   * that can be used to read from the systemId URL.  The parser ends
272
   * up using this via the InputSource to read the DTD.
273
   *
274
   * @param systemId a URI (in practice URL) to be checked and opened
275
   */
276
  private InputStream checkURLConnection (String systemId)
277
                      throws SAXException
278
  {
279
    try {
280

  
281
      return (new URL(systemId).openStream());
282

  
283
    } catch (MalformedURLException e) {
284
      throw new SAXException
285
      ("DBEntityResolver.checkURLConnection(): " + e.getMessage());
286
    } catch (IOException e) {
287
      throw new SAXException
288
      ("DBEntityResolver.checkURLConnection(): " + e.getMessage());
289
    }    
290
  }   
209 291
}
210 292

  
211 293
/**
212 294
 * '$Log$
295
 * 'Revision 1.15  2000/08/14 20:53:33  jones
296
 * 'Added "release" keyword to all metacat source files so that the release
297
 * 'number will be evident in software distributions.
298
 * '
213 299
 * 'Revision 1.14  2000/06/30 00:52:04  jones
214 300
 * 'changed char stream to byte stream
215 301
 * '
src/edu/ucsb/nceas/metacat/AccessControlList.java
21 21

  
22 22
import org.xml.sax.Attributes;
23 23
import org.xml.sax.InputSource;
24
import org.xml.sax.ContentHandler;
25
import org.xml.sax.EntityResolver;
26
import org.xml.sax.ErrorHandler;
24 27
import org.xml.sax.SAXException;
25 28
import org.xml.sax.SAXParseException;
26 29
import org.xml.sax.XMLReader;
......
42 45
  private String parserName;
43 46
  private Stack elementStack;
44 47

  
48
  private boolean	processingDTD;
49
  private String 	docname;
50
  private String 	doctype;
51
  private String 	systemid;
52

  
45 53
  private String resourceId;
46 54
  private Vector principalName;
47 55
  private int    permission;
......
50 58
  private String beginTime;
51 59
  private String endTime;
52 60
  private int    ticketCount;
53
  
61

  
54 62
  /**
55 63
   * Construct an instance of the AccessControlList class.
56 64
   * It is used by the permission check up from DBQuery and DocumentImpl
......
79 87

  
80 88
    this.conn = conn;
81 89
    this.parserName = parserName;
90
    this.processingDTD = false;
82 91
    this.elementStack = new Stack();
83 92
    
84 93
    this.principalName = new Vector();
......
115 124
    // Get an instance of the parser
116 125
    parser = XMLReaderFactory.createXMLReader(parserName);
117 126

  
127
    // Turn off validation
128
    parser.setFeature("http://xml.org/sax/features/validation", false);
129
      
130
    // Set Handlers in the parser
118 131
    // Set the ContentHandler to this instance
119
    parser.setContentHandler(this);
132
    parser.setContentHandler((ContentHandler)this);
120 133

  
134
    // make a DBEntityResolver instance
135
    // Set the EntityReslover to DBEntityResolver instance
136
    EntityResolver eresolver = new DBEntityResolver(conn,this,null);
137
    parser.setEntityResolver((EntityResolver)eresolver);
138

  
121 139
    // Set the ErrorHandler to this instance
122
    parser.setErrorHandler(this);
140
    parser.setErrorHandler((ErrorHandler)this);
123 141

  
124 142
    return parser;
125 143
  }
......
237 255
    }
238 256

  
239 257
  }
240
                          
258

  
259
  /** SAX Handler that receives notification of DOCTYPE. Sets the DTD */
260
  public void startDTD(String name, String publicId, String systemId) 
261
              throws SAXException {
262
    docname = name;
263
    doctype = publicId;
264
    systemid = systemId;
265
//    processingDTD = true;
266
  }
267

  
268
  /** 
269
   * SAX Handler that receives notification of the start of entities
270
   */
271
  public void startEntity(String name) throws SAXException {
272
    if (name.equals("[dtd]")) {
273
      processingDTD = true;
274
    }
275
  }
276

  
277
  /** 
278
   * SAX Handler that receives notification of the end of entities
279
   */
280
  public void endEntity(String name) throws SAXException {
281
    if (name.equals("[dtd]")) {
282
      processingDTD = false;
283
    }
284
  }
285

  
286
  /**
287
   * get the document name
288
   */
289
  public String getDocname() {
290
    return docname;
291
  }
292

  
293
  /**
294
   * get the document processing state
295
   */
296
  public boolean processingDTD() {
297
    return processingDTD;
298
  }
299
  
241 300
  /** Insert into db calculated permission for the list of principals */
242 301
  private void insertPermissions( String permType ) 
243 302
          throws SQLException 

Also available in: Unified diff