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.Collections;
21  import java.util.List;
22  
23  import javax.persistence.EntityManager;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.juddi.config.Constants;
28  import org.apache.juddi.query.util.DynamicQuery;
29  import org.apache.juddi.query.util.FindQualifiers;
30  import org.apache.juddi.query.util.KeyedRefTModelComparator;
31  import org.uddi.api_v3.IdentifierBag;
32  import org.uddi.api_v3.KeyedReference;
33  
34  /**
35   * Returns the list of "entity" keys possessing the keyedReferences in the passed identifier bag.
36   * Output is restricted by list of "entity" keys passed in.  If null, all entities are searched.
37   * Output is produced by building the appropriate JPA query based on input and find qualifiers.
38   * 
39   * NOTES:
40   * 1) Identifiers are grouped with a logical OR by default.
41   * 2) In the case that the "andAllKeys" find qualifier is used the identifiers are AND'd together.  The only way this can be done
42   *    with a single query was to create a self-join for each identifier.  If there are a lot of identifiers, the performance could suffer.
43   *    TODO:  Test performance with multiple AND'd identifiers.  If too slow, look to process this query in multiple steps.
44   * 3) The "orLikeKeys" qualifier complicates matters.  The "like" keys are OR'd together and these groups of "like" keys are AND'd together.
45   *    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
46   *    will reduce to an "andAllKeys" query.  If all are alike, then this will query will exhibit the default behavior of OR'ing all keys.
47   * 
48   * @author <a href="mailto:jfaath@apache.org">Jeff Faath</a>
49   */
50  public class FindEntityByIdentifierQuery extends EntityQuery {
51  	
52  	@SuppressWarnings("unused")
53  	private final static Log log = LogFactory.getLog(FindEntityByIdentifierQuery.class);
54  
55  	private final String entityName;
56  	private final String entityAlias;
57  	private final String keyName;
58  	private final String entityField;
59  	private final String entityNameChild;
60  	private final String entityAliasChild;
61  	private final String selectSQL;
62  	private String signaturePresent;
63  
64  	public FindEntityByIdentifierQuery(String entityName, String entityAlias, String keyName, 
65  			String entityField, String entityNameChild, String signaturePresent) {
66  		this.entityName = entityName;
67  		this.entityAlias = entityAlias;
68  		this.keyName = keyName;
69  		this.entityField = entityField;
70  		this.entityNameChild = entityNameChild;
71  		this.entityAliasChild = buildAlias(entityNameChild);
72  		this.signaturePresent = signaturePresent;
73  		
74  		StringBuilder sql = new StringBuilder(200);
75  		sql.append("select distinct ").append(entityAlias).append(".").append(keyName).append(" from ").append(entityName).append(" ").append(entityAlias).append(" ");
76  		selectSQL = sql.toString();
77  	}
78  	
79  	public String getEntityName() {
80  		return entityName;
81  	}
82  
83  	public String getEntityAlias() {
84  		return entityAlias;
85  	}
86  
87  	public String getKeyName() {
88  		return keyName;
89  	}
90  
91  	public String getEntityField() {
92  		return entityField;
93  	}
94  
95  	public String getEntityNameChild() {
96  		return entityNameChild;
97  	}
98  	
99  	public String getEntityAliasChild() {
100 		return entityAliasChild;
101 	}
102 	
103 	public String getSelectSQL() {
104 		return selectSQL;
105 	}
106 	
107 	public String getSignaturePresent() {
108 		return signaturePresent;
109 	}
110 
111 	public void setSignaturePresent(String signaturePresent) {
112 		this.signaturePresent = signaturePresent;
113 	}
114 
115 	
116 	public List<Object> select(EntityManager em, FindQualifiers fq, IdentifierBag identifiers, List<Object> keysIn, DynamicQuery.Parameter... restrictions) {
117 		// If keysIn is not null and empty, then search is over.
118 		if ((keysIn != null) && (keysIn.size() == 0))
119 			return keysIn;
120 		
121 		if (identifiers == null)
122 			return keysIn;
123 		
124 		List<KeyedReference> keyedRefs = identifiers.getKeyedReference();
125 		if (keyedRefs == null || keyedRefs.size() == 0)
126 			return keysIn;
127 		
128 		DynamicQuery dynamicQry = new DynamicQuery(selectSQL);
129 		appendConditions(dynamicQry, fq, keyedRefs);
130 		if (restrictions != null && restrictions.length > 0)
131 			dynamicQry.AND().pad().appendGroupedAnd(restrictions);
132 
133 		return getQueryResult(em, dynamicQry, keysIn, entityAlias + "." + keyName);
134 	}
135 	
136 	
137 	/*
138 	 * Appends the conditions to the query based on the keyedReference list.  With the default or when "andAllKeys" is passed, the keyedReferences are autonomous and are
139 	 * all OR'd or AND'd respectively.  However, "orLikeKeys" requires special treatment.  The goal is to create the conditions in this format:
140 	 * 
141 	 * (likeKey1 = X or likeKey1 = Y) and (likeKey2 = A or likeKey2 = B or likeKey2 = C) 
142 	 * 
143 	 * ie. the "like" KeyedReferences are OR'd and the groups of "like" KeyedReferences are AND'd with each other.
144 	 */
145 	public void appendConditions(DynamicQuery qry, FindQualifiers fq, List<KeyedReference> keyedRefs) {
146 		
147 		// Append the necessary tables (one will always be added connecting the entity to its identifier table).
148 		appendJoinTables(qry, fq, keyedRefs);
149 		qry.AND().pad().openParen().pad();
150 		
151 		String predicate = DynamicQuery.PREDICATE_EQUALS;
152 		if (fq.isApproximateMatch()) {
153 			predicate = DynamicQuery.PREDICATE_LIKE;
154 		}
155 		
156 		// Sorting the collection by tModel Key
157 		Collections.sort(keyedRefs, new KeyedRefTModelComparator());
158 
159 		String prevTModelKey = null;
160 		int count = 0;
161 		int tblCount = -1;
162 		for(KeyedReference keyedRef : keyedRefs) {
163 			String tmodelKey = keyedRef.getTModelKey();
164 			String keyValue = keyedRef.getKeyValue();
165 			String keyName = keyedRef.getKeyName();
166 			
167 			if (fq.isApproximateMatch()) {
168 				// JUDDI-235: wildcards are provided by user (only commenting in case a new interpretation arises)
169 				//keyValue = keyValue.endsWith(DynamicQuery.WILDCARD)?keyValue:keyValue + DynamicQuery.WILDCARD;
170 				//keyName = keyName.endsWith(DynamicQuery.WILDCARD)?keyName:keyName + DynamicQuery.WILDCARD;
171 			}
172 
173 			// 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
174 			// the table count.
175 			if (fq.isOrLikeKeys()) {
176 				if (count == 0) {
177 					qry.openParen().pad();
178 					tblCount++;
179 				}
180 				else {
181 					if (!tmodelKey.equals(prevTModelKey)) {
182 						qry.closeParen().pad().AND().pad().openParen().pad();
183 						tblCount++;
184 					}
185 					else
186 						qry.OR().pad();
187 				}
188 			}
189 			else
190 				tblCount++;
191 			
192 			String keyValueTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyValue";
193 			String keyNameTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".keyName";
194 			String tmodelKeyTerm = (fq.isAndAllKeys()||fq.isOrLikeKeys()?entityAliasChild + tblCount:entityAliasChild + "0") + ".tmodelKeyRef";
195 			if (fq.isCaseInsensitiveMatch()) {
196 				keyValueTerm = "upper(" + keyValueTerm + ")";
197 				keyValue = keyValue.toUpperCase();
198 				
199 				keyNameTerm = "upper(" + keyNameTerm + ")";
200 				keyName = keyName.toUpperCase();
201 			}
202 			
203 			
204 			// According to specification, if the "general keyword" tmodel is used, then the keyName must be part of the query.
205 			if (Constants.GENERAL_KEYWORD_TMODEL.equalsIgnoreCase(tmodelKey)) {
206 				qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS),
207 									 new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate),
208 									 new DynamicQuery.Parameter(keyNameTerm, keyName, predicate));
209 			}
210 			else {
211 				qry.appendGroupedAnd(new DynamicQuery.Parameter(tmodelKeyTerm, tmodelKey, DynamicQuery.PREDICATE_EQUALS),
212 									 new DynamicQuery.Parameter(keyValueTerm, keyValue, predicate));
213 				
214 			}
215 			
216 			if (count + 1 < keyedRefs.size()) {
217 				if (fq.isAndAllKeys())
218 					qry.AND().pad();
219 				else if (fq.isOrLikeKeys()) {
220 				}
221 				else
222 					qry.OR().pad();
223 			}
224 			
225 			// The "orLikeKeys" will always leave an unclosed parenthesis.  This will close it.
226 			if (fq.isOrLikeKeys() && (count + 1 == keyedRefs.size()))
227 				qry.closeParen().pad();
228 
229 			prevTModelKey = tmodelKey;
230 			count++;
231 		}
232 		qry.closeParen().pad();
233 		
234 	}
235 	
236 	/*
237 	 * Appends the necessary join table for the child entity and additional tables for when keys are AND'd.  When "orLikeKeys" is used, 
238 	 * we only need an extra table for each distinct tmodelKey.
239 	 */
240 	public void appendJoinTables(DynamicQuery qry, FindQualifiers fq, List<KeyedReference> keyedRefs) {
241 		
242 		if (keyedRefs != null && keyedRefs.size() > 0) {
243 			// Sorting the collection by tModel Key
244 			Collections.sort(keyedRefs, new KeyedRefTModelComparator());
245 
246 			StringBuffer thetaJoins = new StringBuffer(200);
247 			int tblCount = 0;
248 			int count = 0;
249 			String curTModelKey = null;
250 			String prevTModelKey = null;
251 			for(KeyedReference kr : keyedRefs) {
252 				curTModelKey = kr.getTModelKey();
253 				if (count != 0) {
254 					if (fq.isOrLikeKeys() && curTModelKey.equals(prevTModelKey)) {
255 						// Do nothing
256 					}
257 					else {
258 						tblCount++;
259 						qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad();
260 						thetaJoins.append(entityAliasChild + (tblCount - 1) + "." + entityField + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " ");
261 						thetaJoins.append(DynamicQuery.OPERATOR_AND + " ");
262 					}
263 
264 				}
265 				else {
266 					qry.comma().pad().append(entityNameChild + " " + entityAliasChild + tblCount).pad();
267 					thetaJoins.append(entityAlias + "." + keyName + " = " + entityAliasChild + tblCount + "." + entityField + "." + keyName + " ");
268 					thetaJoins.append(DynamicQuery.OPERATOR_AND + " ");
269 				}
270 				prevTModelKey = curTModelKey;
271 				count++;
272 			}
273 			
274 			qry.WHERE().pad().openParen().pad();
275 
276 			String thetaJoinsStr = thetaJoins.toString();
277 			if (thetaJoinsStr.endsWith(DynamicQuery.OPERATOR_AND + " "))
278 				thetaJoinsStr = thetaJoinsStr.substring(0, thetaJoinsStr.length() - (DynamicQuery.OPERATOR_AND + " ").length());
279 			qry.append(thetaJoinsStr);
280 
281 			qry.closeParen().pad();
282 			if (fq!=null && fq.isSignaturePresent()) {
283 				qry.AND().pad().openParen().pad().append(getSignaturePresent()).pad().closeParen().pad();
284 			}
285 		}
286 	}
287 	
288 }