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;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.LinkedList;
35 import java.util.List;
38 import javax.xml.bind.annotation.XmlType;
40 import org.apache.commons.lang.StringUtils;
41 import org.onap.aai.inventory.v14.Relationship;
42 import org.onap.aai.inventory.v14.RelationshipData;
43 import org.onap.aai.inventory.v14.RelationshipList;
44 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
45 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public class AAIServiceUtils {
51 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
53 private AAIServiceUtils() {
56 public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
58 getLogger().debug(resourceClass.getName());
61 Annotation[] annotations = resourceClass.getAnnotations();
62 for(Annotation annotation : annotations) {
63 Class<? extends Annotation> anotationType = annotation.annotationType();
64 String annotationName = anotationType.getName();
66 // 2. find string property setters and getters for the lists
67 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
68 XmlType order = (XmlType)annotation;
69 String[] values = order.propOrder();
70 for(String value : values) {
71 String id = camelCaseToDashedString(value);
76 } catch(Exception exc) {
77 getLogger().warn("getPrimaryIdFromClass failed", exc);
82 public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
83 getLogger().debug(resourceClass.getName());
86 Annotation[] annotations = resourceClass.getAnnotations();
87 for(Annotation annotation : annotations) {
88 Class<? extends Annotation> anotationType = annotation.annotationType();
89 String annotationName = anotationType.getName();
91 // 2. find string property setters and getters for the lists
92 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
93 boolean primaryIdFound = false;
94 XmlType order = (XmlType)annotation;
95 String[] values = order.propOrder();
96 for(String value : values) {
97 String id = camelCaseToDashedString(value);
101 primaryIdFound = true;
106 } catch(Exception exc) {
112 public static Method getRelationshipListGetterMethodFromClassDefinition(Class resourceClass) {
113 Method getRelationshipListMethod = null;
116 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
117 } catch(Exception exc) {
118 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
120 return getRelationshipListMethod;
123 private static Logger getLogger() {
128 private static final String regex = "([A-Z][a-z,0-9]+)";
129 private static final String replacement = "-$1";
131 public static String camelCaseToDashedString(String propOrder) {
132 return propOrder.replaceAll(regex, replacement).toLowerCase();
135 public static HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
140 getLogger().debug("Converting key [" + key + "] to where clause");
142 if (key.startsWith("'") && key.endsWith("'")) {
143 key = key.substring(1, key.length() - 1);
145 getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
148 String[] keyTerms = key.split("\\s+");
150 StringBuffer whereBuff = new StringBuffer();
154 HashMap<String, String> results = new HashMap<String, String>();
156 for (int i = 0; i < keyTerms.length; i++) {
158 if ("and".equalsIgnoreCase(keyTerms[i])
159 || "or".equalsIgnoreCase(keyTerms[i])) {
162 term1 = resolveTerm(keyTerms[i], ctx);
164 } else if (op == null) {
165 if ("==".equals(keyTerms[i])) {
171 term2 = resolveTerm(keyTerms[i], ctx);
172 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
173 results.put(term1, term2);
184 private static String resolveTerm(String term, SvcLogicContext ctx) {
189 getLogger().debug("resolveTerm: term is " + term);
191 if (term.startsWith("$") && (ctx != null)) {
192 // Resolve any index variables.
194 return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
195 } else if (term.startsWith("'") || term.startsWith("\"")) {
198 return (term.replaceAll("-", "_"));
203 private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
205 if (ctxVarName.indexOf('[') == -1) {
206 // Ctx variable contains no arrays
207 return (ctx.getAttribute(ctxVarName));
210 // Resolve any array references
211 StringBuffer sbuff = new StringBuffer();
212 String[] ctxVarParts = ctxVarName.split("\\[");
213 sbuff.append(ctxVarParts[0]);
214 for (int i = 1; i < ctxVarParts.length; i++) {
215 if (ctxVarParts[i].startsWith("$")) {
216 int endBracketLoc = ctxVarParts[i].indexOf("]");
217 if (endBracketLoc == -1) {
218 // Missing end bracket ... give up parsing
219 getLogger().warn("Variable reference " + ctxVarName
220 + " seems to be missing a ']'");
221 return (ctx.getAttribute(ctxVarName));
224 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
225 String remainder = ctxVarParts[i].substring(endBracketLoc);
228 sbuff.append(ctx.getAttribute(idxVarName));
229 sbuff.append(remainder);
232 // Index is not a variable reference
234 sbuff.append(ctxVarParts[i]);
238 return (ctx.getAttribute(sbuff.toString()));
241 public static void populateRelationshipDataFromPath(RelationshipList rl) throws URISyntaxException {
242 List<Relationship> list = rl.getRelationship();
243 if(list != null && !list.isEmpty()) {
244 for(Relationship relationship : list) {
245 if(relationship.getRelationshipData().isEmpty()){
246 String link = relationship.getRelatedLink();
247 URI uri = new URI(link);
248 link = uri.getPath();
249 HashMap<String,String> contributors = pathToHashMap(link);
250 for(String key : contributors.keySet()) {
251 RelationshipData rd = new RelationshipData();
252 rd.setRelationshipKey(key);
253 rd.setRelationshipValue(contributors.get(key));
254 relationship.getRelationshipData().add(rd);
261 protected static HashMap<String,String> pathToHashMap(String path) {
262 HashMap<String, String> nameValues = new HashMap<String, String>();
264 String[] split = path.split("/");
266 LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
267 Iterator<String> it = list.iterator();
269 while(it.hasNext()) {
270 String tag = it.next();
272 if(AAIRequest.getResourceNames().contains(tag)){
274 // get the class from tag
275 Class<? extends AAIDatum> clazz = AAIRequest.getClassFromResource(tag);
276 String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
278 String value = it.next();
279 if(!StringUtils.isEmpty(value)){
280 nameValues.put(String.format("%s.%s", tag, fieldName), value);
286 case "service-capability":
288 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
289 if(secondaryFieldName != null) {
291 nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value);
304 public static String getPathForResource(String resource, String key, SvcLogicContext ctx ) throws MalformedURLException{
305 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
306 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
308 for(String name : nameValues.keySet()) {
309 request.addRequestProperty(name, nameValues.get(name));
311 return request.getRequestPath();
314 public static boolean isValidFormat(String resource, Map<String, String> nameValues) {
318 case "formatted-query":
319 case "generic-query":
323 case "l2-bridge-sbg":
324 case "l2-bridge-bgf":
329 if(resource.contains(":")) {
330 resource = resource.substring(0, resource.indexOf(":"));
333 Set<String> keys = nameValues.keySet();
334 for(String key : keys) {
335 if(!key.contains(".")) {
336 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))
339 getLogger().warn(String.format("key '%s' is incompatible with resource type '%s'", key, resource));
346 public static boolean containsResource(String resource, HashMap<String, String> nameValues) {
347 if(resource.contains(":")) {
353 case "formatted-query":
354 case "generic-query":
358 case "l2-bridge-sbg":
359 case "l2-bridge-bgf":
365 if(nameValues.containsKey("selflink")) {
370 Set<String> tags = new HashSet<>();
372 for(String key : nameValues.keySet()) {
373 key = key.replace("_", "-");
374 if(key.contains(".")) {
375 String[] split = key.split("\\.");
381 return tags.contains(resource);