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: 2008-03-20 17:32:01 -0700 (Thu, 20 Mar 2008) $'
13
 * '$Revision: 3771 $'
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
/** a utility class that represents a single term in a query */
36
public class QueryTerm
37
{
38
    private static Logger log = Logger.getLogger(QueryTerm.class);
39

    
40
    private boolean casesensitive = false;
41

    
42
    private String searchmode = null;
43

    
44
    private String value = null;
45

    
46
    private String pathexpr = null;
47

    
48
    private boolean percentageSymbol = false;
49

    
50
    private int countPercentageSearchItem = 0;
51
    
52
    private boolean inUnionGroup = false;
53
    
54
    public static final String CONTAINS = "contains";
55
    
56
    public static final String EQUALS = "equals";
57

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

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

    
98
    /** determine if the QueryTerm is case sensitive */
99
    public boolean isCaseSensitive()
100
    {
101
        return casesensitive;
102
    }
103

    
104
    /** get the searchmode parameter */
105
    public String getSearchMode()
106
    {
107
        return searchmode;
108
    }
109

    
110
    /** get the Value parameter */
111
    public String getValue()
112
    {
113
        return value;
114
    }
115

    
116
    /** get the path expression parameter */
117
    public String getPathExpression()
118
    {
119
        return pathexpr;
120
    }
121

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

    
146
    /**
147
     * create a SQL serialization of the query that this instance represents
148
     */
149
    public String printSQL(boolean useXMLIndex)
150
    {
151
        StringBuffer self = new StringBuffer();
152

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

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

    
219

    
220
        // to check xml_path_index can be used
221
        boolean usePathIndex = false;
222

    
223
        // if pathexpr has been specified in metacat.properties for indexing
224
        if(pathexpr != null){
225
            if(MetaCatUtil.pathsForIndexing.contains(pathexpr)){
226
                usePathIndex = true;
227
            }
228
        }
229

    
230
        if(usePathIndex){
231
            // using xml_path_index table.....
232
        	if(notEqual == true ){
233
        		if (!inUnionGroup)
234
        		{
235
        			self.append("SELECT DISTINCT docid from xml_path_index WHERE");
236
        			self.append(" docid NOT IN (Select docid FROM xml_path_index WHERE ");
237
        			self.append(searchexpr);
238
        			self.append("AND path LIKE '" + pathexpr + "') ");
239
        		}
240
        		else
241
        		{
242
        			//if this is in union group we need to use "OR" to modify query
243
        			self.append("("+searchexpr);
244
        			self.append("AND path LIKE '" + pathexpr + "') ");
245
        		}
246
        	} else {
247
        		if (!inUnionGroup)
248
        		{
249
        			self.append("SELECT DISTINCT docid FROM xml_path_index WHERE ");
250
        			self.append(searchexpr);
251
        			self.append("AND path LIKE '" + pathexpr + "' ");
252
        		}
253
        		else
254
        		{
255
        			//if this is in union group we need to use "OR" to modify query
256
        			self.append("("+searchexpr);
257
        			self.append("AND path LIKE '" + pathexpr + "') ");
258
        		}
259
        	}
260

    
261
        } else {
262
            // using xml_nodes and xml_index tables
263

    
264
        	if(notEqual == true){
265
        		self.append("SELECT DISTINCT docid from xml_nodes WHERE");
266
        		self.append(" docid NOT IN (Select docid FROM xml_nodes WHERE ");
267
        	} else {
268
        		self.append("(SELECT DISTINCT docid FROM xml_nodes WHERE ");
269
        	}
270
        	self.append(searchexpr);
271
        	
272
            if (pathexpr != null) {
273

    
274
                // use XML Index
275
                if (useXMLIndex) {
276
                    if (!hasAttributeInPath(pathexpr)) {
277
                        // without attributes in path
278
                        self.append("AND parentnodeid IN ");
279
                    } else {
280
                        // has a attribute in path
281
                        String attributeName = QuerySpecification
282
                            .getAttributeName(pathexpr);
283
                        self.append(
284
                            "AND nodetype LIKE 'ATTRIBUTE' AND nodename LIKE '"
285
                            + attributeName + "' ");
286
                        // and the path expression includes element content other than
287
                        // just './' or '../'
288
                        if ( (!pathexpr.startsWith(QuerySpecification.
289
                            ATTRIBUTESYMBOL)) &&
290
                            (!pathexpr.startsWith("./" +
291
                                                  QuerySpecification.ATTRIBUTESYMBOL)) &&
292
                            (!pathexpr.startsWith("../" +
293
                                                  QuerySpecification.ATTRIBUTESYMBOL))) {
294

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

    
317
            }
318
            self.append(") ");
319
        }
320

    
321
        return self.toString();
322
    }
323

    
324
    /** A method to judge if a path have attribute */
325
    private boolean hasAttributeInPath(String path)
326
    {
327
        if (path.indexOf(QuerySpecification.ATTRIBUTESYMBOL) != -1) {
328
            return true;
329
        } else {
330
            return false;
331
        }
332
    }
333

    
334
   
335
    public static String useNestedStatements(String pathexpr)
336
    {
337
        log.info("useNestedStatements()");
338
        log.info("pathexpr: " + pathexpr);
339
        String elementPrefix = " parentnodeid IN ";
340
        String attributePrefix  =  " nodeid IN ";
341
        boolean lastOneIsAttribute = false;
342
        StringBuffer nestedStmts = new StringBuffer();
343
        String path = pathexpr.trim();
344
        String sql = "";
345

    
346
        if (path.indexOf('/') == 0)
347
        {
348
            nestedStmts.append("AND parentnodeid = rootnodeid ");
349
            path = path.substring(1).trim();
350
        }
351

    
352
        do
353
        {
354
            int inx = path.indexOf('/');
355
            int predicateStart = -1;
356
            int predicateEnd;
357
            String node;
358
            Vector predicates = new Vector();
359

    
360
            // extract predicates
361
            predicateStart = path.indexOf(QuerySpecification.PREDICATE_START, predicateStart + 1);
362

    
363
            // any predicates in this node?
364
            if (inx != -1 && (predicateStart == -1 || predicateStart > inx))
365
            {
366
                // no
367
                node = path.substring(0, inx).trim();
368
                path = path.substring(inx + 1).trim();
369
            }
370
            else if (predicateStart == -1)
371
            {
372
                // no and it's the last node
373
                node = path;
374
                if (node != null && node.indexOf(QuerySpecification.ATTRIBUTESYMBOL) != -1)
375
                {
376
                	lastOneIsAttribute = true;
377
                	node = removeAttributeSymbol(node);
378
                }
379
                path = "";
380
            }
381
            else
382
            {
383
                // yes
384
                node = path.substring(0, predicateStart).trim();
385
                path = path.substring(predicateStart);
386
                predicateStart = 0;
387

    
388
                while (predicateStart == 0)
389
                {
390
                    predicateEnd = path.indexOf(QuerySpecification.PREDICATE_END,
391
                            predicateStart);
392

    
393
                    if (predicateEnd == -1)
394
                    {
395
                        log.warn("useNestedStatements(): ");
396
                        log.warn("    Invalid path: " + pathexpr);
397
                        return "";
398
                    }
399

    
400
                    predicates.add(path.substring(1, predicateEnd).trim());
401
                    path = path.substring(predicateEnd + 1).trim();
402
                    inx = path.indexOf('/');
403
                    predicateStart = path.indexOf(QuerySpecification.PREDICATE_START);
404
                }
405

    
406
                if (inx == 0)
407
                    path = path.substring(1).trim();
408
                else if (!path.equals(""))
409
                {
410
                    log.warn("useNestedStatements(): ");
411
                    log.warn("    Invalid path: " + pathexpr);
412
                    return "";
413
                }
414
            }
415

    
416
            nestedStmts.insert(0, "' ").insert(0, node).insert(0,
417
                    "(SELECT nodeid FROM xml_nodes WHERE nodename LIKE '");
418

    
419
            // for the last statement: it is without " AND parentnodeid IN "
420
            if (!path.equals(""))
421
                nestedStmts.insert(0, "AND parentnodeid IN ");
422

    
423
            if (predicates.size() > 0)
424
            {
425
                for (int n = 0; n < predicates.size(); n++)
426
                {
427
                    String predSQL = predicate2SQL((String) predicates.get(n));
428

    
429
                    if (predSQL.equals(""))
430
                        return "";
431

    
432
                    nestedStmts.append(predSQL).append(' ');
433
                }
434
            }
435

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

    
491
    /**
492
     * 
493
     */
494
    public static String predicate2SQL(String predicate)
495
    {
496
        String path = predicate.trim();
497
        int equals = path.indexOf('=');
498
        String literal = null;
499

    
500
        if (equals != -1)
501
        {
502
            literal = path.substring(equals + 1).trim();
503
            path = path.substring(0, equals).trim();
504
            int sQuote = literal.indexOf('\'');
505
            int dQuote = literal.indexOf('"');
506

    
507
            if (sQuote == -1 && dQuote == -1)
508
            {
509
                log.warn("predicate2SQL(): ");
510
                log.warn("    Invalid or unsupported predicate: " + predicate);
511
                return "";
512
            }
513

    
514
            if (sQuote == -1 &&
515
                (dQuote != 0 ||
516
                 literal.indexOf('"', dQuote + 1) != literal.length() - 1))
517
            {
518
                log.warn("predicate2SQL(): ");
519
                log.warn("    Invalid or unsupported predicate: " + predicate);
520
                return "";
521
            }
522

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

    
532
        StringBuffer sql = new StringBuffer();
533
        int attribute = path.indexOf('@');
534

    
535
        if (attribute == -1)
536
        {
537
            if (literal != null)
538
            {
539
                sql.append("AND nodeid IN (SELECT parentnodeid FROM xml_nodes WHERE nodetype = 'TEXT' AND nodedata LIKE ")
540
                    .append(literal).append(")");
541
            }
542
        }
543
        else
544
        {
545
            sql.append(
546
                    "AND nodeid IN (SELECT parentnodeid FROM xml_nodes WHERE nodetype = 'ATTRIBUTE' AND nodename LIKE '")
547
                    .append(path.substring(attribute + 1).trim()).append("' ");
548

    
549
            if (literal != null)
550
            {
551
                sql.append("AND nodedata LIKE ").append(literal);
552
            }
553

    
554
            sql.append(")");
555
            path = path.substring(0, attribute).trim();
556

    
557
            if (path.endsWith("/"))
558
                path = path.substring(0, path.length() - 1).trim();
559
            else
560
            {
561
                if (!path.equals(""))
562
                {
563
                    log.warn("predicate2SQL(): ");
564
                    log.warn("    Invalid or unsupported predicate: " + predicate);
565
                    return "";
566
                }
567
            }
568
        }
569

    
570
        while (!path.equals(""))
571
        {
572
            int ndx = path.lastIndexOf('/');
573
            int predicateEnd = -1;
574
            int predicateStart;
575
            String node;
576

    
577
            if (ndx != -1)
578
            {
579
                node = path.substring(ndx + 1).trim();
580
                path = path.substring(0, ndx).trim();
581
            }
582
            else
583
            {
584
                node = path;
585
                path = "";
586
            }
587

    
588
            if (!node.equals(""))
589
                sql.insert(0, "' ").insert(0, node)
590
                    .insert(0, "(SELECT parentnodeid FROM xml_nodes WHERE nodename LIKE '").append(") ");
591
            else if (!path.equals(""))
592
            {
593
                log.warn("predicate2SQL(): ");
594
                log.warn("    Invalid or unsupported predicate: " + predicate);
595
                return "";
596
            }
597

    
598
            if (path.equals(""))
599
            {
600
                sql.insert(0,
601
                        node.equals("") ? "AND rootnodeid IN " : "AND nodeid IN ");
602
            }
603
            else
604
            {
605
                sql.append("AND nodeid IN ");
606
            }
607
        }
608

    
609
        return sql.toString();
610
    }
611

    
612
    /**
613
     * create a String description of the query that this instance represents.
614
     * This should become a way to get the XML serialization of the query.
615
     */
616
    public String toString()
617
    {
618

    
619
        return this.printSQL(true);
620
    }
621
    
622
    /**
623
     * Compare two query terms to see if they have same search value.
624
     * @param term
625
     * @return
626
     */
627
    public boolean hasSameSearchValue(QueryTerm term)
628
    {
629
    	boolean same = false;
630
    	if (term != null)
631
    	{
632
    		String searchValue = term.getValue();
633
    		if (searchValue != null && this.value != null)
634
    		{
635
    			if (searchValue.equalsIgnoreCase(this.value))
636
    			{
637
    				same = true;
638
    			}
639
    		}
640
    	}
641
    	return same;
642
    }
643
}
(53-53/64)