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;
31 import java.net.URISyntaxException;
33 import java.net.URLDecoder;
34 import java.net.URLEncoder;
35 import java.nio.charset.StandardCharsets;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.BitSet;
39 import java.util.HashSet;
40 import java.util.HashMap;
41 import java.util.LinkedHashMap;
42 import java.util.List;
44 import java.util.Properties;
46 import java.util.TreeSet;
48 import org.apache.commons.lang.StringUtils;
49 import org.onap.aai.inventory.v14.GenericVnf;
50 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
51 import org.osgi.framework.Bundle;
52 import org.osgi.framework.BundleContext;
53 import org.osgi.framework.FrameworkUtil;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 import com.fasterxml.jackson.core.JsonParseException;
58 import com.fasterxml.jackson.core.JsonProcessingException;
59 import com.fasterxml.jackson.databind.JsonMappingException;
60 import com.fasterxml.jackson.databind.ObjectMapper;
62 public abstract class AAIRequest {
63 protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
65 protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
67 protected static final String MASTER_REQUEST = "master-request";
69 public static final String RESOURCE_VERSION = "resource-version";
71 public static final String DEPTH = "depth";
73 protected static Properties configProperties;
74 protected final String targetUri;
75 protected static AAIService aaiService;
77 protected AAIDatum requestDatum;
79 protected final Properties requestProperties = new Properties();
82 public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
84 String resoource = resoourceName;
85 String masterResource = null;
90 if(resoource.contains(":")) {
91 String[] tokens = resoource.split(":");
92 if(tokens != null && tokens.length == 2) {
93 resoource = tokens[1];
94 masterResource = tokens[0];
95 Class<? extends AAIDatum> clazz = getClassFromResource(resoource) ;
103 if(nameValues.containsKey("selflink")){
104 Class<? extends AAIDatum> clazz = getClassFromResource(resoource) ;
107 return new SelfLinkRequest(clazz);
113 case "generic-query":
114 return new GenericQueryRequest();
116 return new NamedQueryRequest();
118 return new NodesQueryRequest();
120 case "formatted-query":
121 return new CustomQueryRequest();
124 return new EchoRequest();
127 case "l2-bridge-sbg":
128 case "l2-bridge-bgf":
130 resoource = "l-interface";
131 return getRequestFromResource("l-interface");
133 case "relationship-list":
134 return new RelationshipListRequest(AAIRequest.createRequest(masterResource, nameValues));
136 return new RelationshipRequest(AAIRequest.createRequest(masterResource, nameValues));
138 return getRequestFromResource(resoource);
144 * Map containing resource tag to its bit position in bitset mapping
146 private static Map<String, String> tagValues = new LinkedHashMap<>();
148 * Map containing bitset value of the path to its path mapping
150 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
153 public static Set<String> getResourceNames() {
154 return tagValues.keySet();
158 public static void setProperties(Properties props, AAIService aaiService) {
159 AAIRequest.configProperties = props;
160 AAIRequest.aaiService = aaiService;
165 Bundle bundle = FrameworkUtil.getBundle(AAIService.class);
167 BundleContext ctx = bundle.getBundleContext();
171 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
173 url = aaiService.getClass().getResource("/aai-path.properties");
176 InputStream in = url.openStream();
177 Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
179 Properties properties = new Properties();
180 properties.load(reader);
181 LOG.info("loaded " + properties.size());
183 Set<String> keys = properties.stringPropertyNames();
186 Set<String> resourceNames = new TreeSet<>();
188 for(String key : keys) {
189 String[] tags = key.split("\\|");
190 for(String tag : tags) {
191 if(!resourceNames.contains(tag)) {
192 resourceNames.add(tag);
193 tagValues.put(tag, Integer.toString(++index));
196 BitSet bs = new BitSet(256);
197 for(String tag : tags) {
198 String value = tagValues.get(tag);
199 Integer bitIndex = Integer.parseInt(value) ;
202 String path = properties.getProperty(key);
203 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
204 bitsetPaths.put(bs, path);
206 LOG.info("loaded " + resourceNames.toString());
210 LOG.error("Caught exception", e);
214 public AAIRequest() {
215 targetUri = configProperties.getProperty(TARGET_URI);
218 public void addRequestProperty(String key, String value) {
219 requestProperties.put(key, value);
222 public final void setRequestObject(AAIDatum value) {
223 requestDatum = value;
226 public final AAIDatum getRequestObject() {
230 public final void addMasterRequest(AAIRequest masterRequest) {
231 requestProperties.put(MASTER_REQUEST, masterRequest);
234 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
235 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
238 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
239 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
242 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
244 String request_url = null;
246 request_url = targetUri + updatePathDataValues(resourceVersion);
248 URL http_req_url = new URL(request_url);
250 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
255 public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
256 String request_url = getRequestPath();
258 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
260 for(String resoourceName:uniqueResources) {
261 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
262 if(locRequest != null) {
263 Class<?> clazz = locRequest.getClass();
264 Method function = null;
266 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
267 request_url = (String) function.invoke(null, request_url, requestProperties);
268 } catch (Exception e) {
274 if(resourceVersion != null) {
275 request_url = request_url +"?resource-version="+resourceVersion;
281 protected String getRequestPath() throws MalformedURLException {
282 return getRequestPath(null);
285 protected String getRequestPath(String resource) throws MalformedURLException {
286 if(requestProperties.containsKey("resource-path")) {
287 return requestProperties.getProperty("resource-path");
290 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
291 if(resource != null) {
292 // for group search add itself, but remove singular version of itself
293 if(!uniqueResources.contains(resource)) {
294 boolean replaced = false;
295 Set<String> tmpUniqueResources = new HashSet<String>();
296 tmpUniqueResources.addAll(uniqueResources);
297 for(String item : tmpUniqueResources){
298 String plural = item +"s";
299 if(item.endsWith("y")){
300 plural = item.substring(0, item.length()-1)+ "ies";
302 if(plural.equals(resource)) {
303 uniqueResources.remove(item);
304 uniqueResources.add(resource);
310 if(!uniqueResources.contains(resource)) {
311 uniqueResources.add(resource);
316 BitSet bitset = new BitSet();
317 for(String key : uniqueResources) {
318 if(tagValues.containsKey(key)) {
319 Object tmpValue = tagValues.get(key);
320 if(tmpValue != null) {
321 String value = tmpValue.toString();
322 int bitIndex = Integer.parseInt(value);
323 bitset.set(bitIndex);
328 String path = bitsetPaths.get(bitset);
330 throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
335 public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException;
337 public abstract String toJSONString();
339 public abstract String[] getArgsList();
341 public abstract Class<? extends AAIDatum> getModelClass() ;
343 public String getPrimaryResourceName(String resource) {
347 public String formatKey(String argument) {
351 public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
352 if(jsonData == null) {
356 AAIDatum response = null;
357 ObjectMapper mapper = getObjectMapper();
358 response = mapper.readValue(jsonData, getModelClass());
362 protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
363 Set<String> uniqueResources = new TreeSet<>();
364 List<String> keys = new ArrayList<>(keySet);
365 for(String resource : keys) {
366 if(resource.contains(".")) {
367 String [] split = resource.split("\\.");
368 uniqueResources.add(split[0].replaceAll("_", "-"));
371 return uniqueResources;
374 public void processRequestPathValues(Map<String, String> nameValues) {
375 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
377 Set<String> tokens = new TreeSet<>();
379 tokens.addAll(Arrays.asList(this.getArgsList()));
381 for(String resoourceName:uniqueResources) {
382 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
383 if(locRequest != null)
384 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
387 String[] arguments = tokens.toArray(new String[0]);
388 for(String name : arguments) {
389 String tmpName = name.replaceAll("-", "_");
390 String value = nameValues.get(tmpName);
391 if(value != null && !value.isEmpty()) {
392 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
393 this.addRequestProperty(name, value);
398 public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
402 public boolean isDeleteDataRequired() {
406 ObjectMapper getObjectMapper() {
407 return AAIService.getObjectMapper();
410 public static Class<? extends AAIDatum> getClassFromResource(String resoourceName) {
411 String className = GenericVnf.class.getName();
412 String[] split = resoourceName.split("-");
413 for(int i = 0; i < split.length; i++) {
414 split[i] = StringUtils.capitalize(split[i]);
417 String caps = StringUtils.join(split);
418 className = className.replace("GenericVnf", caps);
420 return (Class<? extends AAIDatum>)Class.forName(className);
421 } catch (ClassNotFoundException e) {
422 LOG.warn("AAIRequest does not support class: " + e.getMessage());
427 protected static AAIRequest getRequestFromResource(String resoourceName) {
429 Class<? extends AAIDatum> clazz = getClassFromResource(resoourceName);
434 GenericRequest request = new GenericRequest(clazz);
438 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
439 Map<String, String> query_pairs = new LinkedHashMap<>();
441 if(query != null && !query.isEmpty()) {
442 String[] pairs = query.split("&");
443 for (String pair : pairs) {
444 int idx = pair.indexOf('=');
445 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
451 public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
452 Map<String, String> query_pairs = new LinkedHashMap<>();
454 if(path != null && !path.isEmpty()) {
455 String[] pairs = path.split("/");
456 for (String pair : pairs) {
457 int idx = pair.indexOf('=');
458 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
464 protected boolean expectsDataFromPUTRequest() {
469 public String getTargetUri() {
473 public static final String getSupportedAAIVersion() {
474 return configProperties.getProperty(AAIDeclarations.AAI_VERSION, "/v14/");