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