2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 ONAP 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.net.MalformedURLException;
27 import java.net.URISyntaxException;
28 import java.util.Arrays;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.LinkedList;
32 import java.util.List;
35 import javax.xml.bind.annotation.XmlType;
37 import org.apache.commons.lang.StringUtils;
38 import org.openecomp.aai.inventory.v11.Relationship;
39 import org.openecomp.aai.inventory.v11.RelationshipData;
40 import org.openecomp.aai.inventory.v11.RelationshipList;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public class AAIServiceUtils {
48 private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
50 public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
52 getLogger().debug(resourceClass.getName());
53 AAIDatum instance = null;
56 instance = resourceClass.newInstance();
58 Annotation[] annotations = resourceClass.getAnnotations();
59 for(Annotation annotation : annotations) {
60 Class<? extends Annotation> anotationType = annotation.annotationType();
61 String annotationName = anotationType.getName();
63 // 2. find string property setters and getters for the lists
64 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
65 XmlType order = (XmlType)annotation;
66 String[] values = order.propOrder();
67 for(String value : values) {
68 String id = camelCaseToDashedString(value);
73 } catch(Exception exc) {
79 public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
81 getLogger().debug(resourceClass.getName());
82 AAIDatum instance = null;
85 instance = resourceClass.newInstance();
87 Annotation[] annotations = resourceClass.getAnnotations();
88 for(Annotation annotation : annotations) {
89 Class<? extends Annotation> anotationType = annotation.annotationType();
90 String annotationName = anotationType.getName();
92 // 2. find string property setters and getters for the lists
93 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
94 boolean primaryIdFound = false;
95 XmlType order = (XmlType)annotation;
96 String[] values = order.propOrder();
97 for(String value : values) {
98 String id = camelCaseToDashedString(value);
102 primaryIdFound = true;
107 } catch(Exception exc) {
114 private static Logger getLogger() {
119 private static final String regex = "([A-Z][a-z,0-9]+)";
120 private static final String replacement = "-$1";
122 public static String camelCaseToDashedString(String propOrder) {
123 return propOrder.replaceAll(regex, replacement).toLowerCase();
126 public static HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
131 getLogger().debug("Converting key [" + key + "] to where clause");
133 if (key.startsWith("'") && key.endsWith("'")) {
134 key = key.substring(1, key.length() - 1);
136 getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
139 String[] keyTerms = key.split("\\s+");
141 StringBuffer whereBuff = new StringBuffer();
145 HashMap<String, String> results = new HashMap<String, String>();
147 for (int i = 0; i < keyTerms.length; i++) {
149 if ("and".equalsIgnoreCase(keyTerms[i])
150 || "or".equalsIgnoreCase(keyTerms[i])) {
153 term1 = resolveTerm(keyTerms[i], ctx);
155 } else if (op == null) {
156 if ("==".equals(keyTerms[i])) {
162 term2 = resolveTerm(keyTerms[i], ctx);
163 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
164 results.put(term1, term2);
175 private static String resolveTerm(String term, SvcLogicContext ctx) {
180 getLogger().debug("resolveTerm: term is " + term);
182 if (term.startsWith("$") && (ctx != null)) {
183 // Resolve any index variables.
185 return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
186 } else if (term.startsWith("'") || term.startsWith("\"")) {
189 return (term.replaceAll("-", "_"));
194 private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
196 if (ctxVarName.indexOf('[') == -1) {
197 // Ctx variable contains no arrays
198 return (ctx.getAttribute(ctxVarName));
201 // Resolve any array references
202 StringBuffer sbuff = new StringBuffer();
203 String[] ctxVarParts = ctxVarName.split("\\[");
204 sbuff.append(ctxVarParts[0]);
205 for (int i = 1; i < ctxVarParts.length; i++) {
206 if (ctxVarParts[i].startsWith("$")) {
207 int endBracketLoc = ctxVarParts[i].indexOf("]");
208 if (endBracketLoc == -1) {
209 // Missing end bracket ... give up parsing
210 getLogger().warn("Variable reference " + ctxVarName
211 + " seems to be missing a ']'");
212 return (ctx.getAttribute(ctxVarName));
215 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
216 String remainder = ctxVarParts[i].substring(endBracketLoc);
219 sbuff.append(ctx.getAttribute(idxVarName));
220 sbuff.append(remainder);
223 // Index is not a variable reference
225 sbuff.append(ctxVarParts[i]);
229 return (ctx.getAttribute(sbuff.toString()));
232 public static void populateRelationshipDataFromPath(RelationshipList rl) throws URISyntaxException {
233 List<Relationship> list = rl.getRelationship();
234 if(list != null && !list.isEmpty()) {
235 for(Relationship relationship : list) {
236 if(relationship.getRelationshipData().isEmpty()){
237 String link = relationship.getRelatedLink();
238 URI uri = new URI(link);
239 link = uri.getPath();
240 HashMap<String,String> contributors = pathToHashMap(link);
241 for(String key : contributors.keySet()) {
242 RelationshipData rd = new RelationshipData();
243 rd.setRelationshipKey(key);
244 rd.setRelationshipValue(contributors.get(key));
245 relationship.getRelationshipData().add(rd);
252 protected static HashMap<String,String> pathToHashMap(String path) {
253 HashMap<String, String> nameValues = new HashMap<String, String>();
255 String[] split = path.split("/");
257 LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
258 Iterator<String> it = list.iterator();
260 while(it.hasNext()) {
261 String tag = it.next();
263 if(AAIRequest.getResourceNames().contains(tag)){
265 // get the class from tag
266 Class<? extends AAIDatum> clazz = null;
268 clazz = AAIRequest.getClassFromResource(tag);
269 String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
271 String value = it.next();
272 if(!StringUtils.isEmpty(value)){
273 nameValues.put(String.format("%s.%s", tag, fieldName), value);
279 case "service-capability":
281 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
282 if(secondaryFieldName != null) {
284 nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value);
291 } catch (ClassNotFoundException exc) {
292 LOG.info("Caught exception", exc);
300 public static String getPathForResource(String resource, String key, SvcLogicContext ctx ) throws MalformedURLException{
301 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
302 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
304 for(String name : nameValues.keySet()) {
305 request.addRequestProperty(name, nameValues.get(name));
307 return request.getRequestPath();
310 public static boolean isValidFormat(String resource, HashMap<String, String> nameValues) {
313 case "formatted-query":
314 case "generic-query":
318 case "l2-bridge-sbg":
319 case "l2-bridge-bgf":
324 if(resource.contains(":")) {
325 resource = resource.substring(0, resource.indexOf(":"));
328 Set<String> keys = nameValues.keySet();
329 for(String key : keys) {
330 if(!key.contains(".")) {
331 if("depth".equals(key) || "related-to".equals(key) || "related_to".equals(key) || "related-link".equals(key) || "related_link".equals(key) || "selflink".equals(key))
334 getLogger().warn(String.format("key %s is incompatible with resource type '%s'", key, resource));