2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
14 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
24 * @author Rich Tabedzki
27 package org.onap.ccsdk.sli.adaptors.aai;
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;
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;
49 import java.util.Properties;
51 import java.util.TreeSet;
53 import org.apache.commons.lang.StringUtils;
54 import org.onap.aai.inventory.v16.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;
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;
67 public abstract class AAIRequest {
68 protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
70 protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
72 protected static final String MASTER_REQUEST = "master-request";
74 public static final String RESOURCE_VERSION = "resource-version";
76 public static final String DEPTH = "depth";
78 protected static Properties configProperties;
79 protected final String targetUri;
80 protected static AAIService aaiService;
82 protected AAIDatum requestDatum;
84 protected final Properties requestProperties = new Properties();
87 public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
89 String resoource = resoourceName;
90 String masterResource = null;
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) ;
108 if(nameValues.containsKey("selflink")){
109 Class<? extends AAIDatum> clazz = getClassFromResource(resoource) ;
112 return new SelfLinkRequest(clazz);
118 case "generic-query":
119 return new GenericQueryRequest();
121 return new NodesQueryRequest();
123 case "formatted-query":
124 return new CustomQueryRequest();
127 return new EchoRequest();
130 case "l2-bridge-sbg":
131 case "l2-bridge-bgf":
133 resoource = "l-interface";
134 return getRequestFromResource("l-interface");
136 case "relationship-list":
137 return new RelationshipListRequest(AAIRequest.createRequest(masterResource, nameValues));
139 return new RelationshipRequest(AAIRequest.createRequest(masterResource, nameValues));
141 return getRequestFromResource(resoource);
147 * Map containing resource tag to its bit position in bitset mapping
149 private static Map<String, String> tagValues = new LinkedHashMap<>();
151 * Map containing bitset value of the path to its path mapping
153 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
156 public static Set<String> getResourceNames() {
157 return tagValues.keySet();
161 public static void setProperties(Properties props, AAIService aaiService) {
162 AAIRequest.configProperties = props;
163 AAIRequest.aaiService = aaiService;
168 Bundle bundle = FrameworkUtil.getBundle(AAIService.class);
170 BundleContext ctx = bundle.getBundleContext();
174 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
176 url = aaiService.getClass().getResource("/aai-path.properties");
179 InputStream in = url.openStream();
180 Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
182 Properties properties = new Properties();
183 properties.load(reader);
184 LOG.info("loaded " + properties.size());
186 Set<String> keys = properties.stringPropertyNames();
189 Set<String> resourceNames = new TreeSet<>();
191 for(String key : keys) {
192 String[] tags = key.split("\\|");
193 for(String tag : tags) {
194 if(!resourceNames.contains(tag)) {
195 resourceNames.add(tag);
196 tagValues.put(tag, Integer.toString(++index));
199 BitSet bs = new BitSet(256);
200 for(String tag : tags) {
201 String value = tagValues.get(tag);
202 Integer bitIndex = Integer.parseInt(value) ;
205 String path = properties.getProperty(key);
206 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
207 bitsetPaths.put(bs, path);
209 LOG.info("loaded " + resourceNames.toString());
213 LOG.error("Caught exception", e);
217 public AAIRequest() {
218 targetUri = configProperties.getProperty(TARGET_URI);
221 public void addRequestProperty(String key, String value) {
222 requestProperties.put(key, value);
225 public final void setRequestObject(AAIDatum value) {
226 requestDatum = value;
229 public final AAIDatum getRequestObject() {
233 public final void addMasterRequest(AAIRequest masterRequest) {
234 requestProperties.put(MASTER_REQUEST, masterRequest);
237 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
238 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
241 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
242 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
245 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
247 String request_url = null;
249 request_url = targetUri + updatePathDataValues(resourceVersion);
251 URL http_req_url = new URL(request_url);
253 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
258 public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
259 String request_url = getRequestPath();
261 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
263 for(String resoourceName:uniqueResources) {
264 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
265 if(locRequest != null) {
266 Class<?> clazz = locRequest.getClass();
267 Method function = null;
269 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
270 request_url = (String) function.invoke(null, request_url, requestProperties);
271 } catch (Exception e) {
272 LOG.error("Caught exception", e);
277 if(resourceVersion != null) {
278 request_url = request_url +"?resource-version="+resourceVersion;
284 protected String getRequestPath() throws MalformedURLException {
285 return getRequestPath(null);
288 protected String getRequestPath(String resource) throws MalformedURLException {
289 if(requestProperties.containsKey("resource-path")) {
290 return requestProperties.getProperty("resource-path");
293 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
294 if(resource != null) {
295 // for group search add itself, but remove singular version of itself
296 if(!uniqueResources.contains(resource)) {
297 boolean replaced = false;
298 Set<String> tmpUniqueResources = new HashSet<>();
299 tmpUniqueResources.addAll(uniqueResources);
300 for(String item : tmpUniqueResources){
301 String plural = item +"s";
302 if(item.endsWith("y")){
303 plural = item.substring(0, item.length()-1)+ "ies";
305 if(plural.equals(resource)) {
306 uniqueResources.remove(item);
307 uniqueResources.add(resource);
313 if(!uniqueResources.contains(resource)) {
314 uniqueResources.add(resource);
319 BitSet bitset = new BitSet();
320 for(String key : uniqueResources) {
321 if(tagValues.containsKey(key)) {
322 Object tmpValue = tagValues.get(key);
323 if(tmpValue != null) {
324 String value = tmpValue.toString();
325 int bitIndex = Integer.parseInt(value);
326 bitset.set(bitIndex);
331 String path = bitsetPaths.get(bitset);
333 throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
338 public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException;
340 public abstract String toJSONString();
342 public abstract String[] getArgsList();
344 public abstract Class<? extends AAIDatum> getModelClass() ;
346 public String getPrimaryResourceName(String resource) {
350 public String formatKey(String argument) {
354 public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
355 if(jsonData == null) {
359 AAIDatum response = null;
360 ObjectMapper mapper = getObjectMapper();
361 response = mapper.readValue(jsonData, getModelClass());
365 protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
366 Set<String> uniqueResources = new TreeSet<>();
367 List<String> keys = new ArrayList<>(keySet);
368 for(String resource : keys) {
369 if(resource.contains(".")) {
370 String [] split = resource.split("\\.");
371 uniqueResources.add(split[0].replaceAll("_", "-"));
374 return uniqueResources;
377 public void processRequestPathValues(Map<String, String> nameValues) {
378 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
380 Set<String> tokens = new TreeSet<>();
382 tokens.addAll(Arrays.asList(this.getArgsList()));
384 for(String resoourceName:uniqueResources) {
385 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
386 if(locRequest != null)
387 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
390 String[] arguments = tokens.toArray(new String[0]);
391 for(String name : arguments) {
392 String tmpName = name.replaceAll("-", "_");
393 String value = nameValues.get(tmpName);
394 if(value != null && !value.isEmpty()) {
395 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
396 this.addRequestProperty(name, value);
401 public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
405 public boolean isDeleteDataRequired() {
409 ObjectMapper getObjectMapper() {
410 return AAIService.getObjectMapper();
413 public static Class<? extends AAIDatum> getClassFromResource(String resoourceName) {
414 String className = GenericVnf.class.getName();
415 String[] split = resoourceName.split("-");
416 for(int i = 0; i < split.length; i++) {
417 split[i] = StringUtils.capitalize(split[i]);
420 String caps = StringUtils.join(split);
421 className = className.replace("GenericVnf", caps);
423 return (Class<? extends AAIDatum>)Class.forName(className);
424 } catch (ClassNotFoundException e) {
425 LOG.warn("AAIRequest does not support class: " + e.getMessage());
430 protected static AAIRequest getRequestFromResource(String resoourceName) {
432 Class<? extends AAIDatum> clazz = getClassFromResource(resoourceName);
437 return new GenericRequest(clazz);
440 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
441 Map<String, String> query_pairs = new LinkedHashMap<>();
443 if(query != null && !query.isEmpty()) {
444 String[] pairs = query.split("&");
445 for (String pair : pairs) {
446 int idx = pair.indexOf('=');
447 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
453 public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
454 Map<String, String> query_pairs = new LinkedHashMap<>();
456 if(path != null && !path.isEmpty()) {
457 String[] pairs = path.split("/");
458 for (String pair : pairs) {
459 int idx = pair.indexOf('=');
460 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
466 protected boolean expectsDataFromPUTRequest() {
471 public String getTargetUri() {
475 public static final String getSupportedAAIVersion() {
476 return configProperties.getProperty(AAIDeclarations.AAI_VERSION, "/v16/");