Project

General

Profile

Revision 2075

Added by Matt Jones over 16 years ago

Reformatted DBQuery.java for readability and consistency.

View differences:

src/edu/ucsb/nceas/metacat/DBQuery.java
57 57
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
58 58

  
59 59
/**
60
 * A Class that searches a relational DB for elements and
61
 * attributes that have free text matches a query string,
62
 * or structured query matches to a path specified node in the
63
 * XML hierarchy.  It returns a result set consisting of the
64
 * document ID for each document that satisfies the query
60
 * A Class that searches a relational DB for elements and attributes that have
61
 * free text matches a query string, or structured query matches to a path
62
 * specified node in the XML hierarchy. It returns a result set consisting of
63
 * the document ID for each document that satisfies the query
65 64
 */
66
public class DBQuery {
65
public class DBQuery
66
{
67 67

  
68
  static final int ALL = 1;
69
  static final int WRITE = 2;
70
  static final int READ = 4;
68
    static final int ALL = 1;
71 69

  
72
  //private Connection  conn = null;
73
  private String  parserName = null;
74
  private MetaCatUtil util = new MetaCatUtil();
75
  
76
  /**
77
   * the main routine used to test the DBQuery utility.
78
   * <p>
79
   * Usage: java DBQuery <xmlfile>
80
   *
81
   * @param xmlfile the filename of the xml file containing the query
82
   */
83
  static public void main(String[] args) {
70
    static final int WRITE = 2;
84 71

  
85
     if (args.length < 1)
86
     {
87
        System.err.println("Wrong number of arguments!!!");
88
        System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
89
        return;
90
     } else {
91
        try {
72
    static final int READ = 4;
92 73

  
93
          int i = 0;
94
          boolean showRuntime = false;
95
          boolean useXMLIndex = false;
96
          if ( args[i].equals( "-t" ) ) {
97
            showRuntime = true;
98
            i++;
99
          }
100
          if ( args[i].equals( "-index" ) ) {
101
            useXMLIndex = true;
102
            i++;
103
          }
104
          String xmlfile  = args[i];
74
    //private Connection conn = null;
75
    private String parserName = null;
105 76

  
106
          // Time the request if asked for
107
          double startTime = System.currentTimeMillis();
77
    private MetaCatUtil util = new MetaCatUtil();
108 78

  
109
          // Open a connection to the database
110
          MetaCatUtil   util = new MetaCatUtil();
111
          //Connection dbconn = util.openDBConnection();
79
    /**
80
     * the main routine used to test the DBQuery utility.
81
     * <p>
82
     * Usage: java DBQuery <xmlfile>
83
     * 
84
     * @param xmlfile the filename of the xml file containing the query
85
     */
86
    static public void main(String[] args)
87
    {
112 88

  
113
          double connTime = System.currentTimeMillis();
89
        if (args.length < 1) {
90
            System.err.println("Wrong number of arguments!!!");
91
            System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
92
            return;
93
        } else {
94
            try {
114 95

  
115
          // Execute the query
116
          DBQuery queryobj = new DBQuery(MetaCatUtil.getOption("saxparser"));
117
          FileReader xml = new FileReader(new File(xmlfile));
118
          Hashtable nodelist = null;
119
          nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
96
                int i = 0;
97
                boolean showRuntime = false;
98
                boolean useXMLIndex = false;
99
                if (args[i].equals("-t")) {
100
                    showRuntime = true;
101
                    i++;
102
                }
103
                if (args[i].equals("-index")) {
104
                    useXMLIndex = true;
105
                    i++;
106
                }
107
                String xmlfile = args[i];
120 108

  
121
          // Print the reulting document listing
122
          StringBuffer result = new StringBuffer();
123
          String document = null;
124
          String docid = null;
125
          result.append("<?xml version=\"1.0\"?>\n");
126
          result.append("<resultset>\n");
109
                // Time the request if asked for
110
                double startTime = System.currentTimeMillis();
127 111

  
128
          if (!showRuntime)
129
          {
130
            Enumeration doclist = nodelist.keys();
131
            while (doclist.hasMoreElements()) {
132
              docid = (String)doclist.nextElement();
133
              document = (String)nodelist.get(docid);
134
              result.append("  <document>\n    " + document +
135
                            "\n  </document>\n");
136
            }
112
                // Open a connection to the database
113
                MetaCatUtil util = new MetaCatUtil();
114
                //Connection dbconn = util.openDBConnection();
137 115

  
138
            result.append("</resultset>\n");
139
          }
140
          // Time the request if asked for
141
          double stopTime = System.currentTimeMillis();
142
          double dbOpenTime = (connTime - startTime)/1000;
143
          double readTime = (stopTime - connTime)/1000;
144
          double executionTime = (stopTime - startTime)/1000;
145
          if (showRuntime) {
146
            System.out.print("  " + executionTime);
147
            System.out.print("  " + dbOpenTime);
148
            System.out.print("  " + readTime);
149
            System.out.print("  " + nodelist.size());
150
            System.out.println();
151
          }
152
          //System.out.println(result);
153
          //write into a file "result.txt"
154
          if (!showRuntime)
155
          {
156
            File f = new File("./result.txt");
157
            FileWriter fw = new FileWriter(f);
158
            BufferedWriter out = new BufferedWriter(fw);
159
            out.write(result.toString());
160
            out.flush();
161
            out.close();
162
            fw.close();
163
          }
116
                double connTime = System.currentTimeMillis();
164 117

  
165
        }
166
        catch (Exception e) {
167
          System.err.println("Error in DBQuery.main");
168
          System.err.println(e.getMessage());
169
          e.printStackTrace(System.err);
170
        }
171
     }
172
  }
118
                // Execute the query
119
                DBQuery queryobj = new DBQuery(MetaCatUtil
120
                        .getOption("saxparser"));
121
                FileReader xml = new FileReader(new File(xmlfile));
122
                Hashtable nodelist = null;
123
                nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
173 124

  
174
  /**
175
   * construct an instance of the DBQuery class
176
   *
177
   * <p>Generally, one would call the findDocuments() routine after creating
178
   * an instance to specify the search query</p>
179
   *
180
   * @param conn the JDBC connection that we use for the query
181
   * @param parserName the fully qualified name of a Java class implementing
182
   *                   the org.xml.sax.XMLReader interface
183
   */
184
  public DBQuery(String parserName )
185
                  throws IOException,
186
                         SQLException,
187
                         ClassNotFoundException {
188
    //this.conn = conn;
189
    this.parserName = parserName;
190
  }
125
                // Print the reulting document listing
126
                StringBuffer result = new StringBuffer();
127
                String document = null;
128
                String docid = null;
129
                result.append("<?xml version=\"1.0\"?>\n");
130
                result.append("<resultset>\n");
191 131

  
192
  /**
193
   * routine to search the elements and attributes looking to match query
194
   *
195
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
196
   * @param user the username of the user
197
   * @param group the group of the user
198
   */
199
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups)
200
  {
201
    boolean useXMLIndex = (new Boolean(
202
            MetaCatUtil.getOption("usexmlindex"))).booleanValue();
203
    return findDocuments(xmlquery, user, groups, useXMLIndex);
204
  }
132
                if (!showRuntime) {
133
                    Enumeration doclist = nodelist.keys();
134
                    while (doclist.hasMoreElements()) {
135
                        docid = (String) doclist.nextElement();
136
                        document = (String) nodelist.get(docid);
137
                        result.append("  <document>\n    " + document
138
                                + "\n  </document>\n");
139
                    }
205 140

  
206
  /**
207
   * routine to search the elements and attributes looking to match query
208
   *
209
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
210
   * @param user the username of the user
211
   * @param group the group of the user
212
   * @param useXMLIndex flag whether to search using the path index
213
   */
214
  public Hashtable findDocuments(Reader xmlquery, String user, String[] groups,
215
                                 boolean useXMLIndex)
216
  {
217
      Hashtable result = new Hashtable();
218
      try
219
      {
220
        // Get the XML query and covert it into a SQL statment
221
        QuerySpecification qspec = new QuerySpecification(xmlquery,
222
                                   parserName,
223
                                   MetaCatUtil.getOption("accNumSeparator"));
224
        result = findDocuments(qspec, user, groups, useXMLIndex);
225
      }
226
      catch (IOException ioe)
227
      {
228
        MetaCatUtil.debugMessage("IO error in DBQuery.findDocuments:", 30);
229
        MetaCatUtil.debugMessage(ioe.getMessage(), 30);
230
      }
231
      return result;
232
  }
141
                    result.append("</resultset>\n");
142
                }
143
                // Time the request if asked for
144
                double stopTime = System.currentTimeMillis();
145
                double dbOpenTime = (connTime - startTime) / 1000;
146
                double readTime = (stopTime - connTime) / 1000;
147
                double executionTime = (stopTime - startTime) / 1000;
148
                if (showRuntime) {
149
                    System.out.print("  " + executionTime);
150
                    System.out.print("  " + dbOpenTime);
151
                    System.out.print("  " + readTime);
152
                    System.out.print("  " + nodelist.size());
153
                    System.out.println();
154
                }
155
                //System.out.println(result);
156
                //write into a file "result.txt"
157
                if (!showRuntime) {
158
                    File f = new File("./result.txt");
159
                    FileWriter fw = new FileWriter(f);
160
                    BufferedWriter out = new BufferedWriter(fw);
161
                    out.write(result.toString());
162
                    out.flush();
163
                    out.close();
164
                    fw.close();
165
                }
233 166

  
234
  /**
235
   * routine to search the elements and attributes looking to match query
236
   *
237
   * @param qspec java object of the query
238
   * @param user the username of the user
239
   * @param group the group of the user
240
   * @param useXMLIndex flag whether to search using the path index
241
   */
242
  public Hashtable findDocuments(QuerySpecification qspec, String user,
243
                                  String[] groups, boolean useXMLIndex)
244
  {
245
      Hashtable   docListResult = new Hashtable();
246
      PreparedStatement pstmt = null;
247
      String docid = null;
248
      String docname = null;
249
      String doctype = null;
250
      String createDate = null;
251
      String updateDate = null;
252
      String fieldname = null;
253
      String fielddata = null;
254
      String relation = null;
255
      //Connection dbconn = null;
256
      //Connection dbconn2 = null;
257
      int rev = 0;
258
      StringBuffer document = null;
259
      DBConnection dbconn = null;
260
      int serialNumber = -1;
167
            } catch (Exception e) {
168
                System.err.println("Error in DBQuery.main");
169
                System.err.println(e.getMessage());
170
                e.printStackTrace(System.err);
171
            }
172
        }
173
    }
261 174

  
262
      try {
175
    /**
176
     * construct an instance of the DBQuery class
177
     * 
178
     * <p>
179
     * Generally, one would call the findDocuments() routine after creating an
180
     * instance to specify the search query
181
     * </p>
182
     * 
183
     * @param conn the JDBC connection that we use for the query
184
     * @param parserName the fully qualified name of a Java class implementing
185
     *            the org.xml.sax.XMLReader interface
186
     */
187
    public DBQuery(String parserName) throws IOException, SQLException,
188
            ClassNotFoundException
189
    {
190
        //this.conn = conn;
191
        this.parserName = parserName;
192
    }
263 193

  
194
    /**
195
     * routine to search the elements and attributes looking to match query
196
     * 
197
     * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
198
     * @param user the username of the user
199
     * @param group the group of the user
200
     */
201
    public Hashtable findDocuments(Reader xmlquery, String user, String[] groups)
202
    {
203
        boolean useXMLIndex = (new Boolean(MetaCatUtil.getOption("usexmlindex")))
204
                .booleanValue();
205
        return findDocuments(xmlquery, user, groups, useXMLIndex);
206
    }
264 207

  
265
        dbconn=DBConnectionPool.getDBConnection("DBQuery.findDocuments");
266
        serialNumber=dbconn.getCheckOutSerialNumber();
267

  
268
        String query = qspec.printSQL(useXMLIndex);
269
        String ownerQuery = getOwnerQuery(user);
270
        MetaCatUtil.debugMessage("query: "+query, 30);
271
        //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
272
        // if query is not the owner query, we need to check the permission
273
        // otherwise we don't need (owner has all permission by default)
274
        if (!query.equals(ownerQuery))
275
        {
276
          // set user name and group
277
          qspec.setUserName(user);
278
          qspec.setGroup(groups);
279
          // Get access query
280
          String accessQuery = qspec.getAccessQuery();
281
          query = query + accessQuery;
282
          MetaCatUtil.debugMessage(" final query: "+query, 30);
208
    /**
209
     * routine to search the elements and attributes looking to match query
210
     * 
211
     * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
212
     * @param user the username of the user
213
     * @param group the group of the user
214
     * @param useXMLIndex flag whether to search using the path index
215
     */
216
    public Hashtable findDocuments(Reader xmlquery, String user,
217
            String[] groups, boolean useXMLIndex)
218
    {
219
        Hashtable result = new Hashtable();
220
        try {
221
            // Get the XML query and covert it into a SQL statment
222
            QuerySpecification qspec = new QuerySpecification(xmlquery,
223
                    parserName, MetaCatUtil.getOption("accNumSeparator"));
224
            result = findDocuments(qspec, user, groups, useXMLIndex);
225
        } catch (IOException ioe) {
226
            MetaCatUtil.debugMessage("IO error in DBQuery.findDocuments:", 30);
227
            MetaCatUtil.debugMessage(ioe.getMessage(), 30);
283 228
        }
229
        return result;
230
    }
284 231

  
285
        double startTime = System.currentTimeMillis()/1000;
286
        pstmt = dbconn.prepareStatement(query);
232
    /**
233
     * routine to search the elements and attributes looking to match query
234
     * 
235
     * @param qspec java object of the query
236
     * @param user the username of the user
237
     * @param group the group of the user
238
     * @param useXMLIndex flag whether to search using the path index
239
     */
240
    public Hashtable findDocuments(QuerySpecification qspec, String user,
241
            String[] groups, boolean useXMLIndex)
242
    {
243
        Hashtable docListResult = new Hashtable();
244
        PreparedStatement pstmt = null;
245
        String docid = null;
246
        String docname = null;
247
        String doctype = null;
248
        String createDate = null;
249
        String updateDate = null;
250
        String fieldname = null;
251
        String fielddata = null;
252
        String relation = null;
253
        //Connection dbconn = null;
254
        //Connection dbconn2 = null;
255
        int rev = 0;
256
        StringBuffer document = null;
257
        DBConnection dbconn = null;
258
        int serialNumber = -1;
287 259

  
288
        // Execute the SQL query using the JDBC connection
289
        pstmt.execute();
290
        ResultSet rs = pstmt.getResultSet();
291
        double queryExecuteTime =System.currentTimeMillis()/1000;
292
        MetaCatUtil.debugMessage("Time for execute query: "+
293
                                            (queryExecuteTime -startTime), 30);
294
        boolean tableHasRows = rs.next();
295
        while (tableHasRows)
296
        {
297
          docid = rs.getString(1).trim();
298
          //long checkTimeStart = System.currentTimeMillis();
299
          //boolean permit =hasPermission(user, groups, docid);
300
          //long checkTimeEnd = System.currentTimeMillis();
301
          //MetaCatUtil.debugMessage("check permission time: "+
302
                                  //(checkTimeEnd - checkTimeStart), 30);
303
          //if ( !permit ) {
304
            // Advance to the next record in the cursor
305
            //tableHasRows = rs.next();
306
            //continue;
307
          //}
260
        try {
308 261

  
309
          docname = rs.getString(2);
310
          doctype = rs.getString(3);
311
          createDate = rs.getString(4);
312
          updateDate = rs.getString(5);
313
          rev = rs.getInt(6);
262
            dbconn = DBConnectionPool.getDBConnection("DBQuery.findDocuments");
263
            serialNumber = dbconn.getCheckOutSerialNumber();
314 264

  
315
          // if there are returndocs to match, backtracking can be performed
316
          // otherwise, just return the document that was hit
317
          Vector returndocVec = qspec.getReturnDocList();
318
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
319
              && !qspec.isPercentageSearch())
320
          {
321
            MetaCatUtil.debugMessage("Back tracing now...", 20);
322
            String sep = MetaCatUtil.getOption("accNumSeparator");
323
            StringBuffer btBuf = new StringBuffer();
324
            btBuf.append("select docid from xml_relation where ");
325

  
326
            //build the doctype list for the backtracking sql statement
327
            btBuf.append("packagetype in (");
328
            for(int i=0; i<returndocVec.size(); i++)
329
            {
330
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
331
              if (i != (returndocVec.size() - 1))
332
              {
333
                btBuf.append(", ");
334
              }
265
            String query = qspec.printSQL(useXMLIndex);
266
            String ownerQuery = getOwnerQuery(user);
267
            MetaCatUtil.debugMessage("query: " + query, 30);
268
            //MetaCatUtil.debugMessage("query: "+ownerQuery, 30);
269
            // if query is not the owner query, we need to check the permission
270
            // otherwise we don't need (owner has all permission by default)
271
            if (!query.equals(ownerQuery)) {
272
                // set user name and group
273
                qspec.setUserName(user);
274
                qspec.setGroup(groups);
275
                // Get access query
276
                String accessQuery = qspec.getAccessQuery();
277
                query = query + accessQuery;
278
                MetaCatUtil.debugMessage(" final query: " + query, 30);
335 279
            }
336
            btBuf.append(") ");
337 280

  
338
            btBuf.append("and (subject like '");
339
            btBuf.append(docid).append("'");
340
            btBuf.append("or object like '");
341
            btBuf.append(docid).append("')");
281
            double startTime = System.currentTimeMillis() / 1000;
282
            pstmt = dbconn.prepareStatement(query);
342 283

  
343
            PreparedStatement npstmt = dbconn.
344
                                       prepareStatement(btBuf.toString());
345
            //should incease usage count
346
            dbconn.increaseUsageCount(1);
347
            npstmt.execute();
348
            ResultSet btrs = npstmt.getResultSet();
349
            boolean hasBtRows = btrs.next();
350
            while (hasBtRows)
351
            { //there was a backtrackable document found
352
              DocumentImpl xmldoc = null;
353
              String packageDocid = btrs.getString(1);
354
              MetaCatUtil.debugMessage("Getting document for docid: "+packageDocid,40);
355
              try
356
              {
357
                //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not needed here
358
                // xmldoc = new DocumentImpl(dbconn, packageDocid);
359
                //  thus use the following to get the doc info only
360
                //  xmldoc = new DocumentImpl(dbconn);
361
                xmldoc = new DocumentImpl(packageDocid, false);
362
                if (xmldoc == null) {
363
                    MetaCatUtil.debugMessage("Document was null for: "+packageDocid, 50);
364
                }
365
              }
366
              catch(Exception e)
367
              {
368
                System.out.println("Error getting document in " +
369
                                   "DBQuery.findDocuments: " + e.getMessage());
370
              }
284
            // Execute the SQL query using the JDBC connection
285
            pstmt.execute();
286
            ResultSet rs = pstmt.getResultSet();
287
            double queryExecuteTime = System.currentTimeMillis() / 1000;
288
            MetaCatUtil.debugMessage("Time for execute query: "
289
                    + (queryExecuteTime - startTime), 30);
290
            boolean tableHasRows = rs.next();
291
            while (tableHasRows) {
292
                docid = rs.getString(1).trim();
293
                //long checkTimeStart = System.currentTimeMillis();
294
                //boolean permit =hasPermission(user, groups, docid);
295
                //long checkTimeEnd = System.currentTimeMillis();
296
                //MetaCatUtil.debugMessage("check permission time: "+
297
                //(checkTimeEnd - checkTimeStart), 30);
298
                //if ( !permit ) {
299
                // Advance to the next record in the cursor
300
                //tableHasRows = rs.next();
301
                //continue;
302
                //}
371 303

  
372
              String docid_org = xmldoc.getDocID();
373
              if (docid_org == null) {
374
                  MetaCatUtil.debugMessage("Docid_org was null.", 40);
375
              }
376
              docid   = docid_org.trim();
377
              docname = xmldoc.getDocname();
378
              doctype = xmldoc.getDoctype();
379
              createDate = xmldoc.getCreateDate();
380
              updateDate = xmldoc.getUpdateDate();
381
              rev = xmldoc.getRev();
304
                docname = rs.getString(2);
305
                doctype = rs.getString(3);
306
                createDate = rs.getString(4);
307
                updateDate = rs.getString(5);
308
                rev = rs.getInt(6);
382 309

  
383
              document = new StringBuffer();
310
                // if there are returndocs to match, backtracking can be
311
                // performed
312
                // otherwise, just return the document that was hit
313
                Vector returndocVec = qspec.getReturnDocList();
314
                if (returndocVec.size() != 0 && !returndocVec.contains(doctype)
315
                        && !qspec.isPercentageSearch()) {
316
                    MetaCatUtil.debugMessage("Back tracing now...", 20);
317
                    String sep = MetaCatUtil.getOption("accNumSeparator");
318
                    StringBuffer btBuf = new StringBuffer();
319
                    btBuf.append("select docid from xml_relation where ");
384 320

  
385
              String completeDocid = docid + MetaCatUtil.getOption("accNumSeparator");
386
              completeDocid += rev;
387
              document.append("<docid>").append(completeDocid);
388
              document.append("</docid>");
389
              if (docname != null) {
390
                document.append("<docname>" + docname + "</docname>");
391
              }
392
              if (doctype != null) {
393
                document.append("<doctype>" + doctype + "</doctype>");
394
              }
395
              if (createDate != null) {
396
                document.append("<createdate>" + createDate + "</createdate>");
397
              }
398
              if (updateDate != null) {
399
                document.append("<updatedate>" + updateDate + "</updatedate>");
400
              }
401
              // Store the document id and the root node id
402
              docListResult.put(docid,(String)document.toString());
321
                    //build the doctype list for the backtracking sql
322
                    // statement
323
                    btBuf.append("packagetype in (");
324
                    for (int i = 0; i < returndocVec.size(); i++) {
325
                        btBuf.append("'").append((String) returndocVec.get(i))
326
                                .append("'");
327
                        if (i != (returndocVec.size() - 1)) {
328
                            btBuf.append(", ");
329
                        }
330
                    }
331
                    btBuf.append(") ");
403 332

  
404
              // Get the next package document linked to our hit
405
              hasBtRows = btrs.next();
406
            }
407
            npstmt.close();
408
            btrs.close();
409
          }
410
          else if (returndocVec.size() != 0 && returndocVec.contains(doctype))
411
          {
333
                    btBuf.append("and (subject like '");
334
                    btBuf.append(docid).append("'");
335
                    btBuf.append("or object like '");
336
                    btBuf.append(docid).append("')");
412 337

  
413
            document = new StringBuffer();
338
                    PreparedStatement npstmt = dbconn.prepareStatement(btBuf
339
                            .toString());
340
                    //should incease usage count
341
                    dbconn.increaseUsageCount(1);
342
                    npstmt.execute();
343
                    ResultSet btrs = npstmt.getResultSet();
344
                    boolean hasBtRows = btrs.next();
345
                    while (hasBtRows) { //there was a backtrackable document
346
                                        // found
347
                        DocumentImpl xmldoc = null;
348
                        String packageDocid = btrs.getString(1);
349
                        MetaCatUtil.debugMessage("Getting document for docid: "
350
                                + packageDocid, 40);
351
                        try {
352
                            //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not
353
                            // needed here
354
                            // xmldoc = new DocumentImpl(dbconn, packageDocid);
355
                            //  thus use the following to get the doc info only
356
                            //  xmldoc = new DocumentImpl(dbconn);
357
                            xmldoc = new DocumentImpl(packageDocid, false);
358
                            if (xmldoc == null) {
359
                                MetaCatUtil.debugMessage(
360
                                        "Document was null for: "
361
                                                + packageDocid, 50);
362
                            }
363
                        } catch (Exception e) {
364
                            System.out.println("Error getting document in "
365
                                    + "DBQuery.findDocuments: "
366
                                    + e.getMessage());
367
                        }
414 368

  
415
            String completeDocid = docid + MetaCatUtil.getOption("accNumSeparator");
416
            completeDocid += rev;
417
            document.append("<docid>").append(completeDocid).append("</docid>");
418
            if (docname != null) {
419
              document.append("<docname>" + docname + "</docname>");
420
            }
421
            if (doctype != null) {
422
              document.append("<doctype>" + doctype + "</doctype>");
423
            }
424
            if (createDate != null) {
425
              document.append("<createdate>" + createDate + "</createdate>");
426
            }
427
            if (updateDate != null) {
428
              document.append("<updatedate>" + updateDate + "</updatedate>");
429
            }
430
            // Store the document id and the root node id
431
            docListResult.put(docid,(String)document.toString());
369
                        String docid_org = xmldoc.getDocID();
370
                        if (docid_org == null) {
371
                            MetaCatUtil.debugMessage("Docid_org was null.", 40);
372
                        }
373
                        docid = docid_org.trim();
374
                        docname = xmldoc.getDocname();
375
                        doctype = xmldoc.getDoctype();
376
                        createDate = xmldoc.getCreateDate();
377
                        updateDate = xmldoc.getUpdateDate();
378
                        rev = xmldoc.getRev();
432 379

  
433
          }
380
                        document = new StringBuffer();
434 381

  
435
          // Advance to the next record in the cursor
436
          tableHasRows = rs.next();
437
        }
438
        rs.close();
439
        pstmt.close();
440
        double docListTime =System.currentTimeMillis()/1000;
441
        MetaCatUtil.debugMessage("prepare docid list time: "
442
                                          +(docListTime-queryExecuteTime), 30);
382
                        String completeDocid = docid
383
                                + MetaCatUtil.getOption("accNumSeparator");
384
                        completeDocid += rev;
385
                        document.append("<docid>").append(completeDocid);
386
                        document.append("</docid>");
387
                        if (docname != null) {
388
                            document.append("<docname>" + docname
389
                                    + "</docname>");
390
                        }
391
                        if (doctype != null) {
392
                            document.append("<doctype>" + doctype
393
                                    + "</doctype>");
394
                        }
395
                        if (createDate != null) {
396
                            document.append("<createdate>" + createDate
397
                                    + "</createdate>");
398
                        }
399
                        if (updateDate != null) {
400
                            document.append("<updatedate>" + updateDate
401
                                    + "</updatedate>");
402
                        }
403
                        // Store the document id and the root node id
404
                        docListResult.put(docid, (String) document.toString());
443 405

  
444
        if (qspec.containsExtendedSQL())
445
        {
446
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
447
          Vector results = new Vector();
448
          Enumeration keylist = docListResult.keys();
449
          StringBuffer doclist = new StringBuffer();
450
          Vector parentidList = new Vector();
451
          Hashtable returnFieldValue = new Hashtable();
452
          while(keylist.hasMoreElements())
453
          {
454
            doclist.append("'");
455
            doclist.append((String)keylist.nextElement());
456
            doclist.append("',");
457
          }
458
          if (doclist.length() > 0)
459
          {
460
            Hashtable controlPairs = new Hashtable();
461
            double extendedQueryStart = System.currentTimeMillis()/1000;
462
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
463
            // check if user has permission to see the return field data
464
            String accessControlSQL = qspec.
465
                        printAccessControlSQLForReturnField(doclist.toString());
466
            pstmt = dbconn.prepareStatement(accessControlSQL);
467
            //increase dbconnection usage count
468
            dbconn.increaseUsageCount(1);
469
            pstmt.execute();
470
            rs = pstmt.getResultSet();
471
            tableHasRows = rs.next();
472
            while(tableHasRows)
473
            {
474
              long startNodeId = rs.getLong(1);
475
              long endNodeId = rs.getLong(2);
476
              controlPairs.put(new Long(startNodeId), new Long(endNodeId));
477
              tableHasRows = rs.next();
478
            }
406
                        // Get the next package document linked to our hit
407
                        hasBtRows = btrs.next();
408
                    }
409
                    npstmt.close();
410
                    btrs.close();
411
                } else if (returndocVec.size() != 0
412
                        && returndocVec.contains(doctype)) {
479 413

  
480
            double extendedAccessQueryEnd = System.currentTimeMillis()/1000;
481
            MetaCatUtil.debugMessage("Time for execute access extended query: "
482
                              +(extendedAccessQueryEnd-extendedQueryStart), 30);
414
                    document = new StringBuffer();
483 415

  
484
            String extendedQuery = qspec.printExtendedSQL(doclist.toString(), 
485
                    controlPairs, useXMLIndex);
486
            MetaCatUtil.debugMessage("Extended query: "+ extendedQuery, 30);
487
            pstmt = dbconn.prepareStatement(extendedQuery);
488
            //increase dbconnection usage count
489
            dbconn.increaseUsageCount(1);
490
            pstmt.execute();
491
            rs = pstmt.getResultSet();
492
            double extendedQueryEnd = System.currentTimeMillis()/1000;
493
            MetaCatUtil.debugMessage("Time for execute extended query: "
494
                                    +(extendedQueryEnd-extendedQueryStart), 30);
495
            tableHasRows = rs.next();
496
            while(tableHasRows)
497
            {
498
              ReturnFieldValue returnValue = new ReturnFieldValue();
499
              docid = rs.getString(1).trim();
500
              fieldname = rs.getString(2);
501
              fielddata = rs.getString(3);
502
              fielddata = MetaCatUtil.normalize(fielddata);
416
                    String completeDocid = docid
417
                            + MetaCatUtil.getOption("accNumSeparator");
418
                    completeDocid += rev;
419
                    document.append("<docid>").append(completeDocid).append(
420
                            "</docid>");
421
                    if (docname != null) {
422
                        document.append("<docname>" + docname + "</docname>");
423
                    }
424
                    if (doctype != null) {
425
                        document.append("<doctype>" + doctype + "</doctype>");
426
                    }
427
                    if (createDate != null) {
428
                        document.append("<createdate>" + createDate
429
                                + "</createdate>");
430
                    }
431
                    if (updateDate != null) {
432
                        document.append("<updatedate>" + updateDate
433
                                + "</updatedate>");
434
                    }
435
                    // Store the document id and the root node id
436
                    docListResult.put(docid, (String) document.toString());
503 437

  
504
              String parentId = rs.getString(4);
438
                }
505 439

  
506
              StringBuffer value = new StringBuffer();
507
              if (!containsKey(parentidList,parentId))
508
              {
509
                // don't need to merger nodedata
510
                value.append("<param name=\"");
511
                value.append(fieldname);
512
                value.append("\">");
513
                value.append(fielddata);
514
                value.append("</param>");
515
                //set returnvalue
516
                returnValue.setDocid(docid);
517
                returnValue.setFieldValue(fielddata);
518
                returnValue.setXMLFieldValue(value.toString());
519
                // Store it in hastable
520
                putInArray(parentidList, parentId, returnValue);
521
              }
522
              else
523
              {
524
                // need to merge nodedata if they have same parent id ant
525
                // node type is text
526
                fielddata = (String)((ReturnFieldValue)
527
                       getArrayValue(parentidList,parentId)).getFieldValue() +  fielddata;
528
                value.append("<param name=\"");
529
                value.append(fieldname);
530
                value.append("\">");
531
                value.append(fielddata);
532
                value.append("</param>");
533
                returnValue.setDocid(docid);
534
                returnValue.setFieldValue(fielddata);
535
                returnValue.setXMLFieldValue(value.toString());
536
                // remove the old return value from paretnidList
537
                parentidList.remove(parentId);
538
                // store the new return value in parentidlit
539
                putInArray(parentidList,parentId, returnValue);
540
              }
541
               tableHasRows = rs.next();
542
            }//while
440
                // Advance to the next record in the cursor
441
                tableHasRows = rs.next();
442
            }
543 443
            rs.close();
544 444
            pstmt.close();
445
            double docListTime = System.currentTimeMillis() / 1000;
446
            MetaCatUtil.debugMessage("prepare docid list time: "
447
                    + (docListTime - queryExecuteTime), 30);
545 448

  
546
            // put the merger node data info into doclistReult
547
            Enumeration xmlFieldValue = (getElements(parentidList)).elements();
548
            while( xmlFieldValue.hasMoreElements() )
549
            {
550
              ReturnFieldValue object = (ReturnFieldValue)
551
                                         xmlFieldValue.nextElement();
552
              docid = object.getDocid();
553
              if (docListResult.containsKey(docid))
554
              {
555
                  String removedelement = (String)docListResult.remove(docid);
556
                  docListResult.put(docid, removedelement +
557
                                    object.getXMLFieldValue());
558
              }
559
              else
560
              {
561
                  docListResult.put(docid, object.getXMLFieldValue());
562
              }
563
            }//while
564
            double docListResultEnd = System.currentTimeMillis()/1000;
565
            MetaCatUtil.debugMessage("Time for prepare doclistresult after"+
566
                                      " execute extended query: "
567
                                    +(docListResultEnd-extendedQueryEnd), 30);
449
            if (qspec.containsExtendedSQL()) {
450
                Vector extendedFields = new Vector(qspec.getReturnFieldList());
451
                Vector results = new Vector();
452
                Enumeration keylist = docListResult.keys();
453
                StringBuffer doclist = new StringBuffer();
454
                Vector parentidList = new Vector();
455
                Hashtable returnFieldValue = new Hashtable();
456
                while (keylist.hasMoreElements()) {
457
                    doclist.append("'");
458
                    doclist.append((String) keylist.nextElement());
459
                    doclist.append("',");
460
                }
461
                if (doclist.length() > 0) {
462
                    Hashtable controlPairs = new Hashtable();
463
                    double extendedQueryStart = System.currentTimeMillis() / 1000;
464
                    doclist.deleteCharAt(doclist.length() - 1); //remove the
465
                                                                // last comma
466
                    // check if user has permission to see the return field
467
                    // data
468
                    String accessControlSQL = qspec
469
                            .printAccessControlSQLForReturnField(doclist
470
                                    .toString());
471
                    pstmt = dbconn.prepareStatement(accessControlSQL);
472
                    //increase dbconnection usage count
473
                    dbconn.increaseUsageCount(1);
474
                    pstmt.execute();
475
                    rs = pstmt.getResultSet();
476
                    tableHasRows = rs.next();
477
                    while (tableHasRows) {
478
                        long startNodeId = rs.getLong(1);
479
                        long endNodeId = rs.getLong(2);
480
                        controlPairs.put(new Long(startNodeId), new Long(
481
                                endNodeId));
482
                        tableHasRows = rs.next();
483
                    }
568 484

  
485
                    double extendedAccessQueryEnd = System.currentTimeMillis() / 1000;
486
                    MetaCatUtil
487
                            .debugMessage(
488
                                    "Time for execute access extended query: "
489
                                            + (extendedAccessQueryEnd - extendedQueryStart),
490
                                    30);
569 491

  
570
            // get attribures return
571
            docListResult = getAttributeValueForReturn(qspec, docListResult, 
572
                    doclist.toString(), useXMLIndex);
573
          }//if doclist lenght is great than zero
492
                    String extendedQuery = qspec.printExtendedSQL(doclist
493
                            .toString(), controlPairs, useXMLIndex);
494
                    MetaCatUtil.debugMessage(
495
                            "Extended query: " + extendedQuery, 30);
496
                    pstmt = dbconn.prepareStatement(extendedQuery);
497
                    //increase dbconnection usage count
498
                    dbconn.increaseUsageCount(1);
499
                    pstmt.execute();
500
                    rs = pstmt.getResultSet();
501
                    double extendedQueryEnd = System.currentTimeMillis() / 1000;
502
                    MetaCatUtil.debugMessage(
503
                            "Time for execute extended query: "
504
                                    + (extendedQueryEnd - extendedQueryStart),
505
                            30);
506
                    tableHasRows = rs.next();
507
                    while (tableHasRows) {
508
                        ReturnFieldValue returnValue = new ReturnFieldValue();
509
                        docid = rs.getString(1).trim();
510
                        fieldname = rs.getString(2);
511
                        fielddata = rs.getString(3);
512
                        fielddata = MetaCatUtil.normalize(fielddata);
574 513

  
575
        }//if has extended query
514
                        String parentId = rs.getString(4);
576 515

  
516
                        StringBuffer value = new StringBuffer();
517
                        if (!containsKey(parentidList, parentId)) {
518
                            // don't need to merger nodedata
519
                            value.append("<param name=\"");
520
                            value.append(fieldname);
521
                            value.append("\">");
522
                            value.append(fielddata);
523
                            value.append("</param>");
524
                            //set returnvalue
525
                            returnValue.setDocid(docid);
526
                            returnValue.setFieldValue(fielddata);
527
                            returnValue.setXMLFieldValue(value.toString());
528
                            // Store it in hastable
529
                            putInArray(parentidList, parentId, returnValue);
530
                        } else {
531
                            // need to merge nodedata if they have same parent
532
                            // id ant
533
                            // node type is text
534
                            fielddata = (String) ((ReturnFieldValue) getArrayValue(
535
                                    parentidList, parentId)).getFieldValue()
536
                                    + fielddata;
537
                            value.append("<param name=\"");
538
                            value.append(fieldname);
539
                            value.append("\">");
540
                            value.append(fielddata);
541
                            value.append("</param>");
542
                            returnValue.setDocid(docid);
543
                            returnValue.setFieldValue(fielddata);
544
                            returnValue.setXMLFieldValue(value.toString());
545
                            // remove the old return value from paretnidList
546
                            parentidList.remove(parentId);
547
                            // store the new return value in parentidlit
548
                            putInArray(parentidList, parentId, returnValue);
549
                        }
550
                        tableHasRows = rs.next();
551
                    }//while
552
                    rs.close();
553
                    pstmt.close();
577 554

  
578
        //this loop adds the relation data to the resultdoc
579
        //this code might be able to be added to the backtracking code above
580
        double startRelation = System.currentTimeMillis()/1000;
581
        Enumeration docidkeys = docListResult.keys();
582
        while(docidkeys.hasMoreElements())
583
        {
584
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
585
          String connstring = "%docid=";
586
          String docidkey = (String)docidkeys.nextElement();
587
          pstmt = dbconn.prepareStatement(QuerySpecification.printRelationSQL(docidkey));
588
          pstmt.execute();
589
          rs = pstmt.getResultSet();
590
          tableHasRows = rs.next();
591
          while(tableHasRows)
592
          {
593
            String sub = rs.getString(1);
594
            String rel = rs.getString(2);
595
            String obj = rs.getString(3);
596
            String subDT = rs.getString(4);
597
            String objDT = rs.getString(5);
555
                    // put the merger node data info into doclistReult
556
                    Enumeration xmlFieldValue = (getElements(parentidList))
557
                            .elements();
558
                    while (xmlFieldValue.hasMoreElements()) {
559
                        ReturnFieldValue object = (ReturnFieldValue) xmlFieldValue
560
                                .nextElement();
561
                        docid = object.getDocid();
562
                        if (docListResult.containsKey(docid)) {
563
                            String removedelement = (String) docListResult
564
                                    .remove(docid);
565
                            docListResult.put(docid, removedelement
566
                                    + object.getXMLFieldValue());
567
                        } else {
568
                            docListResult.put(docid, object.getXMLFieldValue());
569
                        }
570
                    }//while
571
                    double docListResultEnd = System.currentTimeMillis() / 1000;
572
                    MetaCatUtil
573
                            .debugMessage(
574
                                    "Time for prepare doclistresult after"
575
                                            + " execute extended query: "
576
                                            + (docListResultEnd - extendedQueryEnd),
577
                                    30);
598 578

  
599
            document = new StringBuffer();
600
            document.append("<triple>");
601
            document.append("<subject>").append(MetaCatUtil.normalize(sub));
602
            document.append("</subject>");
603
            if ( subDT != null ) {
604
              document.append("<subjectdoctype>").append(subDT);
605
              document.append("</subjectdoctype>");
606
            }
607
            document.append("<relationship>").
608
                                          append(MetaCatUtil.normalize(rel));
609
            document.append("</relationship>");
610
            document.append("<object>").append(MetaCatUtil.normalize(obj));
611
            document.append("</object>");
612
            if ( objDT != null ) {
613
              document.append("<objectdoctype>").append(objDT);
614
              document.append("</objectdoctype>");
615
            }
616
            document.append("</triple>");
579
                    // get attribures return
580
                    docListResult = getAttributeValueForReturn(qspec,
581
                            docListResult, doclist.toString(), useXMLIndex);
582
                }//if doclist lenght is great than zero
617 583

  
618
            String removedelement = (String)docListResult.remove(docidkey);
619
            docListResult.put(docidkey, removedelement +
620
                              document.toString());
621
            tableHasRows = rs.next();
622
          }
623
          rs.close();
624
          pstmt.close();
625
        }
626
        double endRelation = System.currentTimeMillis()/1000;
627
        MetaCatUtil.debugMessage("Time for adding relation to docListResult: "+
628
                                (endRelation-startRelation), 30);
584
            }//if has extended query
629 585

  
630
      } catch (SQLException e) {
631
        System.err.println("SQL Error in DBQuery.findDocuments: " +
632
                           e.getMessage());
633
      } catch (Exception ee) {
634
        System.err.println("Exception in DBQuery.findDocuments: " +
635
                           ee.getMessage());
636
        ee.printStackTrace(System.err);
637
      }
638
      finally
639
      {
640
        try
641
        {
642
          pstmt.close();
643
        }//try
644
        catch (SQLException sqlE)
645
        {
646
          MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
647
                                      +sqlE.getMessage(), 30);
648
        }//catch
649
        finally
650
        {
651
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
652
        }//finally
653
      }//finally
654
    //System.out.println("docListResult: ");
655
    //System.out.println(docListResult.toString());
656
    return docListResult;
657
  }
586
            //this loop adds the relation data to the resultdoc
587
            //this code might be able to be added to the backtracking code
588
            // above
589
            double startRelation = System.currentTimeMillis() / 1000;
590
            Enumeration docidkeys = docListResult.keys();
591
            while (docidkeys.hasMoreElements()) {
592
                //String connstring =
593
                // "metacat://"+util.getOption("server")+"?docid=";
594
                String connstring = "%docid=";
595
                String docidkey = (String) docidkeys.nextElement();
596
                pstmt = dbconn.prepareStatement(QuerySpecification
597
                        .printRelationSQL(docidkey));
598
                pstmt.execute();
599
                rs = pstmt.getResultSet();
600
                tableHasRows = rs.next();
601
                while (tableHasRows) {
602
                    String sub = rs.getString(1);
603
                    String rel = rs.getString(2);
604
                    String obj = rs.getString(3);
605
                    String subDT = rs.getString(4);
606
                    String objDT = rs.getString(5);
658 607

  
659
  /*
660
   * A method to search if Vector contains a particular key string
661
   */
662
  private boolean containsKey(Vector parentidList,String parentId){
608
                    document = new StringBuffer();
609
                    document.append("<triple>");
610
                    document.append("<subject>").append(
611
                            MetaCatUtil.normalize(sub));
612
                    document.append("</subject>");
613
                    if (subDT != null) {
614
                        document.append("<subjectdoctype>").append(subDT);
615
                        document.append("</subjectdoctype>");
616
                    }
617
                    document.append("<relationship>").append(
618
                            MetaCatUtil.normalize(rel));
619
                    document.append("</relationship>");
620
                    document.append("<object>").append(
621
                            MetaCatUtil.normalize(obj));
622
                    document.append("</object>");
623
                    if (objDT != null) {
624
                        document.append("<objectdoctype>").append(objDT);
625
                        document.append("</objectdoctype>");
626
                    }
627
                    document.append("</triple>");
663 628

  
664
    Vector tempVector = null;
629
                    String removedelement = (String) docListResult
630
                            .remove(docidkey);
631
                    docListResult.put(docidkey, removedelement
632
                            + document.toString());
633
                    tableHasRows = rs.next();
634
                }
635
                rs.close();
636
                pstmt.close();
637
            }
638
            double endRelation = System.currentTimeMillis() / 1000;
639
            MetaCatUtil.debugMessage(
640
                    "Time for adding relation to docListResult: "
641
                            + (endRelation - startRelation), 30);
665 642

  
666
    for(int count = 0; count < parentidList.size(); count++){
667
      tempVector = (Vector)parentidList.get(count);
668
      if(parentId.compareTo((String)tempVector.get(0)) == 0){
669
        return false;
670
      }
643
        } catch (SQLException e) {
644
            System.err.println("SQL Error in DBQuery.findDocuments: "
645
                    + e.getMessage());
646
        } catch (Exception ee) {
647
            System.err.println("Exception in DBQuery.findDocuments: "
648
                    + ee.getMessage());
649
            ee.printStackTrace(System.err);
650
        } finally {
651
            try {
652
                pstmt.close();
653
            }//try
654
            catch (SQLException sqlE) {
655
                MetaCatUtil.debugMessage("Error in DBQuery.findDocuments: "
656
                        + sqlE.getMessage(), 30);
657
            }//catch
658
            finally {
659
                DBConnectionPool.returnDBConnection(dbconn, serialNumber);
660
            }//finally
661
        }//finally
662
        //System.out.println("docListResult: ");
663
        //System.out.println(docListResult.toString());
664
        return docListResult;
671 665
    }
672
    return false;
673
  }
674 666

  
675
  /*
676
   * A method to put key and value in Vector
677
   */
678
  private void putInArray(Vector parentidList, String key,
679
                          ReturnFieldValue value){
667
    /*
668
     * A method to search if Vector contains a particular key string
669
     */
670
    private boolean containsKey(Vector parentidList, String parentId)
671
    {
680 672

  
681
    Vector tempVector = null;
673
        Vector tempVector = null;
682 674

  
683
    for(int count = 0; count < parentidList.size(); count++){
684
      tempVector = (Vector)parentidList.get(count);
685

  
686
      if(key.compareTo((String)tempVector.get(0)) == 0){
687
        tempVector.remove(1);
688
        tempVector.add(1, value);
689
        return;
690
      }
675
        for (int count = 0; count < parentidList.size(); count++) {
676
            tempVector = (Vector) parentidList.get(count);
677
            if (parentId.compareTo((String) tempVector.get(0)) == 0) { return false; }
678
        }
679
        return false;
691 680
    }
692 681

  
693
    tempVector = new Vector();
694
    tempVector.add(0, key);
695
    tempVector.add(1, value);
696
    parentidList.add(tempVector);
697
    return;
698
  }
682
    /*
683
     * A method to put key and value in Vector
684
     */
685
    private void putInArray(Vector parentidList, String key,
686
            ReturnFieldValue value)
687
    {
699 688

  
700
  /*
701
   * A method to get value in Vector given a key
702
   */
703
  private ReturnFieldValue getArrayValue(Vector parentidList,
704
                                         String key){
689
        Vector tempVector = null;
705 690

  
706
    Vector tempVector = null;
691
        for (int count = 0; count < parentidList.size(); count++) {
692
            tempVector = (Vector) parentidList.get(count);
707 693

  
708
    for(int count = 0; count < parentidList.size(); count++){
709
      tempVector = (Vector)parentidList.get(count);
694
            if (key.compareTo((String) tempVector.get(0)) == 0) {
695
                tempVector.remove(1);
696
                tempVector.add(1, value);
697
                return;
698
            }
699
        }
710 700

  
711
      if(key.compareTo((String)tempVector.get(0)) == 0){
712
        return (ReturnFieldValue)tempVector.get(1);
713
      }
701
        tempVector = new Vector();
702
        tempVector.add(0, key);
703
        tempVector.add(1, value);
704
        parentidList.add(tempVector);
705
        return;
714 706
    }
715
    return null;
716
  }
717 707

  
718
  /*
719
   * A method to get enumeration of all values in Vector
720
   */
721
  private Vector getElements(Vector parentidList){
722
    Vector enum = new Vector();
723
    Vector tempVector = null;
724

  
725
    for(int count = 0; count < parentidList.size(); count++){
726
      tempVector = (Vector)parentidList.get(count);
727

  
728
      enum.add(tempVector.get(1));
729
    }
730
    return enum;
731
  }
732

  
733
  /*
734
   * A method to return search result after running a query which return
735
   * field have attribue
736
   */
737
  private Hashtable getAttributeValueForReturn(QuerySpecification squery, 
738
          Hashtable docInformationList, String docList, boolean useXMLIndex)
739
  {
740
    StringBuffer XML = null;
741
    String sql = null;
742
    DBConnection dbconn = null;
743
    PreparedStatement pstmt = null;
744
    ResultSet rs = null;
745
    int serialNumber = -1;
746
    boolean tableHasRows =false;
747

  
748
    //check the parameter
749
    if (squery == null || docList==null || docList.length() <0)
708
    /*
709
     * A method to get value in Vector given a key
710
     */
711
    private ReturnFieldValue getArrayValue(Vector parentidList, String key)
750 712
    {
751
      return docInformationList;
752
    }
753 713

  
754
    // if has attribute as return field
755
    if (squery.containAttributeReturnField())
756
    {
757
      sql = squery.printAttributeQuery(docList, useXMLIndex);
758
      try
759
      {
760
        dbconn=DBConnectionPool.getDBConnection("DBQuery.getAttributeValue");
761
        serialNumber=dbconn.getCheckOutSerialNumber();
762
        pstmt = dbconn.prepareStatement(sql);
763
        pstmt.execute();
764
        rs = pstmt.getResultSet();
765
        tableHasRows = rs.next();
766
        while(tableHasRows)
767
        {
768
          String docid = rs.getString(1).trim();
769
          String fieldname = rs.getString(2);
770
          String fielddata = rs.getString(3);
771
          String attirbuteName = rs.getString(4);
772
          XML = new StringBuffer();
714
        Vector tempVector = null;
773 715

  
774
          XML.append("<param name=\"");
775
          XML.append(fieldname);
776
          XML.append(QuerySpecification.ATTRIBUTESYMBOL);
777
          XML.append(attirbuteName);
778
          XML.append("\">");
779
          XML.append(fielddata);
780
          XML.append("</param>");
781
          tableHasRows = rs.next();
716
        for (int count = 0; count < parentidList.size(); count++) {
717
            tempVector = (Vector) parentidList.get(count);
782 718

  
783
          if (docInformationList.containsKey(docid))
784
          {
785
            String removedelement = (String)docInformationList.remove(docid);
786
            docInformationList.put(docid, removedelement + XML.toString());
787
          }
788
          else
789
          {
790
            docInformationList.put(docid, XML.toString());
791
          }
792
        }//while
793
        rs.close();
794
        pstmt.close();
795
      }
796
      catch(Exception se)
797
      {
798
        MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue1: "
799
                                      +se.getMessage(), 30);
800
      }
801
      finally
802
      {
803
        try
804
        {
805
          pstmt.close();
806
        }//try
807
        catch (SQLException sqlE)
808
        {
809
          MetaCatUtil.debugMessage("Error in DBQuery.getAttributeValue2: "
810
                                      +sqlE.getMessage(), 30);
811
        }//catch
812
        finally
813
        {
814
          DBConnectionPool.returnDBConnection(dbconn, serialNumber);
815
        }//finally
816
      }//finally
817
    }//if
818
    return docInformationList;
819

  
820
  }
821

  
822

  
823
  /*
824
   * A method to create a query to get owner's docid list
825
   */
826
  private String getOwnerQuery(String owner)
827
  {
828
    if (owner != null)
829
    {
830
      owner = owner.toLowerCase();
719
            if (key.compareTo((String) tempVector.get(0)) == 0) { return (ReturnFieldValue) tempVector
720
                    .get(1); }
721
        }
722
        return null;
831 723
    }
832
    StringBuffer self = new StringBuffer();
833
  
834
    self.append("SELECT docid,docname,doctype,");
835
    self.append("date_created, date_updated, rev ");
836
    self.append("FROM xml_documents WHERE docid IN (");
837
    self.append("(");
838
    self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
839
    self.append("nodedata LIKE '%%%' ");
840
    self.append(") \n");
841
    self.append(") ");
842
    self.append(" AND (");
843
    self.append(" lower(user_owner) = '" + owner + "'");
844
    self.append(") ");
845
    return self.toString();
846
  }
847 724

  
848
  /**
849
   * format a structured query as an XML document that conforms
850
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
851
   * structured query engine
852
   *
853
   * @param params The list of parameters that should be included in the query
854
   */
855
  public static String createSQuery(Hashtable params)
856
  {
857
    StringBuffer query = new StringBuffer();
858
    Enumeration elements;
859
    Enumeration keys;
860
    String filterDoctype = null;
861
    String casesensitive = null;
862
    String searchmode = null;
863
    Object nextkey;
864
    Object nextelement;
865
    //add the xml headers
866
    query.append("<?xml version=\"1.0\"?>\n");
867
    query.append("<pathquery version=\"1.0\">\n");
868

  
869
    if (params.containsKey("meta_file_id"))
725
    /*
726
     * A method to get enumeration of all values in Vector
727
     */
728
    private Vector getElements(Vector parentidList)
870 729
    {
871
      query.append("<meta_file_id>");
872
      query.append( ((String[])params.get("meta_file_id"))[0]);
873
      query.append("</meta_file_id>");
874
    }
730
        Vector enum = new Vector();
731
        Vector tempVector = null;
875 732

  
876
    if (params.containsKey("returndoctype"))
877
    {
878
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
879
      for(int i=0; i<returnDoctypes.length; i++)
880
      {
881
        String doctype = (String)returnDoctypes[i];
733
        for (int count = 0; count < parentidList.size(); count++) {
734
            tempVector = (Vector) parentidList.get(count);
882 735

  
883
        if (!doctype.equals("any") &&
884
            !doctype.equals("ANY") &&
885
            !doctype.equals("") )
886
        {
887
          query.append("<returndoctype>").append(doctype);
888
          query.append("</returndoctype>");
736
            enum.add(tempVector.get(1));
889 737
        }
890
      }
738
        return enum;
891 739
    }
892 740

  
893
    if (params.containsKey("filterdoctype"))
741
    /*
742
     * A method to return search result after running a query which return
743
     * field have attribue
744
     */
745
    private Hashtable getAttributeValueForReturn(QuerySpecification squery,
746
            Hashtable docInformationList, String docList, boolean useXMLIndex)
894 747
    {
895
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
896
      for(int i=0; i<filterDoctypes.length; i++)
897
      {
898
        query.append("<filterdoctype>").append(filterDoctypes[i]);
899
        query.append("</filterdoctype>");
900
      }
901
    }
748
        StringBuffer XML = null;
749
        String sql = null;
750
        DBConnection dbconn = null;
751
        PreparedStatement pstmt = null;
752
        ResultSet rs = null;
753
        int serialNumber = -1;
754
        boolean tableHasRows = false;
902 755

  
903
    if (params.containsKey("returnfield"))
904
    {
905
      String[] returnfield = ((String[])params.get("returnfield"));
906
      for(int i=0; i<returnfield.length; i++)
907
      {
908
        query.append("<returnfield>").append(returnfield[i]);
909
        query.append("</returnfield>");
910
      }
911
    }
756
        //check the parameter
757
        if (squery == null || docList == null || docList.length() < 0) { return docInformationList; }
912 758

  
913
    if (params.containsKey("owner"))
914
    {
915
      String[] owner = ((String[])params.get("owner"));
916
      for(int i=0; i<owner.length; i++)
917
      {
918
        query.append("<owner>").append(owner[i]);
919
        query.append("</owner>");
920
      }
921
    }
759
        // if has attribute as return field
760
        if (squery.containAttributeReturnField()) {
761
            sql = squery.printAttributeQuery(docList, useXMLIndex);
762
            try {
763
                dbconn = DBConnectionPool
764
                        .getDBConnection("DBQuery.getAttributeValue");
765
                serialNumber = dbconn.getCheckOutSerialNumber();
766
                pstmt = dbconn.prepareStatement(sql);
767
                pstmt.execute();
768
                rs = pstmt.getResultSet();
769
                tableHasRows = rs.next();
770
                while (tableHasRows) {
771
                    String docid = rs.getString(1).trim();
772
                    String fieldname = rs.getString(2);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff