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.openecomp.sdnc.sli.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.runners.MethodSorters;
52 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
53 import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
54 import org.openecomp.aai.inventory.v10.GenericVnf;
55 import org.openecomp.aai.inventory.v10.InventoryResponseItems;
56 import org.openecomp.sdnc.sli.aai.AAIClient;
57 import org.openecomp.sdnc.sli.aai.AAIDeclarations;
58 import org.openecomp.sdnc.sli.aai.AAIRequest;
59 import org.openecomp.sdnc.sli.aai.AAIService;
60 import org.openecomp.sdnc.sli.aai.data.AAIDatum;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 import com.fasterxml.jackson.annotation.JsonProperty;
65 import com.fasterxml.jackson.databind.ObjectMapper;
69 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
70 public class R1607AutoGeneratedTest {
72 private static final Logger LOG = LoggerFactory.getLogger(R1607AutoGeneratedTest.class);
74 protected static AAIClient client;
76 protected Map<String, String> cache = new HashMap<String, String>();
79 public static void setUp() throws Exception {
81 URL url = AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES);
82 client = new AAIService(url);
83 LOG.info("\nTaicAAIResourceTest.setUp\n");
87 public static void tearDown() throws Exception {
90 LOG.info("----------------------- AAIResourceTest.tearDown -----------------------");
95 public void test01AutoGeneratedRequest() {
97 String[] requestDefinition = {
98 "query|generic-vnf|generic-vnf.vnf-id:assign:value:bnfm0001v-1147"
101 for(String line : requestDefinition){
102 // parse request line resource | key structure
103 String[] segments = line.split("\\|");
104 String action = segments[0];
105 String resource = segments[1];
106 String[] tmpKeys = segments[2].split("&");
109 String localId = null;
111 List<String> keys = new ArrayList<String>();
112 String keyLine = null;
114 for(String instruction : tmpKeys) {
115 String[] parts = instruction.split(":");
116 String identifier = parts[0];
117 String method = parts[2];
119 if(identifier.startsWith(resource)) {
120 localId = identifier;
121 } else if(identifier.startsWith("l-interface") && "l2-bridge-bgf".equals(resource)) {
122 localId = identifier;
123 } else if(identifier.startsWith("l-interface") && "l2-bridge-sbg".equals(resource)) {
124 localId = identifier;
129 String postProcesss = parts[3];
130 keyLine = processAssign(identifier, method, postProcesss);
131 if(keyLine != null && !keyLine.trim().isEmpty()) {
136 keyLine = processCached(identifier, method);
137 if(keyLine != null && !keyLine.trim().isEmpty()) {
147 List<String> x = Arrays.asList(localId.split("\\."));
149 testAutoGeneratedSaveRequest(resource, keys, x.get(x.size() - 1), cache.get(localId));
152 test03AutoGeneratedQueryRequest(resource, keys);
155 test03AutoGeneratedDeleteRequest(resource, keys);
164 public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) {
165 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
169 Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext());
170 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
171 Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request==null ? GenericVnf.class : request.getModelClass());
173 Map<String, String> data = new HashMap<String, String>();
175 for(Field field : resourceClass.getDeclaredFields()) {
176 String type = field.getType().getName();
177 if(type.startsWith("java.lang.")){
178 Annotation[] fieldAnnotations = field.getAnnotations();
179 for(int i = 0; i < fieldAnnotations.length; i++) {
180 Annotation a = fieldAnnotations[i];
181 if(a instanceof JsonProperty){
182 JsonProperty pa = (JsonProperty)a;
183 String name = pa.value();
186 case "java.lang.Integer":
187 case "java.lang.Long":
188 value = RandomStringUtils.random(6, false, true);
190 case "java.lang.Boolean":
194 if(name.equals(identifier)) {
197 value = RandomStringUtils.random(10, true, false);
200 data.put(name, value);
202 if(a instanceof javax.xml.bind.annotation.XmlElement) {
203 XmlElement xe = (XmlElement)a;
204 String name = xe.name();
205 if("link-type".equals(name)){
206 data.put(name, "roadmTail");
209 if("operational-status".equals(name)){
210 data.put(name, "available");
215 case "java.lang.Integer":
216 case "java.lang.Long":
217 value = RandomStringUtils.random(6, false, true);
219 case "java.lang.Boolean":
223 if(name.equals(identifier)) {
226 value = RandomStringUtils.random(10, true, false);
229 data.put(name, value);
235 SvcLogicContext ctx = new SvcLogicContext();
237 data.remove("resource-version");
239 QueryStatus resp = null;
241 //(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms, String prefix, SvcLogicContext ctx)
242 resp = client.save(resource, false, false, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx);
246 LOG.error("Caught exception", e);
247 fail("Caught exception");
251 public void test03AutoGeneratedQueryRequest(String resource, List<String> requestKeys) {
252 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
254 SvcLogicContext ctx = new SvcLogicContext();
258 QueryStatus response = null;
260 response = client.query(resource, false, null, StringUtils.join(requestKeys, " AND "), "aaiTest", null, ctx);
264 LOG.error("Caught exception", e);
265 fail("Caught exception");
270 public void test03AutoGeneratedDeleteRequest(String resource, List<String> requestKeys) {
271 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
275 SvcLogicContext ctx = new SvcLogicContext();
277 QueryStatus response = null;
279 response = client.delete(resource, StringUtils.join(requestKeys, " AND "), ctx);
283 LOG.error("Caught exception", e);
284 fail("Caught exception");
288 static ArrayList<Method> findSetters(Class<?> c) {
289 ArrayList<Method> list = new ArrayList<Method>();
290 Method[] methods = c.getDeclaredMethods();
291 for (Method method : methods)
292 if (isGetter(method))
298 public static boolean isGetter(Method method) {
299 if (Modifier.isPublic(method.getModifiers()) &&
300 method.getParameterTypes().length == 0) {
301 if (method.getName().matches("^get[A-Z].*") &&
302 !method.getReturnType().equals(void.class))
304 if (method.getName().matches("^is[A-Z].*") &&
305 method.getReturnType().equals(boolean.class))
311 public static boolean isSetter(Method method) {
312 return Modifier.isPublic(method.getModifiers()) &&
313 method.getReturnType().equals(void.class) &&
314 method.getParameterTypes().length == 1 &&
315 method.getName().matches("^set[A-Z].*");
318 private String processAssign(String identifier, String method, String postProcess) {
320 if("uuid".equals(method)) {
321 value = UUID.randomUUID().toString();
324 if("cache".equals(postProcess)) {
325 cache.put(identifier, value);
328 if("value".equals(method)) {
329 cache.put(identifier, postProcess);
333 String key = String.format("%s = '%s'", identifier, value);
337 private String processCached(String identifier, String method) {
338 String value = cache.get(identifier);
340 String key = String.format("%s = '%s'", identifier, value);
344 protected HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) {
349 LOG.debug("Converting key [" + key + "] to where clause");
351 if (key.startsWith("'") && key.endsWith("'")) {
352 key = key.substring(1, key.length() - 1);
354 LOG.debug("Stripped outer single quotes - key is now [" + key + "]");
357 String[] keyTerms = key.split("\\s+");
359 StringBuffer whereBuff = new StringBuffer();
363 HashMap<String, String> results = new HashMap<String, String>();
365 for (int i = 0; i < keyTerms.length; i++) {
367 if ("and".equalsIgnoreCase(keyTerms[i])
368 || "or".equalsIgnoreCase(keyTerms[i])) {
371 term1 = resolveTerm(keyTerms[i], ctx);
373 } else if (op == null) {
374 if ("==".equals(keyTerms[i])) {
380 term2 = resolveTerm(keyTerms[i], ctx);
381 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
382 results.put(term1, term2);
393 private String resolveTerm(String term, SvcLogicContext ctx) {
398 LOG.debug("resolveTerm: term is " + term);
400 if (term.startsWith("$") && (ctx != null)) {
401 // Resolve any index variables.
403 return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
404 } else if (term.startsWith("'") || term.startsWith("\"")) {
407 return (term.replaceAll("-", "_"));
413 private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
415 if (ctxVarName.indexOf('[') == -1) {
416 // Ctx variable contains no arrays
417 return (ctx.getAttribute(ctxVarName));
420 // Resolve any array references
421 StringBuffer sbuff = new StringBuffer();
422 String[] ctxVarParts = ctxVarName.split("\\[");
423 sbuff.append(ctxVarParts[0]);
424 for (int i = 1; i < ctxVarParts.length; i++) {
425 if (ctxVarParts[i].startsWith("$")) {
426 int endBracketLoc = ctxVarParts[i].indexOf("]");
427 if (endBracketLoc == -1) {
428 // Missing end bracket ... give up parsing
429 LOG.warn("Variable reference " + ctxVarName
430 + " seems to be missing a ']'");
431 return (ctx.getAttribute(ctxVarName));
434 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
435 String remainder = ctxVarParts[i].substring(endBracketLoc);
438 sbuff.append(ctx.getAttribute(idxVarName));
439 sbuff.append(remainder);
442 // Index is not a variable reference
444 sbuff.append(ctxVarParts[i]);
448 return (ctx.getAttribute(sbuff.toString()));
452 public void test04VceDataPost() {
453 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
457 URL resource = this.getClass().getResource("/json/tails4.json");
459 LOG.info("Resource is " + resource.getFile());
460 File requestFile = new File(resource.getFile());
461 if(!requestFile.exists()) {
462 fail("Test file does not exist");
464 SvcLogicContext ctx = new SvcLogicContext();
465 ObjectMapper mapper = AAIService.getObjectMapper();
466 InventoryResponseItems request = mapper.readValue(requestFile, InventoryResponseItems.class);
467 Map<String, Object> subnetsList = mapper.convertValue(request, Map.class);
468 AAIDeclarations.class.cast(client).writeMap(subnetsList, "aaiTmp", ctx);
469 assertNotNull(request);
474 LOG.error("Caught exception", e);
475 fail("Caught exception");
479 static class MySchemaOutputResolver extends SchemaOutputResolver {
481 public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
482 File file = new File(suggestedFileName);
483 StreamResult result = new StreamResult(file);
484 result.setSystemId(file.getAbsolutePath());