215f9ae8284ebd0e87976c42cdf271e8d1f13843
[ccsdk/sli/adaptors.git] / aai-service / provider / src / main / java / org / onap / ccsdk / sli / adaptors / aai / AAIRequest.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.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.Reader;
28 import java.io.UnsupportedEncodingException;
29 import java.lang.reflect.Method;
30 import java.net.MalformedURLException;
31 import java.net.URL;
32 import java.net.URLDecoder;
33 import java.net.URLEncoder;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.BitSet;
37 import java.util.HashSet;
38 import java.util.HashMap;
39 import java.util.LinkedHashMap;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.Properties;
43 import java.util.Set;
44 import java.util.TreeSet;
45
46 import org.apache.commons.lang.StringUtils;
47 import org.openecomp.aai.inventory.v11.GenericVnf;
48 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
49 import org.osgi.framework.Bundle;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 import com.fasterxml.jackson.core.JsonParseException;
56 import com.fasterxml.jackson.core.JsonProcessingException;
57 import com.fasterxml.jackson.databind.JsonMappingException;
58 import com.fasterxml.jackson.databind.ObjectMapper;
59
60 public abstract class AAIRequest {
61     protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
62
63     protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
64
65     protected static final String MASTER_REQUEST = "master-request";
66
67     public static final String RESOURCE_VERSION = "resource-version";
68
69     public static final String DEPTH = "depth";
70
71     protected static Properties configProperties;
72     protected final String targetUri;
73     protected static AAIService aaiService;
74
75     protected AAIDatum requestDatum;
76
77     protected final Properties requestProperties = new Properties();
78
79
80     public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
81
82         String resoource = resoourceName;
83
84         if(resoource == null)
85             return null;
86
87         if(resoource.contains(":")) {
88             String[] tokens = resoource.split(":");
89             if(tokens != null && tokens.length > 0) {
90                 resoource = tokens[0];
91             }
92         }
93
94         if(nameValues.containsKey("selflink")){
95             Class<? extends AAIDatum> clazz = null;
96             try {
97                 clazz = getClassFromResource(resoource) ;
98             } catch (ClassNotFoundException e) {
99                 LOG.warn("AAIRequest does not support class: " + e.getMessage());
100                 return null;
101             }
102
103             if(clazz != null)
104                 return new SelfLinkRequest(clazz);
105             else
106                 return null;
107         }
108
109         switch(resoource){
110         case "generic-query":
111             return new GenericQueryRequest();
112         case "named-query":
113             return new NamedQueryRequest();
114         case "nodes-query":
115             return new NodesQueryRequest();
116         case "custom-query":
117         case "formatted-query":
118             return new CustomQueryRequest();
119         case "echo":
120         case "test":
121             return new EchoRequest();
122
123         case "linterface":
124         case "l2-bridge-sbg":
125         case "l2-bridge-bgf":
126             {
127                 resoource = "l-interface";
128                 AAIRequest request = getRequestFromResource("l-interface");
129                 if(request ==  null) {
130                     return null;
131                 }
132                 return request;
133             }
134
135         default:
136             {
137                 AAIRequest request = getRequestFromResource(resoource);
138                 if(request ==  null) {
139                     return null;
140                 }
141                 return request;
142             }
143         }
144     }
145
146
147     /**
148      * Map containing resource tag to its bit position in bitset mapping
149      */
150     private static Map<String, String> tagValues = new LinkedHashMap<>();
151     /**
152      * Map containing bitset value of the path to its path mapping
153      */
154     private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
155
156
157     public static Set<String> getResourceNames() {
158         return tagValues.keySet();
159     }
160
161
162     public static void setProperties(Properties props, AAIService aaiService) {
163         AAIRequest.configProperties = props;
164         AAIRequest.aaiService = aaiService;
165
166         try
167         {
168             URL url = null;
169             Bundle bundle = FrameworkUtil.getBundle(AAIServiceActivator.class);
170             if(bundle != null) {
171                 BundleContext ctx = bundle.getBundleContext();
172                 if(ctx == null)
173                     return;
174
175                 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
176             } else {
177                 url = aaiService.getClass().getResource("/aai-path.properties");
178             }
179
180             InputStream in = url.openStream();
181             Reader reader = new InputStreamReader(in, "UTF-8");
182
183             Properties properties = new Properties();
184             properties.load(reader);
185             LOG.info("loaded " + properties.size());
186
187             Set<String> keys = properties.stringPropertyNames();
188
189             int index = 0;
190             Set<String> resourceNames = new TreeSet<>();
191
192             for(String key : keys) {
193                 String[] tags = key.split("\\|");
194                 for(String tag : tags) {
195                     if(!resourceNames.contains(tag)) {
196                         resourceNames.add(tag);
197                         tagValues.put(tag, Integer.toString(++index));
198                     }
199                 }
200                 BitSet bs = new BitSet(256);
201                 for(String tag : tags) {
202                     String value = tagValues.get(tag);
203                     Integer bitIndex = Integer.parseInt(value) ;
204                     bs.set(bitIndex);
205                 }
206                 String path = properties.getProperty(key);
207                 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
208                 bitsetPaths.put(bs, path);
209             }
210             LOG.info("loaded " + resourceNames.toString());
211         }
212         catch (Exception e)
213         {
214             LOG.error("Caught exception", e);
215         }
216     }
217
218     public AAIRequest() {
219         targetUri    = configProperties.getProperty(TARGET_URI);
220     }
221
222     public void addRequestProperty(String key, String value) {
223         requestProperties.put(key, value);
224     }
225
226     public final void setRequestObject(AAIDatum value) {
227         requestDatum = value;
228     }
229
230     public final AAIDatum getRequestObject() {
231         return requestDatum;
232     }
233
234     public final void addMasterRequest(AAIRequest masterRequest) {
235         requestProperties.put(MASTER_REQUEST, masterRequest);
236     }
237
238     protected static String encodeQuery(String param) throws UnsupportedEncodingException {
239         return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
240     }
241
242     protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
243         aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
244     }
245
246     public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
247
248         String request_url = null;
249
250         request_url = targetUri + updatePathDataValues(resourceVersion);
251
252         URL http_req_url =    new URL(request_url);
253
254         aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
255
256         return http_req_url;
257     }
258
259     public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
260         String request_url = getRequestPath();
261
262         Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
263
264         for(String resoourceName:uniqueResources) {
265             AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
266             if(locRequest != null) {
267                 Class<?> clazz = locRequest.getClass();
268                 Method function = null;
269                 try {
270                     function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
271                     request_url = (String) function.invoke(null, request_url,  requestProperties);
272                 } catch (Exception e) {
273                     e.printStackTrace();
274                 }
275             }
276         }
277
278         if(resourceVersion != null) {
279             request_url = request_url +"?resource-version="+resourceVersion;
280         }
281
282         return request_url;
283     }
284
285     protected String getRequestPath() throws MalformedURLException {
286         return getRequestPath(null);
287     }
288
289     protected String getRequestPath(String resource) throws MalformedURLException {
290         Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
291         if(resource != null) {
292             // for group search add itself, but remove singular version of itself
293             if(!uniqueResources.contains(resource)) {
294                 boolean replaced =  false;
295                 Set<String> tmpUniqueResources = new HashSet<String>();
296                 tmpUniqueResources.addAll(uniqueResources);
297                 for(String item : tmpUniqueResources){
298                     String plural = item +"s";
299                     if(item.endsWith("y")){
300                         plural = item.substring(0, item.length()-1)+ "ies";
301                     }
302                     if(plural.equals(resource)) {
303                         uniqueResources.remove(item);
304                         uniqueResources.add(resource);
305                         replaced = true;
306                         break;
307                     }
308                 }
309                 if(!replaced){
310                     if(!uniqueResources.contains(resource)) {
311                         uniqueResources.add(resource);
312                     }
313                 }
314             }
315         }
316         BitSet bitset = new BitSet();
317         for(String key : uniqueResources) {
318             if(tagValues.containsKey(key)) {
319                 Object tmpValue = tagValues.get(key);
320                 if(tmpValue != null) {
321                     String value = tmpValue.toString();
322                     int bitIndex = Integer.parseInt(value);
323                     bitset.set(bitIndex);
324                 }
325             }
326         }
327
328         String path = bitsetPaths.get(bitset);
329         if(path == null) {
330             throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
331         }
332         return path;
333     }
334
335     public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException;
336
337     public abstract String toJSONString();
338
339     public abstract String[] getArgsList();
340
341     public abstract Class<? extends AAIDatum> getModelClass() ;
342
343     public String getPrimaryResourceName(String resource) {
344         return resource;
345     }
346
347     public String formatKey(String argument) {
348         return argument;
349     }
350
351     public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
352         if(jsonData == null) {
353             return null;
354         }
355
356         AAIDatum response = null;
357         ObjectMapper mapper = getObjectMapper();
358         response = mapper.readValue(jsonData, getModelClass());
359         return response;
360     }
361
362     protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
363         Set<String> uniqueResources = new TreeSet<>();
364         List<String> keys = new ArrayList<>(keySet);
365         for(String resource : keys) {
366             if(resource.contains(".")) {
367                 String [] split = resource.split("\\.");
368                 uniqueResources.add(split[0].replaceAll("_", "-"));
369             }
370         }
371         return uniqueResources;
372     }
373
374     public void processRequestPathValues(Map<String, String> nameValues) {
375         Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
376
377         Set<String> tokens = new TreeSet<>();
378         tokens.add(DEPTH);
379         tokens.addAll(Arrays.asList(this.getArgsList()));
380
381         for(String resoourceName:uniqueResources) {
382             AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
383             if(locRequest != null)
384                 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
385         }
386
387         String[] arguments = tokens.toArray(new String[0]);
388         for(String name : arguments) {
389             String tmpName = name.replaceAll("-", "_");
390             String value = nameValues.get(tmpName);
391             if(value != null && !value.isEmpty()) {
392                 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
393                 this.addRequestProperty(name, value);
394             }
395         }
396     }
397
398     public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
399         return request_url;
400     }
401
402     public boolean isDeleteDataRequired() {
403         return false;
404     }
405
406     ObjectMapper getObjectMapper() {
407         return AAIService.getObjectMapper();
408     }
409
410     public static Class<? extends AAIDatum> getClassFromResource(String resoourceName) throws ClassNotFoundException {
411         String className = GenericVnf.class.getName();
412         String[] split = resoourceName.split("-");
413         for(int i = 0; i < split.length; i++) {
414             split[i] = StringUtils.capitalize(split[i]);
415         }
416
417         String caps = StringUtils.join(split);
418         className = className.replace("GenericVnf", caps);
419         Class<? extends AAIDatum> clazz = null;
420         try {
421             clazz = (Class<? extends AAIDatum>)Class.forName(className);
422         } catch (ClassNotFoundException e) {
423             LOG.warn("AAIRequest does not support class: " + e.getMessage());
424             return null;
425         }
426
427         return clazz;
428     }
429
430     protected static AAIRequest getRequestFromResource(String resoourceName) {
431
432         Class<? extends AAIDatum> clazz = null;
433         try {
434             clazz = getClassFromResource(resoourceName);
435         } catch (ClassNotFoundException e) {
436             LOG.warn("AAIRequest does not support class: " + e.getMessage());
437             return null;
438         }
439         if(clazz == null) {
440             return null;
441         }
442         GenericRequest request = new GenericRequest(clazz);
443         return request;
444     }
445
446     public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
447         Map<String, String> query_pairs = new LinkedHashMap<>();
448
449         if(query != null && !query.isEmpty()) {
450             String[] pairs = query.split("&");
451             for (String pair : pairs) {
452                 int idx = pair.indexOf('=');
453                 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
454             }
455         }
456         return query_pairs;
457     }
458
459     public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
460         Map<String, String> query_pairs = new LinkedHashMap<>();
461
462         if(path != null && !path.isEmpty()) {
463             String[] pairs = path.split("/");
464             for (String pair : pairs) {
465                 int idx = pair.indexOf('=');
466                 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
467             }
468         }
469         return query_pairs;
470     }
471
472     protected boolean expectsDataFromPUTRequest() {
473         return false;
474     }
475
476
477     public String getTargetUri() {
478         return targetUri;
479     }
480 }