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