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