This project has retired. For details please refer to its Attic page.
FindEntityByCategoryQuery xref
View Javadoc
1   /*
2    * Copyright 2001-2008 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.apache.juddi.query;
19  
20  import java.util.ArrayList;
21  import java.util.Collections;
22  import java.util.List;
23  
24  import javax.persistence.EntityManager;
25  
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.apache.juddi.config.Constants;
29  import org.apache.juddi.query.util.DynamicQuery;
30  import org.apache.juddi.query.util.FindQualifiers;
31  import org.apache.juddi.query.util.KeyedRefTModelComparator;
32  import org.uddi.api_v3.CategoryBag;
33  import org.uddi.api_v3.KeyedReference;
34  
35  /**
36   * Returns the list of "entity" keys possessing the keyedReferences in the passed category bag.
37   * Output is restricted by list of "entity" keys passed in.  If null, all entities are searched.
38   * Output is produced by building the appropriate JPA query based on input and find qualifiers.
39   * 
40   * NOTES:
41   * 1) Categories are grouped with a logical AND by default.
42   * 2) Concerning when the categories are AND'd together - the only way this can be done with a single query was to create a self-join for 
43   *    each category.  If there are a lot of categories, the performance could suffer.
44   *    TODO:  Test performance with multiple AND'd categories.  If too slow, look to process this query in multiple steps.
45   * 3) The "orLikeKeys" qualifier complicates matters.  The "like" keys are OR'd together and these groups of "like" keys are AND'd together.
46   *    As with "andAllKeys", self-joins are created but only one for each group of "like" keys.  If none of the keyedReferences passed are alike then this
47   *    will reduce to an "andAllKeys" query.  If all are alike, then this will query will exhibit the behavior of OR'ing all keys.
48   * 
49   * @author <a href="mailto:jfaath@apache.org">Jeff Faath</a>
50   */
51  public class FindEntityByCategoryQuery extends EntityQuery {
52  	
53  	@SuppressWarnings("unused")
54  	private final static Log log = LogFactory.getLog(FindEntityByCategoryQuery.class);
55  
56  	private static final String ENTITY_KEYEDREFERENCE = "KeyedReference";
57  	private static final String ALIAS_KEYEDREFERENCE = buildAlias(ENTITY_KEYEDREFERENCE);
58  	private static final String FIELD_CATEGORYBAG = "categoryBag";
59  	
60  	protected String entityName;
61  	protected String entityAlias;
62  	protected String keyName;
63  	protected String entityField;
64  	protected String entityNameChild;
65  	protected String entityAliasChild;
66  	protected String selectSQL;
67  	protected String signaturePresent;
68  
69  	public FindEntityByCategoryQuery(String entityName, String entityAlias, String keyName,
70  			String entityField, String entityNameChild, String signaturePresent) {
71  		this.entityName = entityName;
72  		this.entityAlias = entityAlias;
73  		this.keyName = keyName;
74  		this.entityField = entityField;
75  		this.entityNameChild = entityNameChild;
76  		this.entityAliasChild = buildAlias(entityNameChild);
77  		this.signaturePresent = signaturePresent;
78  		
79  		StringBuffer sql = new StringBuffer(200);
80  		sql.append("select distinct " + entityAlias + "." + keyName + " from " + entityName + " " + entityAlias + " , " + entityNameChild + " " + entityAliasChild + " ");
81  		selectSQL = sql.toString();
82  	}
83  	
84  	public String getEntityName() {
85  		return entityName;
86  	}
87  
88  	public String getEntityAlias() {
89  		return entityAlias;
90  	}
91  
92  	public String getKeyName() {
93  		return keyName;
94  	}
95  
96  	public String getEntityField() {
97  		return entityField;
98  	}
99  
100 	public String getEntityNameChild() {
101 		return entityNameChild;
102 	}
103 	
104 	public String getEntityAliasChild() {
105 		return entityAliasChild;
106 	}
107 	
108 	public String getSelectSQL() {
109 		return selectSQL;
110 	}
111 	
112 	public String getSignaturePresent() {
113 		return signaturePresent;
114 	}
115 
116 	public void setSignaturePresent(String signaturePresent) {
117 		this.signaturePresent = signaturePresent;
118 	}
119 	
120 	public List<Object> select(EntityManager em, FindQualifiers fq, CategoryBag categoryBag, List<Object> keysIn, DynamicQuery.Parameter... restrictions) {
121 		// If keysIn is not null and empty, then search is over.
122 		if ((keysIn != null) && (keysIn.size() == 0))
123 			return keysIn;
124 		
125 		if (categoryBag == null)
126 			return keysIn;
127 		
128 		List<KeyedReference> categories = categoryBag.getKeyedReference();
129 		if (categories == null || categories.size() == 0)
130 			return keysIn;
131 		
132 		List<KeyedReference> keyedRefs = new ArrayList<KeyedReference>(0);
133 		for (KeyedReference elem : categories) {
134 			if (elem instanceof KeyedReference)
135 				keyedRefs.add((KeyedReference)elem);
136 		}
137 		if (keyedRefs.isEmpty())
138 			return keysIn;		
139 		
140 		DynamicQuery dynamicQry = new DynamicQuery(selectSQL);
141 		appendConditions(dynamicQry, fq, keyedRefs);
142 		if (restrictions != null && restrictions.length > 0)
143 			dynamicQry.AND().pad().appendGroupedAnd(restrictions);
144 
145 		return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName);
146 	}
147 	
148 	
149 	/*
150 	 * Appends the conditions to the query based on the keyedReference list.  With the default or when "orAllKeys" is passed, the keyedReferences are autonomous and are
151 	 * all AND'd or OR'd respectively.  However, "orLikeKeys" requires special treatment.  The goal is to create the conditions in this format:
152 	 * 
153 	 * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) 
154 	 * 
155 	 * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other.
156 	 */
157 	public void appendConditions(DynamicQuery qry, FindQualifiers fq, List<KeyedReference> keyedRefs) {
158 		
159 		// Append the necessary tables (two will always be added connecting the entity to its category table and then the category table to the keyed references).
160 		appendJoinTables(qry, fq, keyedRefs);
161 		qry.AND().pad().openParen().pad();
162 		
163 		String predicate = DynamicQuery.PREDICATE_EQUALS;
164 		if (fq.isApproximateMatch()) {
165 			predicate = DynamicQuery.PREDICATE_LIKE;
166 		}
167 		
168 		// Sorting the collection by tModel Key
169 		Collections.sort(keyedRefs, new KeyedRefTModelComparator());
170 
171 		String prevTModelKey = null;
172 		int count = 0;
173 		int tblCount = -1;
174 		for(KeyedReference keyedRef : keyedRefs) {
175 			String tmodelKey = keyedRef.getTModelKey();
176 			String keyValue = keyedRef.getKeyValue();
177 			String keyName = keyedRef.getKeyName();
178 			
179 			if (fq.isApproximateMatch()) {
180 				// JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises)
181 				//keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD;
182 				//keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD;
183 			}
184 
185 			// Either opening up (and AND'ing) a new "group" of like keys or simply appending an "or".  If this is not "orLikeKeys", then just need to increment
186 			// the table count.
187 			if (fq.isOrLikeKeys()) {
188 				if (count == 0) {
189 					qry.openParen().pad();
190 					tblCount++;
191 				}
192 				else {
193 					if (!tmodelKey.equals(prevTModelKey)) {
194 						qry.closeParen().pad().AND().pad().openParen().pad();
195 						tblCount++;
196 					}
197 					else
198 						qry.OR().pad();
199 				}
200 			}
201 			else
202 				tblCount++;
203 			
204 			String keyValueTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyValue";
205 			String keyNameTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".keyName";
206 			String tmodelKeyTerm = (fq.isOrAllKeys()?ALIAS_KEYEDREFERENCE + "0":ALIAS_KEYEDREFERENCE + tblCount) + ".tmodelKeyRef";
207 			if (fq.isCaseInsensitiveMatch()) {
208 				keyValueTerm = "upper(" + keyValueTerm + ")";
209 				keyValue = keyValue.toUpperCase();
210 				
211 				keyNameTerm = "upper(" + keyNameTerm + ")";
212 				keyName = keyName.toUpperCase();
213 			}
214 			
215 			
216 			// According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query.
217 			if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) {
218 				qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS),
219 									 new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate),
220 									 new DynamicQuery.Parameter(keyNameTerm, keyName, predicate));
221 			}
222 			else {
223 				qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS),
224 									 new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate));
225 				
226 			}
227 			
228 			if (count + 1 < keyedRefs.size()) {
229 				if (fq.isOrAllKeys())
230 					qry.OR().pad();
231 				else if (fq.isOrLikeKeys()) {
232 				}
233 				else
234 					qry.AND().pad();
235 			}
236 			
237 			// The "orLikeKeys" will always leave an unclosed parenthesis.  This will close it.
238 			if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size()))
239 				qry.closeParen().pad();
240 
241 			prevTModelKey = tmodelKey;
242 			count++;
243 		}
244 		qry.closeParen().pad();
245 		
246 	}
247 
248 	
249 	
250 	/*
251 	 * Appends the necessary join table for the child entity and additional tables for when keys are AND'd.  When "orLikeKeys" is used, 
252 	 * we only need an extra table for each distinct tmodelKey.
253 	 */
254 	public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List<KeyedReference> keyedRefs) {
255 		
256 		if (keyedRefs != null && keyedRefs.size() > 0) {
257 			// Sorting the collection by tModel Key
258 			Collections.sort(keyedRefs, new KeyedRefTModelComparator());
259 
260 			StringBuffer thetaJoins = new StringBuffer(200);
261 			int tblCount = 0;
262 			int count = 0;
263 			String curTModelKey = null;
264 			String prevTModelKey = null;
265 			for(KeyedReference kr : keyedRefs) {
266 				curTModelKey = kr.getTModelKey();
267 				if (count != 0) {
268 					if (!fq.isOrAllKeys()) {
269 						if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) {
270 							// Do nothing
271 						}
272 						else {
273 							tblCount++;
274 							qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad();
275 							thetaJoins.append(ALIAS_KEYEDREFERENCE + (tblCount - 1) + "." + FIELD_CATEGORYBAG + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id ");
276 							thetaJoins.append(DynamicQuery.OPERATOR_AND + " ");
277 						}
278 					}
279 
280 				}
281 				else {
282 					qry.comma().pad().append(ENTITY_KEYEDREFERENCE + " " + ALIAS_KEYEDREFERENCE + tblCount).pad();
283 					thetaJoins.append(entityAliasChild + ".id = " + ALIAS_KEYEDREFERENCE + tblCount + "." + FIELD_CATEGORYBAG + ".id ");
284 					thetaJoins.append(DynamicQuery.OPERATOR_AND + " ");
285 				}
286 				prevTModelKey = curTModelKey;
287 				count++;
288 			}
289 			
290 			qry.WHERE().pad().openParen().pad();
291 			
292 			// Appending the middling entity-specific category table condition
293 			qry.append(entityAlias + "." + keyName + " = " + entityAliasChild + "." + entityField + "." + KEY_NAME).pad();
294 			qry.AND().pad();
295 
296 			String thetaJoinsStr = thetaJoins.toString();
297 			if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " "))
298 				thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length());
299 			qry.append(thetaJoinsStr);
300 
301 			qry.closeParen().pad();
302 			if (fq!=null && fq.isSignaturePresent()) {
303 				qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad();
304 			}
305 		}
306 	}
307 	
308 }