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
 *
11
 *   '$Author: tao $'
12
 *     '$Date: 2007-08-16 21:14:40 -0700 (Thu, 16 Aug 2007) $'
13
 * '$Revision: 3360 $'
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 2 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 */
29

    
30
package edu.ucsb.nceas.metacat;
31

    
32
import java.io.IOException;
33
import java.io.Reader;
34
import java.io.StringReader;
35
import java.util.Enumeration;
36
import java.util.Hashtable;
37
import java.util.Stack;
38
import java.util.Vector;
39

    
40
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
41

    
42
import org.apache.log4j.Logger;
43
import org.xml.sax.Attributes;
44
import org.xml.sax.InputSource;
45
import org.xml.sax.SAXException;
46
import org.xml.sax.XMLReader;
47
import org.xml.sax.helpers.DefaultHandler;
48
import org.xml.sax.helpers.XMLReaderFactory;
49
import java.util.Iterator;
50

    
51
/**
52
 * A Class that represents a structured query, and can be constructed from an
53
 * XML serialization conforming to
54
 *
55
 * @see pathquery.dtd. The printSQL() method can be used to print a SQL
56
 *      serialization of the query.
57
 */
58
public class QuerySpecification extends DefaultHandler
59
{
60

    
61
    /** flag determining whether extended query terms are present */
62
    private boolean containsExtendedSQL = false;
63

    
64
    /** flag determining whether predicates are present */
65
    private boolean containsPredicates = false;
66

    
67
    /** Identifier for this query document */
68
    private String meta_file_id;
69

    
70
    /** Title of this query */
71
    private String queryTitle;
72

    
73
    /** List of document types to be returned using package back tracing */
74
    private Vector returnDocList;
75

    
76
    /** List of document types to be searched */
77
    private Vector filterDocList;
78

    
79
    /** List of fields to be returned in result set */
80
    private Vector returnFieldList;
81

    
82
    /** List of users owning documents to be searched */
83
    private Vector ownerList;
84

    
85
    /** The root query group that contains the recursive query constraints */
86
    private QueryGroup query = null;
87

    
88
    // Query data structures used temporarily during XML parsing
89
    private Stack elementStack;
90

    
91
    private Stack queryStack;
92

    
93
    private String currentValue;
94

    
95
    private String currentPathexpr;
96

    
97
    private String parserName = null;
98

    
99
    private String accNumberSeparator = null;
100

    
101
    private static final AbstractDatabase dbAdapter = MetaCatUtil.dbAdapter;
102

    
103
    private boolean percentageSearch = false;
104

    
105
    private String userName = null;
106

    
107
    private static final String PUBLIC = "public";
108

    
109
    private String[] group = null;
110

    
111
    public static final String ATTRIBUTESYMBOL = "@";
112

    
113
    public static final char PREDICATE_START = '[';
114

    
115
    public static final char PREDICATE_END = ']';
116

    
117
    //private boolean hasAttributeReturnField = false;
118

    
119
    //private Hashtable attributeReturnList = new Hashtable();
120

    
121
    //private int countAttributeReturnField = 0;
122

    
123
    private StringBuffer textBuffer = new StringBuffer();
124
    
125
   
126
    private static Logger logMetacat = Logger.getLogger(QuerySpecification.class);
127

    
128
    /**
129
     * construct an instance of the QuerySpecification class
130
     *
131
     * @param queryspec
132
     *            the XML representation of the query (should conform to
133
     *            pathquery.dtd) as a Reader
134
     * @param parserName
135
     *            the fully qualified name of a Java Class implementing the
136
     *            org.xml.sax.XMLReader interface
137
     */
138
    public QuerySpecification(Reader queryspec, String parserName,
139
            String accNumberSeparator) throws IOException
140
    {
141
        super();
142

    
143
        // Initialize the class variables
144
        returnDocList = new Vector();
145
        filterDocList = new Vector();
146
        elementStack = new Stack();
147
        queryStack = new Stack();
148
        returnFieldList = new Vector();
149
        ownerList = new Vector();
150
        this.parserName = parserName;
151
        this.accNumberSeparator = accNumberSeparator;
152

    
153
        // Initialize the parser and read the queryspec
154
        XMLReader parser = initializeParser();
155
        if (parser == null) {
156
            System.err.println("SAX parser not instantiated properly.");
157
        }
158
        try {
159
            parser.parse(new InputSource(queryspec));
160
        } catch (SAXException e) {
161
            System.err.println("error parsing data in "
162
                    + "QuerySpecification.QuerySpecification");
163
            System.err.println(e.getMessage());
164
        }
165
    }
166

    
167
    /**
168
     * construct an instance of the QuerySpecification class
169
     *
170
     * @param queryspec
171
     *            the XML representation of the query (should conform to
172
     *            pathquery.dtd) as a String
173
     * @param parserName
174
     *            the fully qualified name of a Java Class implementing the
175
     *            org.xml.sax.Parser interface
176
     */
177
    public QuerySpecification(String queryspec, String parserName,
178
            String accNumberSeparator) throws IOException
179
    {
180
        this(new StringReader(queryspec), parserName, accNumberSeparator);
181
    }
182

    
183
    /**
184
     * construct an instance of the QuerySpecification class which don't need
185
     * to parser a xml document
186
     *
187
     * @param accNumberSeparator
188
     *            the separator between doc version
189
     */
190
    public QuerySpecification(String accNumberSeparator) throws IOException
191
    {
192
        // Initialize the class variables
193
        returnDocList = new Vector();
194
        filterDocList = new Vector();
195
        elementStack = new Stack();
196
        queryStack = new Stack();
197
        returnFieldList = new Vector();
198
        ownerList = new Vector();
199
        this.accNumberSeparator = accNumberSeparator;
200
    }
201

    
202
    /**
203
     * Method to set user name
204
     *
205
     * @param myName
206
     *            the user name
207
     */
208
    public void setUserName(String myName)
209
    {
210
        //to lower case
211
        if (myName != null) {
212
            this.userName = myName.toLowerCase();
213
        } else {
214
            this.userName = myName;
215
        }
216
    }
217

    
218
    /**
219
     * Method to set user group
220
     *
221
     * @param myGroup
222
     *            the user group
223
     */
224
    public void setGroup(String[] myGroup)
225
    {
226
        this.group = myGroup;
227
    }
228

    
229
    /**
230
     * Method to indicate this query is a percentage search
231
     */
232
    public boolean isPercentageSearch()
233
    {
234
        return percentageSearch;
235
    }
236

    
237
    /*
238
     * Method to get owner query. If it is owner it has all permission
239
     */
240
    private String createOwerQuery()
241
    {
242
        String ownerQuery = null;
243
        //if user is public, we don't need to run owner query
244
        if (userName != null && !userName.equalsIgnoreCase(PUBLIC))
245
        {
246
	        ownerQuery = "SELECT docid FROM xml_documents WHERE ";
247
	        if (userName != null && !userName.equals("")) {
248
	            ownerQuery = ownerQuery + "lower(user_owner) ='" + userName + "'";
249
	        }
250
        }
251
        logMetacat.info("OwnerQuery: " + ownerQuery);
252
        return ownerQuery;
253
    }
254

    
255
    /*
256
     * Method to create query for xml_access, this part is to get docid list
257
     * which have a allow rule for a given user
258
     */
259
    private String createAllowRuleQuery()
260
    {
261
        String allowQuery = null;
262
        String allowString = constructAllowString();
263
        allowQuery = "SELECT docid from xml_access WHERE( " + allowString;
264
        allowQuery = allowQuery + ")";
265
        logMetacat.info("allow query is: " + allowQuery);
266
        return allowQuery;
267

    
268
    }
269

    
270
    /* Method to construct a allow rule string */
271
    private String constructAllowString()
272
    {
273
        String allowQuery = "";
274
        
275
       // add public
276
        allowQuery = "(lower(principal_name) = '" + PUBLIC
277
                + "'";
278
                
279
        // add user name
280
        if (userName != null && !userName.equals("") && !userName.equalsIgnoreCase(PUBLIC)) {
281
            allowQuery = allowQuery + "OR lower(principal_name) = '" + userName +"'";
282
                    
283
        }
284
        // add  group
285
        if (group != null) {
286
            for (int i = 0; i < group.length; i++) {
287
                String groupUint = group[i];
288
                if (groupUint != null && !groupUint.equals("")) {
289
                    groupUint = groupUint.toLowerCase();
290
                    allowQuery = allowQuery + " OR lower(principal_name) = '"
291
                            + groupUint + "'";
292
                }//if
293
            }//for
294
        }//if
295
        // add allow rule
296
        allowQuery = allowQuery + ") AND perm_type = 'allow'" + " AND permission > 3";
297
        logMetacat.info("allow string is: " + allowQuery);
298
        return allowQuery;
299
    }
300

    
301
    /*
302
     * Method to create query for xml_access, this part is to get docid list
303
     * which have a deny rule and perm_order is allowFirst for a given user.
304
     * This means the user will be denied to read
305
     */
306
    private String createDenyRuleQuery()
307
    {
308
        String denyQuery = null;
309
        String denyString = constructDenyString();
310
        denyQuery = "SELECT docid from xml_access WHERE( " + denyString;
311
        denyQuery = denyQuery + ") ";
312
        logMetacat.info("denyquery is: " + denyQuery);
313
        return denyQuery;
314

    
315
    }
316

    
317
    /* Construct deny string */
318
    private String constructDenyString()
319
    {
320
        String denyQuery = "";
321
         
322
        // add public
323
        denyQuery = "(lower(principal_name) = '" + PUBLIC
324
                 + "'";
325
                 
326
         // add user name
327
         if (userName != null && !userName.equals("") && !userName.equalsIgnoreCase(PUBLIC)) {
328
        	 denyQuery = denyQuery + "OR lower(principal_name) = '" + userName +"'";
329
                     
330
         }
331
         // add  groups
332
         if (group != null) {
333
             for (int i = 0; i < group.length; i++) {
334
                 String groupUint = group[i];
335
                 if (groupUint != null && !groupUint.equals("")) {
336
                     groupUint = groupUint.toLowerCase();
337
                     denyQuery = denyQuery + " OR lower(principal_name) = '"
338
                             + groupUint + "'";
339
                 }//if
340
             }//for
341
         }//if
342
         // add deny rules
343
         denyQuery = denyQuery + ") AND perm_type = 'deny'" +  " AND perm_order ='allowFirst'" +" AND permission > 3";
344
         logMetacat.info("allow string is: " + denyQuery);
345
         return denyQuery;
346
        
347
    }
348

    
349
    /**
350
     * Method to append a access control query to SQL. So in DBQuery class, we
351
     * can get docid from both user specified query and access control query.
352
     * We don't need to checking permission after we get the doclist. It will
353
     * be good to performance
354
     *
355
     */
356
    public String getAccessQuery()
357
    {
358
        String accessQuery = null;
359
        String onwer = createOwerQuery();
360
        String allow = createAllowRuleQuery();
361
        String deny = createDenyRuleQuery();
362
        //logMetacat.warn("onwer " +onwer);
363
        //logMetacat.warn("allow "+allow);
364
        //logMetacat.warn("deny "+deny);
365
        if (onwer != null)
366
        {
367
          accessQuery = " AND (docid IN(" + onwer + ")";
368
          accessQuery = accessQuery + " OR (docid IN (" + allow + ")"
369
                + " AND docid NOT IN (" + deny + ")))";
370
        }
371
        else
372
        {
373
        	accessQuery = " AND (docid IN (" + allow + ")"
374
                + " AND docid NOT IN (" + deny + "))";
375
        }
376
        logMetacat.warn("accessquery is: " + accessQuery);
377
        return accessQuery;
378
    }
379

    
380
    /**
381
     * Returns true if the parsed query contains and extended xml query (i.e.
382
     * there is at least one &lt;returnfield&gt; in the pathquery document)
383
     */
384
    public boolean containsExtendedSQL()
385
    {
386
        if (containsExtendedSQL) {
387
            return true;
388
        } else {
389
            return false;
390
        }
391
    }
392

    
393
  
394
    /**
395
     * Accessor method to return the identifier of this Query
396
     */
397
    public String getIdentifier()
398
    {
399
        return meta_file_id;
400
    }
401

    
402
    /**
403
     * method to set the identifier of this query
404
     */
405
    public void setIdentifier(String id)
406
    {
407
        this.meta_file_id = id;
408
    }
409

    
410
    /**
411
     * Accessor method to return the title of this Query
412
     */
413
    public String getQueryTitle()
414
    {
415
        return queryTitle;
416
    }
417

    
418
    /**
419
     * method to set the title of this query
420
     */
421
    public void setQueryTitle(String title)
422
    {
423
        this.queryTitle = title;
424
    }
425

    
426
    /**
427
     * Accessor method to return a vector of the return document types as
428
     * defined in the &lt;returndoctype&gt; tag in the pathquery dtd.
429
     */
430
    public Vector getReturnDocList()
431
    {
432
        return this.returnDocList;
433
    }
434

    
435
    /**
436
     * method to set the list of return docs of this query
437
     */
438
    public void setReturnDocList(Vector returnDocList)
439
    {
440
        this.returnDocList = returnDocList;
441
    }
442

    
443
    /**
444
     * Accessor method to return a vector of the filter doc types as defined in
445
     * the &lt;filterdoctype&gt; tag in the pathquery dtd.
446
     */
447
    public Vector getFilterDocList()
448
    {
449
        return this.filterDocList;
450
    }
451

    
452
    /**
453
     * method to set the list of filter docs of this query
454
     */
455
    public void setFilterDocList(Vector filterDocList)
456
    {
457
        this.filterDocList = filterDocList;
458
    }
459

    
460
    /**
461
     * Accessor method to return a vector of the extended return fields as
462
     * defined in the &lt;returnfield&gt; tag in the pathquery dtd.
463
     */
464
    public Vector getReturnFieldList()
465
    {
466
        return this.returnFieldList;
467
    }
468

    
469
    /**
470
     * method to set the list of fields to be returned by this query
471
     */
472
    public void setReturnFieldList(Vector returnFieldList)
473
    {
474
        this.returnFieldList = returnFieldList;
475
    }
476

    
477
    /**
478
     * Accessor method to return a vector of the owner fields as defined in the
479
     * &lt;owner&gt; tag in the pathquery dtd.
480
     */
481
    public Vector getOwnerList()
482
    {
483
        return this.ownerList;
484
    }
485

    
486
    /**
487
     * method to set the list of owners used to constrain this query
488
     */
489
    public void setOwnerList(Vector ownerList)
490
    {
491
        this.ownerList = ownerList;
492
    }
493

    
494
    /**
495
     * get the QueryGroup used to express query constraints
496
     */
497
    public QueryGroup getQueryGroup()
498
    {
499
        return query;
500
    }
501

    
502
    /**
503
     * set the querygroup
504
     */
505
    public void setQueryGroup(QueryGroup group)
506
    {
507
        query = group;
508
    }
509

    
510
    /**
511
     * set if this query sepcification has extendQuery(has return doc type or
512
     * not)
513
     */
514
    public void setContainsExtenedSQL(boolean hasExtenedQuery)
515
    {
516
        containsExtendedSQL = hasExtenedQuery;
517
    }
518

    
519
    /**
520
     * Set up the SAX parser for reading the XML serialized query
521
     */
522
    private XMLReader initializeParser()
523
    {
524
        XMLReader parser = null;
525

    
526
        // Set up the SAX document handlers for parsing
527
        try {
528

    
529
            // Get an instance of the parser
530
            parser = XMLReaderFactory.createXMLReader(parserName);
531

    
532
            // Set the ContentHandler to this instance
533
            parser.setContentHandler(this);
534

    
535
            // Set the error Handler to this instance
536
            parser.setErrorHandler(this);
537

    
538
        } catch (Exception e) {
539
            System.err.println("Error in QuerySpcecification.initializeParser "
540
                    + e.toString());
541
        }
542

    
543
        return parser;
544
    }
545

    
546
    /**
547
     * callback method used by the SAX Parser when the start tag of an element
548
     * is detected. Used in this context to parse and store the query
549
     * information in class variables.
550
     */
551
    public void startElement(String uri, String localName, String qName,
552
            Attributes atts) throws SAXException
553
    {
554
        BasicNode currentNode = new BasicNode(localName);
555
        // add attributes to BasicNode here
556
        if (atts != null) {
557
            int len = atts.getLength();
558
            for (int i = 0; i < len; i++) {
559
                currentNode
560
                        .setAttribute(atts.getLocalName(i), atts.getValue(i));
561
            }
562
        }
563

    
564
        elementStack.push(currentNode);
565
        if (currentNode.getTagName().equals("querygroup")) {
566
            QueryGroup currentGroup = new QueryGroup(currentNode
567
                    .getAttribute("operator"));
568
            if (query == null) {
569
                query = currentGroup;
570
            } else {
571
                QueryGroup parentGroup = (QueryGroup) queryStack.peek();
572
                parentGroup.addChild(currentGroup);
573
            }
574
            queryStack.push(currentGroup);
575
        }
576
    }
577

    
578
    /**
579
     * callback method used by the SAX Parser when the end tag of an element is
580
     * detected. Used in this context to parse and store the query information
581
     * in class variables.
582
     */
583
    public void endElement(String uri, String localName, String qName)
584
            throws SAXException
585
    {
586
        BasicNode leaving = (BasicNode) elementStack.pop();
587
        if (leaving.getTagName().equals("queryterm")) {
588
            boolean isCaseSensitive = (new Boolean(leaving
589
                    .getAttribute("casesensitive"))).booleanValue();
590
            QueryTerm currentTerm = null;
591
            if (currentPathexpr == null) {
592
                currentTerm = new QueryTerm(isCaseSensitive, leaving
593
                        .getAttribute("searchmode"), currentValue);
594
            } else {
595
                currentTerm = new QueryTerm(isCaseSensitive, leaving
596
                        .getAttribute("searchmode"), currentValue,
597
                        currentPathexpr);
598
            }
599
            QueryGroup currentGroup = (QueryGroup) queryStack.peek();
600
            currentGroup.addChild(currentTerm);
601
            currentValue = null;
602
            currentPathexpr = null;
603
        } else if (leaving.getTagName().equals("querygroup")) {
604
            QueryGroup leavingGroup = (QueryGroup) queryStack.pop();
605
        } else if (leaving.getTagName().equals("meta_file_id")) {
606
              meta_file_id = textBuffer.toString().trim();
607
        } else if (leaving.getTagName().equals("querytitle")) {
608
              queryTitle = textBuffer.toString().trim();
609
        } else if (leaving.getTagName().equals("value")) {
610
              currentValue = textBuffer.toString().trim();
611
        } else if (leaving.getTagName().equals("pathexpr")) {
612
              currentPathexpr = textBuffer.toString().trim();
613
        } else if (leaving.getTagName().equals("returndoctype")) {
614
              returnDocList.add(textBuffer.toString().trim());
615
        } else if (leaving.getTagName().equals("filterdoctype")) {
616
              filterDocList.add(textBuffer.toString().trim());
617
        } else if (leaving.getTagName().equals("returnfield")) {
618
              handleReturnField(textBuffer.toString().trim());
619
        } else if (leaving.getTagName().equals("filterdoctype")) {
620
              filterDocList.add(textBuffer.toString().trim());
621
        } else if (leaving.getTagName().equals("owner")) {
622
              ownerList.add(textBuffer.toString().trim());
623
        }
624

    
625
        //rest textBuffer
626
        textBuffer = new StringBuffer();
627

    
628
    }
629

    
630
    /**
631
     * callback method used by the SAX Parser when the text sequences of an xml
632
     * stream are detected. Used in this context to parse and store the query
633
     * information in class variables.
634
     */
635
    public void characters(char ch[], int start, int length)
636
    {
637
      // buffer all text nodes for same element. This is for text was splited
638
      // into different nodes
639
      textBuffer.append(new String(ch, start, length));
640

    
641
    }
642

    
643
   /**
644
    * Method to handle return field. It will be callied in ecogrid part
645
    * @param inputString
646
    */
647
    public void handleReturnField(String inputString)
648
    {
649
        int attributePos = inputString.indexOf(ATTRIBUTESYMBOL);
650
        int predicateStart = -1;
651
        int predicateEnd;
652
        boolean hasPredicate = false;
653

    
654
        while (true)
655
        {
656
            predicateStart = inputString.indexOf(PREDICATE_START, predicateStart + 1);
657

    
658
            if (attributePos == -1)
659
                break;
660

    
661
            if (predicateStart == -1)
662
                break;
663

    
664
            hasPredicate = true;
665

    
666
            if (attributePos < predicateStart)
667
                break;
668

    
669
            predicateEnd = inputString.indexOf(PREDICATE_END, predicateStart);
670

    
671
            if (predicateEnd == -1)
672
            {
673
                logMetacat.warn("handleReturnField(): ");
674
                logMetacat.warn("    Invalid path: " + inputString);
675
                return;
676
            }
677

    
678
            while (attributePos < predicateEnd)
679
            {
680
                attributePos = inputString.indexOf(ATTRIBUTESYMBOL, attributePos + 1);
681

    
682
                if (attributePos == -1)
683
                    break;
684
            }
685
        }
686

    
687
        if (hasPredicate)
688
            containsPredicates = true;
689

    
690
        containsExtendedSQL = true;
691

    
692
     
693
            // no attribute value will be returned
694
            logMetacat.info("QuerySpecification.handleReturnField(): " );
695
            logMetacat.info("  there are no attributes in the XPATH statement" );
696
            returnFieldList.add(inputString);
697
       
698

    
699
       
700
    }
701

    
702
    /**
703
     * create a SQL serialization of the query that this instance represents
704
     */
705
    public String printSQL(boolean useXMLIndex)
706
    {
707

    
708
        StringBuffer self = new StringBuffer();
709
        StringBuffer queryString = new StringBuffer();
710

    
711
        queryString.append("SELECT docid,docname,doctype,");
712
        queryString.append("date_created, date_updated, rev ");
713
        queryString.append("FROM xml_documents WHERE");
714

    
715
        // Get the query from the QueryGroup and check
716
        // if no query has been returned
717
        String queryFromQueryGroup = query.printSQL(useXMLIndex);
718
        logMetacat.info("Query from query in QuerySpec.printSQL: " 
719
        		+ queryFromQueryGroup);
720
        
721
        if(!queryFromQueryGroup.trim().equals("")){
722
            self.append(" docid IN (");
723
            self.append(queryFromQueryGroup);
724
            self.append(") ");
725
        }
726

    
727
        // Add SQL to filter for doctypes requested in the query
728
        // This is an implicit OR for the list of doctypes. Only doctypes in
729
        // this
730
        // list will be searched if the tag is present
731
        if (!filterDocList.isEmpty()) {
732
            boolean firstdoctype = true;
733
            boolean emptyString = true;
734

    
735
            if(!self.toString().equals("")){
736
                self.append(" AND (");
737
                emptyString = false;
738
            }
739

    
740
            Enumeration en = filterDocList.elements();
741
            while (en.hasMoreElements()) {
742
                String currentDoctype = (String) en.nextElement();
743
                if (firstdoctype) {
744
                    firstdoctype = false;
745
                    self.append(" doctype = '" + currentDoctype + "'");
746
                } else {
747
                    self.append(" OR doctype = '" + currentDoctype + "'");
748
                }
749
            }
750

    
751
            if(!emptyString){
752
                self.append(") ");
753
            }
754
        }
755

    
756
        // Add SQL to filter for owners requested in the query
757
        // This is an implicit OR for the list of owners
758
        if (!ownerList.isEmpty()) {
759
            boolean first = true;
760
            boolean emptyString = true;
761

    
762
            if(!self.toString().equals("")){
763
                self.append(" AND (");
764
                emptyString = false;
765
            }
766

    
767
            Enumeration en = ownerList.elements();
768
            while (en.hasMoreElements()) {
769
                String current = (String) en.nextElement();
770
                if (current != null) {
771
                    current = current.toLowerCase();
772
                }
773
                if (first) {
774
                    first = false;
775
                    self.append(" lower(user_owner) = '" + current + "'");
776
                } else {
777
                    self.append(" OR lower(user_owner) = '" + current + "'");
778
                }
779
            }
780

    
781
            if(!emptyString){
782
                self.append(") ");
783
            }
784
        }
785

    
786
        // if there is only one percentage search item, this query is a
787
        // percentage
788
        // search query
789
        logMetacat.info("percentage number: "
790
                + query.getPercentageSymbolCount());
791
        if (query.getPercentageSymbolCount() == 1) {
792
            logMetacat.info("It is a percentage search");
793
            percentageSearch = true;
794
        }
795

    
796
        queryString.append(self.toString());
797
        return queryString.toString();
798
    }
799

    
800
   
801

    
802
    /**
803
     * This method prints sql based upon the &lt;returnfield&gt; tag in the
804
     * pathquery document. This allows for customization of the returned fields.
805
     * If the boolean useXMLIndex paramter is false, it uses a recursive query on
806
     * xml_nodes to find the fields to be included by their path expression, and
807
     * avoids the use of the xml_index table.
808
     *
809
     * @param doclist the list of document ids to search
810
     * @param unaccessableNodePair the node pairs (start id and end id) which
811
     *            this user should not access
812
     * @param useXMLIndex a boolean flag indicating whether to search using
813
     *            xml_index
814
     */
815
    public String printExtendedSQL(String doclist, boolean useXMLIndex)
816
    {
817
        if (useXMLIndex && !containsPredicates)
818
        {
819
            return printExtendedSQL(doclist);
820
        }
821
        else
822
        {
823
            StringBuffer self = new StringBuffer();
824

    
825
            boolean firstfield = true;
826
            //put the returnfields into the query
827
            //the for loop allows for multiple fields
828
            for (int i = 0; i < returnFieldList.size(); i++)
829
            {
830
                if (firstfield)
831
                {
832
                    firstfield = false;
833
                }
834
                else
835
                {
836
                    self.append(" UNION ");
837
                }
838
                String path  = (String) returnFieldList.elementAt(i);
839
                self.append("select xml_nodes.docid, ");
840
                self.append("'"+ path.replaceAll("'", "''") + "' as path, xml_nodes.nodedata, ");
841
                self.append("xml_nodes.parentnodeid ");
842
                self.append("from xml_nodes, xml_documents ");
843
                self.append("where parentnodeid IN ");
844
                self.append(QueryTerm.useNestedStatements(path));
845

    
846
                self.append(" AND xml_nodes.docid in (");
847
                self.append(doclist);
848
                self.append(") AND xml_nodes.nodetype = 'TEXT'");
849
                self.append(" AND xml_nodes.rootnodeid = xml_documents.rootnodeid");
850

    
851
                //addAccessRestrictionSQL(unaccessableNodePair, self);
852
            }
853

    
854
            return self.toString();
855
        }
856
    }
857

    
858
    /**
859
     * This method prints sql based upon the &lt;returnfield&gt; tag in the
860
     * pathquery document. This allows for customization of the returned fields.
861
     * It uses the xml_index table and so assumes that this table has been
862
     * built.
863
     *
864
     * @param doclist the list of document ids to search
865
     * @param unaccessableNodePair the node pairs (start id and end id)
866
     *            which this user should not access
867
     */
868
    private String printExtendedSQL(String doclist)
869
    {
870
        logMetacat.info("querySpecification.printExtendedSQL called\n");
871
        StringBuffer self = new StringBuffer();
872
        Vector elementVector = new Vector();
873
        Vector attributeVector = new Vector();
874

    
875
        boolean usePathIndex = true;
876

    
877
        // test if the are elements in the return fields
878
        if ( returnFieldList.size() == 0 ) {
879
            return null;
880
        }
881

    
882
        for (int i = 0; i < returnFieldList.size(); i++) {
883
        	String path = (String)returnFieldList.elementAt(i);
884
        	if (path != null && path.indexOf(ATTRIBUTESYMBOL) != -1)
885
        	{
886
        		attributeVector.add(path);
887
        	}
888
        	else 
889
        	{
890
        		elementVector.add(path);
891
        	}       	
892
            if(!MetaCatUtil.pathsForIndexing.contains(path)){
893
                usePathIndex = false;              
894
            }
895
         
896
        }
897
        // check if has return field
898
        if (elementVector.size() == 0 && attributeVector.size()==0)
899
        {
900
        	return null;
901
        }
902

    
903
        if(usePathIndex){
904
            self.append("select docid, path, nodedata, parentnodeid ");
905
            self.append("from xml_path_index where path in( '");
906

    
907
            boolean firstfield = true;
908
            //put the returnfields into the query
909
            //the for loop allows for multiple fields
910
            for (int i = 0; i < returnFieldList.size(); i++) {
911
                if (firstfield) {
912
                    firstfield = false;
913
                    self.append( (String) returnFieldList.elementAt(i));
914
                    self.append("' ");
915
                }
916
                else {
917
                    self.append(", '");
918
                    self.append( (String) returnFieldList.elementAt(i));
919
                    self.append("' ");
920
                }
921
            }
922
            self.append(") AND docid in (");
923
            self.append(doclist);
924
            self.append(")");
925

    
926
        } else {
927
            self.append("select xml_nodes.docid, xml_index.path, xml_nodes.nodedata,  ");
928
            self.append("xml_nodes.parentnodeid ");
929
            self.append("FROM xml_index, xml_nodes WHERE (");
930
           
931

    
932
            boolean firstElement = true;
933
            boolean firstAttribute = true;
934
            //put the returnfields into the query
935
            //the for loop allows for multiple fields
936
            if (elementVector.size() != 0)
937
            {
938
	            for (int i = 0; i < elementVector.size(); i++) {
939
	            	String path = (String) elementVector.elementAt(i);
940
	                if (firstElement) {
941
	                	firstElement = false;
942
	                	self.append(" (xml_index.nodeid=xml_nodes.parentnodeid AND xml_index.path IN ('");
943
	                    self.append(path);
944
	                    self.append("'");
945
	                 }
946
	                else 
947
	                {
948
	                    self.append(", '");
949
	                    self.append(path);
950
	                    self.append("' ");
951
	                }
952
	            }
953
	            self.append(") AND xml_nodes.nodetype = 'TEXT')");
954
            }
955
            
956
            if (attributeVector.size() != 0)
957
            {
958
            	for (int j=0; j<attributeVector.size(); j++)
959
            	{
960
            		String path = (String) attributeVector.elementAt(j);
961
            		if (firstAttribute)
962
            		{
963
            			firstAttribute = false;
964
            			if (!firstElement)
965
                		{
966
                			self.append(" OR ");
967
                		}
968
            			self.append(" (xml_index.nodeid=xml_nodes.nodeid AND ( xml_index.path IN ( '");
969
	                    self.append(path);
970
	                    self.append("'");
971
            		}
972
            		else 
973
	                {
974
	                    self.append(", '");
975
	                    self.append(path);
976
	                    self.append("' ");
977
	                }
978
            	}
979
            	self.append(") AND xml_nodes.nodetype = 'ATTRIBUTE'))");
980
            }
981
            
982
          
983
            self.append(") AND xml_nodes.docid in (");
984
            self.append(doclist);
985
            self.append(")");
986

    
987
        }
988

    
989
        return self.toString();
990
    }
991

    
992

    
993
    /**
994
     * Method to return a String generated after sorting the returnFieldList
995
     * Vector
996
     */
997
    public String getSortedReturnFieldString(){
998
        String returnFields = "";
999

    
1000
        // Create a temporary vector and copy returnFieldList into it
1001
        Vector tempVector = new Vector();
1002

    
1003
        Iterator it = returnFieldList.iterator();
1004
        while(it.hasNext()){
1005
            tempVector.add(it.next());
1006
        }
1007

    
1008
        /*Enumeration attEnum = attributeReturnList.elements();
1009
        while(attEnum.hasMoreElements()){
1010
            Iterator tempIt = ((Vector)attEnum.nextElement()).iterator();
1011
	    String rfield = "";
1012
            if(tempIt.hasNext()){
1013
		String element = (String)tempIt.next();
1014
		if(element != null) {
1015
		    rfield +=element;
1016
		}
1017
	    }
1018
            if(tempIt.hasNext()){
1019
		String attribute = (String)tempIt.next();
1020
		if(attribute != null) {
1021
  		    rfield = rfield + "@" + attribute;
1022
                }
1023
	    }
1024
            tempVector.add(rfield);
1025
        }*/
1026

    
1027
        // Sort the temporary vector
1028
        java.util.Collections.sort(tempVector);
1029

    
1030
        // Generate the string and return it
1031
        it = tempVector.iterator();
1032
        while(it.hasNext()){
1033
            returnFields = returnFields + it.next() + "|";
1034
        }
1035
        return returnFields;
1036
    }
1037

    
1038

    
1039
  
1040

    
1041

    
1042
    public static String printRelationSQL(String docid)
1043
    {
1044
        StringBuffer self = new StringBuffer();
1045
        self.append("select subject, relationship, object, subdoctype, ");
1046
        self.append("objdoctype from xml_relation ");
1047
        self.append("where docid like '").append(docid).append("'");
1048
        return self.toString();
1049
    }
1050

    
1051
    public static String printGetDocByDoctypeSQL(String docid)
1052
    {
1053
        StringBuffer self = new StringBuffer();
1054

    
1055
        self.append("SELECT docid,docname,doctype,");
1056
        self.append("date_created, date_updated ");
1057
        self.append("FROM xml_documents WHERE docid IN (");
1058
        self.append(docid).append(")");
1059
        return self.toString();
1060
    }
1061

    
1062
    /**
1063
     * create a String description of the query that this instance represents.
1064
     * This should become a way to get the XML serialization of the query.
1065
     */
1066
    public String toString()
1067
    {
1068
        return "meta_file_id=" + meta_file_id + "\n" + query;
1069
        //DOCTITLE attr cleared from the db
1070
        //return "meta_file_id=" + meta_file_id + "\n" +
1071
        //"querytitle=" + querytitle + "\n" + query;
1072
    }
1073

    
1074
    /** A method to get rid of attribute part in path expression */
1075
    public static String newPathExpressionWithOutAttribute(String pathExpression)
1076
    {
1077
        if (pathExpression == null) { return null; }
1078
        int index = pathExpression.lastIndexOf(ATTRIBUTESYMBOL);
1079
        String newExpression = null;
1080
        if (index != 0) {
1081
            newExpression = pathExpression.substring(0, index - 1);
1082
        }
1083
        logMetacat.info("The path expression without attributes: "
1084
                + newExpression);
1085
        return newExpression;
1086
    }
1087

    
1088
    /** A method to get attribute name from path */
1089
    public static String getAttributeName(String path)
1090
    {
1091
        if (path == null) { return null; }
1092
        int index = path.lastIndexOf(ATTRIBUTESYMBOL);
1093
        int size = path.length();
1094
        String attributeName = null;
1095
        if (index != 1) {
1096
            attributeName = path.substring(index + 1, size);
1097
        }
1098
        logMetacat.info("The attirbute name from path: "
1099
                + attributeName);
1100
        return attributeName;
1101
    }
1102

    
1103
}
(54-54/66)