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