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: bojilova $'
14
 *     '$Date: 2001-06-01 16:12:52 -0700 (Fri, 01 Jun 2001) $'
15
 * '$Revision: 768 $'
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
      Connection dbconn2 = null;
214
      int rev = 0;
215
      StringBuffer document = null; 
216
      
217
      try {
218
        if (conn == null || conn.isClosed()) {
219
          dbconn = util.openDBConnection();
220
        } else {
221
          dbconn = conn;
222
        }
223
        // problem with ODBC driver multi-threading
224
        dbconn2 = util.openDBConnection(); // for use by AccessControlList
225
        
226
        // Get the XML query and covert it into a SQL statment
227
        QuerySpecification qspec = new QuerySpecification(xmlquery, 
228
                                   parserName, 
229
                                   util.getOption("accNumSeparator"));
230
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
231

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

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

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

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

    
305
              document = new StringBuffer();
306

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

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

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

    
393
            document.append("<param name=\"");
394
            document.append(fieldname);
395
            document.append("\">");
396
            document.append(fielddata);
397
            document.append("</param>");
398

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

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

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

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

    
564
    if (params.containsKey("meta_file_id"))
565
    {
566
      query.append("<meta_file_id>");
567
      query.append( ((String[])params.get("meta_file_id"))[0]);
568
      query.append("</meta_file_id>");
569
    }
570
    
571
    if (params.containsKey("returndoctype"))
572
    {
573
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
574
      for(int i=0; i<returnDoctypes.length; i++)
575
      {
576
        String doctype = (String)returnDoctypes[i];
577

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

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

    
737
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
738
       xmlquery.append("<returndoctype>");
739
       xmlquery.append(doctype).append("</returndoctype>");
740
     }
741

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

    
756
     
757
     return (xmlquery.toString());
758
   }
759

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