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: daigle $'
12
 *     '$Date: 2009-02-18 16:30:06 -0800 (Wed, 18 Feb 2009) $'
13
 * '$Revision: 4812 $'
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.util.Vector;
33
import org.apache.log4j.Logger;
34

    
35
import edu.ucsb.nceas.metacat.util.MetacatUtil;
36
import edu.ucsb.nceas.metacat.util.SystemUtil;
37
import edu.ucsb.nceas.metacat.util.UtilException;
38

    
39
/** a utility class that represents a single term in a query */
40
public class QueryTerm
41
{
42
    private static Logger log = Logger.getLogger(QueryTerm.class);
43

    
44
    private boolean casesensitive = false;
45

    
46
    private String searchmode = null;
47

    
48
    private String value = null;
49

    
50
    private String pathexpr = null;
51

    
52
    private boolean percentageSymbol = false;
53

    
54
    private int countPercentageSearchItem = 0;
55
    
56
    private boolean inUnionGroup = false;
57
    
58
    public static final String CONTAINS = "contains";
59
    
60
    public static final String EQUALS = "equals";
61

    
62
    /**
63
     * Construct a new instance of a query term for a free text search (using
64
     * the value only)
65
     *
66
     * @param casesensitive
67
     *            flag indicating whether case is used to match
68
     * @param searchmode
69
     *            determines what kind of substring match is performed (one of
70
     *            starts-with|ends-with|contains|matches-exactly)
71
     * @param value
72
     *            the text value to match
73
     */
74
    public QueryTerm(boolean casesensitive, String searchmode, String value)
75
    {
76
        this.casesensitive = casesensitive;
77
        this.searchmode = searchmode;
78
        this.value = value;
79
    }
80

    
81
    /**
82
     * Construct a new instance of a query term for a structured search
83
     * (matching the value only for those nodes in the pathexpr)
84
     *
85
     * @param casesensitive
86
     *            flag indicating whether case is used to match
87
     * @param searchmode
88
     *            determines what kind of substring match is performed (one of
89
     *            starts-with|ends-with|contains|matches-exactly)
90
     * @param value
91
     *            the text value to match
92
     * @param pathexpr
93
     *            the hierarchical path to the nodes to be searched
94
     */
95
    public QueryTerm(boolean casesensitive, String searchmode, String value,
96
            String pathexpr)
97
    {
98
        this(casesensitive, searchmode, value);
99
        this.pathexpr = pathexpr;
100
    }
101

    
102
    /** determine if the QueryTerm is case sensitive */
103
    public boolean isCaseSensitive()
104
    {
105
        return casesensitive;
106
    }
107

    
108
    /** get the searchmode parameter */
109
    public String getSearchMode()
110
    {
111
        return searchmode;
112
    }
113

    
114
    /** get the Value parameter */
115
    public String getValue()
116
    {
117
        return value;
118
    }
119

    
120
    /** get the path expression parameter */
121
    public String getPathExpression()
122
    {
123
        return pathexpr;
124
    }
125

    
126
    /** get the percentage count for one query term */
127
    public int getPercentageSymbolCount()
128
    {
129
        return countPercentageSearchItem;
130
    }
131
    
132
    /**
133
     * Set the query term in a union group
134
     * @param inUnionGroup
135
     */
136
    public void setInUnionGroup (boolean inUnionGroup)
137
    {
138
    	this.inUnionGroup = inUnionGroup;
139
    }
140
    
141
    /**
142
     * If this query group in Union group
143
     * @return
144
     */
145
    public boolean isInUnionGroup()
146
    {
147
    	return this.inUnionGroup;
148
    }
149

    
150
    /**
151
     * create a SQL serialization of the query that this instance represents
152
     */
153
    public String printSQL(boolean useXMLIndex)
154
    {
155
        StringBuffer self = new StringBuffer();
156

    
157
        // Uppercase the search string if case match is not important
158
        String casevalue = null;
159
        String nodedataterm = null;
160
        boolean notEqual = false;
161
        if (casesensitive) {
162
            nodedataterm = "nodedata";
163
            casevalue = value;
164
        } else {
165
            nodedataterm = "UPPER(nodedata)";
166
            casevalue = value.toUpperCase();
167
        }
168

    
169
        // Add appropriate wildcards to search string
170
        String searchexpr = null;
171
        if (searchmode.equals("starts-with")) {
172
            searchexpr = nodedataterm + " LIKE '" + casevalue + "%' ";
173
        } else if (searchmode.equals("ends-with")) {
174
            searchexpr = nodedataterm + " LIKE '%" + casevalue + "' ";
175
        } else if (searchmode.equals("contains")) {
176
            if (!casevalue.equals("%")) {
177
                searchexpr = nodedataterm + " LIKE '%" + casevalue + "%' ";
178
            } else {
179
                searchexpr = nodedataterm + " LIKE '" + casevalue + "' ";
180
                // find percentage symbol
181
                percentageSymbol = true;
182
            }
183
        } else if (searchmode.equals("not-contains")) {
184
        	notEqual = true;
185
            searchexpr = nodedataterm + " LIKE '%" + casevalue + "%' ";
186
        } else if (searchmode.equals("equals")) {
187
            searchexpr = nodedataterm + " = '" + casevalue + "' ";
188
        } else if (searchmode.equals("isnot-equal")) {
189
        	notEqual = true;
190
            searchexpr = nodedataterm + " = '" + casevalue + "' ";
191
        } else {
192
            String oper = null;
193
            if (searchmode.equals("greater-than")) {
194
                oper = ">";
195
                nodedataterm = "nodedatanumerical";
196
            } else if (searchmode.equals("greater-than-equals")) {
197
                oper = ">=";
198
                nodedataterm = "nodedatanumerical";
199
            } else if (searchmode.equals("less-than")) {
200
                oper = "<";
201
                nodedataterm = "nodedatanumerical";
202
            } else if (searchmode.equals("less-than-equals")) {
203
                oper = "<=";
204
                nodedataterm = "nodedatanumerical";
205
            } else {
206
                System.out
207
                        .println("NOT expected case. NOT recognized operator: "
208
                                + searchmode);
209
                return null;
210
            }
211
            try {
212
                // it is number; numeric comparison
213
                // but we need to make sure there is no string in node data
214
                searchexpr = nodedataterm + " " + oper + " "
215
                        + new Double(casevalue) + " ";
216
            } catch (NumberFormatException nfe) {
217
                // these are characters; character comparison
218
                searchexpr = nodedataterm + " " + oper + " '" + casevalue
219
                        + "' ";
220
            }
221
        }
222

    
223

    
224
        // to check xml_path_index can be used
225
        boolean usePathIndex = false;
226

    
227
        // if pathexpr has been specified in metacat.properties for indexing
228
        if(pathexpr != null){
229
        	try {
230
				if (SystemUtil.getPathsForIndexing().contains(pathexpr)) {
231
					usePathIndex = true;
232
				}
233
			} catch (UtilException ue) {
234
				log.warn("Could not get index paths: " + ue.getMessage());
235
			}
236
        }
237
        
238
        if(usePathIndex){
239
            // using xml_path_index table.....
240
        	if(notEqual == true ){
241
        		if (!inUnionGroup)
242
        		{
243
        			self.append("SELECT DISTINCT docid from xml_path_index WHERE");
244
        			self.append(" docid NOT IN (Select docid FROM xml_path_index WHERE ");
245
        			self.append(searchexpr);
246
        			self.append("AND path LIKE '" + pathexpr + "') ");
247
        		}
248
        		else
249
        		{
250
        			//if this is in union group we need to use "OR" to modify query
251
        			self.append("("+searchexpr);
252
        			self.append("AND path LIKE '" + pathexpr + "') ");
253
        		}
254
        	} else {
255
        		if (!inUnionGroup)
256
        		{
257
        			self.append("SELECT DISTINCT docid FROM xml_path_index WHERE ");
258
        			self.append(searchexpr);
259
        			self.append("AND path LIKE '" + pathexpr + "' ");
260
        		}
261
        		else
262
        		{
263
        			//if this is in union group we need to use "OR" to modify query
264
        			self.append("("+searchexpr);
265
        			self.append("AND path LIKE '" + pathexpr + "') ");
266
        		}
267
        	}
268

    
269
        } else {
270
            // using xml_nodes and xml_index tables
271

    
272
        	if(notEqual == true){
273
        		self.append("SELECT DISTINCT docid from xml_nodes WHERE");
274
        		self.append(" docid NOT IN (Select docid FROM xml_nodes WHERE ");
275
        	} else {
276
        		self.append("(SELECT DISTINCT docid FROM xml_nodes WHERE ");
277
        	}
278
        	self.append(searchexpr);
279
        	
280
            if (pathexpr != null) {
281
             String path = pathexpr;
282
                // use XML Index
283
                if (useXMLIndex) {
284
                    if (!hasAttributeInPath(pathexpr)) {
285
                        // without attributes in path
286
                        self.append("AND parentnodeid IN ");
287
                    } else {
288
                        // has a attribute in path
289
                        String attributeName = QuerySpecification
290
                            .getAttributeName(pathexpr);
291
                        self.append(
292
                            "AND nodetype LIKE 'ATTRIBUTE' AND nodename LIKE '"
293
                            + attributeName + "' ");
294
                        // and the path expression includes element content other than
295
                        // just './' or '../'
296
                        if ( (!pathexpr.startsWith(QuerySpecification.
297
                            ATTRIBUTESYMBOL)) &&
298
                            (!pathexpr.startsWith("./" +
299
                                                  QuerySpecification.ATTRIBUTESYMBOL)) &&
300
                            (!pathexpr.startsWith("../" +
301
                                                  QuerySpecification.ATTRIBUTESYMBOL))) {
302

    
303
                            self.append("AND parentnodeid IN ");
304
                            path = QuerySpecification
305
                                .newPathExpressionWithOutAttribute(pathexpr);
306
                        }
307
                    }
308
                    self.append(
309
                        "(SELECT nodeid FROM xml_index WHERE path LIKE "
310
                        + "'" + path + "') ");
311
                }
312
                else {
313
                    // without using XML Index; using nested statements instead
314
                    //self.append("AND parentnodeid IN ");
315
                	self.append("AND ");
316
                    self.append(useNestedStatements(pathexpr));
317
                }
318
            }
319
            else if ( (value.trim()).equals("%")) {
320
                //if pathexpr is null and search value is %, is a
321
                // percentageSearchItem
322
                // the count number will be increase one
323
                countPercentageSearchItem++;
324

    
325
            }
326
            self.append(") ");
327
        }
328

    
329
        return self.toString();
330
    }
331

    
332
    /** A method to judge if a path have attribute */
333
    private boolean hasAttributeInPath(String path)
334
    {
335
        if (path.indexOf(QuerySpecification.ATTRIBUTESYMBOL) != -1) {
336
            return true;
337
        } else {
338
            return false;
339
        }
340
    }
341

    
342
   
343
    public static String useNestedStatements(String pathexpr)
344
    {
345
        log.info("useNestedStatements()");
346
        log.info("pathexpr: " + pathexpr);
347
        String elementPrefix = " parentnodeid IN ";
348
        String attributePrefix  =  " nodeid IN ";
349
        boolean lastOneIsAttribute = false;
350
        StringBuffer nestedStmts = new StringBuffer();
351
        String path = pathexpr.trim();
352
        String sql = "";
353

    
354
        if (path.indexOf('/') == 0)
355
        {
356
            nestedStmts.append("AND parentnodeid = rootnodeid ");
357
            path = path.substring(1).trim();
358
        }
359

    
360
        do
361
        {
362
            int inx = path.indexOf('/');
363
            int predicateStart = -1;
364
            int predicateEnd;
365
            String node;
366
            Vector predicates = new Vector();
367

    
368
            // extract predicates
369
            predicateStart = path.indexOf(QuerySpecification.PREDICATE_START, predicateStart + 1);
370

    
371
            // any predicates in this node?
372
            if (inx != -1 && (predicateStart == -1 || predicateStart > inx))
373
            {
374
                // no
375
                node = path.substring(0, inx).trim();
376
                path = path.substring(inx + 1).trim();
377
            }
378
            else if (predicateStart == -1)
379
            {
380
                // no and it's the last node
381
                node = path;
382
                if (node != null && node.indexOf(QuerySpecification.ATTRIBUTESYMBOL) != -1)
383
                {
384
                	lastOneIsAttribute = true;
385
                	node = removeAttributeSymbol(node);
386
                }
387
                path = "";
388
            }
389
            else
390
            {
391
                // yes
392
                node = path.substring(0, predicateStart).trim();
393
                path = path.substring(predicateStart);
394
                predicateStart = 0;
395

    
396
                while (predicateStart == 0)
397
                {
398
                    predicateEnd = path.indexOf(QuerySpecification.PREDICATE_END,
399
                            predicateStart);
400

    
401
                    if (predicateEnd == -1)
402
                    {
403
                        log.warn("useNestedStatements(): ");
404
                        log.warn("    Invalid path: " + pathexpr);
405
                        return "";
406
                    }
407

    
408
                    predicates.add(path.substring(1, predicateEnd).trim());
409
                    path = path.substring(predicateEnd + 1).trim();
410
                    inx = path.indexOf('/');
411
                    predicateStart = path.indexOf(QuerySpecification.PREDICATE_START);
412
                }
413

    
414
                if (inx == 0)
415
                    path = path.substring(1).trim();
416
                else if (!path.equals(""))
417
                {
418
                    log.warn("useNestedStatements(): ");
419
                    log.warn("    Invalid path: " + pathexpr);
420
                    return "";
421
                }
422
            }
423

    
424
            nestedStmts.insert(0, "' ").insert(0, node).insert(0,
425
                    "(SELECT nodeid FROM xml_nodes WHERE nodename LIKE '");
426

    
427
            // for the last statement: it is without " AND parentnodeid IN "
428
            if (!path.equals(""))
429
                nestedStmts.insert(0, "AND parentnodeid IN ");
430

    
431
            if (predicates.size() > 0)
432
            {
433
                for (int n = 0; n < predicates.size(); n++)
434
                {
435
                    String predSQL = predicate2SQL((String) predicates.get(n));
436

    
437
                    if (predSQL.equals(""))
438
                        return "";
439

    
440
                    nestedStmts.append(predSQL).append(' ');
441
                }
442
            }
443

    
444
            nestedStmts.append(") ");
445
        }
446
        while (!path.equals(""));
447
        if (lastOneIsAttribute)
448
        {
449
        	sql = attributePrefix+nestedStmts.toString();
450
        }
451
        else
452
        {
453
        	sql = elementPrefix+nestedStmts.toString();
454
        }
455
        return sql;
456
    }
457
    
458
    
459
    /*
460
     * Removes @ symbol from path. For example, if path is @entity, entity will be returned.
461
     * If path is entity, entity will be returned. 
462
     */
463
    private static String removeAttributeSymbol(String path)
464
    {
465
    	String newPath  ="";
466
    	log.debug("Original string before removing @ is " + path);
467
    	if (path != null)
468
    	{
469
    		
470
    		int attribute = path.indexOf(QuerySpecification.ATTRIBUTESYMBOL);
471
    		if (attribute != -1)
472
    		{
473
    			// has attribute symbol. Reomve it and return the remained part. 
474
    			try
475
    			{
476
    		         newPath = path.substring(attribute + 1).trim();
477
    			}
478
    			catch (Exception e)
479
    			{
480
    				newPath = path;
481
    			}
482
    		}
483
    		else
484
    		{
485
    			// doesn't have attribute symbol. Return original string
486
    			newPath = path;
487
    		}
488
    	}
489
    	else
490
    	{
491
    		// if is null, return null;
492
    		newPath = path;
493
    	}
494
    	log.debug("String after removing @ is " + newPath);
495
    	return newPath;
496
    	
497
    }
498

    
499
    /**
500
     * 
501
     */
502
    public static String predicate2SQL(String predicate)
503
    {
504
        String path = predicate.trim();
505
        int equals = path.indexOf('=');
506
        String literal = null;
507

    
508
        if (equals != -1)
509
        {
510
            literal = path.substring(equals + 1).trim();
511
            path = path.substring(0, equals).trim();
512
            int sQuote = literal.indexOf('\'');
513
            int dQuote = literal.indexOf('"');
514

    
515
            if (sQuote == -1 && dQuote == -1)
516
            {
517
                log.warn("predicate2SQL(): ");
518
                log.warn("    Invalid or unsupported predicate: " + predicate);
519
                return "";
520
            }
521

    
522
            if (sQuote == -1 &&
523
                (dQuote != 0 ||
524
                 literal.indexOf('"', dQuote + 1) != literal.length() - 1))
525
            {
526
                log.warn("predicate2SQL(): ");
527
                log.warn("    Invalid or unsupported predicate: " + predicate);
528
                return "";
529
            }
530

    
531
            if (sQuote != 0 ||
532
                literal.indexOf('\'', sQuote + 1) != literal.length() - 1)
533
            {
534
                log.warn("predicate2SQL(): ");
535
                log.warn("    Invalid or unsupported predicate: " + predicate);
536
                return "";
537
            }
538
        }
539

    
540
        StringBuffer sql = new StringBuffer();
541
        int attribute = path.indexOf('@');
542

    
543
        if (attribute == -1)
544
        {
545
            if (literal != null)
546
            {
547
                sql.append("AND nodeid IN (SELECT parentnodeid FROM xml_nodes WHERE nodetype = 'TEXT' AND nodedata LIKE ")
548
                    .append(literal).append(")");
549
            }
550
        }
551
        else
552
        {
553
            sql.append(
554
                    "AND nodeid IN (SELECT parentnodeid FROM xml_nodes WHERE nodetype = 'ATTRIBUTE' AND nodename LIKE '")
555
                    .append(path.substring(attribute + 1).trim()).append("' ");
556

    
557
            if (literal != null)
558
            {
559
                sql.append("AND nodedata LIKE ").append(literal);
560
            }
561

    
562
            sql.append(")");
563
            path = path.substring(0, attribute).trim();
564

    
565
            if (path.endsWith("/"))
566
                path = path.substring(0, path.length() - 1).trim();
567
            else
568
            {
569
                if (!path.equals(""))
570
                {
571
                    log.warn("predicate2SQL(): ");
572
                    log.warn("    Invalid or unsupported predicate: " + predicate);
573
                    return "";
574
                }
575
            }
576
        }
577

    
578
        while (!path.equals(""))
579
        {
580
            int ndx = path.lastIndexOf('/');
581
            int predicateEnd = -1;
582
            int predicateStart;
583
            String node;
584

    
585
            if (ndx != -1)
586
            {
587
                node = path.substring(ndx + 1).trim();
588
                path = path.substring(0, ndx).trim();
589
            }
590
            else
591
            {
592
                node = path;
593
                path = "";
594
            }
595

    
596
            if (!node.equals(""))
597
                sql.insert(0, "' ").insert(0, node)
598
                    .insert(0, "(SELECT parentnodeid FROM xml_nodes WHERE nodename LIKE '").append(") ");
599
            else if (!path.equals(""))
600
            {
601
                log.warn("predicate2SQL(): ");
602
                log.warn("    Invalid or unsupported predicate: " + predicate);
603
                return "";
604
            }
605

    
606
            if (path.equals(""))
607
            {
608
                sql.insert(0,
609
                        node.equals("") ? "AND rootnodeid IN " : "AND nodeid IN ");
610
            }
611
            else
612
            {
613
                sql.append("AND nodeid IN ");
614
            }
615
        }
616

    
617
        return sql.toString();
618
    }
619

    
620
    /**
621
     * create a String description of the query that this instance represents.
622
     * This should become a way to get the XML serialization of the query.
623
     */
624
    public String toString()
625
    {
626

    
627
        return this.printSQL(true);
628
    }
629
    
630
    /**
631
     * Compare two query terms to see if they have same search value.
632
     * @param term
633
     * @return
634
     */
635
    public boolean hasSameSearchValue(QueryTerm term)
636
    {
637
    	boolean same = false;
638
    	if (term != null)
639
    	{
640
    		String searchValue = term.getValue();
641
    		if (searchValue != null && this.value != null)
642
    		{
643
    			if (searchValue.equalsIgnoreCase(this.value))
644
    			{
645
    				same = true;
646
    			}
647
    		}
648
    	}
649
    	return same;
650
    }
651
}
(58-58/69)