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