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.HashSet;
38 import java.util.HashMap;
39 import java.util.LinkedHashMap;
40 import java.util.List;
42 import java.util.Properties;
44 import java.util.TreeSet;
46 import org.apache.commons.lang.StringUtils;
47 import org.openecomp.aai.inventory.v11.GenericVnf;
48 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
49 import org.osgi.framework.Bundle;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 import com.fasterxml.jackson.core.JsonParseException;
56 import com.fasterxml.jackson.core.JsonProcessingException;
57 import com.fasterxml.jackson.databind.JsonMappingException;
58 import com.fasterxml.jackson.databind.ObjectMapper;
60 public abstract class AAIRequest {
61 protected static final Logger LOG = LoggerFactory.getLogger(AAIRequest.class);
63 protected static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
65 protected static final String MASTER_REQUEST = "master-request";
67 public static final String RESOURCE_VERSION = "resource-version";
69 public static final String DEPTH = "depth";
71 protected static Properties configProperties;
72 protected final String targetUri;
73 protected static AAIService aaiService;
75 protected AAIDatum requestDatum;
77 protected final Properties requestProperties = new Properties();
80 public static AAIRequest createRequest(String resoourceName, Map<String, String> nameValues){
82 String resoource = resoourceName;
87 if(resoource.contains(":")) {
88 String[] tokens = resoource.split(":");
89 if(tokens != null && tokens.length > 0) {
90 resoource = tokens[0];
94 if(nameValues.containsKey("selflink")){
95 Class<? extends AAIDatum> clazz = null;
97 clazz = getClassFromResource(resoource) ;
98 } catch (ClassNotFoundException e) {
99 LOG.warn("AAIRequest does not support class: " + e.getMessage());
104 return new SelfLinkRequest(clazz);
110 case "generic-query":
111 return new GenericQueryRequest();
113 return new NamedQueryRequest();
115 return new NodesQueryRequest();
117 case "formatted-query":
118 return new CustomQueryRequest();
121 return new EchoRequest();
124 case "l2-bridge-sbg":
125 case "l2-bridge-bgf":
127 resoource = "l-interface";
128 AAIRequest request = getRequestFromResource("l-interface");
129 if(request == null) {
137 AAIRequest request = getRequestFromResource(resoource);
138 if(request == null) {
148 * Map containing resource tag to its bit position in bitset mapping
150 private static Map<String, String> tagValues = new LinkedHashMap<>();
152 * Map containing bitset value of the path to its path mapping
154 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<>();
157 public static Set<String> getResourceNames() {
158 return tagValues.keySet();
162 public static void setProperties(Properties props, AAIService aaiService) {
163 AAIRequest.configProperties = props;
164 AAIRequest.aaiService = aaiService;
169 Bundle bundle = FrameworkUtil.getBundle(AAIServiceActivator.class);
171 BundleContext ctx = bundle.getBundleContext();
175 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
177 url = aaiService.getClass().getResource("/aai-path.properties");
180 InputStream in = url.openStream();
181 Reader reader = new InputStreamReader(in, "UTF-8");
183 Properties properties = new Properties();
184 properties.load(reader);
185 LOG.info("loaded " + properties.size());
187 Set<String> keys = properties.stringPropertyNames();
190 Set<String> resourceNames = new TreeSet<>();
192 for(String key : keys) {
193 String[] tags = key.split("\\|");
194 for(String tag : tags) {
195 if(!resourceNames.contains(tag)) {
196 resourceNames.add(tag);
197 tagValues.put(tag, Integer.toString(++index));
200 BitSet bs = new BitSet(256);
201 for(String tag : tags) {
202 String value = tagValues.get(tag);
203 Integer bitIndex = Integer.parseInt(value) ;
206 String path = properties.getProperty(key);
207 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
208 bitsetPaths.put(bs, path);
210 LOG.info("loaded " + resourceNames.toString());
214 LOG.error("Caught exception", e);
218 public AAIRequest() {
219 targetUri = configProperties.getProperty(TARGET_URI);
222 public void addRequestProperty(String key, String value) {
223 requestProperties.put(key, value);
226 public final void setRequestObject(AAIDatum value) {
227 requestDatum = value;
230 public final AAIDatum getRequestObject() {
234 public final void addMasterRequest(AAIRequest masterRequest) {
235 requestProperties.put(MASTER_REQUEST, masterRequest);
238 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
239 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
242 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
243 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
246 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
248 String request_url = null;
250 request_url = targetUri + updatePathDataValues(resourceVersion);
252 URL http_req_url = new URL(request_url);
254 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
259 public String updatePathDataValues(Object resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
260 String request_url = getRequestPath();
262 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
264 for(String resoourceName:uniqueResources) {
265 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
266 if(locRequest != null) {
267 Class<?> clazz = locRequest.getClass();
268 Method function = null;
270 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
271 request_url = (String) function.invoke(null, request_url, requestProperties);
272 } catch (Exception e) {
278 if(resourceVersion != null) {
279 request_url = request_url +"?resource-version="+resourceVersion;
285 protected String getRequestPath() throws MalformedURLException {
286 return getRequestPath(null);
289 protected String getRequestPath(String resource) throws MalformedURLException {
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;
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) throws ClassNotFoundException {
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);
419 Class<? extends AAIDatum> clazz = null;
421 clazz = (Class<? extends AAIDatum>)Class.forName(className);
422 } catch (ClassNotFoundException e) {
423 LOG.warn("AAIRequest does not support class: " + e.getMessage());
430 protected static AAIRequest getRequestFromResource(String resoourceName) {
432 Class<? extends AAIDatum> clazz = null;
434 clazz = getClassFromResource(resoourceName);
435 } catch (ClassNotFoundException e) {
436 LOG.warn("AAIRequest does not support class: " + e.getMessage());
442 GenericRequest request = new GenericRequest(clazz);
446 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
447 Map<String, String> query_pairs = new LinkedHashMap<>();
449 if(query != null && !query.isEmpty()) {
450 String[] pairs = query.split("&");
451 for (String pair : pairs) {
452 int idx = pair.indexOf('=');
453 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
459 public static Map<String, String> splitPath(String path) throws UnsupportedEncodingException {
460 Map<String, String> query_pairs = new LinkedHashMap<>();
462 if(path != null && !path.isEmpty()) {
463 String[] pairs = path.split("/");
464 for (String pair : pairs) {
465 int idx = pair.indexOf('=');
466 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
472 protected boolean expectsDataFromPUTRequest() {
477 public String getTargetUri() {