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