Project

General

Profile

1 155 jones
/**
2 203 jones
 *  '$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 349 jones
 *    Release: @release@
12 155 jones
 *
13 203 jones
 *   '$Author$'
14
 *     '$Date$'
15
 * '$Revision$'
16 669 jones
 *
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 155 jones
 */
31
32 607 bojilova
package edu.ucsb.nceas.metacat;
33 155 jones
34
import java.io.*;
35 401 berkley
import java.util.Vector;
36 155 jones
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 706 bojilova
import java.io.File;
43
import java.io.FileWriter;
44
import java.io.BufferedWriter;
45 155 jones
46
/**
47 172 jones
 * 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 155 jones
 */
53
public class DBQuery {
54
55 441 bojilova
  static final int ALL = 1;
56
  static final int WRITE = 2;
57
  static final int READ = 4;
58
59 535 jones
  private Connection  conn = null;
60
  private String  parserName = null;
61 465 berkley
  private MetaCatUtil util = new MetaCatUtil();
62 155 jones
  /**
63
   * the main routine used to test the DBQuery utility.
64 184 jones
   * <p>
65
   * Usage: java DBQuery <xmlfile>
66 155 jones
   *
67 170 jones
   * @param xmlfile the filename of the xml file containing the query
68 155 jones
   */
69
  static public void main(String[] args) {
70
71 184 jones
     if (args.length < 1)
72 155 jones
     {
73
        System.err.println("Wrong number of arguments!!!");
74 706 bojilova
        System.err.println("USAGE: java DBQuery [-t] [-index] <xmlfile>");
75 155 jones
        return;
76
     } else {
77
        try {
78
79 706 bojilova
          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 155 jones
          // Open a connection to the database
96 184 jones
          MetaCatUtil   util = new MetaCatUtil();
97
          Connection dbconn = util.openDBConnection();
98 706 bojilova
99 705 berkley
          double connTime = System.currentTimeMillis();
100 706 bojilova
101 170 jones
          // Execute the query
102 184 jones
          DBQuery queryobj = new DBQuery(dbconn, util.getOption("saxparser"));
103 170 jones
          FileReader xml = new FileReader(new File(xmlfile));
104 155 jones
          Hashtable nodelist = null;
105 706 bojilova
          nodelist = queryobj.findDocuments(xml, null, null, useXMLIndex);
106
107 172 jones
          // Print the reulting document listing
108 155 jones
          StringBuffer result = new StringBuffer();
109
          String document = null;
110 170 jones
          String docid = null;
111 155 jones
          result.append("<?xml version=\"1.0\"?>\n");
112 296 higgins
          result.append("<resultset>\n");
113 706 bojilova
  // following line removed by Dan Higgins to avoid insertion of query XML inside returned XML doc
114 710 berkley
  //        result.append("  <query>" + xmlfile + "</query>\n");
115 743 jones
          if (!showRuntime)
116 710 berkley
          {
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 155 jones
          }
127 706 bojilova
          // Time the request if asked for
128
          double stopTime = System.currentTimeMillis();
129 705 berkley
          double dbOpenTime = (connTime - startTime)/1000;
130 706 bojilova
          double readTime = (stopTime - connTime)/1000;
131 705 berkley
          double executionTime = (stopTime - startTime)/1000;
132 706 bojilova
          if (showRuntime) {
133 710 berkley
            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 706 bojilova
          }
139
          //System.out.println(result);
140
          //write into a file "result.txt"
141 743 jones
          if (!showRuntime)
142 710 berkley
          {
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 675 berkley
          System.err.println("Error in DBQuery.main");
155 155 jones
          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 172 jones
   * @param parserName the fully qualified name of a Java class implementing
169 185 jones
   *                   the org.xml.sax.XMLReader interface
170 155 jones
   */
171 172 jones
  public DBQuery( Connection conn, String parserName )
172 155 jones
                  throws IOException,
173
                         SQLException,
174 172 jones
                         ClassNotFoundException {
175 155 jones
    this.conn = conn;
176 172 jones
    this.parserName = parserName;
177 155 jones
  }
178
179 706 bojilova
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
180
                                 boolean useXMLIndex)
181 465 berkley
  {
182 706 bojilova
    return findDocuments(xmlquery, user, group, null, useXMLIndex);
183 465 berkley
  }
184
185 706 bojilova
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
186
                                 String[] returndoc)
187
  {
188
    return findDocuments(xmlquery, user, group, returndoc, true);
189
  }
190
191 155 jones
  /**
192
   * routine to search the elements and attributes looking to match query
193
   *
194 178 jones
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
195 465 berkley
   * @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 155 jones
   */
199 465 berkley
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
200 706 bojilova
                                 String[] returndoc, boolean useXMLIndex)
201 453 berkley
  {
202 535 jones
      Hashtable   docListResult = new Hashtable();
203 667 berkley
      PreparedStatement pstmt = null;
204 170 jones
      String docid = null;
205 155 jones
      String docname = null;
206
      String doctype = null;
207 401 berkley
      String createDate = null;
208
      String updateDate = null;
209
      String fieldname = null;
210
      String fielddata = null;
211 453 berkley
      String relation = null;
212 667 berkley
      Connection dbconn = null;
213 624 berkley
      int rev = 0;
214 155 jones
      StringBuffer document = null;
215 465 berkley
      Vector returndocVec = new Vector();
216
217 743 jones
      //add the returndoc elements to a vector for easier manipulation
218
      if (returndoc != null)
219
      {
220 465 berkley
        for(int i=0; i<returndoc.length; i++)
221
        {
222
          returndocVec.add(new String((String)returndoc[i]));
223
        }
224
      }
225
226 155 jones
      try {
227 743 jones
        if (conn == null || conn.isClosed()) {
228 710 berkley
          dbconn = util.openDBConnection();
229 743 jones
        } else {
230 710 berkley
          dbconn = conn;
231
        }
232 172 jones
        // Get the XML query and covert it into a SQL statment
233 178 jones
        QuerySpecification qspec = new QuerySpecification(xmlquery,
234 535 jones
                                   parserName,
235 624 berkley
                                   util.getOption("accNumSeparator"));
236 706 bojilova
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
237 155 jones
238 172 jones
        // Execute the SQL query using the JDBC connection
239 155 jones
        pstmt.execute();
240
        ResultSet rs = pstmt.getResultSet();
241
        boolean tableHasRows = rs.next();
242 667 berkley
        while (tableHasRows)
243
        {
244 170 jones
          docid = rs.getString(1);
245 667 berkley
          if ( !hasPermission(dbconn, user, group, docid) ) {
246 612 bojilova
            // Advance to the next record in the cursor
247
            tableHasRows = rs.next();
248
            continue;
249
          }
250 155 jones
          docname = rs.getString(2);
251
          doctype = rs.getString(3);
252 692 bojilova
          createDate = rs.getString(4);
253
          updateDate = rs.getString(5);
254
          rev = rs.getInt(6);
255 743 jones
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 465 berkley
            StringBuffer btBuf = new StringBuffer();
262 743 jones
            btBuf.append("select docid from xml_relation where ");
263
264 465 berkley
            //build the doctype list for the backtracking sql statement
265 743 jones
            btBuf.append("packagetype in (");
266 465 berkley
            for(int i=0; i<returndocVec.size(); i++)
267
            {
268
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
269 743 jones
              if (i != (returndocVec.size() - 1))
270 465 berkley
              {
271
                btBuf.append(", ");
272 475 berkley
              }
273 465 berkley
            }
274
            btBuf.append(") ");
275 743 jones
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 667 berkley
281 743 jones
            PreparedStatement npstmt = dbconn.
282
                                       prepareStatement(btBuf.toString());
283 671 berkley
            npstmt.execute();
284
            ResultSet btrs = npstmt.getResultSet();
285 465 berkley
            boolean hasBtRows = btrs.next();
286 743 jones
            while (hasBtRows)
287 465 berkley
            { //there was a backtrackable document found
288
              DocumentImpl xmldoc = null;
289 743 jones
              String packageDocid = btrs.getString(1);
290
              //MetacatURL objURL = new MetacatURL(packageDocid);
291 465 berkley
              try
292
              {
293 743 jones
                //xmldoc = new DocumentImpl(dbconn, objURL.getParam(0)[1]);
294
                xmldoc = new DocumentImpl(dbconn, packageDocid);
295 465 berkley
              }
296
              catch(Exception e)
297
              {
298 675 berkley
                System.out.println("Error getting document in " +
299
                                   "DBQuery.findDocuments: " + e.getMessage());
300 465 berkley
              }
301
302
              docid   = xmldoc.getDocID();
303
              docname = xmldoc.getDocname();
304
              doctype = xmldoc.getDoctype();
305
              createDate = xmldoc.getCreateDate();
306
              updateDate = xmldoc.getUpdateDate();
307 743 jones
              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 465 berkley
            }
333 671 berkley
            npstmt.close();
334 465 berkley
            btrs.close();
335 743 jones
          } else {
336 465 berkley
337 743 jones
            document = new StringBuffer();
338
339 624 berkley
            String completeDocid = docid + util.getOption("accNumSeparator");
340
            completeDocid += rev;
341
            document.append("<docid>").append(completeDocid).append("</docid>");
342 465 berkley
            if (docname != null) {
343
              document.append("<docname>" + docname + "</docname>");
344
            }
345
            if (doctype != null) {
346
              document.append("<doctype>" + doctype + "</doctype>");
347
            }
348 743 jones
            if (createDate != null) {
349 465 berkley
              document.append("<createdate>" + createDate + "</createdate>");
350
            }
351 743 jones
            if (updateDate != null) {
352 465 berkley
              document.append("<updatedate>" + updateDate + "</updatedate>");
353
            }
354
            // Store the document id and the root node id
355
            docListResult.put(docid,(String)document.toString());
356 743 jones
357 155 jones
          }
358
359
          // Advance to the next record in the cursor
360
          tableHasRows = rs.next();
361
        }
362 667 berkley
        rs.close();
363 671 berkley
        //pstmt.close();
364 401 berkley
365 743 jones
        if (qspec.containsExtendedSQL())
366 401 berkley
        {
367
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
368
          Vector results = new Vector();
369 465 berkley
          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 667 berkley
          pstmt.close();
379
          pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
380 465 berkley
                                        doclist.toString()));
381 401 berkley
          pstmt.execute();
382
          rs = pstmt.getResultSet();
383
          tableHasRows = rs.next();
384
          while(tableHasRows)
385
          {
386
            docid = rs.getString(1);
387 673 bojilova
            if ( !hasPermission(dbconn, user, group, docid) ) {
388
              // Advance to the next record in the cursor
389
              tableHasRows = rs.next();
390
              continue;
391
            }
392 401 berkley
            fieldname = rs.getString(2);
393
            fielddata = rs.getString(3);
394
395
            document = new StringBuffer();
396
397 423 berkley
            document.append("<param name=\"");
398 405 berkley
            document.append(fieldname);
399 423 berkley
            document.append("\">");
400 401 berkley
            document.append(fielddata);
401 423 berkley
            document.append("</param>");
402 401 berkley
403
            tableHasRows = rs.next();
404 743 jones
            if (docListResult.containsKey(docid))
405 401 berkley
            {
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 667 berkley
          rs.close();
415 401 berkley
        }
416 453 berkley
417 465 berkley
        //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 453 berkley
        {
422 602 berkley
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
423
          String connstring = "%docid=";
424 465 berkley
          String docidkey = (String)docidkeys.nextElement();
425 743 jones
426 667 berkley
          pstmt.close();
427 743 jones
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
428 465 berkley
          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 489 berkley
            String subDT = rs.getString(4);
437
            String objDT = rs.getString(5);
438
439 743 jones
            //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 465 berkley
                document = new StringBuffer();
446 743 jones
                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 465 berkley
463
                String removedelement = (String)docListResult.remove(docidkey);
464 743 jones
                docListResult.put(docidkey, removedelement +
465
                                  document.toString());
466 465 berkley
467 743 jones
              //}
468
            //}
469 465 berkley
            tableHasRows = rs.next();
470 453 berkley
          }
471 667 berkley
          rs.close();
472
          pstmt.close();
473 453 berkley
        }
474 667 berkley
475 155 jones
      } catch (SQLException e) {
476 667 berkley
        System.err.println("SQL Error in DBQuery.findDocuments: " +
477
                           e.getMessage());
478 170 jones
      } catch (IOException ioe) {
479 675 berkley
        System.err.println("IO error in DBQuery.findDocuments:");
480 170 jones
        System.err.println(ioe.getMessage());
481 667 berkley
      } catch (Exception ee) {
482 675 berkley
        System.out.println("Exception in DBQuery.findDocuments: " +
483 667 berkley
                           ee.getMessage());
484 155 jones
      }
485 667 berkley
      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 423 berkley
    //System.out.println("docListResult: ");
496
    //System.out.println(docListResult.toString());
497 155 jones
    return docListResult;
498
  }
499 342 berkley
500
  /**
501 436 berkley
   * 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 667 berkley
    PreparedStatement pstmt = null;
514 436 berkley
    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 675 berkley
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
536 667 berkley
    } finally {
537
      try
538
      {
539
        pstmt.close();
540
      }
541
      catch(SQLException sqle) {}
542
    }
543 436 berkley
    return result.toArray();
544
  }
545
546
  /**
547 342 berkley
   * 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 743 jones
   * @param params The list of parameters that should be included in the query
552 342 berkley
   */
553 372 berkley
  public static String createSQuery(Hashtable params)
554 350 berkley
  {
555
    StringBuffer query = new StringBuffer();
556 342 berkley
    Enumeration elements;
557
    Enumeration keys;
558 743 jones
    String filterDoctype = null;
559 372 berkley
    String casesensitive = null;
560
    String searchmode = null;
561 342 berkley
    Object nextkey;
562
    Object nextelement;
563 350 berkley
    //add the xml headers
564
    query.append("<?xml version=\"1.0\"?>\n");
565 743 jones
    query.append("<pathquery version=\"1.0\">\n");
566
567
    if (params.containsKey("meta_file_id"))
568 342 berkley
    {
569 743 jones
      query.append("<meta_file_id>");
570 342 berkley
      query.append( ((String[])params.get("meta_file_id"))[0]);
571 535 jones
      query.append("</meta_file_id>");
572 342 berkley
    }
573 350 berkley
574 743 jones
    if (params.containsKey("returndoctype"))
575 372 berkley
    {
576 744 jones
      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 372 berkley
    }
590 744 jones
591 743 jones
    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 372 berkley
601 743 jones
    if (params.containsKey("returnfield"))
602 401 berkley
    {
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 743 jones
    if (params.containsKey("owner"))
612 535 jones
    {
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 743 jones
    if (params.containsKey("site"))
622 535 jones
    {
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 350 berkley
    //allows the dynamic switching of boolean operators
632 743 jones
    if (params.containsKey("operator"))
633 350 berkley
    {
634
      query.append("<querygroup operator=\"" +
635 535 jones
                ((String[])params.get("operator"))[0] + "\">");
636 350 berkley
    }
637
    else
638
    { //the default operator is UNION
639
      query.append("<querygroup operator=\"UNION\">");
640
    }
641 535 jones
642 743 jones
    if (params.containsKey("casesensitive"))
643 372 berkley
    {
644
      casesensitive = ((String[])params.get("casesensitive"))[0];
645
    }
646
    else
647
    {
648
      casesensitive = "false";
649
    }
650
651 743 jones
    if (params.containsKey("searchmode"))
652 372 berkley
    {
653
      searchmode = ((String[])params.get("searchmode"))[0];
654
    }
655
    else
656
    {
657
      searchmode = "contains";
658
    }
659 535 jones
660 342 berkley
    //anyfield is a special case because it does a
661
    //free text search.  It does not have a <pathexpr>
662 350 berkley
    //tag.  This allows for a free text search within the structured
663
    //query.  This is useful if the INTERSECT operator is used.
664 743 jones
    if (params.containsKey("anyfield"))
665 342 berkley
    {
666 372 berkley
       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 350 berkley
       {
670 743 jones
         if (!anyfield[i].equals(""))
671 372 berkley
         {
672
           query.append("<queryterm casesensitive=\"" + casesensitive +
673
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
674 535 jones
                        anyfield[i] +
675
                        "</value></queryterm>");
676 372 berkley
         }
677 350 berkley
       }
678 342 berkley
    }
679 535 jones
680 342 berkley
    //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 535 jones
      nextelement = elements.nextElement();
689 372 berkley
690 535 jones
      //make sure we aren't querying for any of these
691
      //parameters since the are already in the query
692 342 berkley
      //in one form or another.
693 743 jones
      if (!nextkey.toString().equals("returndoctype") &&
694
         !nextkey.toString().equals("filterdoctype")  &&
695 535 jones
         !nextkey.toString().equals("action")  &&
696
         !nextkey.toString().equals("qformat") &&
697
         !nextkey.toString().equals("anyfield") &&
698 401 berkley
         !nextkey.toString().equals("returnfield") &&
699 535 jones
         !nextkey.toString().equals("owner") &&
700
         !nextkey.toString().equals("site") &&
701
         !nextkey.toString().equals("operator") )
702
      {
703 372 berkley
        //allow for more than value per field name
704
        for(int i=0; i<((String[])nextelement).length; i++)
705
        {
706 743 jones
          if (!((String[])nextelement)[i].equals(""))
707 372 berkley
          {
708
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " +
709 535 jones
                         "searchmode=\"" + searchmode + "\">" +
710
                         "<value>" +
711 372 berkley
                         //add the query value
712 535 jones
                         ((String[])nextelement)[i] +
713
                         "</value><pathexpr>" +
714
                         //add the path to query by
715 372 berkley
                         nextkey.toString() +
716
                         "</pathexpr></queryterm>");
717
          }
718
        }
719 535 jones
      }
720 342 berkley
    }
721
    query.append("</querygroup></pathquery>");
722 350 berkley
    //append on the end of the xml and return the result as a string
723 342 berkley
    return query.toString();
724
  }
725
726 181 jones
  /**
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 350 berkley
     //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 743 jones
     if (!value.equals(""))
750 350 berkley
     {
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 181 jones
     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 441 bojilova
774 570 bojilova
  /**
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 605 bojilova
                  throws SQLException
781 570 bojilova
  {
782 441 bojilova
    // b' of the command line invocation
783
    if ( (user == null) && (group == null) ) {
784
      return true;
785
    }
786
787 570 bojilova
    // Check for READ permission on @docid for @user and/or @group
788 607 bojilova
    AccessControlList aclobj = new AccessControlList(conn);
789
    boolean hasPermission = aclobj.hasPermission("READ",user,docid);
790 570 bojilova
    if ( !hasPermission && group != null ) {
791 607 bojilova
      hasPermission = aclobj.hasPermission("READ",group,docid);
792 441 bojilova
    }
793 570 bojilova
794
    return hasPermission;
795 441 bojilova
  }
796
797 155 jones
}