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.r1607;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.fail;
28 import java.io.IOException;
29 import java.lang.annotation.Annotation;
30 import java.lang.reflect.Field;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.Modifier;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.UUID;
41 import javax.xml.bind.SchemaOutputResolver;
42 import javax.xml.bind.annotation.XmlElement;
43 import javax.xml.transform.Result;
44 import javax.xml.transform.stream.StreamResult;
46 import org.apache.commons.lang.RandomStringUtils;
47 import org.apache.commons.lang.StringUtils;
48 import org.junit.AfterClass;
49 import org.junit.BeforeClass;
50 import org.junit.FixMethodOrder;
51 import org.junit.Test;
52 import org.junit.runners.MethodSorters;
53 import org.onap.ccsdk.sli.adaptors.aai.AAIClient;
54 import org.onap.ccsdk.sli.adaptors.aai.AAIDeclarations;
55 import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
56 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
57 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
58 import org.openecomp.aai.inventory.v11.GenericVnf;
59 import org.openecomp.aai.inventory.v11.InventoryResponseItems;
60 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
61 import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 import com.fasterxml.jackson.annotation.JsonProperty;
66 import com.fasterxml.jackson.databind.ObjectMapper;
70 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
71 public class R1607AutoGeneratedTest {
73 private static final Logger LOG = LoggerFactory.getLogger(R1607AutoGeneratedTest.class);
75 protected static AAIClient client;
77 protected Map<String, String> cache = new HashMap<String, String>();
80 public static void setUp() throws Exception {
82 URL url = AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES);
83 // client = new AAIService(url);
84 LOG.info("\nTaicAAIResourceTest.setUp\n");
88 public static void tearDown() throws Exception {
91 LOG.info("----------------------- AAIResourceTest.tearDown -----------------------");
96 public void test01AutoGeneratedRequest() {
98 String[] requestDefinition = {
99 "query|generic-vnf|generic-vnf.vnf-id:assign:value:bnfm0001v-1147"
102 for(String line : requestDefinition){
103 // parse request line resource | key structure
104 String[] segments = line.split("\\|");
105 String action = segments[0];
106 String resource = segments[1];
107 String[] tmpKeys = segments[2].split("&");
110 String localId = null;
112 List<String> keys = new ArrayList<String>();
113 String keyLine = null;
115 for(String instruction : tmpKeys) {
116 String[] parts = instruction.split(":");
117 String identifier = parts[0];
118 String method = parts[2];
120 if(identifier.startsWith(resource)) {
121 localId = identifier;
122 } else if(identifier.startsWith("l-interface") && "l2-bridge-bgf".equals(resource)) {
123 localId = identifier;
124 } else if(identifier.startsWith("l-interface") && "l2-bridge-sbg".equals(resource)) {
125 localId = identifier;
130 String postProcesss = parts[3];
131 keyLine = processAssign(identifier, method, postProcesss);
132 if(keyLine != null && !keyLine.trim().isEmpty()) {
137 keyLine = processCached(identifier, method);
138 if(keyLine != null && !keyLine.trim().isEmpty()) {
148 List<String> x = Arrays.asList(localId.split("\\."));
150 testAutoGeneratedSaveRequest(resource, keys, x.get(x.size() - 1), cache.get(localId));
153 test03AutoGeneratedQueryRequest(resource, keys);
156 test03AutoGeneratedDeleteRequest(resource, keys);
165 public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) {
166 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
170 Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext());
171 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
172 Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request==null ? GenericVnf.class : request.getModelClass());
174 Map<String, String> data = new HashMap<String, String>();
176 for(Field field : resourceClass.getDeclaredFields()) {
177 String type = field.getType().getName();
178 if(type.startsWith("java.lang.")){
179 Annotation[] fieldAnnotations = field.getAnnotations();
180 for(int i = 0; i < fieldAnnotations.length; i++) {
181 Annotation a = fieldAnnotations[i];
182 if(a instanceof JsonProperty){
183 JsonProperty pa = (JsonProperty)a;
184 String name = pa.value();
187 case "java.lang.Integer":
188 case "java.lang.Long":
189 value = RandomStringUtils.random(6, false, true);
191 case "java.lang.Boolean":
195 if(name.equals(identifier)) {
198 value = RandomStringUtils.random(10, true, false);
201 data.put(name, value);
203 if(a instanceof javax.xml.bind.annotation.XmlElement) {
204 XmlElement xe = (XmlElement)a;
205 String name = xe.name();
206 if("link-type".equals(name)){
207 data.put(name, "roadmTail");
210 if("operational-status".equals(name)){
211 data.put(name, "available");
216 case "java.lang.Integer":
217 case "java.lang.Long":
218 value = RandomStringUtils.random(6, false, true);
220 case "java.lang.Boolean":
224 if(name.equals(identifier)) {
227 value = RandomStringUtils.random(10, true, false);
230 data.put(name, value);
236 SvcLogicContext ctx = new SvcLogicContext();
238 data.remove("resource-version");
240 QueryStatus resp = null;
242 //(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms, String prefix, SvcLogicContext ctx)
243 resp = client.save(resource, false, false, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx);
247 LOG.error("Caught exception", e);
248 fail("Caught exception");
252 public void test03AutoGeneratedQueryRequest(String resource, List<String> requestKeys) {
253 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
255 SvcLogicContext ctx = new SvcLogicContext();
259 QueryStatus response = null;
261 response = client.query(resource, false, null, StringUtils.join(requestKeys, " AND "), "aaiTest", null, ctx);
265 LOG.error("Caught exception", e);
266 fail("Caught exception");
271 public void test03AutoGeneratedDeleteRequest(String resource, List<String> requestKeys) {
272 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
276 SvcLogicContext ctx = new SvcLogicContext();
278 QueryStatus response = null;
280 response = client.delete(resource, StringUtils.join(requestKeys, " AND "), ctx);
284 LOG.error("Caught exception", e);
285 fail("Caught exception");
289 static ArrayList<Method> findSetters(Class<?> c) {
290 ArrayList<Method> list = new ArrayList<Method>();
291 Method[] methods = c.getDeclaredMethods();
292 for (Method method : methods)
293 if (isGetter(method))
299 public static boolean isGetter(Method method) {
300 if (Modifier.isPublic(method.getModifiers()) &&
301 method.getParameterTypes().length == 0) {
302 if (method.getName().matches("^get[A-Z].*") &&
303 !method.getReturnType().equals(void.class))
305 if (method.getName().matches("^is[A-Z].*") &&
306 method.getReturnType().equals(boolean.class))
312 public static boolean isSetter(Method method) {
313 return Modifier.isPublic(method.getModifiers()) &&
314 method.getReturnType().equals(void.class) &&
315 method.getParameterTypes().length == 1 &&
316 method.getName().matches("^set[A-Z].*");
319 private String processAssign(String identifier, String method, String postProcess) {
321 if("uuid".equals(method)) {
322 value = UUID.randomUUID().toString();
325 if("cache".equals(postProcess)) {
326 cache.put(identifier, value);
329 if("value".equals(method)) {
330 cache.put(identifier, postProcess);
334 String key = String.format("%s = '%s'", identifier, value);
338 private String processCached(String identifier, String method) {
339 String value = cache.get(identifier);
341 String key = String.format("%s = '%s'", identifier, value);
345 protected HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
350 LOG.debug("Converting key [" + key + "] to where clause");
352 if (key.startsWith("'") && key.endsWith("'")) {
353 key = key.substring(1, key.length() - 1);
355 LOG.debug("Stripped outer single quotes - key is now [" + key + "]");
358 String[] keyTerms = key.split("\\s+");
360 StringBuffer whereBuff = new StringBuffer();
364 HashMap<String, String> results = new HashMap<String, String>();
366 for (int i = 0; i < keyTerms.length; i++) {
368 if ("and".equalsIgnoreCase(keyTerms[i])
369 || "or".equalsIgnoreCase(keyTerms[i])) {
372 term1 = resolveTerm(keyTerms[i], ctx);
374 } else if (op == null) {
375 if ("==".equals(keyTerms[i])) {
381 term2 = resolveTerm(keyTerms[i], ctx);
382 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
383 results.put(term1, term2);
394 private String resolveTerm(String term, SvcLogicContext ctx) {
399 LOG.debug("resolveTerm: term is " + term);
401 if (term.startsWith("$") && (ctx != null)) {
402 // Resolve any index variables.
404 return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
405 } else if (term.startsWith("'") || term.startsWith("\"")) {
408 return (term.replaceAll("-", "_"));
414 private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
416 if (ctxVarName.indexOf('[') == -1) {
417 // Ctx variable contains no arrays
418 return (ctx.getAttribute(ctxVarName));
421 // Resolve any array references
422 StringBuffer sbuff = new StringBuffer();
423 String[] ctxVarParts = ctxVarName.split("\\[");
424 sbuff.append(ctxVarParts[0]);
425 for (int i = 1; i < ctxVarParts.length; i++) {
426 if (ctxVarParts[i].startsWith("$")) {
427 int endBracketLoc = ctxVarParts[i].indexOf("]");
428 if (endBracketLoc == -1) {
429 // Missing end bracket ... give up parsing
430 LOG.warn("Variable reference " + ctxVarName
431 + " seems to be missing a ']'");
432 return (ctx.getAttribute(ctxVarName));
435 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
436 String remainder = ctxVarParts[i].substring(endBracketLoc);
439 sbuff.append(ctx.getAttribute(idxVarName));
440 sbuff.append(remainder);
443 // Index is not a variable reference
445 sbuff.append(ctxVarParts[i]);
449 return (ctx.getAttribute(sbuff.toString()));
453 public void test04VceDataPost() {
454 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
458 URL resource = this.getClass().getResource("/json/tails4.json");
460 LOG.info("Resource is " + resource.getFile());
461 File requestFile = new File(resource.getFile());
462 if(!requestFile.exists()) {
463 fail("Test file does not exist");
465 SvcLogicContext ctx = new SvcLogicContext();
466 ObjectMapper mapper = AAIService.getObjectMapper();
467 InventoryResponseItems request = mapper.readValue(requestFile, InventoryResponseItems.class);
468 Map<String, Object> subnetsList = mapper.convertValue(request, Map.class);
469 AAIDeclarations.class.cast(client).writeMap(subnetsList, "aaiTmp", ctx);
470 assertNotNull(request);
475 LOG.error("Caught exception", e);
476 fail("Caught exception");
481 static class MySchemaOutputResolver extends SchemaOutputResolver {
483 public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
484 File file = new File(suggestedFileName);
485 StreamResult result = new StreamResult(file);
486 result.setSystemId(file.getAbsolutePath());