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 String VERSION_PATTERN = "/v$/";
53 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
55 private AAIServiceUtils() {
58 public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
60 getLogger().debug(resourceClass.getName());
63 Annotation[] annotations = resourceClass.getAnnotations();
64 for(Annotation annotation : annotations) {
65 Class<? extends Annotation> anotationType = annotation.annotationType();
66 String annotationName = anotationType.getName();
68 // 2. find string property setters and getters for the lists
69 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
70 XmlType order = (XmlType)annotation;
71 String[] values = order.propOrder();
72 for(String value : values) {
73 String id = camelCaseToDashedString(value);
78 } catch(Exception exc) {
79 getLogger().warn("getPrimaryIdFromClass failed", exc);
84 public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
85 getLogger().debug(resourceClass.getName());
88 Annotation[] annotations = resourceClass.getAnnotations();
89 for(Annotation annotation : annotations) {
90 Class<? extends Annotation> anotationType = annotation.annotationType();
91 String annotationName = anotationType.getName();
93 // 2. find string property setters and getters for the lists
94 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
95 boolean primaryIdFound = false;
96 XmlType order = (XmlType)annotation;
97 String[] values = order.propOrder();
98 for(String value : values) {
99 String id = camelCaseToDashedString(value);
103 primaryIdFound = true;
108 } catch(Exception exc) {
114 public static Method getRelationshipListGetterMethodFromClassDefinition(Class resourceClass) {
115 Method getRelationshipListMethod = null;
118 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
119 } catch(Exception exc) {
120 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
122 return getRelationshipListMethod;
125 private static Logger getLogger() {
130 private static final String regex = "([A-Z][a-z,0-9]+)";
131 private static final String replacement = "-$1";
133 public static String camelCaseToDashedString(String propOrder) {
134 return propOrder.replaceAll(regex, replacement).toLowerCase();
137 public static HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
142 getLogger().debug("Converting key [" + key + "] to where clause");
144 if (key.startsWith("'") && key.endsWith("'")) {
145 key = key.substring(1, key.length() - 1);
147 getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
150 String[] keyTerms = key.split("\\s+");
152 StringBuffer whereBuff = new StringBuffer();
156 HashMap<String, String> results = new HashMap<String, String>();
158 for (int i = 0; i < keyTerms.length; i++) {
160 if ("and".equalsIgnoreCase(keyTerms[i])
161 || "or".equalsIgnoreCase(keyTerms[i])) {
164 term1 = resolveTerm(keyTerms[i], ctx);
166 } else if (op == null) {
167 if ("==".equals(keyTerms[i])) {
173 term2 = resolveTerm(keyTerms[i], ctx);
174 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
175 results.put(term1, term2);
186 private static String resolveTerm(String term, SvcLogicContext ctx) {
191 getLogger().debug("resolveTerm: term is " + term);
193 if (term.startsWith("$") && (ctx != null)) {
194 // Resolve any index variables.
196 term = ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
197 if (term.contains(VERSION_PATTERN) && (ctx != null)) {
198 return term.replace(VERSION_PATTERN, AAIRequest.getSupportedAAIVersion());
201 } else if (term.contains(VERSION_PATTERN) && (ctx != null)) {
202 return term.replace(VERSION_PATTERN, AAIRequest.getSupportedAAIVersion());
203 } else if (term.startsWith("'") || term.startsWith("\"")) {
206 return (term.replaceAll("-", "_"));
211 private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
213 if (ctxVarName.indexOf('[') == -1) {
214 // Ctx variable contains no arrays
215 return (ctx.getAttribute(ctxVarName));
218 // Resolve any array references
219 StringBuffer sbuff = new StringBuffer();
220 String[] ctxVarParts = ctxVarName.split("\\[");
221 sbuff.append(ctxVarParts[0]);
222 for (int i = 1; i < ctxVarParts.length; i++) {
223 if (ctxVarParts[i].startsWith("$")) {
224 int endBracketLoc = ctxVarParts[i].indexOf("]");
225 if (endBracketLoc == -1) {
226 // Missing end bracket ... give up parsing
227 getLogger().warn("Variable reference " + ctxVarName
228 + " seems to be missing a ']'");
229 return (ctx.getAttribute(ctxVarName));
232 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
233 String remainder = ctxVarParts[i].substring(endBracketLoc);
236 sbuff.append(ctx.getAttribute(idxVarName));
237 sbuff.append(remainder);
240 // Index is not a variable reference
242 sbuff.append(ctxVarParts[i]);
246 return (ctx.getAttribute(sbuff.toString()));
249 public static void populateRelationshipDataFromPath(RelationshipList rl) throws URISyntaxException {
250 List<Relationship> list = rl.getRelationship();
251 if(list != null && !list.isEmpty()) {
252 for(Relationship relationship : list) {
253 if(relationship.getRelationshipData().isEmpty()){
254 String link = relationship.getRelatedLink();
255 URI uri = new URI(link);
256 link = uri.getPath();
257 HashMap<String,String> contributors = pathToHashMap(link);
258 for(String key : contributors.keySet()) {
259 RelationshipData rd = new RelationshipData();
260 rd.setRelationshipKey(key);
261 rd.setRelationshipValue(contributors.get(key));
262 relationship.getRelationshipData().add(rd);
269 protected static HashMap<String,String> pathToHashMap(String path) {
270 HashMap<String, String> nameValues = new HashMap<String, String>();
272 String[] split = path.split("/");
274 LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
275 Iterator<String> it = list.iterator();
277 while(it.hasNext()) {
278 String tag = it.next();
280 if(AAIRequest.getResourceNames().contains(tag)){
282 // get the class from tag
283 Class<? extends AAIDatum> clazz = AAIRequest.getClassFromResource(tag);
284 String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
286 String value = it.next();
287 if(!StringUtils.isEmpty(value)){
288 nameValues.put(String.format("%s.%s", tag, fieldName), value);
294 case "service-capability":
296 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
297 if(secondaryFieldName != null) {
299 nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value);
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, Map<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);