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 package org.onap.ccsdk.sli.adaptors.aai;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.Reader;
30 import java.io.UnsupportedEncodingException;
31 import java.lang.reflect.Method;
32 import java.net.MalformedURLException;
33 import java.net.URISyntaxException;
35 import java.net.URLDecoder;
36 import java.net.URLEncoder;
37 import java.nio.charset.StandardCharsets;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.BitSet;
41 import java.util.HashSet;
42 import java.util.HashMap;
43 import java.util.LinkedHashMap;
44 import java.util.List;
46 import java.util.Properties;
48 import java.util.TreeSet;
50 import org.apache.commons.lang.StringUtils;
51 import org.onap.aai.inventory.v14.GenericVnf;
52 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
53 import org.osgi.framework.Bundle;
54 import org.osgi.framework.BundleContext;
55 import org.osgi.framework.FrameworkUtil;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import com.fasterxml.jackson.core.JsonParseException;
60 import com.fasterxml.jackson.core.JsonProcessingException;
61 import com.fasterxml.jackson.databind.JsonMappingException;
62 import com.fasterxml.jackson.databind.ObjectMapper;
64 public abstract class AAIRequest {
65 protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
67 protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
69 protected static final String MASTER_REQUEST = "master-request";
71 public static final String RESOURCE_VERSION = "resource-version";
73 public static final String DEPTH = "depth";
75 protected static Properties configProperties;
76 protected final String targetUri;
77 protected static AAIService aaiService;
79 protected AAIDatum requestDatum;
81 protected final Properties requestProperties = new Properties();
84 public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
86 String resoource = resoourceName;
87 String masterResource = null;
92 if(resoource.contains(":")) {
93 String[] tokens = resoource.split(":");
94 if(tokens != null && tokens.length == 2) {
95 resoource = tokens[1];
96 masterResource = tokens[0];
97 Class<? extends AAIDatum> clazz = getClassFromResource(resoource) ;
105 if(nameValues.containsKey("selflink")){
106 Class<? extends AAIDatum> clazz = getClassFromResource(resoource) ;
109 return new SelfLinkRequest(clazz);
115 case "generic-query":
116 return new GenericQueryRequest();
118 return new NamedQueryRequest();
120 return new NodesQueryRequest();
122 case "formatted-query":
123 return new CustomQueryRequest();
126 return new EchoRequest();
129 case "l2-bridge-sbg":
130 case "l2-bridge-bgf":
132 resoource = "l-interface";
133 return getRequestFromResource("l-interface");
135 case "relationship-list":
136 return new RelationshipListRequest(AAIRequest.createRequest(masterResource, nameValues));
138 return new RelationshipRequest(AAIRequest.createRequest(masterResource, nameValues));
140 return getRequestFromResource(resoource);
146 * Map containing resource tag to its bit position in bitset mapping
148 private static Map<String, String> tagValues = new LinkedHashMap<>();
150 * Map containing bitset value of the path to its path mapping
152 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
155 public static Set<String> getResourceNames() {
156 return tagValues.keySet();
160 public static void setProperties(Properties props, AAIService aaiService) {
161 AAIRequest.configProperties = props;
162 AAIRequest.aaiService = aaiService;
167 Bundle bundle = FrameworkUtil.getBundle(AAIService.class);
169 BundleContext ctx = bundle.getBundleContext();
173 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
175 url = aaiService.getClass().getResource("/aai-path.properties");
178 InputStream in = url.openStream();
179 Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
181 Properties properties = new Properties();
182 properties.load(reader);
183 LOG.info("loaded " + properties.size());
185 Set<String> keys = properties.stringPropertyNames();
188 Set<String> resourceNames = new TreeSet<>();
190 for(String key : keys) {
191 String[] tags = key.split("\\|");
192 for(String tag : tags) {
193 if(!resourceNames.contains(tag)) {
194 resourceNames.add(tag);
195 tagValues.put(tag, Integer.toString(++index));
198 BitSet bs = new BitSet(256);
199 for(String tag : tags) {
200 String value = tagValues.get(tag);
201 Integer bitIndex = Integer.parseInt(value) ;
204 String path = properties.getProperty(key);
205 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
206 bitsetPaths.put(bs, path);
208 LOG.info("loaded " + resourceNames.toString());
212 LOG.error("Caught exception", e);
216 public AAIRequest() {
217 targetUri = configProperties.getProperty(TARGET_URI);
220 public void addRequestProperty(String key, String value) {
221 requestProperties.put(key, value);
224 public final void setRequestObject(AAIDatum value) {
225 requestDatum = value;
228 public final AAIDatum getRequestObject() {
232 public final void addMasterRequest(AAIRequest masterRequest) {
233 requestProperties.put(MASTER_REQUEST, masterRequest);
236 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
237 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
240 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
241 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
244 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
246 String request_url = null;
248 request_url = targetUri + updatePathDataValues(resourceVersion);
250 URL http_req_url = new URL(request_url);
252 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
257 public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
258 String request_url = getRequestPath();
260 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
262 for(String resoourceName:uniqueResources) {
263 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
264 if(locRequest != null) {
265 Class<?> clazz = locRequest.getClass();
266 Method function = null;
268 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
269 request_url = (String) function.invoke(null, request_url, requestProperties);
270 } catch (Exception e) {
271 LOG.error("Caught exception", e);
276 if(resourceVersion != null) {
277 request_url = request_url +"?resource-version="+resourceVersion;
283 protected String getRequestPath() throws MalformedURLException {
284 return getRequestPath(null);
287 protected String getRequestPath(String resource) throws MalformedURLException {
288 if(requestProperties.containsKey("resource-path")) {
289 return requestProperties.getProperty("resource-path");
292 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
293 if(resource != null) {
294 // for group search add itself, but remove singular version of itself
295 if(!uniqueResources.contains(resource)) {
296 boolean replaced = false;
297 Set<String> tmpUniqueResources = new HashSet<>();
298 tmpUniqueResources.addAll(uniqueResources);
299 for(String item : tmpUniqueResources){
300 String plural = item +"s";
301 if(item.endsWith("y")){
302 plural = item.substring(0, item.length()-1)+ "ies";
304 if(plural.equals(resource)) {
305 uniqueResources.remove(item);
306 uniqueResources.add(resource);
312 if(!uniqueResources.contains(resource)) {
313 uniqueResources.add(resource);
318 BitSet bitset = new BitSet();
319 for(String key : uniqueResources) {
320 if(tagValues.containsKey(key)) {
321 Object tmpValue = tagValues.get(key);
322 if(tmpValue != null) {
323 String value = tmpValue.toString();
324 int bitIndex = Integer.parseInt(value);
325 bitset.set(bitIndex);
330 String path = bitsetPaths.get(bitset);
332 throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
337 public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException;
339 public abstract String toJSONString();
341 public abstract String[] getArgsList();
343 public abstract Class<? extends AAIDatum> getModelClass() ;
345 public String getPrimaryResourceName(String resource) {
349 public String formatKey(String argument) {
353 public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
354 if(jsonData == null) {
358 AAIDatum response = null;
359 ObjectMapper mapper = getObjectMapper();
360 response = mapper.readValue(jsonData, getModelClass());
364 protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
365 Set<String> uniqueResources = new TreeSet<>();
366 List<String> keys = new ArrayList<>(keySet);
367 for(String resource : keys) {
368 if(resource.contains(".")) {
369 String [] split = resource.split("\\.");
370 uniqueResources.add(split[0].replaceAll("_", "-"));
373 return uniqueResources;
376 public void processRequestPathValues(Map<String, String> nameValues) {
377 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
379 Set<String> tokens = new TreeSet<>();
381 tokens.addAll(Arrays.asList(this.getArgsList()));
383 for(String resoourceName:uniqueResources) {
384 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
385 if(locRequest != null)
386 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
389 String[] arguments = tokens.toArray(new String[0]);
390 for(String name : arguments) {
391 String tmpName = name.replaceAll("-", "_");
392 String value = nameValues.get(tmpName);
393 if(value != null && !value.isEmpty()) {
394 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
395 this.addRequestProperty(name, value);
400 public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
404 public boolean isDeleteDataRequired() {
408 ObjectMapper getObjectMapper() {
409 return AAIService.getObjectMapper();
412 public static Class<? extends AAIDatum> getClassFromResource(String resoourceName) {
413 String className = GenericVnf.class.getName();
414 String[] split = resoourceName.split("-");
415 for(int i = 0; i < split.length; i++) {
416 split[i] = StringUtils.capitalize(split[i]);
419 String caps = StringUtils.join(split);
420 className = className.replace("GenericVnf", caps);
422 return (Class<? extends AAIDatum>)Class.forName(className);
423 } catch (ClassNotFoundException e) {
424 LOG.warn("AAIRequest does not support class: " + e.getMessage());
429 protected static AAIRequest getRequestFromResource(String resoourceName) {
431 Class<? extends AAIDatum> clazz = getClassFromResource(resoourceName);
436 return new GenericRequest(clazz);
439 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
440 Map<String, String> query_pairs = new LinkedHashMap<>();
442 if(query != null && !query.isEmpty()) {
443 String[] pairs = query.split("&");
444 for (String pair : pairs) {
445 int idx = pair.indexOf('=');
446 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
452 public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
453 Map<String, String> query_pairs = new LinkedHashMap<>();
455 if(path != null && !path.isEmpty()) {
456 String[] pairs = path.split("/");
457 for (String pair : pairs) {
458 int idx = pair.indexOf('=');
459 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
465 protected boolean expectsDataFromPUTRequest() {
470 public String getTargetUri() {
474 public static final String getSupportedAAIVersion() {
475 return configProperties.getProperty(AAIDeclarations.AAI_VERSION, "/v14/");