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: leinfelder $'
12
 *     '$Date: 2011-07-20 14:51:04 -0700 (Wed, 20 Jul 2011) $'
13
 * '$Revision: 6361 $'
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 edu.ucsb.nceas.dbadapter.*;
33
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
34
import edu.ucsb.nceas.metacat.util.MetacatUtil;
35
import edu.ucsb.nceas.metacat.util.SystemUtil;
36

    
37
import java.io.*;
38
import java.util.Hashtable;
39
import java.util.Stack;
40
import java.util.Vector;
41
import java.util.Enumeration;
42

    
43
import org.apache.log4j.Logger;
44

    
45
 /** a utility class that represents a group of terms in a query */
46
public  class QueryGroup {
47
    private String operator = null;  // indicates how query terms are combined
48
    private Vector children = null;  // the list of query terms and groups
49
    private int countPercentageSearchItem = 0;
50
    private Vector queryTermsWithSameValue = null;//this two dimension vectors.
51
                                                  //will hold query terms which has same search value.
52
    private Vector queryTermsInPathIndex = null; //this vector holds query terms without same value
53
                                                                                 // and search path is in path index.
54
    private Vector queryTerms = null;//this vector only holds query terms without same search value.
55
                                                             // and search path is NOT in path index.
56
    private Vector queryGroupsChildren = null;
57
    private static Logger logMetacat = Logger.getLogger(QueryGroup.class);
58
    public static String UNION = "UNION";
59
    public static String INTERSECT = "INTERSECT";
60

    
61

    
62
    /**
63
     * construct a new QueryGroup
64
     *
65
     * @param operator the boolean conector used to connect query terms
66
     *                    in this query group
67
     */
68
    public QueryGroup(String operator) {
69
      this.operator = operator;
70
      children = new Vector();
71
      queryTermsWithSameValue = new Vector();
72
      queryTermsInPathIndex = new Vector(); 
73
      queryTerms = new Vector();
74
      queryGroupsChildren = new Vector();
75
    }
76

    
77
    /**
78
     * Add a child QueryGroup to this QueryGroup
79
     *
80
     * @param qgroup the query group to be added to the list of terms
81
     */
82
    public void addChild(QueryGroup qgroup) {
83
      children.add((Object)qgroup);
84
      queryGroupsChildren.add(qgroup);
85
    }
86

    
87
    /**
88
     * Add a child QueryTerm to this QueryGroup
89
     *
90
     * @param qterm the query term to be added to the list of terms
91
     */
92
    public void addChild(QueryTerm qterm) {
93
      children.add((Object)qterm);
94
      handleNewQueryTerms(qterm);
95
      
96
    }
97

    
98
    /*
99
     * Retrieve an Enumeration of query terms for this QueryGroup
100
     */
101
    private Enumeration getChildren() {
102
      return children.elements();
103
    }
104

    
105
    public int getPercentageSymbolCount()
106
    {
107
      return countPercentageSearchItem;
108
    }
109

    
110
    /**
111
     * create a SQL serialization of the query that this instance represents
112
     */
113
    public String printSQL(boolean useXMLIndex) {
114
      StringBuffer self = new StringBuffer();
115
      StringBuffer queryString = new StringBuffer();
116

    
117
      boolean first = true;
118
      
119
      if (!queryTermsWithSameValue.isEmpty() || !queryTermsInPathIndex.isEmpty())
120
      {
121
    	  String pathIndexQueryString = printSQLStringInPathIndex();
122
    	  queryString.append(pathIndexQueryString);
123
    	  if (queryString != null)
124
    	  {
125
    		  first = false;
126
    	  }
127
      }
128
      
129
      for (int i=0; i<queryGroupsChildren.size(); i++)
130
      {
131
      
132
        
133
            QueryGroup qg = (QueryGroup)queryGroupsChildren.elementAt(i);
134
        	String queryGroupSQL = qg.printSQL(useXMLIndex);
135
        	logMetacat.info("In QueryGroup.printSQL.. found a QueryGroup: " 
136
        			+ queryGroupSQL);       	
137
        	if (first) {
138
        		first = false;
139
        	} else {
140
        		if(!queryString.toString().equals("") && queryGroupSQL != null &&!queryGroupSQL.equals("")){
141
                    queryString.append(" " + operator + " ");
142
        		}
143
        	}
144
   		  	queryString.append(queryGroupSQL);
145
   		  	
146
   		  	// count percerntage number
147
   		  	int count = qg.getPercentageSymbolCount();
148
   		  	countPercentageSearchItem = countPercentageSearchItem + count;
149
      }
150
      
151
      for (int i=0; i<queryTerms.size(); i++)
152
      {
153
           QueryTerm qt = (QueryTerm)queryTerms.elementAt(i);
154
           String termQueryString = qt.printSQL(useXMLIndex);
155
       	   logMetacat.info("In QueryGroup.printSQL.. found a QueryGroup: " 
156
        			+ termQueryString);
157
           if(!(qt.getSearchMode().equals("contains") && qt.getValue().equals("%"))){
158
        	   if (first) {
159
                   first = false;
160
               } else {
161
                   if(!queryString.toString().equals("")){
162
                       queryString.append(" " + operator + " ");
163
                   }
164
               }
165
               queryString.append(termQueryString);
166
           
167
           // count percerntage number
168
           int count = qt.getPercentageSymbolCount();
169
           countPercentageSearchItem = countPercentageSearchItem + count;
170
        } 
171
      }
172

    
173
      if(!queryString.toString().equals("")){
174
          self.append("(");
175
          self.append(queryString.toString());
176
          self.append(")");
177
      }
178
      
179
      logMetacat.info("In QueryGroup.printSQL.. final query returned is: " 
180
			+ self.toString());
181
      return self.toString();
182
    }
183
    
184
    
185
    
186
    
187
    /*
188
     * If every query term in a queryGroup share a search value and search path
189
     * is in xml_path_index, we should use a new query to replace the original query term query in order to
190
     * improve performance. Also if even the term doesn't share any value with other term
191
     * we still use "OR" to replace UNION action (we only handle union operator in the query group).
192
     * 
193
     */
194
    private String printSQLStringInPathIndex()
195
    {
196
    	String sql ="";
197
    	String value ="";
198
    	StringBuffer sqlBuff = new StringBuffer();
199
    	int index =0;
200
    	if (queryTermsWithSameValue != null && queryTermsInPathIndex != null)
201
    	{
202
    		
203
    		sqlBuff.append("SELECT DISTINCT docid FROM xml_path_index WHERE ");
204
    		if (!queryTermsWithSameValue.isEmpty())
205
    		{
206
    			boolean firstVector = true;
207
	    		for (int j=0; j<queryTermsWithSameValue.size(); j++)
208
	    		{
209
	    	   		Vector queryTermVector = (Vector)queryTermsWithSameValue.elementAt(j);
210
		    		QueryTerm term1 = (QueryTerm)queryTermVector.elementAt(0);
211
		        	value = term1.getValue();
212
		        	boolean first = true;
213
		        	if (firstVector)
214
		        	{
215
					  firstVector = false;
216
		        	}
217
		        	else
218
		        	{
219
		        		sqlBuff.append(" "+"OR"+" ");
220
		        	}
221
		        	
222
					sqlBuff.append(" (");
223
		        	
224
		        	// get the general search criteria (no path info)
225
		        	String searchTermSQL = term1.printSearchExprSQL();
226
					sqlBuff.append(searchTermSQL);
227
					
228
					sqlBuff.append("AND path IN (");
229

    
230
		    		//gets every path in query term object
231
		    		for (int i=0; i<queryTermVector.size(); i++)
232
		    		{
233
		    			QueryTerm term = (QueryTerm)queryTermVector.elementAt(i);
234
		    			value = term.getValue();
235
		    			String path = term.getPathExpression();
236
		    			if (path != null && !path.equals(""))
237
		    			{
238
		    				if (first)
239
		    				{
240
		    					first = false;
241
		    					sqlBuff.append("'");
242
		    					sqlBuff.append(path);
243
		    					sqlBuff.append("'");
244
		    					
245
		    				}
246
		    				else
247
		    				{
248
		    					sqlBuff.append(",'");
249
		    					sqlBuff.append(path);
250
		    					sqlBuff.append("'");
251
		    				}
252
		    				index++;
253
		     				if (value != null && (value.equals("%") || value.equals("%%%")))
254
		                    {
255
		    				  countPercentageSearchItem++;
256
		                    }
257
	    			     }
258
	    		    }
259
	    		    sqlBuff.append("))");
260
	    	
261
	    	    }
262
	    	}
263
    		if (!queryTermsInPathIndex.isEmpty())
264
    		{
265
    			for (int j=0; j<queryTermsInPathIndex.size(); j++)
266
    			{
267
    				QueryTerm term = (QueryTerm)queryTermsInPathIndex.elementAt(j);
268
    				if (term != null)
269
    				{
270
	    				term.setInUnionGroup(true);
271
		    			 if (index > 0)
272
		    			 {
273
		    				 sqlBuff.append(" "+"OR"+" ");
274
		    			 }
275
		    			 sqlBuff.append("(");
276
	    				 sqlBuff.append(term.printSQL(true));
277
	    				 sqlBuff.append(")");
278
	    				 index++;
279
	    			}
280
    			}
281
    		}
282
    	}
283
    	if (index >0)
284
    	{
285
    		sql = sqlBuff.toString();
286
    	}
287
    	return sql;
288
    }
289

    
290
    /**
291
     * create a String description of the query that this instance represents.
292
     * This should become a way to get the XML serialization of the query.
293
     */
294
    public String toString() {
295
      StringBuffer self = new StringBuffer();
296

    
297
      self.append("  (Query group operator=" + operator + "\n");
298
      Enumeration en= getChildren();
299
      while (en.hasMoreElements()) {
300
        Object qobject = en.nextElement();
301
        self.append(qobject);
302
      }
303
      self.append("  )\n");
304
      return self.toString();
305
    }
306
    
307
    /*
308
     * When a new QueryTerm come, first we need to compare it to
309
     * the queryTerm vector, which contains queryTerm that doesn't
310
     * have same search value to any other queryTerm. Here is algorithm.
311
     * 1) If new QueryTerm find a QueryTerm in queryTerms which has same search value,
312
     *    them create a new vector which contain both QueryTerms and add the new vector
313
     *    to two-dimention vector queryTermsWithSameValue, and remove the QueryTerm which
314
     *    was in queryTerm.
315
     * 2) If new QueryTerm couldn't find a QueryTerm in queryTerms which has same search value,
316
     *    then search queryTermsWithSameValue, to see if this vector already has the search value.
317
     *    2.1) if has the search value, add the new QueryTerm to the queryTermsWithSameValue.
318
     *    2.2) if hasn't, add the new QueryTerm to queryTerms vector.
319
     */
320
    private void handleNewQueryTerms(QueryTerm newTerm)
321
    {
322
    	// currently we only handle UNION group
323
    	if (newTerm != null )
324
    	{
325
    		//System.out.println("new term is not null branch in handle new query term");
326
    		//we only handle union operator now.
327
    		try {
328
    			if (operator != null
329
						&& operator.equalsIgnoreCase(UNION)
330
						&& SystemUtil.getPathsForIndexing().contains(
331
								newTerm.getPathExpression())) {
332
					// System.out.println("in only union branch in handle new
333
					// query term");
334
					for (int i = 0; i < queryTermsInPathIndex.size(); i++) {
335
						QueryTerm term = (QueryTerm) queryTermsInPathIndex.elementAt(i);
336
						if (term != null && term.hasSameSearchValue(newTerm)) {
337
							// System.out.println("1Move a query term and add a
338
							// new query term into search value in handle new
339
							// query term");
340
							// find a target which has same search value
341
							Vector newSameValueVector = new Vector();
342
							newSameValueVector.add(term);
343
							newSameValueVector.addElement(newTerm);
344
							queryTermsWithSameValue.add(newSameValueVector);
345
							queryTermsInPathIndex.remove(i);
346
							return;
347
						}
348
					}
349
					// no same search value was found in queryTerms.
350
					// then we need search queryTermsWithSameValue
351
					for (int i = 0; i < queryTermsWithSameValue.size(); i++) {
352
						Vector sameValueVec = (Vector) queryTermsWithSameValue
353
								.elementAt(i);
354
						// we only compare the first query term
355
						QueryTerm term = (QueryTerm) sameValueVec.elementAt(0);
356
						if (term != null && term.hasSameSearchValue(newTerm)) {
357
							// System.out.println("2add a new query term into
358
							// search value in handle new query term");
359
							sameValueVec.add(newTerm);
360
							return;
361
						}
362
					}
363
					// nothing found, but the search path is still in
364
					// xml_path_index,
365
					// save it into queryTermsInPathIndex vector
366
					queryTermsInPathIndex.add(newTerm);
367
					return;
368
				}    		
369
    		} catch (MetacatUtilException ue) {
370
				logMetacat.warn("Could not get index paths: " + ue.getMessage());
371
			}
372
    		
373
    		// add this newTerm to queryTerms since we couldn't find it in xml_path_index
374
    		queryTerms.add(newTerm);
375
    	}
376
    	
377
    }
378
  }
(53-53/65)