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 745 jones
  /**
180
   * routine to search the elements and attributes looking to match query
181
   *
182
   * @param xmlquery the xml serialization of the query (@see pathquery.dtd)
183
   * @param user the username of the user
184
   * @param group the group of the user
185
   */
186
  public Hashtable findDocuments(Reader xmlquery, String user, String group)
187 465 berkley
  {
188 745 jones
    return findDocuments(xmlquery, user, group, true);
189 465 berkley
  }
190 706 bojilova
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 745 jones
   * @param useXMLIndex flag whether to search using the path index
198 155 jones
   */
199 465 berkley
  public Hashtable findDocuments(Reader xmlquery, String user, String group,
200 745 jones
                                 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 766 bojilova
      Connection dbconn2 = null;
214 624 berkley
      int rev = 0;
215 155 jones
      StringBuffer document = null;
216 465 berkley
217 155 jones
      try {
218 743 jones
        if (conn == null || conn.isClosed()) {
219 710 berkley
          dbconn = util.openDBConnection();
220 743 jones
        } else {
221 710 berkley
          dbconn = conn;
222
        }
223 766 bojilova
        // problem with ODBC driver multi-threading
224
        dbconn2 = util.openDBConnection(); // for use by AccessControlList
225
226 172 jones
        // Get the XML query and covert it into a SQL statment
227 178 jones
        QuerySpecification qspec = new QuerySpecification(xmlquery,
228 535 jones
                                   parserName,
229 624 berkley
                                   util.getOption("accNumSeparator"));
230 706 bojilova
        pstmt = dbconn.prepareStatement( qspec.printSQL(useXMLIndex) );
231 155 jones
232 172 jones
        // Execute the SQL query using the JDBC connection
233 155 jones
        pstmt.execute();
234
        ResultSet rs = pstmt.getResultSet();
235
        boolean tableHasRows = rs.next();
236 667 berkley
        while (tableHasRows)
237
        {
238 768 bojilova
          docid = rs.getString(1).trim();
239 766 bojilova
          if ( !hasPermission(dbconn2, user, group, docid) ) {
240 612 bojilova
            // Advance to the next record in the cursor
241
            tableHasRows = rs.next();
242
            continue;
243
          }
244 155 jones
          docname = rs.getString(2);
245
          doctype = rs.getString(3);
246 692 bojilova
          createDate = rs.getString(4);
247
          updateDate = rs.getString(5);
248
          rev = rs.getInt(6);
249 743 jones
250 745 jones
          // if there are returndocs to match, backtracking can be performed
251
          // otherwise, just return the document that was hit
252
          Vector returndocVec = qspec.getReturnDocList();
253 743 jones
          if (returndocVec.size() != 0 && !returndocVec.contains(doctype))
254
          {
255 745 jones
            MetaCatUtil.debugMessage("Back tracing now...");
256 743 jones
            String sep = util.getOption("accNumSeparator");
257 465 berkley
            StringBuffer btBuf = new StringBuffer();
258 743 jones
            btBuf.append("select docid from xml_relation where ");
259
260 465 berkley
            //build the doctype list for the backtracking sql statement
261 743 jones
            btBuf.append("packagetype in (");
262 465 berkley
            for(int i=0; i<returndocVec.size(); i++)
263
            {
264
              btBuf.append("'").append((String)returndocVec.get(i)).append("'");
265 743 jones
              if (i != (returndocVec.size() - 1))
266 465 berkley
              {
267
                btBuf.append(", ");
268 475 berkley
              }
269 465 berkley
            }
270
            btBuf.append(") ");
271 743 jones
272
            btBuf.append("and (subject like '");
273
            btBuf.append(docid).append(sep).append(rev).append("'");
274
            btBuf.append("or object like '");
275
            btBuf.append(docid).append(sep).append(rev).append("')");
276 667 berkley
277 743 jones
            PreparedStatement npstmt = dbconn.
278
                                       prepareStatement(btBuf.toString());
279 671 berkley
            npstmt.execute();
280
            ResultSet btrs = npstmt.getResultSet();
281 465 berkley
            boolean hasBtRows = btrs.next();
282 743 jones
            while (hasBtRows)
283 465 berkley
            { //there was a backtrackable document found
284
              DocumentImpl xmldoc = null;
285 743 jones
              String packageDocid = btrs.getString(1);
286
              //MetacatURL objURL = new MetacatURL(packageDocid);
287 465 berkley
              try
288
              {
289 743 jones
                //xmldoc = new DocumentImpl(dbconn, objURL.getParam(0)[1]);
290
                xmldoc = new DocumentImpl(dbconn, packageDocid);
291 465 berkley
              }
292
              catch(Exception e)
293
              {
294 675 berkley
                System.out.println("Error getting document in " +
295
                                   "DBQuery.findDocuments: " + e.getMessage());
296 465 berkley
              }
297
298 768 bojilova
              docid   = xmldoc.getDocID().trim();
299 465 berkley
              docname = xmldoc.getDocname();
300
              doctype = xmldoc.getDoctype();
301
              createDate = xmldoc.getCreateDate();
302
              updateDate = xmldoc.getUpdateDate();
303 743 jones
              rev = xmldoc.getRev();
304
305
              document = new StringBuffer();
306
307
              String completeDocid = docid + util.getOption("accNumSeparator");
308
              completeDocid += rev;
309
              document.append("<docid>").append(completeDocid);
310
              document.append("</docid>");
311
              if (docname != null) {
312
                document.append("<docname>" + docname + "</docname>");
313
              }
314
              if (doctype != null) {
315
                document.append("<doctype>" + doctype + "</doctype>");
316
              }
317
              if (createDate != null) {
318
                document.append("<createdate>" + createDate + "</createdate>");
319
              }
320
              if (updateDate != null) {
321
                document.append("<updatedate>" + updateDate + "</updatedate>");
322
              }
323
              // Store the document id and the root node id
324
              docListResult.put(docid,(String)document.toString());
325
326
              // Get the next package document linked to our hit
327
              hasBtRows = btrs.next();
328 465 berkley
            }
329 671 berkley
            npstmt.close();
330 465 berkley
            btrs.close();
331 743 jones
          } else {
332 465 berkley
333 743 jones
            document = new StringBuffer();
334
335 624 berkley
            String completeDocid = docid + util.getOption("accNumSeparator");
336
            completeDocid += rev;
337
            document.append("<docid>").append(completeDocid).append("</docid>");
338 465 berkley
            if (docname != null) {
339
              document.append("<docname>" + docname + "</docname>");
340
            }
341
            if (doctype != null) {
342
              document.append("<doctype>" + doctype + "</doctype>");
343
            }
344 743 jones
            if (createDate != null) {
345 465 berkley
              document.append("<createdate>" + createDate + "</createdate>");
346
            }
347 743 jones
            if (updateDate != null) {
348 465 berkley
              document.append("<updatedate>" + updateDate + "</updatedate>");
349
            }
350
            // Store the document id and the root node id
351
            docListResult.put(docid,(String)document.toString());
352 743 jones
353 155 jones
          }
354
355
          // Advance to the next record in the cursor
356
          tableHasRows = rs.next();
357
        }
358 667 berkley
        rs.close();
359 671 berkley
        //pstmt.close();
360 401 berkley
361 743 jones
        if (qspec.containsExtendedSQL())
362 401 berkley
        {
363
          Vector extendedFields = new Vector(qspec.getReturnFieldList());
364
          Vector results = new Vector();
365 465 berkley
          Enumeration keylist = docListResult.keys();
366
          StringBuffer doclist = new StringBuffer();
367
          while(keylist.hasMoreElements())
368
          {
369
            doclist.append("'");
370
            doclist.append((String)keylist.nextElement());
371
            doclist.append("',");
372
          }
373
          doclist.deleteCharAt(doclist.length()-1); //remove the last comma
374 667 berkley
          pstmt.close();
375
          pstmt = dbconn.prepareStatement(qspec.printExtendedSQL(
376 465 berkley
                                        doclist.toString()));
377 401 berkley
          pstmt.execute();
378
          rs = pstmt.getResultSet();
379
          tableHasRows = rs.next();
380
          while(tableHasRows)
381
          {
382 768 bojilova
            docid = rs.getString(1).trim();
383 766 bojilova
            if ( !hasPermission(dbconn2, user, group, docid) ) {
384 673 bojilova
              // Advance to the next record in the cursor
385
              tableHasRows = rs.next();
386
              continue;
387
            }
388 401 berkley
            fieldname = rs.getString(2);
389
            fielddata = rs.getString(3);
390
391
            document = new StringBuffer();
392
393 423 berkley
            document.append("<param name=\"");
394 405 berkley
            document.append(fieldname);
395 423 berkley
            document.append("\">");
396 401 berkley
            document.append(fielddata);
397 423 berkley
            document.append("</param>");
398 401 berkley
399
            tableHasRows = rs.next();
400 743 jones
            if (docListResult.containsKey(docid))
401 401 berkley
            {
402
              String removedelement = (String)docListResult.remove(docid);
403
              docListResult.put(docid, removedelement + document.toString());
404
            }
405
            else
406
            {
407
              docListResult.put(docid, document.toString());
408
            }
409
          }
410 667 berkley
          rs.close();
411 401 berkley
        }
412 453 berkley
413 465 berkley
        //this loop adds the relation data to the resultdoc
414
        //this code might be able to be added to the backtracking code above
415
        Enumeration docidkeys = docListResult.keys();
416
        while(docidkeys.hasMoreElements())
417 453 berkley
        {
418 602 berkley
          //String connstring = "metacat://"+util.getOption("server")+"?docid=";
419
          String connstring = "%docid=";
420 465 berkley
          String docidkey = (String)docidkeys.nextElement();
421 743 jones
422 667 berkley
          pstmt.close();
423 743 jones
          pstmt = dbconn.prepareStatement(qspec.printRelationSQL(docidkey));
424 465 berkley
          pstmt.execute();
425
          rs = pstmt.getResultSet();
426
          tableHasRows = rs.next();
427
          while(tableHasRows)
428
          {
429
            String sub = rs.getString(1);
430
            String rel = rs.getString(2);
431
            String obj = rs.getString(3);
432 489 berkley
            String subDT = rs.getString(4);
433
            String objDT = rs.getString(5);
434
435 743 jones
            //MetacatURL murl = new MetacatURL(sub);
436
            //we only want to process metacat urls here.
437
            //if (murl.getProtocol().equals("metacat")) {
438
              //String[] tempparam = murl.getParam(0);
439
              //if (tempparam[0].equals("docid") && tempparam[1].equals(docidkey))
440
              //{
441 465 berkley
                document = new StringBuffer();
442 743 jones
                document.append("<triple>");
443
                document.append("<subject>").append(sub);
444
                document.append("</subject>");
445
                if (!subDT.equals("null")) {
446
                  document.append("<subjectdoctype>").append(subDT);
447
                  document.append("</subjectdoctype>");
448
                }
449
                document.append("<relationship>").append(rel);
450
                document.append("</relationship>");
451
                document.append("<object>").append(obj);
452
                document.append("</object>");
453
                if (!objDT.equals("null")) {
454
                  document.append("<objectdoctype>").append(objDT);
455
                  document.append("</objectdoctype>");
456
                }
457
                document.append("</triple>");
458 465 berkley
459
                String removedelement = (String)docListResult.remove(docidkey);
460 743 jones
                docListResult.put(docidkey, removedelement +
461
                                  document.toString());
462 465 berkley
463 743 jones
              //}
464
            //}
465 465 berkley
            tableHasRows = rs.next();
466 453 berkley
          }
467 667 berkley
          rs.close();
468
          pstmt.close();
469 453 berkley
        }
470 667 berkley
471 155 jones
      } catch (SQLException e) {
472 667 berkley
        System.err.println("SQL Error in DBQuery.findDocuments: " +
473
                           e.getMessage());
474 170 jones
      } catch (IOException ioe) {
475 675 berkley
        System.err.println("IO error in DBQuery.findDocuments:");
476 170 jones
        System.err.println(ioe.getMessage());
477 667 berkley
      } catch (Exception ee) {
478 675 berkley
        System.out.println("Exception in DBQuery.findDocuments: " +
479 667 berkley
                           ee.getMessage());
480 155 jones
      }
481 667 berkley
      finally {
482
        try
483
        {
484
          dbconn.close();
485 766 bojilova
          dbconn2.close();
486 667 berkley
        }
487
        catch(SQLException sqle)
488
        {
489
          System.out.println("error closing conn in DBQuery.findDocuments");
490
        }
491
      }
492 423 berkley
    //System.out.println("docListResult: ");
493
    //System.out.println(docListResult.toString());
494 155 jones
    return docListResult;
495
  }
496 342 berkley
497
  /**
498 436 berkley
   * returns a string array of the contents of a particular node.
499
   * If the node appears more than once, the contents are returned
500
   * in the order in which they appearred in the document.
501
   * @param nodename the name or path of the particular node.
502
   * @param docid the docid of the document you want the node from.
503
   * @param conn a database connection-this allows this method to be static
504
   */
505
  public static Object[] getNodeContent(String nodename, String docid,
506
                                        Connection conn)
507
  {
508
    StringBuffer query = new StringBuffer();
509
    Vector result = new Vector();
510 667 berkley
    PreparedStatement pstmt = null;
511 436 berkley
    query.append("select nodedata from xml_nodes where parentnodeid in ");
512
    query.append("(select nodeid from xml_index where path like '");
513
    query.append(nodename);
514
    query.append("' and docid like '").append(docid).append("')");
515
    try
516
    {
517
      pstmt = conn.prepareStatement(query.toString());
518
519
      // Execute the SQL query using the JDBC connection
520
      pstmt.execute();
521
      ResultSet rs = pstmt.getResultSet();
522
      boolean tableHasRows = rs.next();
523
      while (tableHasRows)
524
      {
525
        result.add(rs.getString(1));
526
        System.out.println(rs.getString(1));
527
        tableHasRows = rs.next();
528
      }
529
    }
530
    catch (SQLException e)
531
    {
532 675 berkley
      System.err.println("Error in DBQuery.getNodeContent: " + e.getMessage());
533 667 berkley
    } finally {
534
      try
535
      {
536
        pstmt.close();
537
      }
538
      catch(SQLException sqle) {}
539
    }
540 436 berkley
    return result.toArray();
541
  }
542
543
  /**
544 342 berkley
   * format a structured query as an XML document that conforms
545
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
546
   * structured query engine
547
   *
548 743 jones
   * @param params The list of parameters that should be included in the query
549 342 berkley
   */
550 372 berkley
  public static String createSQuery(Hashtable params)
551 350 berkley
  {
552
    StringBuffer query = new StringBuffer();
553 342 berkley
    Enumeration elements;
554
    Enumeration keys;
555 743 jones
    String filterDoctype = null;
556 372 berkley
    String casesensitive = null;
557
    String searchmode = null;
558 342 berkley
    Object nextkey;
559
    Object nextelement;
560 350 berkley
    //add the xml headers
561
    query.append("<?xml version=\"1.0\"?>\n");
562 743 jones
    query.append("<pathquery version=\"1.0\">\n");
563
564
    if (params.containsKey("meta_file_id"))
565 342 berkley
    {
566 743 jones
      query.append("<meta_file_id>");
567 342 berkley
      query.append( ((String[])params.get("meta_file_id"))[0]);
568 535 jones
      query.append("</meta_file_id>");
569 342 berkley
    }
570 350 berkley
571 743 jones
    if (params.containsKey("returndoctype"))
572 372 berkley
    {
573 744 jones
      String[] returnDoctypes = ((String[])params.get("returndoctype"));
574
      for(int i=0; i<returnDoctypes.length; i++)
575
      {
576
        String doctype = (String)returnDoctypes[i];
577
578
        if (!doctype.equals("any") &&
579
            !doctype.equals("ANY") &&
580
            !doctype.equals("") )
581
        {
582
          query.append("<returndoctype>").append(doctype);
583
          query.append("</returndoctype>");
584
        }
585
      }
586 372 berkley
    }
587 744 jones
588 743 jones
    if (params.containsKey("filterdoctype"))
589
    {
590
      String[] filterDoctypes = ((String[])params.get("filterdoctype"));
591
      for(int i=0; i<filterDoctypes.length; i++)
592
      {
593
        query.append("<filterdoctype>").append(filterDoctypes[i]);
594
        query.append("</filterdoctype>");
595
      }
596
    }
597 372 berkley
598 743 jones
    if (params.containsKey("returnfield"))
599 401 berkley
    {
600
      String[] returnfield = ((String[])params.get("returnfield"));
601
      for(int i=0; i<returnfield.length; i++)
602
      {
603
        query.append("<returnfield>").append(returnfield[i]);
604
        query.append("</returnfield>");
605
      }
606
    }
607
608 743 jones
    if (params.containsKey("owner"))
609 535 jones
    {
610
      String[] owner = ((String[])params.get("owner"));
611
      for(int i=0; i<owner.length; i++)
612
      {
613
        query.append("<owner>").append(owner[i]);
614
        query.append("</owner>");
615
      }
616
    }
617
618 743 jones
    if (params.containsKey("site"))
619 535 jones
    {
620
      String[] site = ((String[])params.get("site"));
621
      for(int i=0; i<site.length; i++)
622
      {
623
        query.append("<site>").append(site[i]);
624
        query.append("</site>");
625
      }
626
    }
627
628 350 berkley
    //allows the dynamic switching of boolean operators
629 743 jones
    if (params.containsKey("operator"))
630 350 berkley
    {
631
      query.append("<querygroup operator=\"" +
632 535 jones
                ((String[])params.get("operator"))[0] + "\">");
633 350 berkley
    }
634
    else
635
    { //the default operator is UNION
636
      query.append("<querygroup operator=\"UNION\">");
637
    }
638 535 jones
639 743 jones
    if (params.containsKey("casesensitive"))
640 372 berkley
    {
641
      casesensitive = ((String[])params.get("casesensitive"))[0];
642
    }
643
    else
644
    {
645
      casesensitive = "false";
646
    }
647
648 743 jones
    if (params.containsKey("searchmode"))
649 372 berkley
    {
650
      searchmode = ((String[])params.get("searchmode"))[0];
651
    }
652
    else
653
    {
654
      searchmode = "contains";
655
    }
656 535 jones
657 342 berkley
    //anyfield is a special case because it does a
658
    //free text search.  It does not have a <pathexpr>
659 350 berkley
    //tag.  This allows for a free text search within the structured
660
    //query.  This is useful if the INTERSECT operator is used.
661 743 jones
    if (params.containsKey("anyfield"))
662 342 berkley
    {
663 372 berkley
       String[] anyfield = ((String[])params.get("anyfield"));
664
       //allow for more than one value for anyfield
665
       for(int i=0; i<anyfield.length; i++)
666 350 berkley
       {
667 743 jones
         if (!anyfield[i].equals(""))
668 372 berkley
         {
669
           query.append("<queryterm casesensitive=\"" + casesensitive +
670
                        "\" " + "searchmode=\"" + searchmode + "\"><value>" +
671 535 jones
                        anyfield[i] +
672
                        "</value></queryterm>");
673 372 berkley
         }
674 350 berkley
       }
675 342 berkley
    }
676 535 jones
677 342 berkley
    //this while loop finds the rest of the parameters
678
    //and attempts to query for the field specified
679
    //by the parameter.
680
    elements = params.elements();
681
    keys = params.keys();
682
    while(keys.hasMoreElements() && elements.hasMoreElements())
683
    {
684
      nextkey = keys.nextElement();
685 535 jones
      nextelement = elements.nextElement();
686 372 berkley
687 535 jones
      //make sure we aren't querying for any of these
688
      //parameters since the are already in the query
689 342 berkley
      //in one form or another.
690 743 jones
      if (!nextkey.toString().equals("returndoctype") &&
691
         !nextkey.toString().equals("filterdoctype")  &&
692 535 jones
         !nextkey.toString().equals("action")  &&
693
         !nextkey.toString().equals("qformat") &&
694
         !nextkey.toString().equals("anyfield") &&
695 401 berkley
         !nextkey.toString().equals("returnfield") &&
696 535 jones
         !nextkey.toString().equals("owner") &&
697
         !nextkey.toString().equals("site") &&
698
         !nextkey.toString().equals("operator") )
699
      {
700 372 berkley
        //allow for more than value per field name
701
        for(int i=0; i<((String[])nextelement).length; i++)
702
        {
703 743 jones
          if (!((String[])nextelement)[i].equals(""))
704 372 berkley
          {
705
            query.append("<queryterm casesensitive=\"" + casesensitive +"\" " +
706 535 jones
                         "searchmode=\"" + searchmode + "\">" +
707
                         "<value>" +
708 372 berkley
                         //add the query value
709 535 jones
                         ((String[])nextelement)[i] +
710
                         "</value><pathexpr>" +
711
                         //add the path to query by
712 372 berkley
                         nextkey.toString() +
713
                         "</pathexpr></queryterm>");
714
          }
715
        }
716 535 jones
      }
717 342 berkley
    }
718
    query.append("</querygroup></pathquery>");
719 350 berkley
    //append on the end of the xml and return the result as a string
720 342 berkley
    return query.toString();
721
  }
722
723 181 jones
  /**
724
   * format a simple free-text value query as an XML document that conforms
725
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
726
   * structured query engine
727
   *
728
   * @param value the text string to search for in the xml catalog
729
   * @param doctype the type of documents to include in the result set -- use
730
   *        "any" or "ANY" for unfiltered result sets
731
   */
732
   public static String createQuery(String value, String doctype) {
733
     StringBuffer xmlquery = new StringBuffer();
734
     xmlquery.append("<?xml version=\"1.0\"?>\n");
735
     xmlquery.append("<pathquery version=\"1.0\">");
736
737
     if (!doctype.equals("any") && !doctype.equals("ANY")) {
738
       xmlquery.append("<returndoctype>");
739
       xmlquery.append(doctype).append("</returndoctype>");
740
     }
741
742
     xmlquery.append("<querygroup operator=\"UNION\">");
743 350 berkley
     //chad added - 8/14
744
     //the if statement allows a query to gracefully handle a null
745
     //query.  Without this if a nullpointerException is thrown.
746 743 jones
     if (!value.equals(""))
747 350 berkley
     {
748
       xmlquery.append("<queryterm casesensitive=\"false\" ");
749
       xmlquery.append("searchmode=\"contains\">");
750
       xmlquery.append("<value>").append(value).append("</value>");
751
       xmlquery.append("</queryterm>");
752
     }
753 181 jones
     xmlquery.append("</querygroup>");
754
     xmlquery.append("</pathquery>");
755
756
757
     return (xmlquery.toString());
758
   }
759
760
  /**
761
   * format a simple free-text value query as an XML document that conforms
762
   * to the pathquery.dtd and is appropriate for submission to the DBQuery
763
   * structured query engine
764
   *
765
   * @param value the text string to search for in the xml catalog
766
   */
767
   public static String createQuery(String value) {
768
     return createQuery(value, "any");
769
   }
770 441 bojilova
771 570 bojilova
  /**
772
    * Check for "READ" permission on @docid for @user and/or @group
773
    * from DB connection
774
    */
775
  private boolean hasPermission ( Connection conn, String user,
776
                                  String group, String docid )
777 605 bojilova
                  throws SQLException
778 570 bojilova
  {
779 441 bojilova
    // b' of the command line invocation
780
    if ( (user == null) && (group == null) ) {
781
      return true;
782
    }
783
784 570 bojilova
    // Check for READ permission on @docid for @user and/or @group
785 607 bojilova
    AccessControlList aclobj = new AccessControlList(conn);
786
    boolean hasPermission = aclobj.hasPermission("READ",user,docid);
787 570 bojilova
    if ( !hasPermission && group != null ) {
788 607 bojilova
      hasPermission = aclobj.hasPermission("READ",group,docid);
789 441 bojilova
    }
790 570 bojilova
791
    return hasPermission;
792 441 bojilova
  }
793
794 155 jones
}