Isolate deprecated code in CCSDK aai-service
[ccsdk/sli/adaptors.git] / aai-service / provider / src / main / java / org / onap / ccsdk / sli / adaptors / aai / AAIServiceUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *             reserved.
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.onap.ccsdk.sli.adaptors.aai;
23
24 import java.lang.annotation.Annotation;
25 import java.lang.reflect.Method;
26 import java.net.MalformedURLException;
27 import java.net.URI;
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;
35 import java.util.Set;
36
37 import javax.xml.bind.annotation.XmlType;
38
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;
47
48 public class AAIServiceUtils {
49
50     private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
51
52     public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
53         // 1. find class
54         getLogger().debug(resourceClass.getName());
55         AAIDatum instance = null;
56
57         try {
58             instance = resourceClass.newInstance();
59
60             Annotation[] annotations = resourceClass.getAnnotations();
61             for(Annotation annotation : annotations) {
62                 Class<? extends Annotation> anotationType = annotation.annotationType();
63                 String annotationName = anotationType.getName();
64
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);
71                         return id;
72                     }
73                 }
74             }
75         } catch(Exception exc) {
76
77         }
78         return null;
79     }
80
81     public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
82         // 1. find class
83         getLogger().debug(resourceClass.getName());
84         AAIDatum instance = null;
85
86         try {
87             instance = resourceClass.newInstance();
88
89             Annotation[] annotations = resourceClass.getAnnotations();
90             for(Annotation annotation : annotations) {
91                 Class<? extends Annotation> anotationType = annotation.annotationType();
92                 String annotationName = anotationType.getName();
93
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);
101                         if(primaryIdFound) {
102                             return id;
103                         } else {
104                             primaryIdFound = true;
105                         }
106                     }
107                 }
108             }
109         } catch(Exception exc) {
110
111         }
112         return null;
113     }
114
115         public static Method getRelationshipListGetterMethodFromClassDefinition(Class resourceClass) {
116                 Method getRelationshipListMethod = null;
117                 
118                 try {
119                          getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
120                 } catch(Exception exc) {
121                         getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
122                 }
123                 return getRelationshipListMethod;
124         }
125
126     private static Logger getLogger() {
127         return LOG;
128     }
129
130
131     private static final String regex = "([A-Z][a-z,0-9]+)";
132     private static final String replacement = "-$1";
133
134     public static String camelCaseToDashedString(String propOrder) {
135         return propOrder.replaceAll(regex, replacement).toLowerCase();
136     }
137
138     public static HashMap<String,String> keyToHashMap(String key,    SvcLogicContext ctx) {
139         if (key == null) {
140             return (null);
141         }
142
143         getLogger().debug("Converting key [" + key + "] to where clause");
144
145         if (key.startsWith("'") && key.endsWith("'")) {
146             key = key.substring(1, key.length() - 1);
147
148             getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
149         }
150
151         String[] keyTerms = key.split("\\s+");
152
153         StringBuffer whereBuff = new StringBuffer();
154         String term1 = null;
155         String op = null;
156         String term2 = null;
157         HashMap<String, String> results = new HashMap<String, String>();
158
159         for (int i = 0; i < keyTerms.length; i++) {
160             if (term1 == null) {
161                 if ("and".equalsIgnoreCase(keyTerms[i])
162                         || "or".equalsIgnoreCase(keyTerms[i])) {
163                     // Skip over ADD/OR
164                 } else {
165                     term1 = resolveTerm(keyTerms[i], ctx);
166                 }
167             } else if (op == null) {
168                 if ("==".equals(keyTerms[i])) {
169                     op = "=";
170                 } else {
171                     op = keyTerms[i];
172                 }
173             } else {
174                 term2 = resolveTerm(keyTerms[i], ctx);
175                 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
176                 results.put(term1,  term2);
177
178                 term1 = null;
179                 op = null;
180                 term2 = null;
181             }
182         }
183
184         return (results);
185     }
186
187     private static String resolveTerm(String term, SvcLogicContext ctx) {
188         if (term == null) {
189             return (null);
190         }
191
192         getLogger().debug("resolveTerm: term is " + term);
193
194         if (term.startsWith("$") && (ctx != null)) {
195             // Resolve any index variables.
196
197             return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
198         } else if (term.startsWith("'") || term.startsWith("\"")) {
199             return (term);
200         } else {
201             return (term.replaceAll("-", "_"));
202
203         }
204     }
205
206     private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
207
208         if (ctxVarName.indexOf('[') == -1) {
209             // Ctx variable contains no arrays
210             return (ctx.getAttribute(ctxVarName));
211         }
212
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));
225                 }
226
227                 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
228                 String remainder = ctxVarParts[i].substring(endBracketLoc);
229
230                 sbuff.append("[");
231                 sbuff.append(ctx.getAttribute(idxVarName));
232                 sbuff.append(remainder);
233
234             } else {
235                 // Index is not a variable reference
236                 sbuff.append("[");
237                 sbuff.append(ctxVarParts[i]);
238             }
239         }
240
241         return (ctx.getAttribute(sbuff.toString()));
242     }
243
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);
258                     }
259                 }
260             }
261         }
262     }
263
264     protected static HashMap<String,String> pathToHashMap(String path) {
265         HashMap<String, String> nameValues = new  HashMap<String, String>();
266
267         String[] split = path.split("/");
268
269         LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
270         Iterator<String> it = list.iterator();
271
272         while(it.hasNext()) {
273             String tag = it.next();
274             if(!tag.isEmpty()) {
275                 if(AAIRequest.getResourceNames().contains(tag)){
276                     LOG.info(tag);
277                     // get the class from tag
278                     Class<? extends AAIDatum> clazz = null;
279                     try {
280                         clazz = AAIRequest.getClassFromResource(tag);
281                         String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
282
283                         String value = it.next();
284                         if(!StringUtils.isEmpty(value)){
285                             nameValues.put(String.format("%s.%s", tag, fieldName), value);
286                             switch(tag) {
287                             case "cloud-region":
288                             case "entitlement":
289                             case "license":
290                             case "route-target":
291                             case "service-capability":
292                             case "ctag-pool":
293                                 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
294                                 if(secondaryFieldName != null) {
295                                     value = it.next();
296                                     nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value);
297                                 }
298                                 break;
299                             default:
300                                 break;
301                             }
302                         }
303                     } catch (ClassNotFoundException exc) {
304                         LOG.info("Caught exception", exc);
305                     }
306                 }
307             }
308         }
309         return nameValues;
310     }
311
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);
315
316         for(String name : nameValues.keySet()) {
317             request.addRequestProperty(name, nameValues.get(name));
318         }
319         return request.getRequestPath();
320     }
321
322     public static boolean isValidFormat(String resource, HashMap<String, String> nameValues) {
323
324         switch(resource){
325         case "custom-query":
326         case "formatted-query":
327         case "generic-query":
328         case "named-query":
329         case "nodes-query":
330         case "linterface":
331         case "l2-bridge-sbg":
332         case "l2-bridge-bgf":
333         case "echo":
334         case "test":
335             return true;
336         }
337         if(resource.contains(":")) {
338             resource = resource.substring(0, resource.indexOf(":"));
339         }
340
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))
345                     continue;
346                 else {
347                                         getLogger().warn(String.format("key '%s' is incompatible with resource type '%s'", key, resource));
348                 }
349             }
350         }
351         return true;
352     }
353
354     public static boolean containsResource(String resource, HashMap<String, String> nameValues) {
355         if(resource.contains(":")) {
356             return true;
357         }
358
359         switch(resource){
360         case "custom-query":
361         case "formatted-query":
362         case "generic-query":
363         case "named-query":
364         case "nodes-query":
365         case "linterface":
366         case "l2-bridge-sbg":
367         case "l2-bridge-bgf":
368         case "echo":
369         case "test":
370             return true;
371
372         default:
373             if(nameValues.containsKey("selflink")) {
374                 return true;
375             }
376         }
377
378         Set<String> tags = new HashSet<>();
379
380         for(String key : nameValues.keySet()) {
381             key = key.replace("_", "-");
382             if(key.contains(".")) {
383                 String[] split = key.split("\\.");
384                 tags.add(split[0]);
385             } else {
386                 tags.add(key);
387             }
388         }
389         return tags.contains(resource);
390     }
391 }