[SDNC-30] summary
[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 ONAP 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.net.MalformedURLException;
26 import java.net.URI;
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;
33 import java.util.Set;
34
35 import javax.xml.bind.annotation.XmlType;
36
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;
45
46 public class AAIServiceUtils {
47         
48         private static final Logger LOG = LoggerFactory.getLogger(AAIService.class);
49         
50         public static String getPrimaryIdFromClass(Class<? extends AAIDatum> resourceClass){
51                 // 1. find class
52                 getLogger().debug(resourceClass.getName());
53                 AAIDatum instance = null;
54
55                 try {
56                         instance = resourceClass.newInstance();
57                         
58                         Annotation[] annotations = resourceClass.getAnnotations();
59                         for(Annotation annotation : annotations) {
60                                 Class<? extends Annotation> anotationType = annotation.annotationType();
61                                 String annotationName = anotationType.getName();
62
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);
69                                                 return id;
70                                         }
71                                 }
72                         }
73                 } catch(Exception exc) {
74                         
75                 }
76                 return null;
77         }
78
79         public static String getSecondaryIdFromClass(Class<? extends AAIDatum> resourceClass){
80                 // 1. find class
81                 getLogger().debug(resourceClass.getName());
82                 AAIDatum instance = null;
83
84                 try {
85                         instance = resourceClass.newInstance();
86                         
87                         Annotation[] annotations = resourceClass.getAnnotations();
88                         for(Annotation annotation : annotations) {
89                                 Class<? extends Annotation> anotationType = annotation.annotationType();
90                                 String annotationName = anotationType.getName();
91
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);
99                                                 if(primaryIdFound) {
100                                                         return id;
101                                                 } else {
102                                                         primaryIdFound = true;
103                                                 }
104                                         }
105                                 }
106                         }
107                 } catch(Exception exc) {
108                         
109                 }
110                 return null;
111         }
112
113         
114         private static Logger getLogger() {
115                 return LOG;
116         }
117
118         
119         private static final String regex = "([A-Z][a-z,0-9]+)";
120         private static final String replacement = "-$1";
121
122         public static String camelCaseToDashedString(String propOrder) {
123                 return propOrder.replaceAll(regex, replacement).toLowerCase();
124         }
125         
126         public static HashMap<String,String> keyToHashMap(String key,   SvcLogicContext ctx) {
127                 if (key == null) {
128                         return (null);
129                 }
130
131                 getLogger().debug("Converting key [" + key + "] to where clause");
132
133                 if (key.startsWith("'") && key.endsWith("'")) {
134                         key = key.substring(1, key.length() - 1);
135
136                         getLogger().debug("Stripped outer single quotes - key is now [" + key + "]");
137                 }
138
139                 String[] keyTerms = key.split("\\s+");
140
141                 StringBuffer whereBuff = new StringBuffer();
142                 String term1 = null;
143                 String op = null;
144                 String term2 = null;
145                 HashMap<String, String> results = new HashMap<String, String>();
146
147                 for (int i = 0; i < keyTerms.length; i++) {
148                         if (term1 == null) {
149                                 if ("and".equalsIgnoreCase(keyTerms[i])
150                                                 || "or".equalsIgnoreCase(keyTerms[i])) {
151                                         // Skip over ADD/OR
152                                 } else {
153                                         term1 = resolveTerm(keyTerms[i], ctx);
154                                 }
155                         } else if (op == null) {
156                                 if ("==".equals(keyTerms[i])) {
157                                         op = "=";
158                                 } else {
159                                         op = keyTerms[i];
160                                 }
161                         } else {
162                                 term2 = resolveTerm(keyTerms[i], ctx);
163                                 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
164                                 results.put(term1,  term2);
165
166                                 term1 = null;
167                                 op = null;
168                                 term2 = null;
169                         }
170                 }
171
172                 return (results);
173         }
174         
175         private static String resolveTerm(String term, SvcLogicContext ctx) {
176                 if (term == null) {
177                         return (null);
178                 }
179
180                 getLogger().debug("resolveTerm: term is " + term);
181
182                 if (term.startsWith("$") && (ctx != null)) {
183                         // Resolve any index variables.
184
185                         return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
186                 } else if (term.startsWith("'") || term.startsWith("\"")) {
187                         return (term);
188                 } else {
189                         return (term.replaceAll("-", "_"));
190
191                 }
192         }
193         
194         private static String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
195
196                 if (ctxVarName.indexOf('[') == -1) {
197                         // Ctx variable contains no arrays
198                         return (ctx.getAttribute(ctxVarName));
199                 }
200
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));
213                                 }
214
215                                 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
216                                 String remainder = ctxVarParts[i].substring(endBracketLoc);
217
218                                 sbuff.append("[");
219                                 sbuff.append(ctx.getAttribute(idxVarName));
220                                 sbuff.append(remainder);
221
222                         } else {
223                                 // Index is not a variable reference
224                                 sbuff.append("[");
225                                 sbuff.append(ctxVarParts[i]);
226                         }
227                 }
228
229                 return (ctx.getAttribute(sbuff.toString()));
230         }
231         
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);
246                                         }
247                                 }
248                         }
249                 }
250         }
251         
252         protected static HashMap<String,String> pathToHashMap(String path) {
253                 HashMap<String, String> nameValues = new  HashMap<String, String>();
254                 
255                 String[] split = path.split("/");
256                 
257                 LinkedList<String> list = new LinkedList<String>( Arrays.asList(split));
258                 Iterator<String> it = list.iterator();
259                 
260                 while(it.hasNext()) {
261                         String tag = it.next();
262                         if(!tag.isEmpty()) {
263                                 if(AAIRequest.getResourceNames().contains(tag)){
264                                         LOG.info(tag);
265                                         // get the class from tag
266                                         Class<? extends AAIDatum> clazz = null;
267                                         try {
268                                                 clazz = AAIRequest.getClassFromResource(tag);
269                                                 String fieldName = AAIServiceUtils.getPrimaryIdFromClass(clazz);
270
271                                                 String value = it.next();
272                                                 if(!StringUtils.isEmpty(value)){
273                                                         nameValues.put(String.format("%s.%s", tag, fieldName), value);
274                                                         switch(tag) {
275                                                         case "cloud-region":
276                                                         case "entitlement":
277                                                         case "license":
278                                                         case "route-target":
279                                                         case "service-capability":
280                                                         case "ctag-pool":
281                                                                 String secondaryFieldName = AAIServiceUtils.getSecondaryIdFromClass(clazz);
282                                                                 if(secondaryFieldName != null) {
283                                                                         value = it.next();
284                                                                         nameValues.put(String.format("%s.%s", tag, secondaryFieldName), value); 
285                                                                 }
286                                                                 break;
287                                                         default:
288                                                                 break;
289                                                         }
290                                                 }
291                                         } catch (ClassNotFoundException exc) {
292                                                 LOG.info("Caught exception", exc);
293                                         }
294                                 }
295                         }
296                 }
297                 return nameValues;
298         }
299         
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);
303                 
304                 for(String name : nameValues.keySet()) {
305                         request.addRequestProperty(name, nameValues.get(name));
306                 }
307                 return request.getRequestPath();
308         }
309         
310         public static boolean isValidFormat(String resource, HashMap<String, String> nameValues) {
311
312                 switch(resource){
313                 case "formatted-query":
314                 case "generic-query":
315                 case "named-query":
316                 case "nodes-query":
317                 case "linterface":
318                 case "l2-bridge-sbg":
319                 case "l2-bridge-bgf":
320                 case "echo":
321                 case "test":
322                         return true;
323                 }
324                 if(resource.contains(":")) {
325                         resource = resource.substring(0, resource.indexOf(":"));
326                 }
327
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))
332                                         continue;
333                                 else {
334                                         getLogger().warn(String.format("key %s is incompatible with resource type '%s'", key, resource));
335                                 }
336                         }
337                 }
338                 return true;
339         }
340 }