2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 ONAP 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.v10.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 return new CustomQueryRequest();
118 return new LInterfaceRequest(LInterfaceRequest.TYPE.L2_BRIDGE_SBG);
119 case "l2-bridge-sbg":
120 return new SubInterfaceRequest(SubInterfaceRequest.TYPE.L2_BRIDGE_SBG);
121 case "l2-bridge-bgf":
122 return new SubInterfaceRequest(SubInterfaceRequest.TYPE.L2_BRIDGE_BGF);
125 return new EchoRequest();
129 AAIRequest request = getRequestFromResource(resoource);
130 if(request == null) {
140 * Map containing resource tag to its bit position in bitset mapping
142 private static Map<String, String> tagValues = new LinkedHashMap<String, String>();
144 * Map containing bitset value of the path to its path mapping
146 private static Map<BitSet, String> bitsetPaths = new LinkedHashMap<BitSet, String>();
149 public static void setProperties(Properties props, AAIService aaiService) {
150 AAIRequest.configProperties = props;
151 AAIRequest.aaiService = aaiService;
156 Bundle bundle = FrameworkUtil.getBundle(AAIServiceActivator.class);
158 BundleContext ctx = bundle.getBundleContext();
162 url = ctx.getBundle().getResource(AAIService.PATH_PROPERTIES);
164 url = aaiService.getClass().getResource("/aai-path.properties");
167 InputStream in = url.openStream();
168 Reader reader = new InputStreamReader(in, "UTF-8");
170 Properties properties = new Properties();
171 properties.load(reader);
172 LOG.info("loaded " + properties.size());
174 Set<String> keys = properties.stringPropertyNames();
177 Set<String> resourceNames = new TreeSet<String>();
179 for(String key : keys) {
180 String[] tags = key.split("\\|");
181 for(String tag : tags) {
182 if(!resourceNames.contains(tag)) {
183 resourceNames.add(tag);
184 tagValues.put(tag, Integer.toString(++index));
187 BitSet bs = new BitSet(256);
188 for(String tag : tags) {
189 String value = tagValues.get(tag);
190 Integer bitIndex = Integer.parseInt(value) ;
193 String path = properties.getProperty(key);
194 LOG.info(String.format("bitset %s\t\t%s", bs.toString(), path));
195 bitsetPaths.put(bs, path);
197 LOG.info("loaded " + resourceNames.toString());
201 LOG.error("Caught exception", e);
205 public AAIRequest() {
206 target_uri = configProperties.getProperty(TARGET_URI);
209 public void addRequestProperty(String key, String value) {
210 requestProperties.put(key, value);
213 public final void setRequestObject(AAIDatum value) {
214 requestDatum = value;
217 public final AAIDatum getRequestObject() {
221 public final void addMasterRequest(AAIRequest masterRequest) {
222 requestProperties.put(MASTER_REQUEST, masterRequest);
225 protected static String encodeQuery(String param) throws UnsupportedEncodingException {
226 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
229 protected void handleException(AAIRequest lInterfaceRequest, JsonProcessingException exc) {
230 aaiService.getLogger().warn("Could not deserialize object of type " + lInterfaceRequest.getClass().getSimpleName(), exc) ;
233 // public abstract URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException;
235 public URL getRequestUrl(String method, String resourceVersion) throws UnsupportedEncodingException, MalformedURLException {
237 String request_url = null;
239 request_url = target_uri + getRequestPath();
241 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
243 // request_url = processPathData(request_url, requestProperties);
245 for(String resoourceName:uniqueResources) {
246 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, new HashMap<String, String>());
247 if(locRequest != null) {
248 Class<?> clazz = locRequest.getClass();
249 Method function = null;
251 function = clazz.getMethod("processPathData", request_url.getClass(), requestProperties.getClass());
252 request_url = (String) function.invoke(null, request_url, requestProperties);
253 } catch (Exception e) {
256 // request_url = locRequest.processPathData(request_url, requestProperties);
260 if(resourceVersion != null) {
261 request_url = request_url +"?resource-version="+resourceVersion;
263 URL http_req_url = new URL(request_url);
265 aaiService.LOGwriteFirstTrace(method, http_req_url.toString());
272 protected String getRequestPath() throws MalformedURLException {
273 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(requestProperties.stringPropertyNames());
274 BitSet bitset = new BitSet();
275 for(String key : uniqueResources) {
276 if(tagValues.containsKey(key)) {
277 Object tmpValue = tagValues.get(key);
278 if(tmpValue != null) {
279 String value = tmpValue.toString();
280 int bitIndex = Integer.parseInt(value);
281 bitset.set(bitIndex);
286 String path = bitsetPaths.get(bitset);
288 throw new MalformedURLException("PATH not found for key string containing valies :" +requestProperties.toString());
293 public abstract URL getRequestQueryUrl(String method) throws UnsupportedEncodingException, MalformedURLException;
295 public abstract String toJSONString();
297 public abstract String[] getArgsList();
299 public abstract Class<? extends AAIDatum> getModelClass() ;
301 public String getPrimaryResourceName(String resource) {
305 public String formatKey(String argument) {
309 public AAIDatum jsonStringToObject(String jsonData) throws JsonParseException, JsonMappingException, IOException {
310 if(jsonData == null) {
314 AAIDatum response = null;
315 ObjectMapper mapper = getObjectMapper();
316 response = mapper.readValue(jsonData, getModelClass());
320 protected static Set<String> extractUniqueResourceSetFromKeys(Set<String> keySet) {
321 Set<String> uniqueResources = new TreeSet<String>();
322 List<String> keys = new ArrayList<String>(keySet);
323 for(String resource : keys) {
324 if(resource.contains(".")) {
325 String [] split = resource.split("\\.");
326 uniqueResources.add(split[0].replaceAll("_", "-"));
329 return uniqueResources;
332 public void processRequestPathValues(Map<String, String> nameValues) {
333 Set<String> uniqueResources = extractUniqueResourceSetFromKeys(nameValues.keySet());
335 Set<String> tokens = new TreeSet<String>();
337 tokens.addAll(Arrays.asList(this.getArgsList()));
339 for(String resoourceName:uniqueResources) {
340 AAIRequest locRequest = AAIRequest.createRequest(resoourceName, nameValues);
341 if(locRequest != null)
342 tokens.addAll(Arrays.asList(locRequest.getArgsList()));
345 String[] arguments = tokens.toArray(new String[0]);
346 for(String name : arguments) {
347 String tmpName = name.replaceAll("-", "_");
348 String value = nameValues.get(tmpName);
349 if(value != null && !value.isEmpty()) {
350 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
351 this.addRequestProperty(name, value);
356 public static String processPathData(String request_url, Properties requestProperties) throws UnsupportedEncodingException {
360 public boolean isDeleteDataRequired() {
364 ObjectMapper getObjectMapper() {
365 return AAIService.getObjectMapper();
368 protected static Class<? extends AAIDatum> getClassFromResource(String resoourceName) throws ClassNotFoundException {
369 String className = GenericVnf.class.getName();
370 String[] split = resoourceName.split("-");
371 for(int i = 0; i < split.length; i++) {
372 split[i] = StringUtils.capitalize(split[i]);
375 String caps = StringUtils.join(split);
376 className = className.replace("GenericVnf", caps);
377 Class<? extends AAIDatum> clazz = null;
379 clazz = (Class<? extends AAIDatum>)Class.forName(className);
380 } catch (ClassNotFoundException e) {
381 LOG.warn("AAIRequest does not support class: " + e.getMessage());
388 protected static AAIRequest getRequestFromResource(String resoourceName) {
390 Class<? extends AAIDatum> clazz = null;
392 clazz = getClassFromResource(resoourceName);
393 } catch (ClassNotFoundException e) {
394 LOG.warn("AAIRequest does not support class: " + e.getMessage());
400 GenericRequest request = new GenericRequest(clazz);
404 public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
405 Map<String, String> query_pairs = new LinkedHashMap<String, String>();
407 if(query != null && !query.isEmpty()) {
408 String[] pairs = query.split("&");
409 for (String pair : pairs) {
410 int idx = pair.indexOf("=");
411 query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
417 protected boolean expectsDataFromPUTRequest() {