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 372 berkley
    String doctype = null;
559 743 jones
    String filterDoctype = null;
560 372 berkley
    String casesensitive = null;
561
    String searchmode = null;
562 342 berkley
    Object nextkey;
563
    Object nextelement;
564 350 berkley
    //add the xml headers
565
    query.append("<?xml version=\"1.0\"?>\n");
566 743 jones
    query.append("<pathquery version=\"1.0\">\n");
567
568
    if (params.containsKey("meta_file_id"))
569 342 berkley
    {
570 743 jones
      query.append("<meta_file_id>");
571 342 berkley
      query.append( ((String[])params.get("meta_file_id"))[0]);
572 535 jones
      query.append("</meta_file_id>");
573 342 berkley
    }
574 350 berkley
575 743 jones
    if (params.containsKey("returndoctype"))
576 372 berkley
    {
577 743 jones
      doctype = ((String[])params.get("returndoctype"))[0];
578 372 berkley
    }
579
    else
580
    {
581
      doctype = "ANY";
582
    }
583 743 jones
584
    if (params.containsKey("filterdoctype"))
585
    {
586
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
587
      for(int i=0; i<filterDoctypes.length; i++)
588
      {
589
        query.append("<filterdoctype>").append(filterDoctypes[i]);
590
        query.append("</filterdoctype>");
591
      }
592
    }
593 372 berkley
594 743 jones
    if (params.containsKey("returnfield"))
595 401 berkley
    {
596
      String[] returnfield = ((String[])params.get("returnfield"));
597
      for(int i=0; i<returnfield.length; i++)
598
      {
599
        query.append("<returnfield>").append(returnfield[i]);
600
        query.append("</returnfield>");
601
      }
602
    }
603
604 743 jones
    if (params.containsKey("owner"))
605 535 jones
    {
606
      String[] owner = ((String[])params.get("owner"));
607
      for(int i=0; i<owner.length; i++)
608
      {
609
        query.append("<owner>").append(owner[i]);
610
        query.append("</owner>");
611
      }
612
    }
613
614 743 jones
    if (params.containsKey("site"))
615 535 jones
    {
616
      String[] site = ((String[])params.get("site"));
617
      for(int i=0; i<site.length; i++)
618
      {
619
        query.append("<site>").append(site[i]);
620
        query.append("</site>");
621
      }
622
    }
623
624 743 jones
    // back trace to doctype
625 342 berkley
    if (!doctype.equals("any") &&
626
        !doctype.equals("ANY") &&
627
        !doctype.equals("") )
628
    {
629
       query.append("<returndoctype>");
630
       query.append(doctype).append("</returndoctype>");
631
    }
632 350 berkley
633
    //allows the dynamic switching of boolean operators
634 743 jones
    if (params.containsKey("operator"))
635 350 berkley
    {
636
      query.append("<querygroup operator=\"" +
637 535 jones
                ((String[])params.get("operator"))[0] + "\">");
638 350 berkley
    }
639
    else
640
    { //the default operator is UNION
641
      query.append("<querygroup operator=\"UNION\">");
642
    }
643 535 jones
644 743 jones
    if (params.containsKey("casesensitive"))
645 372 berkley
    {
646
      casesensitive = ((String[])params.get("casesensitive"))[0];
647
    }
648
    else
649
    {
650
      casesensitive = "false";
651
    }
652
653 743 jones
    if (params.containsKey("searchmode"))
654 372 berkley
    {
655
      searchmode = ((String[])params.get("searchmode"))[0];
656
    }
657
    else
658
    {
659
      searchmode = "contains";
660
    }
661 535 jones
662 342 berkley
    //anyfield is a special case because it does a
663
    //free text search.  It does not have a <pathexpr>
664 350 berkley
    //tag.  This allows for a free text search within the structured
665
    //query.  This is useful if the INTERSECT operator is used.
666 743 jones
    if (params.containsKey("anyfield"))
667 342 berkley
    {
668 372 berkley
       String[] anyfield = ((String[])params.get("anyfield"));
669
       //allow for more than one value for anyfield
670
       for(int i=0; i<anyfield.length; i++)
671 350 berkley
       {
672 743 jones
         if (!anyfield[i].equals(""))
673 372 berkley
         {
674
           query.append("<queryterm casesensitive=\"" + casesensitive +
675
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
676 535 jones
                        anyfield[i] +
677
                        "</value></queryterm>");
678 372 berkley
         }
679 350 berkley
       }
680 342 berkley
    }
681 535 jones
682 342 berkley
    //this while loop finds the rest of the parameters
683
    //and attempts to query for the field specified
684
    //by the parameter.
685
    elements = params.elements();
686
    keys = params.keys();
687
    while(keys.hasMoreElements() && elements.hasMoreElements())
688
    {
689
      nextkey = keys.nextElement();
690 535 jones
      nextelement = elements.nextElement();
691 372 berkley
692 535 jones
      //make sure we aren't querying for any of these
693
      //parameters since the are already in the query
694 342 berkley
      //in one form or another.
695 743 jones
      if (!nextkey.toString().equals("returndoctype") &&
696
         !nextkey.toString().equals("filterdoctype")  &&
697 535 jones
         !nextkey.toString().equals("action")  &&
698
         !nextkey.toString().equals("qformat") &&
699
         !nextkey.toString().equals("anyfield") &&
700 401 berkley
         !nextkey.toString().equals("returnfield") &&
701 535 jones
         !nextkey.toString().equals("owner") &&
702
         !nextkey.toString().equals("site") &&
703
         !nextkey.toString().equals("operator") )
704
      {
705 372 berkley
        //allow for more than value per field name
706
        for(int i=0; i<((String[])nextelement).length; i++)
707
        {
708 743 jones
          if (!((String[])nextelement)[i].equals(""))
709 372 berkley
          {
710
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " +
711 535 jones
                         "searchmode=\"" + searchmode + "\">" +
712
                         "<value>" +
713 372 berkley
                         //add the query value
714 535 jones
                         ((String[])nextelement)[i] +
715
                         "</value><pathexpr>" +
716
                         //add the path to query by
717 372 berkley
                         nextkey.toString() +
718
                         "</pathexpr></queryterm>");
719
          }
720
        }
721 535 jones
      }
722 342 berkley
    }
723
    query.append("</querygroup></pathquery>");
724 350 berkley
    //append on the end of the xml and return the result as a string
725 342 berkley
    return query.toString();
726
  }
727
728 181 jones
  /**
729
   * format a simple free-text value query as an XML document that conforms
730
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
731
   * structured query engine
732
   *
733
   * @param value the text string to search for in the xml catalog
734
   * @param doctype the type of documents to include in the result set -- use
735
   *        "any" or "ANY" for unfiltered result sets
736
   */
737
   public static String createQuery(String value, String doctype) {
738
     StringBuffer xmlquery = new StringBuffer();
739
     xmlquery.append("<?xml version=\"1.0\"?>\n");
740
     xmlquery.append("<pathquery version=\"1.0\">");
741
742
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
743
       xmlquery.append("<returndoctype>");
744
       xmlquery.append(doctype).append("</returndoctype>");
745
     }
746
747
     xmlquery.append("<querygroup operator=\"UNION\">");
748 350 berkley
     //chad added - 8/14
749
     //the if statement allows a query to gracefully handle a null
750
     //query.  Without this if a nullpointerException is thrown.
751 743 jones
     if (!value.equals(""))
752 350 berkley
     {
753
       xmlquery.append("<queryterm casesensitive=\"false\" ");
754
       xmlquery.append("searchmode=\"contains\">");
755
       xmlquery.append("<value>").append(value).append("</value>");
756
       xmlquery.append("</queryterm>");
757
     }
758 181 jones
     xmlquery.append("</querygroup>");
759
     xmlquery.append("</pathquery>");
760
761
762
     return (xmlquery.toString());
763
   }
764
765
  /**
766
   * format a simple free-text value query as an XML document that conforms
767
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
768
   * structured query engine
769
   *
770
   * @param value the text string to search for in the xml catalog
771
   */
772
   public static String createQuery(String value) {
773
     return createQuery(value, "any");
774
   }
775 441 bojilova
776 570 bojilova
  /**
777
    * Check for "READ" permission on @docid for @user and/or @group
778
    * from DB connection
779
    */
780
  private boolean hasPermission ( Connection conn, String user,
781
                                  String group, String docid )
782 605 bojilova
                  throws SQLException
783 570 bojilova
  {
784 441 bojilova
    // b' of the command line invocation
785
    if ( (user == null) && (group == null) ) {
786
      return true;
787
    }
788
789 570 bojilova
    // Check for READ permission on @docid for @user and/or @group
790 607 bojilova
    AccessControlList aclobj = new AccessControlList(conn);
791
    boolean hasPermission = aclobj.hasPermission("READ",user,docid);
792 570 bojilova
    if ( !hasPermission && group != null ) {
793 607 bojilova
      hasPermission = aclobj.hasPermission("READ",group,docid);
794 441 bojilova
    }
795 570 bojilova
796
    return hasPermission;
797 441 bojilova
  }
798
799 155 jones
}