2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
24 import java.lang.annotation.Annotation;
25 import java.lang.reflect.Method;
26 import java.net.MalformedURLException;
28 import java.net.URISyntaxException;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.LinkedList;
34 import java.util.List;
37 import javax.xml.bind.annotation.XmlType;
39 import org.apache.commons.lang.StringUtils;
40 import org.openecomp.aai.inventory.v11.Relationship;
41 import org.openecomp.aai.inventory.v11.RelationshipData;
42 import org.openecomp.aai.inventory.v11.RelationshipList;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
44 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public class AAIServiceUtils {
50 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
52 public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
54 getLogger().debug(resourceClass.getName());
55 AAIDatum instance = null;
58 instance = resourceClass.newInstance();
60 Annotation[] annotations = resourceClass.getAnnotations();
61 for(Annotation annotation : annotations) {
62 Class<? extends Annotation> anotationType = annotation.annotationType();
63 String annotationName = anotationType.getName();
65 // 2. find string property setters and getters for the lists
66 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
67 XmlType order = (XmlType)annotation;
68 String[] values = order.propOrder();
69 for(String value : values) {
70 String id = camelCaseToDashedString(value);
75 } catch(Exception exc) {
81 public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
83 getLogger().debug(resourceClass.getName());
84 AAIDatum instance = null;
87 instance = resourceClass.newInstance();
89 Annotation[] annotations = resourceClass.getAnnotations();
90 for(Annotation annotation : annotations) {
91 Class<? extends Annotation> anotationType = annotation.annotationType();
92 String annotationName = anotationType.getName();
94 // 2. find string property setters and getters for the lists
95 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
96 boolean primaryIdFound = false;
97 XmlType order = (XmlType)annotation;
98 String[] values = order.propOrder();
99 for(String value : values) {
100 String id = camelCaseToDashedString(value);
104 primaryIdFound = true;
109 } catch(Exception exc) {
115 public static Method getRelationshipListGetterMethodFromClassDefinition(Class resourceClass) {
116 Method getRelationshipListMethod = null;
119 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
120 } catch(Exception exc) {
121 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
123 return getRelationshipListMethod;
126 private static Logger getLogger() {
131 private static final String regex = "([A-Z][a-z,0-9]+)";
132 private static final String replacement = "-$1";
134 public static String camelCaseToDashedString(String propOrder) {
135 return propOrder.replaceAll(regex, replacement).toLowerCase();
138 public static HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
143 getLogger().debug("Converting key [" + key + "] to where clause");
145 if (key.startsWith("'") && key.endsWith("'")) {
146 key = key.substring(1, key.length() - 1);
148 getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
151 String[] keyTerms = key.split("\\s+");
153 StringBuffer whereBuff = new StringBuffer();
157 HashMap<String, String> results = new HashMap<String, String>();
159 for (int i = 0; i < keyTerms.length; i++) {
161 if ("and".equalsIgnoreCase(keyTerms[i])
162 || "or".equalsIgnoreCase(keyTerms[i])) {
165 term1 = resolveTerm(keyTerms[i], ctx);
167 } else if (op == null) {
168 if ("==".equals(keyTerms[i])) {
174 term2 = resolveTerm(keyTerms[i], ctx);
175 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
176 results.put(term1, term2);
187 private static String resolveTerm(String term, SvcLogicContext ctx) {
192 getLogger().debug("resolveTerm: term is " + term);
194 if (term.startsWith("$") && (ctx != null)) {
195 // Resolve any index variables.
197 return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
198 } else if (term.startsWith("'") || term.startsWith("\"")) {
201 return (term.replaceAll("-", "_"));
206 private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
208 if (ctxVarName.indexOf('[') == -1) {
209 // Ctx variable contains no arrays
210 return (ctx.getAttribute(ctxVarName));
213 // Resolve any array references
214 StringBuffer sbuff = new StringBuffer();
215 String[] ctxVarParts = ctxVarName.split("\\[");
216 sbuff.append(ctxVarParts[0]);
217 for (int i = 1; i < ctxVarParts.length; i++) {
218 if (ctxVarParts[i].startsWith("$")) {
219 int endBracketLoc = ctxVarParts[i].indexOf("]");
220 if (endBracketLoc == -1) {
221 // Missing end bracket ... give up parsing
222 getLogger().warn("Variable reference " + ctxVarName
223 + " seems to be missing a ']'");
224 return (ctx.getAttribute(ctxVarName));
227 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
228 String remainder = ctxVarParts[i].substring(endBracketLoc);
231 sbuff.append(ctx.getAttribute(idxVarName));
232 sbuff.append(remainder);
235 // Index is not a variable reference
237 sbuff.append(ctxVarParts[i]);
241 return (ctx.getAttribute(sbuff.toString()));
244 public static void populateRelationshipDataFromPath(RelationshipList rl) throws URISyntaxException {
245 List<Relationship> list = rl.getRelationship();
246 if(list != null && !list.isEmpty()) {
247 for(Relationship relationship : list) {
248 if(relationship.getRelationshipData().isEmpty()){
249 String link = relationship.getRelatedLink();
250 URI uri = new URI(link);
251 link = uri.getPath();
252 HashMap<String,String> contributors = pathToHashMap(link);
253 for(String key : contributors.keySet()) {
254 RelationshipData rd = new RelationshipData();
255 rd.setRelationshipKey(key);
256 rd.setRelationshipValue(contributors.get(key));
257 relationship.getRelationshipData().add(rd);
264 protected static HashMap<String,String> pathToHashMap(String path) {
265 HashMap<String, String> nameValues = new HashMap<String, String>();
267 String[] split = path.split("/");
269 LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
270 Iterator<String> it = list.iterator();
272 while(it.hasNext()) {
273 String tag = it.next();
275 if(AAIRequest.getResourceNames().contains(tag)){
277 // get the class from tag
278 Class<? extends AAIDatum> clazz = null;
280 clazz = AAIRequest.getClassFromResource(tag);
281 String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
283 String value = it.next();
284 if(!StringUtils.isEmpty(value)){
285 nameValues.put(String.format("%s.%s", tag, fieldName), value);
291 case "service-capability":
293 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
294 if(secondaryFieldName != null) {
296 nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value);
303 } catch (ClassNotFoundException exc) {
304 LOG.info("Caught exception", exc);
312 public static String getPathForResource(String resource, String key, SvcLogicContext ctx ) throws MalformedURLException{
313 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
314 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
316 for(String name : nameValues.keySet()) {
317 request.addRequestProperty(name, nameValues.get(name));
319 return request.getRequestPath();
322 public static boolean isValidFormat(String resource, HashMap<String, String> nameValues) {
326 case "formatted-query":
327 case "generic-query":
331 case "l2-bridge-sbg":
332 case "l2-bridge-bgf":
337 if(resource.contains(":")) {
338 resource = resource.substring(0, resource.indexOf(":"));
341 Set<String> keys = nameValues.keySet();
342 for(String key : keys) {
343 if(!key.contains(".")) {
344 if("depth".equals(key) || "related-to".equals(key) || "related_to".equals(key) || "related-link".equals(key) || "related_link".equals(key) || "selflink".equals(key) || "resource_path".equals(key))
347 getLogger().warn(String.format("key '%s' is incompatible with resource type '%s'", key, resource));
354 public static boolean containsResource(String resource, HashMap<String, String> nameValues) {
355 if(resource.contains(":")) {
361 case "formatted-query":
362 case "generic-query":
366 case "l2-bridge-sbg":
367 case "l2-bridge-bgf":
373 if(nameValues.containsKey("selflink")) {
378 Set<String> tags = new HashSet<>();
380 for(String key : nameValues.keySet()) {
381 key = key.replace("_", "-");
382 if(key.contains(".")) {
383 String[] split = key.split("\\.");
389 return tags.contains(resource);