2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
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;
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;
41 import java.util.Properties;
43 import java.util.TreeSet;
45 import org.apache.commons.lang.StringUtils;
46 import org.openecomp.aai.inventory.v11.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;
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;
59 public abstract class AAIRequest {
60 protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
62 protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
64 protected static final String MASTER_REQUEST = "master-request";
66 public static final String RESOURCE_VERSION = "resource-version";
68 public static final String DEPTH = "depth";
70 protected static Properties configProperties;
71 protected final String target_uri;
72 protected static AAIService aaiService;
74 protected AAIDatum requestDatum;
76 protected final Properties requestProperties = new Properties();
79 public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
81 String resoource = resoourceName;
86 if(resoource.contains(":")) {
87 String[] tokens = resoource.split(":");
88 if(tokens != null && tokens.length > 0) {
89 resoource = tokens[0];
93 if(nameValues.containsKey("selflink")){
94 Class<? extends AAIDatum> clazz = null;
96 clazz = getClassFromResource(resoource) ;
97 } catch (ClassNotFoundException e) {
98 LOG.warn("AAIRequest does not support class: " + e.getMessage());
103 return new SelfLinkRequest(clazz);
109 case "generic-query":
110 return new GenericQueryRequest();
112 return new NamedQueryRequest();
114 return new NodesQueryRequest();
116 case "formatted-query":
117 return new CustomQueryRequest();
119 return new LInterfaceRequest(LInterfaceRequest.TYPE.L2_BRIDGE_SBG);
120 case "l2-bridge-sbg":
121 return new SubInterfaceRequest(SubInterfaceRequest.TYPE.L2_BRIDGE_SBG);
122 case "l2-bridge-bgf":
123 return new SubInterfaceRequest(SubInterfaceRequest.TYPE.L2_BRIDGE_BGF);
126 return new EchoRequest();
130 AAIRequest request = getRequestFromResource(resoource);
131 if(request == null) {
141 * Map containing resource tag to its bit position in bitset mapping
143 private static Map<String, String> tagValues = new LinkedHashMap<>();
145 * Map containing bitset value of the path to its path mapping
147 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
150 public static Set<String> getResourceNames() {
151 return tagValues.keySet();
155 public static void setProperties(Properties props, AAIService aaiService) {
156 AAIRequest.configProperties = props;
157 AAIRequest.aaiService = aaiService;
162 Bundle bundle = FrameworkUtil.getBundle(AAIServiceActivator.class);
164 BundleContext ctx = bundle.getBundleContext();
168 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
170 url = aaiService.getClass().getResource("/aai-path.properties");
173 InputStream in = url.openStream();
174 Reader reader = new InputStreamReader(in, "UTF-8");
176 Properties properties = new Properties();
177 properties.load(reader);
178 LOG.info("loaded " + properties.size());
180 Set<String> keys = properties.stringPropertyNames();
183 Set<String> resourceNames = new TreeSet<>();
185 for(String key : keys) {
186 String[] tags = key.split("\\|");
187 for(String tag : tags) {
188 if(!resourceNames.contains(tag)) {
189 resourceNames.add(tag);
190 tagValues.put(tag, Integer.toString(++index));
193 BitSet bs = new BitSet(256);
194 for(String tag : tags) {
195 String value = tagValues.get(tag);
196 Integer bitIndex = Integer.parseInt(value) ;
199 String path = properties.getProperty(key);
200 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
201 bitsetPaths.put(bs, path);
203 LOG.info("loaded " + resourceNames.toString());
207 LOG.error("Caught exception", e);
211 public AAIRequest() {
212 target_uri = configProperties.getProperty(TARGET_URI);
215 public void addRequestProperty(String key, String value) {
216 requestProperties.put(key, value);
219 public final void setRequestObject(AAIDatum value) {
220 requestDatum = value;
223 public final AAIDatum getRequestObject() {
227 public final void addMasterRequest(AAIRequest masterRequest) {
228 requestProperties.put(MASTER_REQUEST, masterRequest);
231 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
232 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
235 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
236 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
239 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
241 String request_url = null;
243 request_url = target_uri + updatePathDataValues(resourceVersion);
245 URL http_req_url = new URL(request_url);
247 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
252 public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
253 String request_url = getRequestPath();
255 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
257 for(String resoourceName:uniqueResources) {
258 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
259 if(locRequest != null) {
260 Class<?> clazz = locRequest.getClass();
261 Method function = null;
263 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
264 request_url = (String) function.invoke(null, request_url, requestProperties);
265 } catch (Exception e) {
271 if(resourceVersion != null) {
272 request_url = request_url +"?resource-version="+resourceVersion;
279 protected String getRequestPath() throws MalformedURLException {
280 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
281 BitSet bitset = new BitSet();
282 for(String key : uniqueResources) {
283 if(tagValues.containsKey(key)) {
284 Object tmpValue = tagValues.get(key);
285 if(tmpValue != null) {
286 String value = tmpValue.toString();
287 int bitIndex = Integer.parseInt(value);
288 bitset.set(bitIndex);
293 String path = bitsetPaths.get(bitset);
295 throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
300 public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException;
302 public abstract String toJSONString();
304 public abstract String[] getArgsList();
306 public abstract Class<? extends AAIDatum> getModelClass() ;
308 public String getPrimaryResourceName(String resource) {
312 public String formatKey(String argument) {
316 public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
317 if(jsonData == null) {
321 AAIDatum response = null;
322 ObjectMapper mapper = getObjectMapper();
323 response = mapper.readValue(jsonData, getModelClass());
327 protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
328 Set<String> uniqueResources = new TreeSet<>();
329 List<String> keys = new ArrayList<>(keySet);
330 for(String resource : keys) {
331 if(resource.contains(".")) {
332 String [] split = resource.split("\\.");
333 uniqueResources.add(split[0].replaceAll("_", "-"));
336 return uniqueResources;
339 public void processRequestPathValues(Map<String, String> nameValues) {
340 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
342 Set<String> tokens = new TreeSet<>();
344 tokens.addAll(Arrays.asList(this.getArgsList()));
346 for(String resoourceName:uniqueResources) {
347 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
348 if(locRequest != null)
349 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
352 String[] arguments = tokens.toArray(new String[0]);
353 for(String name : arguments) {
354 String tmpName = name.replaceAll("-", "_");
355 String value = nameValues.get(tmpName);
356 if(value != null && !value.isEmpty()) {
357 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
358 this.addRequestProperty(name, value);
363 public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
367 public boolean isDeleteDataRequired() {
371 ObjectMapper getObjectMapper() {
372 return AAIService.getObjectMapper();
375 public static Class<? extends AAIDatum> getClassFromResource(String resoourceName) throws ClassNotFoundException {
376 String className = GenericVnf.class.getName();
377 String[] split = resoourceName.split("-");
378 for(int i = 0; i < split.length; i++) {
379 split[i] = StringUtils.capitalize(split[i]);
382 String caps = StringUtils.join(split);
383 className = className.replace("GenericVnf", caps);
384 Class<? extends AAIDatum> clazz = null;
386 clazz = (Class<? extends AAIDatum>)Class.forName(className);
387 } catch (ClassNotFoundException e) {
388 LOG.warn("AAIRequest does not support class: " + e.getMessage());
395 protected static AAIRequest getRequestFromResource(String resoourceName) {
397 Class<? extends AAIDatum> clazz = null;
399 clazz = getClassFromResource(resoourceName);
400 } catch (ClassNotFoundException e) {
401 LOG.warn("AAIRequest does not support class: " + e.getMessage());
407 GenericRequest request = new GenericRequest(clazz);
411 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
412 Map<String, String> query_pairs = new LinkedHashMap<>();
414 if(query != null && !query.isEmpty()) {
415 String[] pairs = query.split("&");
416 for (String pair : pairs) {
417 int idx = pair.indexOf('=');
418 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
424 public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
425 Map<String, String> query_pairs = new LinkedHashMap<>();
427 if(path != null && !path.isEmpty()) {
428 String[] pairs = path.split("/");
429 for (String pair : pairs) {
430 int idx = pair.indexOf('=');
431 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
437 protected boolean expectsDataFromPUTRequest() {