Fixing trustStore issues in AAI Client
[ccsdk/sli/adaptors.git] / aai-service / provider / src / test / java / org / onap / ccsdk / sli / adaptors / aai / AutoGeneratedRegressionTest.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;
23
24 import static org.junit.Assert.assertTrue;
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.Scanner;
40 import java.util.Set;
41 import java.util.Stack;
42 import java.util.UUID;
43
44 import javax.xml.bind.SchemaOutputResolver;
45 import javax.xml.bind.annotation.XmlElement;
46 import javax.xml.parsers.DocumentBuilder;
47 import javax.xml.parsers.DocumentBuilderFactory;
48 import javax.xml.transform.Result;
49 import javax.xml.transform.stream.StreamResult;
50 import javax.xml.xpath.XPath;
51 import javax.xml.xpath.XPathConstants;
52 import javax.xml.xpath.XPathExpression;
53 import javax.xml.xpath.XPathFactory;
54
55 import org.apache.commons.lang.RandomStringUtils;
56 import org.apache.commons.lang.StringUtils;
57 import org.junit.AfterClass;
58 import org.junit.BeforeClass;
59 import org.junit.FixMethodOrder;
60 import org.junit.Test;
61 import org.junit.runners.MethodSorters;
62 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
63 import org.onap.ccsdk.sli.adaptors.aai.query.NamedQueryData;
64 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
65 import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
66 import org.openecomp.aai.inventory.v13.GenericVnf;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.springframework.core.annotation.AnnotationUtils;
70 import org.w3c.dom.Document;
71 import org.w3c.dom.Element;
72 import org.w3c.dom.Node;
73 import org.w3c.dom.NodeList;
74
75 import com.fasterxml.jackson.annotation.JsonProperty;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77
78
79 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
80 public class AutoGeneratedRegressionTest {
81
82     static {
83         System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "INFO");
84         System.setProperty(org.slf4j.impl.SimpleLogger.LOG_FILE_KEY, String.format("AutoGeneratedRegressionTest-%d.txt", System.currentTimeMillis()));
85     }
86     private static final Logger LOG = LoggerFactory.getLogger(AutoGeneratedRegressionTest.class);
87
88
89     protected static AAIClient client;
90
91     protected Map<String, String> cache = new HashMap<String, String>();
92
93     @BeforeClass
94     public static void setUp() throws Exception {
95         URL url = AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES);
96         client = new AAIService(url);
97         LOG.info("----------------------- aicAAIResourceTest.setUp -----------------------");
98     }
99
100     @AfterClass
101     public static void tearDown() throws Exception {
102         client = null;
103         LOG.info("----------------------- AAIResourceTest.tearDown -----------------------");
104     }
105
106
107     @Test
108     public void mainLoadTest ()
109     {
110         try
111         {
112             String currentDir = System.getProperty("user.dir");
113             File dir = new File(currentDir);
114             if(!dir.exists()) {
115                 System.exit(1);
116             }
117             dir = new File(dir, "src/main/resources");
118             if(!dir.exists()) {
119                 System.exit(1);
120             }
121             // parse the document
122             File file = new File(dir, "aai_schema_v11.xsd");
123             if(!file.exists()) {
124                 assert(false);
125                 return;
126             }
127
128             DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
129             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
130             Document doc = dBuilder.parse(file);
131
132             Stack<String> stack = new Stack<String>();
133             List<String> commands = new ArrayList<String>();
134             listSubNodes("network", doc, stack, commands);
135             listSubNodes("cloud-infrastructure", doc, stack, commands);
136             listSubNodes("service-design-and-creation", doc, stack, commands);
137             listSubNodes("license-management", doc, stack, commands);
138             listSubNodes("business", doc, stack, commands);
139
140             String[] requestDefinition = commands.toArray(new String[0]);
141             LOG.info("\n----------------------------");
142
143             executeTests(requestDefinition);
144         }
145         catch (Throwable e)
146         {
147             LOG.error("", e);
148         }
149     }
150
151     @Test
152     public void testFromFile() {
153         String filename = "testCommands.txt";
154         List<String> lines = new ArrayList<String>();
155         Scanner scanner = null;
156
157         try {
158             File testFile = new File(filename);
159             if(!testFile.exists())
160                 return;
161             scanner = new Scanner(testFile);
162             while (scanner.hasNextLine()) {
163                 lines.add(scanner.nextLine());
164             }
165         } catch (Exception exc) {
166
167         } finally {
168             if(scanner != null)
169                 scanner.close();
170         }
171
172         String[] requestDefinition = lines.toArray(new String[0]);
173         executeTests(requestDefinition);
174     }
175
176
177     @Test
178     public void test01AutoGeneratedRequest() {
179
180         String[] requestDefinition = {
181                 "save|generic-vnf|generic-vnf.vnf-id:assign:value:adb28ac0-a260-4b7d-9ce5-adf15733c458",
182                 "update|generic-vnf|generic-vnf.vnf-id:assign:value:adb28ac0-a260-4b7d-9ce5-adf15733c458",
183                 "query|generic-vnf|generic-vnf.vnf-id:assign:value:adb28ac0-a260-4b7d-9ce5-adf15733c458",
184                 "delete|generic-vnf|generic-vnf.vnf-id:assign:value:adb28ac0-a260-4b7d-9ce5-adf15733c458"
185         };
186
187         executeTests(requestDefinition);
188     }
189
190     public void executeTests(String[] requestDefinition) {
191
192         for(String line : requestDefinition){
193             LOG.info("Executing: " + line);
194
195             // parse request line resource | key structure
196             String[] segments = line.split("\\|");
197             String action = segments[0];
198             String resource = segments[1];
199             String[] tmpKeys = segments[2].split("&");
200             // String array keyStructure can be tmpKey.
201             // options    :assign:uuid:cache
202             //            :cached
203             //            :query:random
204
205
206             String localId = null;
207
208             List<String> keys = new ArrayList<String>();
209             String keyLine = null;
210
211             for(String instruction : tmpKeys) {
212                 String[] parts = instruction.split(":");
213                 String identifier = parts[0];
214                 String method = parts[2];
215
216                 if(identifier.startsWith(resource)) {
217                     localId = identifier;
218                 } else if(identifier.startsWith("l-interface") && "l2-bridge-bgf".equals(resource)) {
219                     localId = identifier;
220                 } else if(identifier.startsWith("l-interface") && "l2-bridge-sbg".equals(resource)) {
221                     localId = identifier;
222                 } else if("nodes-query".equals(resource)) {
223                     localId = identifier;
224                 }
225
226                 switch(parts[1]) {
227                 case "assign":
228                     String postProcesss = parts[3];
229                     keyLine = processAssign(identifier, method, postProcesss);
230                     if(keyLine != null && !keyLine.trim().isEmpty()) {
231                         keys.add(keyLine);
232                     }
233                     break;
234                 case "cached":
235                     keyLine = processCached(identifier, method);
236                     if(keyLine != null && !keyLine.trim().isEmpty()) {
237                         keys.add(keyLine);
238                     }
239                     break;
240                 }
241
242             }
243
244             List<String> x = Arrays.asList(localId.split("\\."));
245             switch(action){
246             case "save":
247                 testAutoGeneratedSaveRequest(resource, keys, x.get(x.size() - 1), cache.get(localId));
248                 break;
249             case "update":
250                 testAutoGeneratedUpdateRequest(resource, keys, x.get(x.size() - 1), cache.get(localId));
251                 break;
252
253             case "query":
254                 test03AutoGeneratedQueryRequest(resource, keys);
255                 break;
256             case "delete":
257                 test03AutoGeneratedDeleteRequest(resource, keys);
258                 break;
259             }
260         }
261
262         LOG.info("done");
263     }
264
265
266     public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) {
267         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
268
269         try
270         {
271             Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext());
272             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
273             Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request==null ? GenericVnf.class : request.getModelClass());
274
275             Map<String, String> data = new HashMap<String, String>();
276
277             for(Field field : resourceClass.getDeclaredFields()) {
278                 String type = field.getType().getName();
279                 switch(type){
280                 case "bool":
281                 case "boolean":
282                     type = Boolean.class.getName();
283                     break;
284                 case "int":
285                     type = Integer.class.getName();
286                     break;
287                 case "long":
288                     type = Long.class.getName();
289                     break;
290
291                 }
292                 if(type.startsWith("java.lang.")){
293                     Annotation[] fieldAnnotations = field.getAnnotations();
294                     for(int i = 0; i < fieldAnnotations.length; i++) {
295                         Annotation a = fieldAnnotations[i];
296                         if(a instanceof JsonProperty){
297                             JsonProperty pa = (JsonProperty)a;
298                             String name = pa.value();
299                             String value;
300                             switch(type) {
301                             case "java.lang.Integer":
302                             case "java.lang.Long":
303                                 value = RandomStringUtils.random(6, false, true);
304                                 break;
305                             case "java.lang.Boolean":
306                                 value = "false";
307                                 break;
308                             default:
309                                 if(name.equals(identifier)) {
310                                     value = idValue;
311                                 } else {
312                                     value = RandomStringUtils.random(10, true, false);
313                                 }
314                             }
315                             data.put(name, value);
316                         } else
317                             if(a instanceof javax.xml.bind.annotation.XmlElement) {
318                                 XmlElement xe = (XmlElement)a;
319                                 String name = xe.name();
320                                 if("model-version-id".equals(name)) {
321                                     continue;
322                                 }
323                                 if("model-invariant-id".equals(name)) {
324                                     continue;
325                                 }
326                                 if("link-type".equals(name)){
327                                     data.put(name, "roadmTail");
328                                     continue;
329                                 }
330                                 if("operational-status".equals(name)){
331                                     data.put(name, "available");
332                                     continue;
333                                 }
334                                 if(name.equals(identifier)) {
335                                     data.put(name, idValue);
336                                     continue;
337                                 }
338
339                                 String value;
340                                 switch(type) {
341                                 case "java.lang.Integer":
342                                 case "java.lang.Long":
343                                     value = RandomStringUtils.random(6, false, true);
344                                     break;
345                                 case "java.lang.Boolean":
346                                     value = "false";
347                                     break;
348                                 default:
349                                     if(name.equals(identifier)) {
350                                         value = idValue;
351                                     } else {
352                                         value = RandomStringUtils.random(10, true, false);
353                                     }
354                                 }
355                                 data.put(name, value);
356                             }
357                     }
358                 }
359             }
360
361             SvcLogicContext ctx = new SvcLogicContext();
362
363             data.remove("resource-version");
364
365             QueryStatus resp = null;
366
367             //(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms, String prefix,    SvcLogicContext ctx)
368             resp = client.save(resource, false, false, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx);
369             if(resp == QueryStatus.SUCCESS) {
370                 LOG.info(String.format("Save %s successfull", resource));
371             } else {
372                 LOG.info(String.format("Save %s failed due to : %s", resource, ctx.getAttribute("aaidata.error.message")));
373             }
374         }
375         catch (Throwable e)
376         {
377             LOG.error("Caught exception", e);
378             fail("Caught exception");
379         }
380     }
381
382     public void test03AutoGeneratedQueryRequest(String resource, List<String> requestKeys) {
383         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
384
385         SvcLogicContext ctx = new SvcLogicContext();
386         try
387         {
388
389             QueryStatus response = null;
390
391             response = client.query(resource,  false, null, StringUtils.join(requestKeys, " AND "), "aaiTest", null, ctx);
392             if(response == QueryStatus.SUCCESS) {
393                 LOG.info(String.format("Query %s successfull", resource));
394                 Set<String> tokens = ctx.getAttributeKeySet();
395                 Map<String, String> reponseData = new HashMap<String, String>();
396
397                 String responsePrefix = String.format("%s", "aaiTest");
398
399                 for(String token : tokens) {
400                     if(token.startsWith(responsePrefix)){
401                         reponseData.put(token, ctx.getAttribute(token));
402                     } else {
403                         LOG.info(String.format("%s = ", token, ctx.getAttribute(token)));
404                     }
405                 }
406
407                 LOG.info("AAIResponse: " + response.toString());
408                 assertTrue("AAIRequest:"+resource, reponseData.size() > 0);
409             } else {
410                 LOG.info(String.format("Query %s failed due to : %s", resource, ctx.getAttribute("aaidata.error.message")));
411                 assert(false);
412             }
413         }
414         catch (Throwable e)
415         {
416             LOG.error("Caught exception", e);
417         }
418     }
419
420
421     public void test03AutoGeneratedDeleteRequest(String resource, List<String> requestKeys) {
422         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
423
424         try
425         {
426             SvcLogicContext ctx = new SvcLogicContext();
427
428             QueryStatus response = null;
429
430             response = client.delete(resource, StringUtils.join(requestKeys, " AND "),  ctx);
431             if(response == QueryStatus.SUCCESS) {
432                 LOG.info(String.format("Delete %s successfull", resource));
433             } else {
434                 LOG.info(String.format("Delete %s failed due to : %s", resource, ctx.getAttribute("aaiDelete.error.message")));
435             }
436         }
437         catch (Throwable e)
438         {
439             LOG.error("Caught exception", e);
440             fail("Caught exception");
441         }
442     }
443
444     public void testAutoGeneratedUpdateRequest(String resource, List<String> requestKeys, String identifier, String idValue) {
445         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
446
447         try
448         {
449             Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext());
450             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
451             Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request==null ? GenericVnf.class : request.getModelClass());
452
453             Map<String, String> data = new HashMap<String, String>();
454
455             boolean skipFirst = true;
456             boolean breakLoop = false;
457             for(Field field : resourceClass.getDeclaredFields()) {
458                 if(skipFirst){
459                     skipFirst = false;
460                     continue;
461                 }
462                 if(breakLoop){
463                     break;
464                 }
465                 String type = field.getType().getName();
466                 if(type.startsWith("java.lang.")){
467                     Annotation[] fieldAnnotations = field.getAnnotations();
468                     for(int i = 0; i < fieldAnnotations.length; i++) {
469                         Annotation a = fieldAnnotations[i];
470                         if(a instanceof JsonProperty){
471                             JsonProperty pa = (JsonProperty)a;
472                             String name = pa.value();
473                             String value;
474                             switch(type) {
475                             case "java.lang.Integer":
476                             case "java.lang.Long":
477                                 value = RandomStringUtils.random(6, false, true);
478                                 break;
479                             case "java.lang.Boolean":
480                                 value = "false";
481                                 break;
482                             default:
483                                 if(name.equals(identifier)) {
484                                     value = idValue;
485                                 } else {
486                                     value = RandomStringUtils.random(10, true, false);
487                                 }
488                             }
489                             data.put(name, value);
490                             breakLoop = true;
491                         } else
492                             if(a instanceof javax.xml.bind.annotation.XmlElement) {
493                                 XmlElement xe = (XmlElement)a;
494                                 String name = xe.name();
495                                 if("link-type".equals(name)){
496                                     data.put(name, "roadmTail");
497                                     continue;
498                                 }
499                                 if("operational-status".equals(name)){
500                                     data.put(name, "available");
501                                     continue;
502                                 }
503                                 String value;
504                                 switch(type) {
505                                 case "java.lang.Integer":
506                                 case "java.lang.Long":
507                                     value = RandomStringUtils.random(6, false, true);
508                                     break;
509                                 case "java.lang.Boolean":
510                                     value = "false";
511                                     break;
512                                 default:
513                                     if(name.equals(identifier)) {
514                                         value = idValue;
515                                     } else {
516                                         value = RandomStringUtils.random(10, true, false);
517                                     }
518                                 }
519                                 data.put(name, value);
520                                 breakLoop = true;
521                             }
522                     }
523                 }
524             }
525
526             SvcLogicContext ctx = new SvcLogicContext();
527
528             data.remove("resource-version");
529
530             QueryStatus resp = null;
531
532             //client.update("ipsec-configuration", "ipsec-configuration.ipsec-configuration-id = 'testConfigurationId01'", data, "aaiTest",  ctx);
533             resp = client.update(resource, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx);
534             if(resp == QueryStatus.SUCCESS) {
535                 LOG.info(String.format("Update %s successfull", resource));
536             } else {
537                 LOG.info(String.format("Update %s failed due to : %s", resource, ctx.getAttribute("aaidata.error.message")));
538             }
539
540         }
541         catch (Throwable e)
542         {
543             LOG.error("Caught exception", e);
544             fail("Caught exception");
545         }
546     }
547
548     static ArrayList<Method> findSetters(Class<?> c) {
549        ArrayList<Method> list = new ArrayList<Method>();
550        Method[] methods = c.getDeclaredMethods();
551        for (Method method : methods)
552           if (isGetter(method))
553              list.add(method);
554        return list;
555     }
556
557
558     public static boolean isGetter(Method method) {
559        if (Modifier.isPublic(method.getModifiers()) &&
560           method.getParameterTypes().length == 0) {
561              if (method.getName().matches("^get[A-Z].*") &&
562                 !method.getReturnType().equals(void.class))
563                    return true;
564              if (method.getName().matches("^is[A-Z].*") &&
565                 method.getReturnType().equals(boolean.class))
566                    return true;
567        }
568        return false;
569     }
570
571     public static boolean isSetter(Method method) {
572        return Modifier.isPublic(method.getModifiers()) &&
573           method.getReturnType().equals(void.class) &&
574              method.getParameterTypes().length == 1 &&
575                 method.getName().matches("^set[A-Z].*");
576     }
577
578     private String processAssign(String identifier, String method, String postProcess) {
579         String value = null;
580         if("uuid".equals(method)) {
581             value = UUID.randomUUID().toString();
582         }
583
584         if("cache".equals(postProcess)) {
585             cache.put(identifier, value);
586         }
587
588         if("value".equals(method)) {
589             cache.put(identifier, postProcess);
590             value = postProcess;
591         }
592
593         String key = String.format("%s = '%s'", identifier, value);
594         return key;
595     }
596
597     private String processCached(String identifier, String method) {
598         String value = cache.get(identifier);
599
600         String key = String.format("%s = '%s'", identifier, value);
601         return key;
602     }
603
604     protected HashMap<String,String> keyToHashMap(String key,    SvcLogicContext ctx) {
605         if (key == null) {
606             return (null);
607         }
608
609         LOG.debug("Converting key [" + key + "] to where clause");
610
611         if (key.startsWith("'") && key.endsWith("'")) {
612             key = key.substring(1, key.length() - 1);
613
614             LOG.debug("Stripped outer single quotes - key is now [" + key + "]");
615         }
616
617         String[] keyTerms = key.split("\\s+");
618
619         String term1 = null;
620         String op = null;
621         String term2 = null;
622         HashMap<String, String> results = new HashMap<String, String>();
623
624         for (int i = 0; i < keyTerms.length; i++) {
625             if (term1 == null) {
626                 if ("and".equalsIgnoreCase(keyTerms[i])
627                         || "or".equalsIgnoreCase(keyTerms[i])) {
628                     // Skip over ADD/OR
629                 } else {
630                     term1 = resolveTerm(keyTerms[i], ctx);
631                 }
632             } else if (op == null) {
633                 if ("==".equals(keyTerms[i])) {
634                     op = "=";
635                 } else {
636                     op = keyTerms[i];
637                 }
638             } else {
639                 term2 = resolveTerm(keyTerms[i], ctx);
640                 term2 = term2.trim().replace("'", "").replace("$", "").replace("'", "");
641                 results.put(term1,  term2);
642
643                 term1 = null;
644                 op = null;
645                 term2 = null;
646             }
647         }
648
649         return (results);
650     }
651
652     private String resolveTerm(String term, SvcLogicContext ctx) {
653         if (term == null) {
654             return (null);
655         }
656
657         LOG.debug("resolveTerm: term is " + term);
658
659         if (term.startsWith("$") && (ctx != null)) {
660             // Resolve any index variables.
661
662             return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'");
663         } else if (term.startsWith("'") || term.startsWith("\"")) {
664             return (term);
665         } else {
666             return (term.replaceAll("-", "_"));
667
668         }
669
670     }
671
672     private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) {
673
674         if (ctxVarName.indexOf('[') == -1) {
675             // Ctx variable contains no arrays
676             return (ctx.getAttribute(ctxVarName));
677         }
678
679         // Resolve any array references
680         StringBuffer sbuff = new StringBuffer();
681         String[] ctxVarParts = ctxVarName.split("\\[");
682         sbuff.append(ctxVarParts[0]);
683         for (int i = 1; i < ctxVarParts.length; i++) {
684             if (ctxVarParts[i].startsWith("$")) {
685                 int endBracketLoc = ctxVarParts[i].indexOf("]");
686                 if (endBracketLoc == -1) {
687                     // Missing end bracket ... give up parsing
688                     LOG.warn("Variable reference " + ctxVarName
689                             + " seems to be missing a ']'");
690                     return (ctx.getAttribute(ctxVarName));
691                 }
692
693                 String idxVarName = ctxVarParts[i].substring(1, endBracketLoc);
694                 String remainder = ctxVarParts[i].substring(endBracketLoc);
695
696                 sbuff.append("[");
697                 sbuff.append(ctx.getAttribute(idxVarName));
698                 sbuff.append(remainder);
699
700             } else {
701                 // Index is not a variable reference
702                 sbuff.append("[");
703                 sbuff.append(ctxVarParts[i]);
704             }
705         }
706
707         return (ctx.getAttribute(sbuff.toString()));
708     }
709
710 //    @Test
711     public void test90QueryTenantRequest()
712     {
713         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
714
715         URL url;
716
717         try {
718             url = client.requestVserverURLNodeQuery("bpsx0001vm001bps001");
719             url = new URL("https://mtanjv9aaas03.aic.cip.att.com:8443/aai/v4/cloud-infrastructure/tenants/tenant/6b012c07bdf1427190ae58f794a86344/vservers/vserver/5acfe828-82e9-swgk092815-13-4d2c-85bb-9c2c1fafcce6");
720             client.getTenantIdFromVserverUrl(url);
721         } catch (Exception e) {
722             // TODO Auto-generated catch block
723             e.printStackTrace();
724         }
725     }
726
727         @Test
728     public void R1702NamedQueryRequest()
729     {
730         LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------");
731         try
732         {
733             SvcLogicContext ctx = new SvcLogicContext();
734             URL resource = this.getClass().getResource("/json/nquery2.json");
735
736             LOG.info("Resource is " + resource.getFile());
737             File requestFile = new File(resource.getFile());
738             if(!requestFile.exists()) {
739                 fail("Test file does not exist");
740             }
741             ObjectMapper mapper = AAIService.getObjectMapper();
742             NamedQueryData request = mapper.readValue(requestFile, NamedQueryData.class);
743             Map<String, Object> map = mapper.convertValue(request, Map.class);
744
745             ctx.setAttribute("namedQueryData.instance-filters.instance-filter[0].l3-network.network-role", "example-network-role-val-432223");
746             ctx.setAttribute("namedQueryData.instance-filters.instance-filter_length", "1");
747             QueryStatus resp = client.query("named-query", false, null, "named-query-uuid = '4f448e43-339f-4c1c-85f6-896c444e25ca' AND prefix = 'namedQueryData' ", "zdzich", null, ctx);
748
749             LOG.info("AAIResponse: " + resp.toString());
750         }
751         catch (Throwable e)
752         {
753             assert(true);
754         }
755     }
756
757
758     static class MySchemaOutputResolver extends SchemaOutputResolver {
759
760         public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException {
761             File file = new File(suggestedFileName);
762             StreamResult result = new StreamResult(file);
763             result.setSystemId(file.getAbsolutePath());
764             return result;
765         }
766
767     }
768
769     private static void listSubNodes(String parent, Document doc, Stack<String> stack, List<String> commands) throws Exception {
770         XPathFactory xFactory = XPathFactory.newInstance();
771         XPath xPath = xFactory.newXPath();
772         String format = "/schema/element[@name='%s']/complexType/sequence/element[@ref]";
773
774         String path = String.format(format, parent);
775
776 //        XPathExpression exp = xPath.compile("/schema/element[@name='generic-vnf']/complexType/sequence/element[@ref]");
777         XPathExpression exp = xPath.compile(path);
778
779         NodeList nl = (NodeList)exp.evaluate(doc.getFirstChild(), XPathConstants.NODESET);
780         LOG.debug("Nodes to process : "+nl.getLength());
781         for (int index = 0; index < nl.getLength(); index++) {
782
783             Node node = nl.item(index);
784
785             if(!(node instanceof Element))
786                 continue;
787
788             String classAlias = null;
789
790             if(node.hasAttributes())
791             {
792                 String nm = ((Element)node).getAttribute("ref");
793                 if(nm != null && !nm.isEmpty()) {
794                     String[] split = nm.split(":");
795                     classAlias = split[split.length - 1];
796                     if("relationship-list".equals(classAlias))
797                         continue;
798                     if("metadata".equals(classAlias))
799                         continue;
800                     if("classes-of-service".equals(classAlias)) {
801                         classAlias = "class-of-service";
802                     } else if("l3-interface-ipv4-address-list".equals(classAlias)) {
803                         ;
804                     } else if("l3-interface-ipv6-address-list".equals(classAlias)) {
805                         ;
806                     } else if("cvlan-tags".equals(classAlias)) {
807                         classAlias = "cvlan-tag-entry";
808                     } else if("network-policies".equals(classAlias)) {
809                         classAlias = "network-policy";
810                     } else if("complexes".equals(classAlias)) {
811                         classAlias = "complex";
812                     } else if("dvs-switches".equals(classAlias)) {
813                         classAlias = "dvs-switch";
814                     } else if("service-capabilities".equals(classAlias)) {
815                         classAlias = "service-capability";
816                     } else {
817                         classAlias = classAlias.substring(0, classAlias.length() -1);
818                     }
819                     AAIRequest request = AAIRequest.createRequest(classAlias, new HashMap<String, String>());
820                     if(request != null) {
821                         Class<?> clazz = request.getModelClass();
822                         Field[] fieldz = clazz.getDeclaredFields();
823                         Field field = fieldz[0];
824                         String fieldName = field.getName();
825                         XmlElement annotation = field.getAnnotation(XmlElement.class);
826
827                         Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
828                         String id = (String)map.get("name");
829                         if("##default".equals(id)) {
830                             id = fieldName;
831                         }
832
833                         if("cloud-region".equals(classAlias)) {
834                             String keystring = "cloud-region.cloud-owner:assign:value:att-aic&cloud-region.cloud-region-id:assign:value:AAIAIC25";
835                             stack.push(keystring);
836                             String[] array = stack.toArray(new String[0]);
837                             String key = StringUtils.join(array, "&");
838
839                             String query = String.format("query|%s|%s", classAlias, key);
840                             commands.add(query);
841                             listSubNodes(classAlias, doc, stack, commands);
842                             stack.pop();
843                         } else if("entitlement".equals(classAlias)) {
844                             String keystring = "entitlement.group-uuid:assign:value:"+UUID.randomUUID()+"&entitlement.resource-uuid:assign:value:"+UUID.randomUUID();
845                             stack.push(keystring);
846                             String[] array = stack.toArray(new String[0]);
847                             String key = StringUtils.join(array, "&");
848
849                             String query = String.format("query|%s|%s", classAlias, key);
850                             commands.add(query);
851                             listSubNodes(classAlias, doc, stack, commands);
852                             stack.pop();
853                         } else if("license".equals(classAlias)) {
854                             String keystring = "license.group-uuid:assign:value:"+UUID.randomUUID()+"&license.resource-uuid:assign:value:"+UUID.randomUUID();
855                             stack.push(keystring);
856                             String[] array = stack.toArray(new String[0]);
857                             String key = StringUtils.join(array, "&");
858
859                             String query = String.format("query|%s|%s", classAlias, key);
860                             commands.add(query);
861                             listSubNodes(classAlias, doc, stack, commands);
862                             stack.pop();
863                         } else if("route-target".equals(classAlias)) {
864                             String keystring = "route-target.global-route-target:assign:value:"+UUID.randomUUID()+"&route-target.route-target-role:assign:value:"+UUID.randomUUID();
865                             stack.push(keystring);
866                             String[] array = stack.toArray(new String[0]);
867                             String key = StringUtils.join(array, "&");
868
869                             String query = String.format("query|%s|%s", classAlias, key);
870                             commands.add(query);
871                             listSubNodes(classAlias, doc, stack, commands);
872                             stack.pop();
873                         } else if("service-capability".equals(classAlias)) {
874                             String keystring = "service-capability.service-type:assign:value:"+UUID.randomUUID()+"&service-capability.vnf-type:assign:value:"+UUID.randomUUID();
875                             stack.push(keystring);
876                             String[] array = stack.toArray(new String[0]);
877                             String key = StringUtils.join(array, "&");
878
879                             String query = String.format("query|%s|%s", classAlias, key);
880                             commands.add(query);
881                             listSubNodes(classAlias, doc, stack, commands);
882                             stack.pop();
883                         } else if("ctag-pool".equals(classAlias)) {
884                             String keystring = "ctag-pool.target-pe:assign:value:"+UUID.randomUUID()+"&ctag-pool.availability-zone-name:assign:value:"+UUID.randomUUID();
885                             stack.push(keystring);
886                             String[] array = stack.toArray(new String[0]);
887                             String key = StringUtils.join(array, "&");
888
889                             String query = String.format("query|%s|%s", classAlias, key);
890                             commands.add(query);
891                             listSubNodes(classAlias, doc, stack, commands);
892                             stack.pop();
893                         } else {
894                             String keystring = String.format("%s.%s:assign:value:%s", classAlias, id, UUID.randomUUID());
895                             stack.push(keystring);
896                             String[] array = stack.toArray(new String[0]);
897                             String key = StringUtils.join(array, "&");
898
899                             String save = String.format("save|%s|%s", classAlias, key);
900                             commands.add(save);
901
902                             String query = String.format("query|%s|%s", classAlias, key);
903                             commands.add(query);
904
905                             String update = String.format("update|%s|%s", classAlias, key);
906                             commands.add(update);
907
908                             if(!parent.equals(classAlias) && !containsCircular(classAlias, id, stack)) {
909                                 listSubNodes(classAlias, doc, stack, commands);
910                             }
911                             String delete = String.format("delete|%s|%s", classAlias, key);
912                             commands.add(delete);
913                             stack.pop();
914                         }
915                     }
916                 }
917             }
918         }
919     }
920
921     public static boolean containsCircular(String classAlias, String id, Stack<String> stack) {
922         String keystring = String.format("%s.%s", classAlias, id);
923
924         Stack<String> localStack = new Stack<String>();
925         localStack.addAll(stack);
926
927         localStack.pop();
928
929         while(!localStack.isEmpty()) {
930             String instruction = localStack.pop();
931             if(instruction.contains(keystring)) {
932                 return true;
933             }
934         }
935
936         return false;
937     }
938 }