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-09-17 10:01:05 -0700 (Mon, 17 Sep 2001) $'
15
 * '$Revision: 834 $'
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[] groups)
187
  {
188
    return findDocuments(xmlquery, user, groups, 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[] groups,
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
  //System.out.println(qspec.printSQL(useXMLIndex)); 
231
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
232
  
233
        // Execute the SQL query using the JDBC connection
234
        pstmt.execute();
235
        ResultSet rs = pstmt.getResultSet();
236
        boolean tableHasRows = rs.next();
237
        while (tableHasRows) 
238
        {
239
          docid = rs.getString(1).trim();
240
          if ( !hasPermission(dbconn, user, groups, docid) ) {
241
            // Advance to the next record in the cursor
242
            tableHasRows = rs.next();
243
            continue;
244
          }
245
          docname = rs.getString(2);
246
          doctype = rs.getString(3);
247
          createDate = rs.getString(4);
248
          updateDate = rs.getString(5);
249
          rev = rs.getInt(6);
250

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

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

    
273
            btBuf.append("and (subject like '");
274
            btBuf.append(docid).append(sep).append(rev).append("'");
275
            btBuf.append("or object like '");
276
            btBuf.append(docid).append(sep).append(rev).append("')");
277
            
278
            PreparedStatement npstmt = dbconn.
279
                                       prepareStatement(btBuf.toString());
280
            npstmt.execute();
281
            ResultSet btrs = npstmt.getResultSet();
282
            boolean hasBtRows = btrs.next();
283
            while (hasBtRows)
284
            { //there was a backtrackable document found
285
              DocumentImpl xmldoc = null;
286
              String packageDocid = btrs.getString(1);
287
              util.debugMessage("Getting document for docid: " + packageDocid);
288
              try
289
              {
290
                //  THIS CONSTRUCTOR BUILDS THE WHOLE XML doc not needed here
291
                // xmldoc = new DocumentImpl(dbconn, packageDocid);
292
                //  thus use the following to get the doc info only
293
                //  xmldoc = new DocumentImpl(dbconn);
294
                xmldoc = new DocumentImpl(dbconn, packageDocid, false);
295
                if (xmldoc == null) {
296
                  util.debugMessage("Document was null for: " + packageDocid);
297
                }
298
              }
299
              catch(Exception e)
300
              {
301
                System.out.println("Error getting document in " + 
302
                                   "DBQuery.findDocuments: " + e.getMessage());
303
              }
304
              
305
              String docid_org = xmldoc.getDocID();
306
              if (docid_org == null) {
307
                util.debugMessage("Docid_org was null.");
308
              }
309
              docid   = docid_org.trim();
310
              docname = xmldoc.getDocname();
311
              doctype = xmldoc.getDoctype();
312
              createDate = xmldoc.getCreateDate();
313
              updateDate = xmldoc.getUpdateDate();
314
              rev = xmldoc.getRev();
315

    
316
              document = new StringBuffer();
317

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

    
346
            String completeDocid = docid + util.getOption("accNumSeparator");
347
            completeDocid += rev;
348
            document.append("<docid>").append(completeDocid).append("</docid>");
349
            if (docname != null) {
350
              document.append("<docname>" + docname + "</docname>");
351
            }
352
            if (doctype != null) {
353
              document.append("<doctype>" + doctype + "</doctype>");
354
            }
355
            if (createDate != null) {
356
              document.append("<createdate>" + createDate + "</createdate>");
357
            }
358
            if (updateDate != null) {
359
              document.append("<updatedate>" + updateDate + "</updatedate>");
360
            }
361
            // Store the document id and the root node id
362
            docListResult.put(docid,(String)document.toString());
363
  
364
          }
365

    
366
          // Advance to the next record in the cursor
367
          tableHasRows = rs.next();
368
        }
369
        rs.close();
370
        pstmt.close();
371
        
372
        if (qspec.containsExtendedSQL())
373
        {
374
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
375
          Vector results = new Vector();
376
          Enumeration keylist = docListResult.keys();
377
          StringBuffer doclist = new StringBuffer();
378
          while(keylist.hasMoreElements())
379
          {
380
            doclist.append("'");
381
            doclist.append((String)keylist.nextElement());
382
            doclist.append("',");
383
          }
384
          if (doclist.length() > 0) {
385
            doclist.deleteCharAt(doclist.length()-1); //remove the last comma
386
            //pstmt.close();
387
            pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
388
                                        doclist.toString()));
389
            pstmt.execute();
390
            rs = pstmt.getResultSet();
391
            tableHasRows = rs.next();
392
            while(tableHasRows) 
393
            {
394
              docid = rs.getString(1).trim();
395
              if ( !hasPermission(dbconn, user, groups, docid) ) {
396
                // Advance to the next record in the cursor
397
                tableHasRows = rs.next();
398
                continue;
399
              }
400
              fieldname = rs.getString(2);
401
              fielddata = rs.getString(3);
402
              
403
              document = new StringBuffer();
404
  
405
              document.append("<param name=\"");
406
              document.append(fieldname);
407
              document.append("\">");
408
              document.append(fielddata);
409
              document.append("</param>");
410
  
411
              tableHasRows = rs.next();
412
              if (docListResult.containsKey(docid))
413
              {
414
                String removedelement = (String)docListResult.remove(docid);
415
                docListResult.put(docid, removedelement + document.toString());
416
              }
417
              else
418
              {
419
                docListResult.put(docid, document.toString()); 
420
              }
421
            }
422
          }
423
          rs.close();
424
        }
425
        pstmt.close();
426
        
427
        //this loop adds the relation data to the resultdoc
428
        //this code might be able to be added to the backtracking code above
429
        Enumeration docidkeys = docListResult.keys();
430
        while(docidkeys.hasMoreElements())
431
        {
432
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
433
          String connstring = "%docid=";
434
          String docidkey = (String)docidkeys.nextElement();
435
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
436
          pstmt.execute();
437
          rs = pstmt.getResultSet();
438
          tableHasRows = rs.next();
439
          while(tableHasRows)
440
          {
441
            String sub = rs.getString(1);
442
            String rel = rs.getString(2);
443
            String obj = rs.getString(3);
444
            String subDT = rs.getString(4);
445
            String objDT = rs.getString(5);
446
            
447
            //MetacatURL murl = new MetacatURL(sub);
448
            //we only want to process metacat urls here.
449
            //if (murl.getProtocol().equals("metacat")) {
450
              //String[] tempparam = murl.getParam(0);
451
              //if (tempparam[0].equals("docid") && tempparam[1].equals(docidkey))
452
              //{
453
                document = new StringBuffer();
454
                document.append("<triple>");
455
                document.append("<subject>").append(sub);
456
                document.append("</subject>");
457
                //if (!subDT.equals("null")) {
458
                if ( subDT != null ) {
459
                  document.append("<subjectdoctype>").append(subDT);
460
                  document.append("</subjectdoctype>");
461
                }
462
                document.append("<relationship>").append(rel);
463
                document.append("</relationship>");
464
                document.append("<object>").append(obj);
465
                document.append("</object>");
466
                //if (!objDT.equals("null")) {
467
                if ( objDT != null ) {
468
                  document.append("<objectdoctype>").append(objDT);
469
                  document.append("</objectdoctype>");
470
                }
471
                document.append("</triple>");
472
                
473
                String removedelement = (String)docListResult.remove(docidkey);
474
                docListResult.put(docidkey, removedelement + 
475
                                  document.toString());
476
                
477
              //}
478
            //}
479
            tableHasRows = rs.next();
480
          }
481
          rs.close();
482
          pstmt.close();
483
        }
484
        
485
      } catch (SQLException e) {
486
        System.err.println("SQL Error in DBQuery.findDocuments: " + 
487
                           e.getMessage());
488
      } catch (IOException ioe) {
489
        System.err.println("IO error in DBQuery.findDocuments:");
490
        System.err.println(ioe.getMessage());
491
      } catch (Exception ee) {
492
        System.err.println("Exception in DBQuery.findDocuments: " + 
493
                           ee.getMessage());
494
        ee.printStackTrace(System.err);
495
      }
496
      finally {
497
        try
498
        {
499
          dbconn.close();
500
        //  dbconn2.close();
501
        }
502
        catch(SQLException sqle)
503
        {
504
          System.out.println("error closing conn in DBQuery.findDocuments");
505
        }
506
      }
507
    //System.out.println("docListResult: ");
508
    //System.out.println(docListResult.toString());
509
    return docListResult;
510
  }
511
  
512
  /**
513
   * returns a string array of the contents of a particular node. 
514
   * If the node appears more than once, the contents are returned 
515
   * in the order in which they appearred in the document.
516
   * @param nodename the name or path of the particular node.
517
   * @param docid the docid of the document you want the node from.
518
   * @param conn a database connection-this allows this method to be static
519
   */
520
  public static Object[] getNodeContent(String nodename, String docid, 
521
                                        Connection conn)
522
  {
523
    StringBuffer query = new StringBuffer();
524
    Vector result = new Vector();
525
    PreparedStatement pstmt = null;
526
    query.append("select nodedata from xml_nodes where parentnodeid in ");
527
    query.append("(select nodeid from xml_index where path like '");
528
    query.append(nodename);
529
    query.append("' and docid like '").append(docid).append("')");
530
    try
531
    {
532
      pstmt = conn.prepareStatement(query.toString());
533

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

    
579
    if (params.containsKey("meta_file_id"))
580
    {
581
      query.append("<meta_file_id>");
582
      query.append( ((String[])params.get("meta_file_id"))[0]);
583
      query.append("</meta_file_id>");
584
    }
585
    
586
    if (params.containsKey("returndoctype"))
587
    {
588
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
589
      for(int i=0; i<returnDoctypes.length; i++)
590
      {
591
        String doctype = (String)returnDoctypes[i];
592

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

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

    
752
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
753
       xmlquery.append("<returndoctype>");
754
       xmlquery.append(doctype).append("</returndoctype>");
755
     }
756

    
757
     xmlquery.append("<querygroup operator=\"UNION\">");
758
     //chad added - 8/14
759
     //the if statement allows a query to gracefully handle a null 
760
     //query.  Without this if a nullpointerException is thrown.
761
     if (!value.equals(""))
762
     {
763
       xmlquery.append("<queryterm casesensitive=\"false\" ");
764
       xmlquery.append("searchmode=\"contains\">");
765
       xmlquery.append("<value>").append(value).append("</value>");
766
       xmlquery.append("</queryterm>");
767
     }
768
     xmlquery.append("</querygroup>");
769
     xmlquery.append("</pathquery>");
770

    
771
     
772
     return (xmlquery.toString());
773
   }
774

    
775
  /**
776
   * format a simple free-text value query as an XML document that conforms
777
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
778
   * structured query engine
779
   *
780
   * @param value the text string to search for in the xml catalog
781
   */
782
   public static String createQuery(String value) {
783
     return createQuery(value, "any");
784
   }
785
   
786
  /** 
787
    * Check for "READ" permission on @docid for @user and/or @group 
788
    * from DB connection 
789
    */
790
  private boolean hasPermission ( Connection conn, String user,
791
                                  String[] groups, String docid ) 
792
                  throws SQLException
793
  {
794
    // Check for READ permission on @docid for @user and/or @groups
795
    AccessControlList aclobj = new AccessControlList(conn);
796
    return aclobj.hasPermission("READ", user, groups, docid);
797
  }
798
   
799
}
(14-14/40)