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-21 14:30:41 -0700 (Mon, 21 May 2001) $'
15
 * '$Revision: 744 $'
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
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
180
                                 boolean useXMLIndex)
181
  {
182
    return findDocuments(xmlquery, user, group, null, useXMLIndex);
183
  }
184
  
185
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
186
                                 String[] returndoc)
187
  {
188
    return findDocuments(xmlquery, user, group, returndoc, 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 returndoc an array of document types to backtrack against.
198
   */
199
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
200
                                 String[] returndoc, 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
      Vector returndocVec = new Vector();
216
      
217
      //add the returndoc elements to a vector for easier manipulation
218
      if (returndoc != null)
219
      {
220
        for(int i=0; i<returndoc.length; i++)
221
        {
222
          returndocVec.add(new String((String)returndoc[i]));
223
        }
224
      }
225
      
226
      try {
227
        if (conn == null || conn.isClosed()) {
228
          dbconn = util.openDBConnection();
229
        } else {
230
          dbconn = conn;
231
        }
232
        // Get the XML query and covert it into a SQL statment
233
        QuerySpecification qspec = new QuerySpecification(xmlquery, 
234
                                   parserName, 
235
                                   util.getOption("accNumSeparator"));
236
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
237

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

    
256
          //if there are returndocs to match, backtracking can be performed
257
          // If no package exists, do not return the document
258
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype))
259
          { 
260
            String sep = util.getOption("accNumSeparator");
261
            StringBuffer btBuf = new StringBuffer();
262
            btBuf.append("select docid from xml_relation where ");
263

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

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

    
309
              document = new StringBuffer();
310

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

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

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

    
397
            document.append("<param name=\"");
398
            document.append(fieldname);
399
            document.append("\">");
400
            document.append(fielddata);
401
            document.append("</param>");
402

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

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

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

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

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

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

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

    
740
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
741
       xmlquery.append("<returndoctype>");
742
       xmlquery.append(doctype).append("</returndoctype>");
743
     }
744

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

    
759
     
760
     return (xmlquery.toString());
761
   }
762

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