Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that represents a structured query, and can be 
4
 *             constructed from an XML serialization conforming to 
5
 *             pathquery.dtd. The printSQL() method can be used to print 
6
 *             a SQL serialization of the query.
7
 *  Copyright: 2000 Regents of the University of California and the
8
 *             National Center for Ecological Analysis and Synthesis
9
 *    Authors: Matt Jones
10
 *    Release: @release@
11
 *
12
 *   '$Author: jones $'
13
 *     '$Date: 2001-02-26 16:45:37 -0800 (Mon, 26 Feb 2001) $'
14
 * '$Revision: 711 $'
15
 *
16
 * This program is free software; you can redistribute it and/or modify
17
 * it under the terms of the GNU General Public License as published by
18
 * the Free Software Foundation; either version 2 of the License, or
19
 * (at your option) any later version.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
 * GNU General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU General Public License
27
 * along with this program; if not, write to the Free Software
28
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29
 */
30

    
31
package edu.ucsb.nceas.metacat;
32

    
33
import java.io.*;
34
import java.util.Stack;
35
import java.util.Vector;
36
import java.util.Enumeration;
37

    
38
import org.xml.sax.Attributes;
39
import org.xml.sax.InputSource;
40
import org.xml.sax.SAXException;
41
import org.xml.sax.SAXParseException;
42
import org.xml.sax.XMLReader;
43
import org.xml.sax.helpers.XMLReaderFactory;
44
import org.xml.sax.helpers.DefaultHandler;
45

    
46
/**
47
 * A Class that represents a structured query, and can be 
48
 * constructed from an XML serialization conforming to @see pathquery.dtd. 
49
 * The printSQL() method can be used to print a SQL serialization of the query.
50
 */
51
public class QuerySpecification extends DefaultHandler {
52
 
53
  private boolean containsExtendedSQL=false;
54
 
55
  // Query data structures
56
  private String meta_file_id;
57
// DOCTITLE attr cleared from the db
58
//  private String querytitle;
59
  private Vector doctypeList;
60
  private Vector returnFieldList;
61
  private Vector ownerList;
62
  private Vector siteList;
63
  private QueryGroup query = null;
64

    
65
  private Stack elementStack;
66
  private Stack queryStack;
67
  private String currentValue;
68
  private String currentPathexpr;
69
  private String parserName = null;
70
  private String accNumberSeparator = null;
71

    
72
  /**
73
   * construct an instance of the QuerySpecification class 
74
   *
75
   * @param queryspec the XML representation of the query (should conform
76
   *                  to pathquery.dtd) as a Reader
77
   * @param parserName the fully qualified name of a Java Class implementing
78
   *                  the org.xml.sax.XMLReader interface
79
   */
80
  public QuerySpecification( Reader queryspec, String parserName,
81
         String accNumberSeparator ) throws IOException {
82
    super();
83
    
84
    // Initialize the class variables
85
    doctypeList = new Vector();
86
    elementStack = new Stack();
87
    queryStack   = new Stack();
88
    returnFieldList = new Vector();
89
    ownerList = new Vector();
90
    siteList = new Vector();
91
    this.parserName = parserName;
92
    this.accNumberSeparator = accNumberSeparator;
93

    
94
    // Initialize the parser and read the queryspec
95
    XMLReader parser = initializeParser();
96
    if (parser == null) {
97
      System.err.println("SAX parser not instantiated properly.");
98
    }
99
    try {
100
      parser.parse(new InputSource(queryspec));
101
    } catch (SAXException e) {
102
      System.err.println("error parsing data in " + 
103
                         "QuerySpecification.QuerySpecification");
104
      System.err.println(e.getMessage());
105
    }
106
  }
107

    
108
  /**
109
   * construct an instance of the QuerySpecification class 
110
   *
111
   * @param queryspec the XML representation of the query (should conform
112
   *                  to pathquery.dtd) as a String
113
   * @param parserName the fully qualified name of a Java Class implementing
114
   *                  the org.xml.sax.Parser interface
115
   */
116
  public QuerySpecification( String queryspec, String parserName,
117
         String accNumberSeparator) throws IOException {
118
    this(new StringReader(queryspec), parserName, accNumberSeparator);
119
  }
120

    
121
  /** Main routine for testing */
122
  static public void main(String[] args) {
123

    
124
     if (args.length < 1) {
125
       System.err.println("Wrong number of arguments!!!");
126
       System.err.println("USAGE: java QuerySpecification <xmlfile>");
127
       return;
128
     } else {
129
       int i = 0;
130
       boolean useXMLIndex = true;
131
       if ( args[i].equals( "-noindex" ) ) {
132
         useXMLIndex = false;
133
         i++;
134
       }
135
       String xmlfile  = args[i];
136

    
137
       try {
138
         MetaCatUtil util = new MetaCatUtil();
139
         FileReader xml = new FileReader(new File(xmlfile));
140
         QuerySpecification qspec = 
141
                 new QuerySpecification(xml, util.getOption("saxparser"),
142
                                        util.getOption("accNumberSeparator"));
143
         System.out.println(qspec.printSQL(useXMLIndex));
144

    
145
       } catch (IOException e) {
146
         System.err.println(e.getMessage());
147
       }
148
         
149
     }
150
  }
151
  
152
  /**
153
   * Returns true if the parsed query contains and extended xml query 
154
   * (i.e. there is at least one &lt;returnfield&gt; in the pathquery document)
155
   */
156
  public boolean containsExtendedSQL()
157
  {
158
    if(containsExtendedSQL)
159
    {
160
      return true;
161
    }
162
    else
163
    {
164
      return false;
165
    }
166
  }
167
  
168
  /**
169
   * Accessor method to return a vector of the extended return fields as
170
   * defined in the &lt;returnfield&gt; tag in the pathquery dtd.
171
   */
172
  public Vector getReturnFieldList()
173
  {
174
    return this.returnFieldList; 
175
  }
176

    
177
  /**
178
   * Set up the SAX parser for reading the XML serialized query
179
   */
180
  private XMLReader initializeParser() {
181
    XMLReader parser = null;
182

    
183
    // Set up the SAX document handlers for parsing
184
    try {
185

    
186
      // Get an instance of the parser
187
      parser = XMLReaderFactory.createXMLReader(parserName);
188

    
189
      // Set the ContentHandler to this instance
190
      parser.setContentHandler(this);
191

    
192
      // Set the error Handler to this instance
193
      parser.setErrorHandler(this);
194

    
195
    } catch (Exception e) {
196
       System.err.println("Error in QuerySpcecification.initializeParser " + 
197
                           e.toString());
198
    }
199

    
200
    return parser;
201
  }
202

    
203
  /**
204
   * callback method used by the SAX Parser when the start tag of an 
205
   * element is detected. Used in this context to parse and store
206
   * the query information in class variables.
207
   */
208
  public void startElement (String uri, String localName, 
209
                            String qName, Attributes atts) 
210
         throws SAXException {
211
    BasicNode currentNode = new BasicNode(localName);
212
    // add attributes to BasicNode here
213
    if (atts != null) {
214
      int len = atts.getLength();
215
      for (int i = 0; i < len; i++) {
216
        currentNode.setAttribute(atts.getLocalName(i), atts.getValue(i));
217
      }
218
    }
219

    
220
    elementStack.push(currentNode); 
221
    if (currentNode.getTagName().equals("querygroup")) {
222
      QueryGroup currentGroup = new QueryGroup(
223
                                currentNode.getAttribute("operator"));
224
      if (query == null) {
225
        query = currentGroup;
226
      } else {
227
        QueryGroup parentGroup = (QueryGroup)queryStack.peek();
228
        parentGroup.addChild(currentGroup);
229
      }
230
      queryStack.push(currentGroup);
231
    }
232
  }
233

    
234
  /**
235
   * callback method used by the SAX Parser when the end tag of an 
236
   * element is detected. Used in this context to parse and store
237
   * the query information in class variables.
238
   */
239
  public void endElement (String uri, String localName,
240
                          String qName) throws SAXException {
241
    BasicNode leaving = (BasicNode)elementStack.pop(); 
242
    if (leaving.getTagName().equals("queryterm")) {
243
      boolean isCaseSensitive = (new Boolean(
244
              leaving.getAttribute("casesensitive"))).booleanValue();
245
      QueryTerm currentTerm = null;
246
      if (currentPathexpr == null) {
247
        currentTerm = new QueryTerm(isCaseSensitive,
248
                      leaving.getAttribute("searchmode"),currentValue);
249
      } else {
250
        currentTerm = new QueryTerm(isCaseSensitive,
251
                      leaving.getAttribute("searchmode"),currentValue,
252
                      currentPathexpr);
253
      }
254
      QueryGroup currentGroup = (QueryGroup)queryStack.peek();
255
      currentGroup.addChild(currentTerm);
256
      currentValue = null;
257
      currentPathexpr = null;
258
    } else if (leaving.getTagName().equals("querygroup")) {
259
      QueryGroup leavingGroup = (QueryGroup)queryStack.pop();
260
    }
261
  }
262

    
263
  /**
264
   * callback method used by the SAX Parser when the text sequences of an 
265
   * xml stream are detected. Used in this context to parse and store
266
   * the query information in class variables.
267
   */
268
  public void characters(char ch[], int start, int length) {
269

    
270
    String inputString = new String(ch, start, length);
271
    BasicNode currentNode = (BasicNode)elementStack.peek(); 
272
    String currentTag = currentNode.getTagName();
273
    if (currentTag.equals("meta_file_id")) {
274
      meta_file_id = inputString;
275
// DOCTITLE attr cleared from the db
276
//    } else if (currentTag.equals("querytitle")) {
277
//      querytitle = inputString;
278
    } else if (currentTag.equals("value")) {
279
      currentValue = inputString;
280
    } else if (currentTag.equals("pathexpr")) {
281
      currentPathexpr = inputString;
282
    } else if (currentTag.equals("returndoctype")) {
283
      doctypeList.add(inputString);
284
    } else if (currentTag.equals("returnfield")) {
285
      returnFieldList.add(inputString);
286
      containsExtendedSQL = true;
287
    } else if (currentTag.equals("owner")) {
288
      ownerList.add(inputString);
289
    } else if (currentTag.equals("site")) {
290
      siteList.add(inputString);
291
    }
292
  }
293

    
294

    
295
  /**
296
   * create a SQL serialization of the query that this instance represents
297
   */
298
  public String printSQL(boolean useXMLIndex) {
299
    StringBuffer self = new StringBuffer();
300

    
301
    self.append("SELECT docid,docname,doctype,");
302
    self.append("date_created, date_updated, rev ");
303
    self.append("FROM xml_documents WHERE docid IN (");
304

    
305
    // This determines the documents that meet the query conditions
306
    self.append(query.printSQL(useXMLIndex));
307

    
308
    self.append(") ");
309
 
310
    // Add SQL to filter for doctypes requested in the query
311
    // This is an implicit OR for the list of doctypes
312
    if (!doctypeList.isEmpty()) {
313
      boolean firstdoctype = true;
314
      self.append(" AND ("); 
315
      Enumeration en = doctypeList.elements();
316
      while (en.hasMoreElements()) {
317
        String currentDoctype = (String)en.nextElement();
318
        if (firstdoctype) {
319
           firstdoctype = false;
320
           self.append(" doctype = '" + currentDoctype + "'"); 
321
        } else {
322
          self.append(" OR doctype = '" + currentDoctype + "'"); 
323
        }
324
      }
325
      self.append(") ");
326
    }
327
    
328
    // Add SQL to filter for owners requested in the query
329
    // This is an implicit OR for the list of owners
330
    if (!ownerList.isEmpty()) {
331
      boolean first = true;
332
      self.append(" AND ("); 
333
      Enumeration en = ownerList.elements();
334
      while (en.hasMoreElements()) {
335
        String current = (String)en.nextElement();
336
        if (first) {
337
           first = false;
338
           self.append(" user_owner = '" + current + "'"); 
339
        } else {
340
          self.append(" OR user_owner = '" + current + "'"); 
341
        }
342
      }
343
      self.append(") ");
344
    }
345

    
346
    // Add SQL to filter for sites requested in the query
347
    // This is an implicit OR for the list of sites
348
    if (!siteList.isEmpty()) {
349
      boolean first = true;
350
      self.append(" AND ("); 
351
      Enumeration en = siteList.elements();
352
      while (en.hasMoreElements()) {
353
        String current = (String)en.nextElement();
354
        if (first) {
355
           first = false;
356
           self.append(" SUBSTR(docid, 1, INSTR(docid, '" +
357
               accNumberSeparator + "')-1) = '" + current + "'"); 
358
        } else {
359
          self.append(" OR SUBSTR(docid, 1, INSTR(docid, '" +
360
               accNumberSeparator + "')-1) = '" + current + "'"); 
361
        }
362
      }
363
      self.append(") ");
364
    }
365
    //System.out.println(self.toString());
366
    return self.toString();
367
  }
368
  
369
  /**
370
   * This method prints sql based upon the &lt;returnfield&gt; tag in the
371
   * pathquery document.  This allows for customization of the 
372
   * returned fields
373
   * @param doclist the list of document ids to search by
374
   */
375
  public String printExtendedSQL(String doclist)
376
  {  
377
    StringBuffer self = new StringBuffer();
378
    self.append("select xml_nodes.docid, xml_index.path, xml_nodes.nodedata ");
379
    self.append("from xml_index, xml_nodes where xml_index.nodeid=");
380
    self.append("xml_nodes.parentnodeid and (xml_index.path like '");
381
    boolean firstfield = true;
382
    //put the returnfields into the query
383
    //the for loop allows for multiple fields
384
    for(int i=0; i<returnFieldList.size(); i++)
385
    {
386
      if(firstfield)
387
      {
388
        firstfield = false;
389
        self.append((String)returnFieldList.elementAt(i));
390
        self.append("' ");
391
      }
392
      else
393
      {
394
        self.append("or xml_index.path like '");
395
        self.append((String)returnFieldList.elementAt(i));
396
        self.append("' ");
397
      }
398
    }
399
    self.append(") AND xml_nodes.docid in (");
400
    //self.append(query.printSQL());
401
    self.append(doclist);
402
    self.append(")");
403
    self.append(" AND xml_nodes.nodetype = 'TEXT'");
404

    
405
    //System.out.println(self.toString());
406
    return self.toString();
407
  }
408
  
409
  public static String printRelationSQL(String docid)
410
  {
411
    StringBuffer self = new StringBuffer();
412
    self.append("select subject, relationship, object, subdoctype, ");
413
    self.append("objdoctype from xml_relation ");
414
    self.append("where subject like '").append(docid).append("'");
415
    return self.toString();
416
  }
417
   
418
  /**
419
   * Prints sql that returns all relations in the database.
420
   */
421
  public static String printPackageSQL()
422
  {
423
    StringBuffer self = new StringBuffer();
424
    self.append("select z.nodedata, x.nodedata, y.nodedata from ");
425
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
426
    self.append("'package/relation/subject') s, (select nodeid, parentnodeid ");
427
    self.append("from xml_index where path like ");
428
    self.append("'package/relation/relationship') rel, ");
429
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
430
    self.append("'package/relation/object') o, ");
431
    self.append("xml_nodes x, xml_nodes y, xml_nodes z ");
432
    self.append("where s.parentnodeid = rel.parentnodeid ");
433
    self.append("and rel.parentnodeid = o.parentnodeid ");
434
    self.append("and x.parentnodeid in rel.nodeid ");
435
    self.append("and y.parentnodeid in o.nodeid ");
436
    self.append("and z.parentnodeid in s.nodeid ");
437
    //self.append("and z.nodedata like '%");
438
    //self.append(docid);
439
    //self.append("%'");
440
    return self.toString();
441
  }
442
  
443
  /**
444
   * Prints sql that returns all relations in the database that were input
445
   * under a specific docid
446
   * @param docid the docid to search for.
447
   */
448
  public static String printPackageSQL(String docid)
449
  {
450
    StringBuffer self = new StringBuffer();
451
    self.append("select z.nodedata, x.nodedata, y.nodedata from ");
452
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
453
    self.append("'package/relation/subject') s, (select nodeid, parentnodeid ");
454
    self.append("from xml_index where path like ");
455
    self.append("'package/relation/relationship') rel, ");
456
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
457
    self.append("'package/relation/object') o, ");
458
    self.append("xml_nodes x, xml_nodes y, xml_nodes z ");
459
    self.append("where s.parentnodeid = rel.parentnodeid ");
460
    self.append("and rel.parentnodeid = o.parentnodeid ");
461
    self.append("and x.parentnodeid in rel.nodeid ");
462
    self.append("and y.parentnodeid in o.nodeid ");
463
    self.append("and z.parentnodeid in s.nodeid ");
464
    self.append("and z.docid like '").append(docid).append("'");
465
    
466
    return self.toString();
467
  }
468
  
469
  /**
470
   * Returns all of the relations that has a certain docid in the subject
471
   * or the object.
472
   * 
473
   * @param docid the docid to search for
474
   */
475
  public static String printPackageSQL(String subDocidURL, String objDocidURL)
476
  {
477
    StringBuffer self = new StringBuffer();
478
    self.append("select z.nodedata, x.nodedata, y.nodedata from ");
479
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
480
    self.append("'package/relation/subject') s, (select nodeid, parentnodeid ");
481
    self.append("from xml_index where path like ");
482
    self.append("'package/relation/relationship') rel, ");
483
    self.append("(select nodeid, parentnodeid from xml_index where path like ");
484
    self.append("'package/relation/object') o, ");
485
    self.append("xml_nodes x, xml_nodes y, xml_nodes z ");
486
    self.append("where s.parentnodeid = rel.parentnodeid ");
487
    self.append("and rel.parentnodeid = o.parentnodeid ");
488
    self.append("and x.parentnodeid in rel.nodeid ");
489
    self.append("and y.parentnodeid in o.nodeid ");
490
    self.append("and z.parentnodeid in s.nodeid ");
491
    self.append("and (z.nodedata like '");
492
    self.append(subDocidURL);
493
    self.append("' or y.nodedata like '");
494
    self.append(objDocidURL);
495
    self.append("')");
496
    return self.toString();
497
  }
498
  
499
  public static String printGetDocByDoctypeSQL(String docid)
500
  {
501
    StringBuffer self = new StringBuffer();
502

    
503
    self.append("SELECT docid,docname,doctype,");
504
    self.append("date_created, date_updated ");
505
    self.append("FROM xml_documents WHERE docid IN (");
506
    self.append(docid).append(")");
507
    return self.toString();
508
  }
509
  
510
  /**
511
   * create a String description of the query that this instance represents.
512
   * This should become a way to get the XML serialization of the query.
513
   */
514
  public String toString() {
515
    return "meta_file_id=" + meta_file_id + "\n" + query;
516
//DOCTITLE attr cleared from the db
517
//    return "meta_file_id=" + meta_file_id + "\n" + 
518
//           "querytitle=" + querytitle + "\n" + query;
519
  }
520

    
521
  /** a utility class that represents a group of terms in a query */
522
  private class QueryGroup {
523
    private String operator = null;  // indicates how query terms are combined
524
    private Vector children = null;  // the list of query terms and groups
525

    
526
    /** 
527
     * construct a new QueryGroup 
528
     *
529
     * @param operator the boolean conector used to connect query terms 
530
     *                    in this query group
531
     */
532
    public QueryGroup(String operator) {
533
      this.operator = operator;
534
      children = new Vector();
535
    }
536

    
537
    /** 
538
     * Add a child QueryGroup to this QueryGroup
539
     *
540
     * @param qgroup the query group to be added to the list of terms
541
     */
542
    public void addChild(QueryGroup qgroup) {
543
      children.add((Object)qgroup); 
544
    }
545

    
546
    /**
547
     * Add a child QueryTerm to this QueryGroup
548
     *
549
     * @param qterm the query term to be added to the list of terms
550
     */
551
    public void addChild(QueryTerm qterm) {
552
      children.add((Object)qterm); 
553
    }
554

    
555
    /**
556
     * Retrieve an Enumeration of query terms for this QueryGroup
557
     */
558
    public Enumeration getChildren() {
559
      return children.elements();
560
    }
561
   
562
    /**
563
     * create a SQL serialization of the query that this instance represents
564
     */
565
    public String printSQL(boolean useXMLIndex) {
566
      StringBuffer self = new StringBuffer();
567
      boolean first = true;
568

    
569
      self.append("(");
570

    
571
      Enumeration en= getChildren();
572
      while (en.hasMoreElements()) {
573
        Object qobject = en.nextElement();
574
        if (first) {
575
          first = false;
576
        } else {
577
          self.append(" " + operator + " ");
578
        }
579
        if (qobject instanceof QueryGroup) {
580
          QueryGroup qg = (QueryGroup)qobject;
581
          self.append(qg.printSQL(useXMLIndex));
582
        } else if (qobject instanceof QueryTerm) {
583
          QueryTerm qt = (QueryTerm)qobject;
584
          self.append(qt.printSQL(useXMLIndex));
585
        } else {
586
          System.err.println("qobject wrong type: fatal error");
587
        }
588
      }
589
      self.append(") \n");
590
      return self.toString();
591
    }
592

    
593
    /**
594
     * create a String description of the query that this instance represents.
595
     * This should become a way to get the XML serialization of the query.
596
     */
597
    public String toString() {
598
      StringBuffer self = new StringBuffer();
599

    
600
      self.append("  (Query group operator=" + operator + "\n");
601
      Enumeration en= getChildren();
602
      while (en.hasMoreElements()) {
603
        Object qobject = en.nextElement();
604
        self.append(qobject);
605
      }
606
      self.append("  )\n");
607
      return self.toString();
608
    }
609
  }
610

    
611
  /** a utility class that represents a single term in a query */
612
  private class QueryTerm {
613
    private boolean casesensitive = false;
614
    private String searchmode = null;
615
    private String value = null;
616
    private String pathexpr = null;
617

    
618
    /**
619
     * Construct a new instance of a query term for a free text search
620
     * (using the value only)
621
     *
622
     * @param casesensitive flag indicating whether case is used to match
623
     * @param searchmode determines what kind of substring match is performed
624
     *        (one of starts-with|ends-with|contains|matches-exactly)
625
     * @param value the text value to match
626
     */
627
    public QueryTerm(boolean casesensitive, String searchmode, 
628
                     String value) {
629
      this.casesensitive = casesensitive;
630
      this.searchmode = searchmode;
631
      this.value = value;
632
    }
633

    
634
    /**
635
     * Construct a new instance of a query term for a structured search
636
     * (matching the value only for those nodes in the pathexpr)
637
     *
638
     * @param casesensitive flag indicating whether case is used to match
639
     * @param searchmode determines what kind of substring match is performed
640
     *        (one of starts-with|ends-with|contains|matches-exactly)
641
     * @param value the text value to match
642
     * @param pathexpr the hierarchical path to the nodes to be searched
643
     */
644
    public QueryTerm(boolean casesensitive, String searchmode, 
645
                     String value, String pathexpr) {
646
      this(casesensitive, searchmode, value);
647
      this.pathexpr = pathexpr;
648
    }
649

    
650
    /** determine if the QueryTerm is case sensitive */
651
    public boolean isCaseSensitive() {
652
      return casesensitive;
653
    }
654

    
655
    /** get the searchmode parameter */
656
    public String getSearchMode() {
657
      return searchmode;
658
    }
659
 
660
    /** get the Value parameter */
661
    public String getValue() {
662
      return value;
663
    }
664

    
665
    /** get the path expression parameter */
666
    public String getPathExpression() {
667
      return pathexpr;
668
    }
669

    
670
    /**
671
     * create a SQL serialization of the query that this instance represents
672
     */
673
    public String printSQL(boolean useXMLIndex) {
674
      StringBuffer self = new StringBuffer();
675

    
676
      // Uppercase the search string if case match is not important
677
      String casevalue = null;
678
      String nodedataterm = null;
679

    
680
      if (casesensitive) {
681
        nodedataterm = "nodedata";
682
        casevalue = value;
683
      } else {
684
        nodedataterm = "UPPER(nodedata)";
685
        casevalue = value.toUpperCase();
686
      }
687

    
688
      // Add appropriate wildcards to search string
689
      String searchvalue = null;
690
      if (searchmode.equals("starts-with")) {
691
        searchvalue = casevalue + "%";
692
      } else if (searchmode.equals("ends-with")) {
693
        searchvalue = "%" + casevalue;
694
      } else if (searchmode.equals("contains")) {
695
        searchvalue = "%" + casevalue + "%";
696
      } else {
697
        searchvalue = casevalue;
698
      }
699

    
700
      self.append("SELECT DISTINCT docid FROM xml_nodes WHERE \n");
701

    
702
      if (pathexpr != null) {
703
        self.append(nodedataterm + " LIKE " + "'" + searchvalue + "' ");
704
        self.append("AND parentnodeid IN ");
705
        // use XML Index
706
        if ( useXMLIndex ) {
707
          self.append("(SELECT nodeid FROM xml_index WHERE path LIKE " + 
708
                      "'" +  pathexpr + "') " );
709
        // without using XML Index; using nested statements instead
710
        } else {
711
          self.append(useNestedStatements(pathexpr));
712
        }
713
      } else {
714
        self.append(nodedataterm + " LIKE " + "'" + searchvalue + "' ");
715
      }
716

    
717
      return self.toString();
718
    }
719

    
720
    /* 
721
     * Constraint the query with @pathexp without using the XML Index,
722
     * but nested SQL statements instead. The query migth be slower.
723
     */
724
    private String useNestedStatements(String pathexpr)
725
    {
726
      StringBuffer nestedStmts = new StringBuffer();
727
      Vector nodes = new Vector();
728
      String path = pathexpr;
729
      int inx = 0;
730

    
731
      do {
732
        inx = path.lastIndexOf("/");
733
//System.out.println(path.substring(inx+1));
734
        nodes.addElement(path.substring(inx+1));
735
        path = path.substring(0, Math.abs(inx));
736
      } while ( inx > 0 );
737
      
738
      // nested statements
739
      int i = 0;
740
      for (i = 0; i < nodes.size()-1; i++) {
741
        nestedStmts.append("(SELECT nodeid FROM xml_nodes" + 
742
                           " WHERE nodename LIKE '" +
743
                             (String)nodes.elementAt(i) + "'" +
744
                           " AND parentnodeid IN ");
745
      }
746
      // for the last statement: it is without " AND parentnodeid IN "
747
      nestedStmts.append("(SELECT nodeid FROM xml_nodes" + 
748
                         " WHERE nodename LIKE '" +
749
                         (String)nodes.elementAt(i) + "'" );
750
      // node.size() number of closing brackets
751
      for (i = 0; i < nodes.size(); i++) {
752
        nestedStmts.append(")");
753
      }
754

    
755

    
756
//System.out.println(nestedStmts.toString());
757
      return nestedStmts.toString();
758
    }
759

    
760
    /**
761
     * create a String description of the query that this instance represents.
762
     * This should become a way to get the XML serialization of the query.
763
     */
764
    public String toString() {
765

    
766
      return this.printSQL(true);
767
    }
768
  }
769
}
(39-39/43)