Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that searches a relational DB for elements and 
4
 *             attributes that have free text matches a query string,
5
 *             or structured query matches to a path specified node in the 
6
 *             XML hierarchy.  It returns a result set consisting of the 
7
 *             document ID for each document that satisfies the query
8
 *  Copyright: 2000 Regents of the University of California and the
9
 *             National Center for Ecological Analysis and Synthesis
10
 *    Authors: Matt Jones
11
 *    Release: @release@
12
 *
13
 *   '$Author: jones $'
14
 *     '$Date: 2001-05-22 15:24:53 -0700 (Tue, 22 May 2001) $'
15
 * '$Revision: 745 $'
16
 *
17
 * This program is free software; you can redistribute it and/or modify
18
 * it under the terms of the GNU General Public License as published by
19
 * the Free Software Foundation; either version 2 of the License, or
20
 * (at your option) any later version.
21
 *
22
 * This program is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25
 * GNU General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU General Public License
28
 * along with this program; if not, write to the Free Software
29
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
 */
31

    
32
package edu.ucsb.nceas.metacat;
33

    
34
import java.io.*;
35
import java.util.Vector;
36
import java.net.URL;
37
import java.net.MalformedURLException;
38
import java.sql.*;
39
import java.util.Stack;
40
import java.util.Hashtable;
41
import java.util.Enumeration;
42
import java.io.File;
43
import java.io.FileWriter;
44
import java.io.BufferedWriter;
45

    
46
/** 
47
 * A Class that searches a relational DB for elements and 
48
 * attributes that have free text matches a query string,
49
 * or structured query matches to a path specified node in the 
50
 * XML hierarchy.  It returns a result set consisting of the 
51
 * document ID for each document that satisfies the query
52
 */
53
public class DBQuery {
54

    
55
  static final int ALL = 1;
56
  static final int WRITE = 2;
57
  static final int READ = 4;
58

    
59
  private Connection  conn = null;
60
  private String  parserName = null;
61
  private MetaCatUtil util = new MetaCatUtil();
62
  /**
63
   * the main routine used to test the DBQuery utility.
64
   * <p>
65
   * Usage: java DBQuery <xmlfile>
66
   *
67
   * @param xmlfile the filename of the xml file containing the query
68
   */
69
  static public void main(String[] args) {
70
     
71
     if (args.length < 1)
72
     {
73
        System.err.println("Wrong number of arguments!!!");
74
        System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
75
        return;
76
     } else {
77
        try {
78

    
79
          int i = 0;
80
          boolean showRuntime = false;
81
          boolean useXMLIndex = false;
82
          if ( args[i].equals( "-t" ) ) {
83
            showRuntime = true;
84
            i++;
85
          }
86
          if ( args[i].equals( "-index" ) ) {
87
            useXMLIndex = true;
88
            i++;
89
          } 
90
          String xmlfile  = args[i];
91

    
92
          // Time the request if asked for
93
          double startTime = System.currentTimeMillis();
94

    
95
          // Open a connection to the database
96
          MetaCatUtil   util = new MetaCatUtil();
97
          Connection dbconn = util.openDBConnection();
98

    
99
          double connTime = System.currentTimeMillis();
100

    
101
          // Execute the query
102
          DBQuery queryobj = new DBQuery(dbconn, util.getOption("saxparser"));
103
          FileReader xml = new FileReader(new File(xmlfile));
104
          Hashtable nodelist = null;
105
          nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
106

    
107
          // Print the reulting document listing
108
          StringBuffer result = new StringBuffer();
109
          String document = null;
110
          String docid = null;
111
          result.append("<?xml version=\"1.0\"?>\n");
112
          result.append("<resultset>\n"); 
113
  // following line removed by Dan Higgins to avoid insertion of query XML inside returned XML doc
114
  //        result.append("  <query>" + xmlfile + "</query>\n"); 
115
          if (!showRuntime)
116
          {
117
            Enumeration doclist = nodelist.keys();
118
            while (doclist.hasMoreElements()) {
119
              docid = (String)doclist.nextElement();
120
              document = (String)nodelist.get(docid);
121
              result.append("  <document>\n    " + document + 
122
                            "\n  </document>\n");
123
            }
124
            
125
            result.append("</resultset>\n");
126
          }
127
          // Time the request if asked for
128
          double stopTime = System.currentTimeMillis();
129
          double dbOpenTime = (connTime - startTime)/1000;
130
          double readTime = (stopTime - connTime)/1000;
131
          double executionTime = (stopTime - startTime)/1000;
132
          if (showRuntime) {
133
            System.out.print("  " + executionTime);
134
            System.out.print("  " + dbOpenTime);
135
            System.out.print("  " + readTime);
136
            System.out.print("  " + nodelist.size());
137
            System.out.println();
138
          }
139
          //System.out.println(result);
140
          //write into a file "result.txt"
141
          if (!showRuntime)
142
          {
143
            File f = new File("./result.txt");
144
            FileWriter fw = new FileWriter(f);
145
            BufferedWriter out = new BufferedWriter(fw);
146
            out.write(result.toString());          
147
            out.flush();
148
            out.close();
149
            fw.close();
150
          }
151
          
152
        } 
153
        catch (Exception e) {
154
          System.err.println("Error in DBQuery.main");
155
          System.err.println(e.getMessage());
156
          e.printStackTrace(System.err);
157
        }
158
     }
159
  }
160
  
161
  /**
162
   * construct an instance of the DBQuery class 
163
   *
164
   * <p>Generally, one would call the findDocuments() routine after creating 
165
   * an instance to specify the search query</p>
166
   *
167
   * @param conn the JDBC connection that we use for the query
168
   * @param parserName the fully qualified name of a Java class implementing
169
   *                   the org.xml.sax.XMLReader interface
170
   */
171
  public DBQuery( Connection conn, String parserName ) 
172
                  throws IOException, 
173
                         SQLException, 
174
                         ClassNotFoundException {
175
    this.conn = conn;
176
    this.parserName = parserName;
177
  }
178
  
179
  /** 
180
   * routine to search the elements and attributes looking to match query
181
   *
182
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
183
   * @param user the username of the user
184
   * @param group the group of the user
185
   */
186
  public Hashtable findDocuments(Reader xmlquery, String user, String group)
187
  {
188
    return findDocuments(xmlquery, user, group, true);
189
  }
190

    
191
  /** 
192
   * routine to search the elements and attributes looking to match query
193
   *
194
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
195
   * @param user the username of the user
196
   * @param group the group of the user
197
   * @param useXMLIndex flag whether to search using the path index
198
   */
199
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
200
                                 boolean useXMLIndex)
201
  {
202
      Hashtable   docListResult = new Hashtable();
203
      PreparedStatement pstmt = null;
204
      String docid = null;
205
      String docname = null;
206
      String doctype = null;
207
      String createDate = null;
208
      String updateDate = null;
209
      String fieldname = null;
210
      String fielddata = null;
211
      String relation = null;
212
      Connection dbconn = null;
213
      int rev = 0;
214
      StringBuffer document = null; 
215
      
216
      try {
217
        if (conn == null || conn.isClosed()) {
218
          dbconn = util.openDBConnection();
219
        } else {
220
          dbconn = conn;
221
        }
222
        // Get the XML query and covert it into a SQL statment
223
        QuerySpecification qspec = new QuerySpecification(xmlquery, 
224
                                   parserName, 
225
                                   util.getOption("accNumSeparator"));
226
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
227

    
228
        // Execute the SQL query using the JDBC connection
229
        pstmt.execute();
230
        ResultSet rs = pstmt.getResultSet();
231
        boolean tableHasRows = rs.next();
232
        while (tableHasRows) 
233
        {
234
          docid = rs.getString(1);
235
          if ( !hasPermission(dbconn, user, group, docid) ) {
236
            // Advance to the next record in the cursor
237
            tableHasRows = rs.next();
238
            continue;
239
          }
240
          docname = rs.getString(2);
241
          doctype = rs.getString(3);
242
          createDate = rs.getString(4);
243
          updateDate = rs.getString(5);
244
          rev = rs.getInt(6);
245

    
246
          // if there are returndocs to match, backtracking can be performed
247
          // otherwise, just return the document that was hit
248
          Vector returndocVec = qspec.getReturnDocList();
249
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype))
250
          { 
251
            MetaCatUtil.debugMessage("Back tracing now...");
252
            String sep = util.getOption("accNumSeparator");
253
            StringBuffer btBuf = new StringBuffer();
254
            btBuf.append("select docid from xml_relation where ");
255

    
256
            //build the doctype list for the backtracking sql statement
257
            btBuf.append("packagetype in (");
258
            for(int i=0; i<returndocVec.size(); i++)
259
            {
260
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
261
              if (i != (returndocVec.size() - 1))
262
              {
263
                btBuf.append(", ");
264
              } 
265
            }
266
            btBuf.append(") ");
267

    
268
            btBuf.append("and (subject like '");
269
            btBuf.append(docid).append(sep).append(rev).append("'");
270
            btBuf.append("or object like '");
271
            btBuf.append(docid).append(sep).append(rev).append("')");
272
            
273
            PreparedStatement npstmt = dbconn.
274
                                       prepareStatement(btBuf.toString());
275
            npstmt.execute();
276
            ResultSet btrs = npstmt.getResultSet();
277
            boolean hasBtRows = btrs.next();
278
            while (hasBtRows)
279
            { //there was a backtrackable document found
280
              DocumentImpl xmldoc = null;
281
              String packageDocid = btrs.getString(1);
282
              //MetacatURL objURL = new MetacatURL(packageDocid);
283
              try
284
              {
285
                //xmldoc = new DocumentImpl(dbconn, objURL.getParam(0)[1]);
286
                xmldoc = new DocumentImpl(dbconn, packageDocid);
287
              }
288
              catch(Exception e)
289
              {
290
                System.out.println("Error getting document in " + 
291
                                   "DBQuery.findDocuments: " + e.getMessage());
292
              }
293
              
294
              docid   = xmldoc.getDocID();
295
              docname = xmldoc.getDocname();
296
              doctype = xmldoc.getDoctype();
297
              createDate = xmldoc.getCreateDate();
298
              updateDate = xmldoc.getUpdateDate();
299
              rev = xmldoc.getRev();
300

    
301
              document = new StringBuffer();
302

    
303
              String completeDocid = docid + util.getOption("accNumSeparator");
304
              completeDocid += rev;
305
              document.append("<docid>").append(completeDocid);
306
              document.append("</docid>");
307
              if (docname != null) {
308
                document.append("<docname>" + docname + "</docname>");
309
              }
310
              if (doctype != null) {
311
                document.append("<doctype>" + doctype + "</doctype>");
312
              }
313
              if (createDate != null) {
314
                document.append("<createdate>" + createDate + "</createdate>");
315
              }
316
              if (updateDate != null) {
317
                document.append("<updatedate>" + updateDate + "</updatedate>");
318
              }
319
              // Store the document id and the root node id
320
              docListResult.put(docid,(String)document.toString());
321
         
322
              // Get the next package document linked to our hit
323
              hasBtRows = btrs.next();
324
            }
325
            npstmt.close();
326
            btrs.close();
327
          } else {
328
          
329
            document = new StringBuffer();
330

    
331
            String completeDocid = docid + util.getOption("accNumSeparator");
332
            completeDocid += rev;
333
            document.append("<docid>").append(completeDocid).append("</docid>");
334
            if (docname != null) {
335
              document.append("<docname>" + docname + "</docname>");
336
            }
337
            if (doctype != null) {
338
              document.append("<doctype>" + doctype + "</doctype>");
339
            }
340
            if (createDate != null) {
341
              document.append("<createdate>" + createDate + "</createdate>");
342
            }
343
            if (updateDate != null) {
344
              document.append("<updatedate>" + updateDate + "</updatedate>");
345
            }
346
            // Store the document id and the root node id
347
            docListResult.put(docid,(String)document.toString());
348
  
349
          }
350

    
351
          // Advance to the next record in the cursor
352
          tableHasRows = rs.next();
353
        }
354
        rs.close();
355
        //pstmt.close();
356
        
357
        if (qspec.containsExtendedSQL())
358
        {
359
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
360
          Vector results = new Vector();
361
          Enumeration keylist = docListResult.keys();
362
          StringBuffer doclist = new StringBuffer();
363
          while(keylist.hasMoreElements())
364
          {
365
            doclist.append("'");
366
            doclist.append((String)keylist.nextElement());
367
            doclist.append("',");
368
          }
369
          doclist.deleteCharAt(doclist.length()-1); //remove the last comma
370
          pstmt.close();
371
          pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
372
                                        doclist.toString()));
373
          pstmt.execute();
374
          rs = pstmt.getResultSet();
375
          tableHasRows = rs.next();
376
          while(tableHasRows) 
377
          {
378
            docid = rs.getString(1);
379
            if ( !hasPermission(dbconn, user, group, docid) ) {
380
              // Advance to the next record in the cursor
381
              tableHasRows = rs.next();
382
              continue;
383
            }
384
            fieldname = rs.getString(2);
385
            fielddata = rs.getString(3);
386
            
387
            document = new StringBuffer();
388

    
389
            document.append("<param name=\"");
390
            document.append(fieldname);
391
            document.append("\">");
392
            document.append(fielddata);
393
            document.append("</param>");
394

    
395
            tableHasRows = rs.next();
396
            if (docListResult.containsKey(docid))
397
            {
398
              String removedelement = (String)docListResult.remove(docid);
399
              docListResult.put(docid, removedelement + document.toString());
400
            }
401
            else
402
            {
403
              docListResult.put(docid, document.toString()); 
404
            }
405
          }
406
          rs.close();
407
        }
408

    
409
        //this loop adds the relation data to the resultdoc
410
        //this code might be able to be added to the backtracking code above
411
        Enumeration docidkeys = docListResult.keys();
412
        while(docidkeys.hasMoreElements())
413
        {
414
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
415
          String connstring = "%docid=";
416
          String docidkey = (String)docidkeys.nextElement();
417

    
418
          pstmt.close();
419
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
420
          pstmt.execute();
421
          rs = pstmt.getResultSet();
422
          tableHasRows = rs.next();
423
          while(tableHasRows)
424
          {
425
            String sub = rs.getString(1);
426
            String rel = rs.getString(2);
427
            String obj = rs.getString(3);
428
            String subDT = rs.getString(4);
429
            String objDT = rs.getString(5);
430
            
431
            //MetacatURL murl = new MetacatURL(sub);
432
            //we only want to process metacat urls here.
433
            //if (murl.getProtocol().equals("metacat")) {
434
              //String[] tempparam = murl.getParam(0);
435
              //if (tempparam[0].equals("docid") && tempparam[1].equals(docidkey))
436
              //{
437
                document = new StringBuffer();
438
                document.append("<triple>");
439
                document.append("<subject>").append(sub);
440
                document.append("</subject>");
441
                if (!subDT.equals("null")) {
442
                  document.append("<subjectdoctype>").append(subDT);
443
                  document.append("</subjectdoctype>");
444
                }
445
                document.append("<relationship>").append(rel);
446
                document.append("</relationship>");
447
                document.append("<object>").append(obj);
448
                document.append("</object>");
449
                if (!objDT.equals("null")) {
450
                  document.append("<objectdoctype>").append(objDT);
451
                  document.append("</objectdoctype>");
452
                }
453
                document.append("</triple>");
454
                
455
                String removedelement = (String)docListResult.remove(docidkey);
456
                docListResult.put(docidkey, removedelement + 
457
                                  document.toString());
458
                
459
              //}
460
            //}
461
            tableHasRows = rs.next();
462
          }
463
          rs.close();
464
          pstmt.close();
465
        }
466
        
467
      } catch (SQLException e) {
468
        System.err.println("SQL Error in DBQuery.findDocuments: " + 
469
                           e.getMessage());
470
      } catch (IOException ioe) {
471
        System.err.println("IO error in DBQuery.findDocuments:");
472
        System.err.println(ioe.getMessage());
473
      } catch (Exception ee) {
474
        System.out.println("Exception in DBQuery.findDocuments: " + 
475
                           ee.getMessage());
476
      }
477
      finally {
478
        try
479
        {
480
          dbconn.close();
481
        }
482
        catch(SQLException sqle)
483
        {
484
          System.out.println("error closing conn in DBQuery.findDocuments");
485
        }
486
      }
487
    //System.out.println("docListResult: ");
488
    //System.out.println(docListResult.toString());
489
    return docListResult;
490
  }
491
  
492
  /**
493
   * returns a string array of the contents of a particular node. 
494
   * If the node appears more than once, the contents are returned 
495
   * in the order in which they appearred in the document.
496
   * @param nodename the name or path of the particular node.
497
   * @param docid the docid of the document you want the node from.
498
   * @param conn a database connection-this allows this method to be static
499
   */
500
  public static Object[] getNodeContent(String nodename, String docid, 
501
                                        Connection conn)
502
  {
503
    StringBuffer query = new StringBuffer();
504
    Vector result = new Vector();
505
    PreparedStatement pstmt = null;
506
    query.append("select nodedata from xml_nodes where parentnodeid in ");
507
    query.append("(select nodeid from xml_index where path like '");
508
    query.append(nodename);
509
    query.append("' and docid like '").append(docid).append("')");
510
    try
511
    {
512
      pstmt = conn.prepareStatement(query.toString());
513

    
514
      // Execute the SQL query using the JDBC connection
515
      pstmt.execute();
516
      ResultSet rs = pstmt.getResultSet();
517
      boolean tableHasRows = rs.next();
518
      while (tableHasRows) 
519
      {
520
        result.add(rs.getString(1));
521
        System.out.println(rs.getString(1));
522
        tableHasRows = rs.next();
523
      }
524
    } 
525
    catch (SQLException e) 
526
    {
527
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
528
    } finally {
529
      try
530
      {
531
        pstmt.close();
532
      }
533
      catch(SQLException sqle) {}
534
    }
535
    return result.toArray();
536
  }
537
  
538
  /**
539
   * format a structured query as an XML document that conforms
540
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
541
   * structured query engine
542
   *
543
   * @param params The list of parameters that should be included in the query
544
   */
545
  public static String createSQuery(Hashtable params)
546
  { 
547
    StringBuffer query = new StringBuffer();
548
    Enumeration elements;
549
    Enumeration keys;
550
    String filterDoctype = null;
551
    String casesensitive = null;
552
    String searchmode = null;
553
    Object nextkey;
554
    Object nextelement;
555
    //add the xml headers
556
    query.append("<?xml version=\"1.0\"?>\n");
557
    query.append("<pathquery version=\"1.0\">\n");
558

    
559
    if (params.containsKey("meta_file_id"))
560
    {
561
      query.append("<meta_file_id>");
562
      query.append( ((String[])params.get("meta_file_id"))[0]);
563
      query.append("</meta_file_id>");
564
    }
565
    
566
    if (params.containsKey("returndoctype"))
567
    {
568
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
569
      for(int i=0; i<returnDoctypes.length; i++)
570
      {
571
        String doctype = (String)returnDoctypes[i];
572

    
573
        if (!doctype.equals("any") && 
574
            !doctype.equals("ANY") &&
575
            !doctype.equals("") ) 
576
        {
577
          query.append("<returndoctype>").append(doctype);
578
          query.append("</returndoctype>");
579
        }
580
      }
581
    }
582
    
583
    if (params.containsKey("filterdoctype"))
584
    {
585
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
586
      for(int i=0; i<filterDoctypes.length; i++)
587
      {
588
        query.append("<filterdoctype>").append(filterDoctypes[i]);
589
        query.append("</filterdoctype>");
590
      }
591
    }
592
    
593
    if (params.containsKey("returnfield"))
594
    {
595
      String[] returnfield = ((String[])params.get("returnfield"));
596
      for(int i=0; i<returnfield.length; i++)
597
      {
598
        query.append("<returnfield>").append(returnfield[i]);
599
        query.append("</returnfield>");
600
      }
601
    }
602
    
603
    if (params.containsKey("owner"))
604
    {
605
      String[] owner = ((String[])params.get("owner"));
606
      for(int i=0; i<owner.length; i++)
607
      {
608
        query.append("<owner>").append(owner[i]);
609
        query.append("</owner>");
610
      }
611
    }
612
    
613
    if (params.containsKey("site"))
614
    {
615
      String[] site = ((String[])params.get("site"));
616
      for(int i=0; i<site.length; i++)
617
      {
618
        query.append("<site>").append(site[i]);
619
        query.append("</site>");
620
      }
621
    }
622
    
623
    //allows the dynamic switching of boolean operators
624
    if (params.containsKey("operator"))
625
    {
626
      query.append("<querygroup operator=\"" + 
627
                ((String[])params.get("operator"))[0] + "\">");
628
    }
629
    else
630
    { //the default operator is UNION
631
      query.append("<querygroup operator=\"UNION\">"); 
632
    }
633
        
634
    if (params.containsKey("casesensitive"))
635
    {
636
      casesensitive = ((String[])params.get("casesensitive"))[0]; 
637
    }
638
    else
639
    {
640
      casesensitive = "false"; 
641
    }
642
    
643
    if (params.containsKey("searchmode"))
644
    {
645
      searchmode = ((String[])params.get("searchmode"))[0]; 
646
    }
647
    else
648
    {
649
      searchmode = "contains"; 
650
    }
651
        
652
    //anyfield is a special case because it does a 
653
    //free text search.  It does not have a <pathexpr>
654
    //tag.  This allows for a free text search within the structured
655
    //query.  This is useful if the INTERSECT operator is used.
656
    if (params.containsKey("anyfield"))
657
    {
658
       String[] anyfield = ((String[])params.get("anyfield"));
659
       //allow for more than one value for anyfield
660
       for(int i=0; i<anyfield.length; i++)
661
       {
662
         if (!anyfield[i].equals(""))
663
         {
664
           query.append("<queryterm casesensitive=\"" + casesensitive + 
665
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
666
                        anyfield[i] +
667
                        "</value></queryterm>"); 
668
         }
669
       }
670
    }
671
        
672
    //this while loop finds the rest of the parameters
673
    //and attempts to query for the field specified
674
    //by the parameter.
675
    elements = params.elements();
676
    keys = params.keys();
677
    while(keys.hasMoreElements() && elements.hasMoreElements())
678
    {
679
      nextkey = keys.nextElement();
680
      nextelement = elements.nextElement();
681

    
682
      //make sure we aren't querying for any of these
683
      //parameters since the are already in the query
684
      //in one form or another.
685
      if (!nextkey.toString().equals("returndoctype") && 
686
         !nextkey.toString().equals("filterdoctype")  &&
687
         !nextkey.toString().equals("action")  &&
688
         !nextkey.toString().equals("qformat") && 
689
         !nextkey.toString().equals("anyfield") &&
690
         !nextkey.toString().equals("returnfield") &&
691
         !nextkey.toString().equals("owner") &&
692
         !nextkey.toString().equals("site") &&
693
         !nextkey.toString().equals("operator") )
694
      {
695
        //allow for more than value per field name
696
        for(int i=0; i<((String[])nextelement).length; i++)
697
        {
698
          if (!((String[])nextelement)[i].equals(""))
699
          {
700
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " + 
701
                         "searchmode=\"" + searchmode + "\">" +
702
                         "<value>" +
703
                         //add the query value
704
                         ((String[])nextelement)[i] +
705
                         "</value><pathexpr>" +
706
                         //add the path to query by 
707
                         nextkey.toString() + 
708
                         "</pathexpr></queryterm>");
709
          }
710
        }
711
      }
712
    }
713
    query.append("</querygroup></pathquery>");
714
    //append on the end of the xml and return the result as a string
715
    return query.toString();
716
  }
717
  
718
  /**
719
   * format a simple free-text value query as an XML document that conforms
720
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
721
   * structured query engine
722
   *
723
   * @param value the text string to search for in the xml catalog
724
   * @param doctype the type of documents to include in the result set -- use
725
   *        "any" or "ANY" for unfiltered result sets
726
   */
727
   public static String createQuery(String value, String doctype) {
728
     StringBuffer xmlquery = new StringBuffer();
729
     xmlquery.append("<?xml version=\"1.0\"?>\n");
730
     xmlquery.append("<pathquery version=\"1.0\">");
731

    
732
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
733
       xmlquery.append("<returndoctype>");
734
       xmlquery.append(doctype).append("</returndoctype>");
735
     }
736

    
737
     xmlquery.append("<querygroup operator=\"UNION\">");
738
     //chad added - 8/14
739
     //the if statement allows a query to gracefully handle a null 
740
     //query.  Without this if a nullpointerException is thrown.
741
     if (!value.equals(""))
742
     {
743
       xmlquery.append("<queryterm casesensitive=\"false\" ");
744
       xmlquery.append("searchmode=\"contains\">");
745
       xmlquery.append("<value>").append(value).append("</value>");
746
       xmlquery.append("</queryterm>");
747
     }
748
     xmlquery.append("</querygroup>");
749
     xmlquery.append("</pathquery>");
750

    
751
     
752
     return (xmlquery.toString());
753
   }
754

    
755
  /**
756
   * format a simple free-text value query as an XML document that conforms
757
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
758
   * structured query engine
759
   *
760
   * @param value the text string to search for in the xml catalog
761
   */
762
   public static String createQuery(String value) {
763
     return createQuery(value, "any");
764
   }
765
   
766
  /** 
767
    * Check for "READ" permission on @docid for @user and/or @group 
768
    * from DB connection 
769
    */
770
  private boolean hasPermission ( Connection conn, String user,
771
                                  String group, String docid ) 
772
                  throws SQLException
773
  {
774
    // b' of the command line invocation
775
    if ( (user == null) && (group == null) ) {
776
      return true;
777
    }
778
    
779
    // Check for READ permission on @docid for @user and/or @group
780
    AccessControlList aclobj = new AccessControlList(conn);
781
    boolean hasPermission = aclobj.hasPermission("READ",user,docid);
782
    if ( !hasPermission && group != null ) {
783
      hasPermission = aclobj.hasPermission("READ",group,docid);
784
    }
785
    
786
    return hasPermission;
787
  }
788
   
789
}
(14-14/43)