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-13 16:40:52 -0700 (Mon, 13 Aug 2007) $'
13
 * '$Revision: 3355 $'
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
    private void handleReturnField(String inputString)
645
    {
646
        int attributePos = inputString.indexOf(ATTRIBUTESYMBOL);
647
        int predicateStart = -1;
648
        int predicateEnd;
649
        boolean hasPredicate = false;
650

    
651
        while (true)
652
        {
653
            predicateStart = inputString.indexOf(PREDICATE_START, predicateStart + 1);
654

    
655
            if (attributePos == -1)
656
                break;
657

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

    
661
            hasPredicate = true;
662

    
663
            if (attributePos < predicateStart)
664
                break;
665

    
666
            predicateEnd = inputString.indexOf(PREDICATE_END, predicateStart);
667

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

    
675
            while (attributePos < predicateEnd)
676
            {
677
                attributePos = inputString.indexOf(ATTRIBUTESYMBOL, attributePos + 1);
678

    
679
                if (attributePos == -1)
680
                    break;
681
            }
682
        }
683

    
684
        if (hasPredicate)
685
            containsPredicates = true;
686

    
687
        containsExtendedSQL = true;
688

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

    
696
       
697
    }
698

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

    
705
        StringBuffer self = new StringBuffer();
706
        StringBuffer queryString = new StringBuffer();
707

    
708
        queryString.append("SELECT docid,docname,doctype,");
709
        queryString.append("date_created, date_updated, rev ");
710
        queryString.append("FROM xml_documents WHERE");
711

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

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

    
732
            if(!self.toString().equals("")){
733
                self.append(" AND (");
734
                emptyString = false;
735
            }
736

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

    
748
            if(!emptyString){
749
                self.append(") ");
750
            }
751
        }
752

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

    
759
            if(!self.toString().equals("")){
760
                self.append(" AND (");
761
                emptyString = false;
762
            }
763

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

    
778
            if(!emptyString){
779
                self.append(") ");
780
            }
781
        }
782

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

    
793
        queryString.append(self.toString());
794
        return queryString.toString();
795
    }
796

    
797
   
798

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

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

    
843
                self.append(" AND xml_nodes.docid in (");
844
                self.append(doclist);
845
                self.append(") AND xml_nodes.nodetype = 'TEXT'");
846
                self.append(" AND xml_nodes.rootnodeid = xml_documents.rootnodeid");
847

    
848
                //addAccessRestrictionSQL(unaccessableNodePair, self);
849
            }
850

    
851
            return self.toString();
852
        }
853
    }
854

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

    
872
        boolean usePathIndex = true;
873

    
874
        // test if the are elements in the return fields
875
        if ( returnFieldList.size() == 0 ) {
876
            return null;
877
        }
878

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

    
900
        if(usePathIndex){
901
            self.append("select docid, path, nodedata, parentnodeid ");
902
            self.append("from xml_path_index where path in( '");
903

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

    
923
        } else {
924
            self.append("select xml_nodes.docid, xml_index.path, xml_nodes.nodedata,  ");
925
            self.append("xml_nodes.parentnodeid ");
926
            self.append("FROM xml_index, xml_nodes WHERE (");
927
           
928

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

    
984
        }
985

    
986
        return self.toString();
987
    }
988

    
989

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

    
997
        // Create a temporary vector and copy returnFieldList into it
998
        Vector tempVector = new Vector();
999

    
1000
        Iterator it = returnFieldList.iterator();
1001
        while(it.hasNext()){
1002
            tempVector.add(it.next());
1003
        }
1004

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

    
1024
        // Sort the temporary vector
1025
        java.util.Collections.sort(tempVector);
1026

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

    
1035

    
1036
  
1037

    
1038

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

    
1048
    public static String printGetDocByDoctypeSQL(String docid)
1049
    {
1050
        StringBuffer self = new StringBuffer();
1051

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

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

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

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

    
1100
}
(54-54/66)