[SDNC-30] summary
[ccsdk/sli/adaptors.git] / aai-service / provider / src / test / java / org / onap / ccsdk / sli / adaptors / aai / r1607 / R1607AutoGeneratedTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : SDN-C
4  * ================================================================================
5  * Copyright (C) 2017 ONAP Intellectual Property. All rights
6  *                                              reserved.
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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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=========================================================
20  */
21
22 package org.onap.ccsdk.sli.adaptors.aai.r1607;
23
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.fail;
26
27 import java.io.File;
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;
33 import java.net.URL;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.UUID;
40
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;
45
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.onap.ccsdk.sli.adaptors.aai.AAIClient;
55 import org.onap.ccsdk.sli.adaptors.aai.AAIDeclarations;
56 import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
57 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
58 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
59 import org.openecomp.aai.inventory.v11.GenericVnf;
60 import org.openecomp.aai.inventory.v11.InventoryResponseItems;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63
64 import com.fasterxml.jackson.annotation.JsonProperty;
65 import com.fasterxml.jackson.databind.ObjectMapper;
66
67
68
69 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
70 public class R1607AutoGeneratedTest {
71
72         private static final Logger LOG = LoggerFactory.getLogger(R1607AutoGeneratedTest.class);
73
74         protected static AAIClient client;
75
76         protected Map<String, String> cache = new HashMap<String, String>();
77
78         @BeforeClass
79         public static void setUp() throws Exception {
80 //              super.setUp();
81                 URL url = AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES);
82                 client = new AAIService(url);
83                 LOG.info("\nTaicAAIResourceTest.setUp\n");
84         }
85
86         @AfterClass
87         public static void tearDown() throws Exception {
88 //              super.tearDown();
89                 client = null;
90                 LOG.info("----------------------- AAIResourceTest.tearDown -----------------------");
91         }
92
93
94 //      @Test
95         public void test01AutoGeneratedRequest() {
96
97                 String[] requestDefinition = {
98                                 "query|generic-vnf|generic-vnf.vnf-id:assign:value:bnfm0001v-1147"
99                 };
100
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("&");
107
108
109                         String localId = null;
110
111                         List<String> keys = new ArrayList<String>();
112                         String keyLine = null;
113
114                         for(String instruction : tmpKeys) {
115                                 String[] parts = instruction.split(":");
116                                 String identifier = parts[0];
117                                 String method = parts[2];
118
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;
125                                 }
126
127                                 switch(parts[1]) {
128                                 case "assign":
129                                         String postProcesss = parts[3];
130                                         keyLine = processAssign(identifier, method, postProcesss);
131                                         if(keyLine != null && !keyLine.trim().isEmpty()) {
132                                                 keys.add(keyLine);
133                                         }
134                                         break;
135                                 case "cached":
136                                         keyLine = processCached(identifier, method);
137                                         if(keyLine != null && !keyLine.trim().isEmpty()) {
138                                                 keys.add(keyLine);
139                                         }
140                                         break;
141                                 }
142
143                         }
144
145                         switch(action){
146                         case "save":
147                                 List<String> x = Arrays.asList(localId.split("\\."));
148
149                                 testAutoGeneratedSaveRequest(resource, keys, x.get(x.size() - 1), cache.get(localId));
150                                 break;
151                         case "query":
152                                 test03AutoGeneratedQueryRequest(resource, keys);
153                                 break;
154                         case "delete":
155                                 test03AutoGeneratedDeleteRequest(resource, keys);
156                                 break;
157                         }
158                 }
159
160                 LOG.info("done");
161         }
162
163
164         public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) {
165                 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
166
167                 try
168                 {
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());
172
173                         Map<String, String> data = new HashMap<String, String>();
174
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();
184                                                         String value;
185                                                         switch(type) {
186                                                         case "java.lang.Integer":
187                                                         case "java.lang.Long":
188                                                                 value = RandomStringUtils.random(6, false, true);
189                                                                 break;
190                                                         case "java.lang.Boolean":
191                                                                 value = "false";
192                                                                 break;
193                                                         default:
194                                                                 if(name.equals(identifier)) {
195                                                                         value = idValue;
196                                                                 } else {
197                                                                         value = RandomStringUtils.random(10, true, false);
198                                                                 }
199                                                         }
200                                                         data.put(name, value);
201                                                 } else
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");
207                                                                         continue;
208                                                                 }
209                                                                 if("operational-status".equals(name)){
210                                                                         data.put(name, "available");
211                                                                         continue;
212                                                                 }
213                                                                 String value;
214                                                                 switch(type) {
215                                                                 case "java.lang.Integer":
216                                                                 case "java.lang.Long":
217                                                                         value = RandomStringUtils.random(6, false, true);
218                                                                         break;
219                                                                 case "java.lang.Boolean":
220                                                                         value = "false";
221                                                                         break;
222                                                                 default:
223                                                                         if(name.equals(identifier)) {
224                                                                                 value = idValue;
225                                                                         } else {
226                                                                                 value = RandomStringUtils.random(10, true, false);
227                                                                         }
228                                                                 }
229                                                                 data.put(name, value);
230                                                         }
231                                         }
232                                 }
233                         }
234
235                         SvcLogicContext ctx = new SvcLogicContext();
236
237                         data.remove("resource-version");
238
239                         QueryStatus resp = null;
240
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);
243                 }
244                 catch (Throwable e)
245                 {
246                         LOG.error("Caught exception", e);
247                         fail("Caught exception");
248                 }
249         }
250
251         public void test03AutoGeneratedQueryRequest(String resource, List<String> requestKeys) {
252                 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
253
254                 SvcLogicContext ctx = new SvcLogicContext();
255                 try
256                 {
257
258                         QueryStatus response = null;
259
260                         response = client.query(resource,  false, null, StringUtils.join(requestKeys, " AND "), "aaiTest", null, ctx);
261                 }
262                 catch (Throwable e)
263                 {
264                         LOG.error("Caught exception", e);
265                         fail("Caught exception");
266                 }
267         }
268
269
270         public void test03AutoGeneratedDeleteRequest(String resource, List<String> requestKeys) {
271                 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
272
273                 try
274                 {
275                         SvcLogicContext ctx = new SvcLogicContext();
276
277                         QueryStatus response = null;
278
279                         response = client.delete(resource, StringUtils.join(requestKeys, " AND "),  ctx);
280                 }
281                 catch (Throwable e)
282                 {
283                         LOG.error("Caught exception", e);
284                         fail("Caught exception");
285                 }
286         }
287
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))
293                  list.add(method);
294            return list;
295         }
296
297
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))
303                        return true;
304                  if (method.getName().matches("^is[A-Z].*") &&
305                     method.getReturnType().equals(boolean.class))
306                        return true;
307            }
308            return false;
309         }
310
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].*");
316         }
317
318         private String processAssign(String identifier, String method, String postProcess) {
319                 String value = null;
320                 if("uuid".equals(method)) {
321                         value = UUID.randomUUID().toString();
322                 }
323
324                 if("cache".equals(postProcess)) {
325                         cache.put(identifier, value);
326                 }
327
328                 if("value".equals(method)) {
329                         cache.put(identifier, postProcess);
330                         value = postProcess;
331                 }
332
333                 String key = String.format("%s = '%s'", identifier, value);
334                 return key;
335         }
336
337         private String processCached(String identifier, String method) {
338                 String value = cache.get(identifier);
339
340                 String key = String.format("%s = '%s'", identifier, value);
341                 return key;
342         }
343
344         protected HashMap<String,String> keyToHashMap(String key,       SvcLogicContext ctx) {
345                 if (key == null) {
346                         return (null);
347                 }
348
349                 LOG.debug("Converting key [" + key + "] to where clause");
350
351                 if (key.startsWith("'") && key.endsWith("'")) {
352                         key = key.substring(1, key.length() - 1);
353
354                         LOG.debug("Stripped outer single quotes - key is now [" + key + "]");
355                 }
356
357                 String[] keyTerms = key.split("\\s+");
358
359                 StringBuffer whereBuff = new StringBuffer();
360                 String term1 = null;
361                 String op = null;
362                 String term2 = null;
363                 HashMap<String, String> results = new HashMap<String, String>();
364
365                 for (int i = 0; i < keyTerms.length; i++) {
366                         if (term1 == null) {
367                                 if ("and".equalsIgnoreCase(keyTerms[i])
368                                                 || "or".equalsIgnoreCase(keyTerms[i])) {
369                                         // Skip over ADD/OR
370                                 } else {
371                                         term1 = resolveTerm(keyTerms[i], ctx);
372                                 }
373                         } else if (op == null) {
374                                 if ("==".equals(keyTerms[i])) {
375                                         op = "=";
376                                 } else {
377                                         op = keyTerms[i];
378                                 }
379                         } else {
380                                 term2 = resolveTerm(keyTerms[i], ctx);
381                                 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
382                                 results.put(term1,  term2);
383
384                                 term1 = null;
385                                 op = null;
386                                 term2 = null;
387                         }
388                 }
389
390                 return (results);
391         }
392
393         private String resolveTerm(String term, SvcLogicContext ctx) {
394                 if (term == null) {
395                         return (null);
396                 }
397
398                 LOG.debug("resolveTerm: term is " + term);
399
400                 if (term.startsWith("$") && (ctx != null)) {
401                         // Resolve any index variables.
402
403                         return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
404                 } else if (term.startsWith("'") || term.startsWith("\"")) {
405                         return (term);
406                 } else {
407                         return (term.replaceAll("-", "_"));
408
409                 }
410
411         }
412
413         private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
414
415                 if (ctxVarName.indexOf('[') == -1) {
416                         // Ctx variable contains no arrays
417                         return (ctx.getAttribute(ctxVarName));
418                 }
419
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));
432                                 }
433
434                                 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
435                                 String remainder = ctxVarParts[i].substring(endBracketLoc);
436
437                                 sbuff.append("[");
438                                 sbuff.append(ctx.getAttribute(idxVarName));
439                                 sbuff.append(remainder);
440
441                         } else {
442                                 // Index is not a variable reference
443                                 sbuff.append("[");
444                                 sbuff.append(ctxVarParts[i]);
445                         }
446                 }
447
448                 return (ctx.getAttribute(sbuff.toString()));
449         }
450
451 //      @Test
452         public void test04VceDataPost() {
453                 LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
454
455                 try
456                 {
457                         URL resource = this.getClass().getResource("/json/tails4.json");
458
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");
463                         }
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);
470
471                 }
472                 catch (Exception e)
473                 {
474                         LOG.error("Caught exception", e);
475                         fail("Caught exception");
476                 }
477         }
478
479 static class MySchemaOutputResolver extends SchemaOutputResolver {
480
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());
485                 return result;
486             }
487
488         }
489 }