Improved Java Code Conventions compliance
[ccsdk/sli/adaptors.git] / aai-service / provider / src / main / java / org / onap / ccsdk / sli / adaptors / aai / AAIDeclarations.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 java.io.IOException;
25 import java.io.UnsupportedEncodingException;
26 import java.lang.annotation.Annotation;
27 import java.lang.reflect.Field;
28 import java.lang.reflect.InvocationTargetException;
29 import java.lang.reflect.Method;
30 import java.net.MalformedURLException;
31 import java.net.URISyntaxException;
32 import java.net.URL;
33 import java.net.URLDecoder;
34 import java.net.URLEncoder;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.HashMap;
38 import java.util.LinkedList;
39 import java.util.List;
40 import java.util.Map;
41 import java.util.Set;
42 import java.util.SortedSet;
43 import java.util.TreeSet;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
46
47 import javax.xml.bind.annotation.XmlType;
48
49 import org.apache.commons.lang.StringUtils;
50 import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum;
51 import org.onap.ccsdk.sli.adaptors.aai.query.FormattedQueryResultList;
52 import org.onap.ccsdk.sli.adaptors.aai.query.InstanceFilter;
53 import org.onap.ccsdk.sli.adaptors.aai.query.InstanceFilters;
54 import org.onap.ccsdk.sli.adaptors.aai.query.NamedQuery;
55 import org.onap.ccsdk.sli.adaptors.aai.query.NamedQueryData;
56 import org.onap.ccsdk.sli.adaptors.aai.query.QueryParameters;
57 import org.onap.ccsdk.sli.adaptors.aai.query.Result;
58 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
59 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
60 import org.openecomp.aai.inventory.v11.GenericVnf;
61 import org.openecomp.aai.inventory.v11.Image;
62 import org.openecomp.aai.inventory.v11.InventoryResponseItem;
63 import org.openecomp.aai.inventory.v11.InventoryResponseItems;
64 import org.openecomp.aai.inventory.v11.L3Network;
65 import org.openecomp.aai.inventory.v11.LogicalLink;
66 import org.openecomp.aai.inventory.v11.Metadata;
67 import org.openecomp.aai.inventory.v11.Metadatum;
68 import org.openecomp.aai.inventory.v11.Pnf;
69 import org.openecomp.aai.inventory.v11.RelatedToProperty;
70 import org.openecomp.aai.inventory.v11.Relationship;
71 import org.openecomp.aai.inventory.v11.RelationshipData;
72 import org.openecomp.aai.inventory.v11.RelationshipList;
73 import org.openecomp.aai.inventory.v11.ResultData;
74 import org.openecomp.aai.inventory.v11.SearchResults;
75 import org.openecomp.aai.inventory.v11.ServiceInstance;
76 import org.openecomp.aai.inventory.v11.Vlan;
77 import org.openecomp.aai.inventory.v11.Vlans;
78 import org.openecomp.aai.inventory.v11.Vserver;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81
82 import com.fasterxml.jackson.core.JsonParseException;
83 import com.fasterxml.jackson.databind.JsonMappingException;
84 import com.fasterxml.jackson.databind.ObjectMapper;
85
86
87 public abstract class AAIDeclarations implements AAIClient {
88
89     public static final String TRUSTSTORE_PATH    = "org.onap.ccsdk.sli.adaptors.aai.ssl.trust";
90     public static final String TRUSTSTORE_PSSWD   = "org.onap.ccsdk.sli.adaptors.aai.ssl.trust.psswd";
91     public static final String KEYSTORE_PATH      = "org.onap.ccsdk.sli.adaptors.aai.ssl.key";
92     public static final String KEYSTORE_PSSWD     = "org.onap.ccsdk.sli.adaptors.aai.ssl.key.psswd";
93
94     public static final String APPLICATION_ID     = "org.onap.ccsdk.sli.adaptors.aai.application";
95
96     public static final String CLIENT_NAME          = "org.onap.ccsdk.sli.adaptors.aai.client.name";
97     public static final String CLIENT_PWWD          = "org.onap.ccsdk.sli.adaptors.aai.client.psswd";
98
99
100     public static final String CONNECTION_TIMEOUT = "connection.timeout";
101     public static final String READ_TIMEOUT       = "read.timeout";
102
103     public static final String TARGET_URI         = "org.onap.ccsdk.sli.adaptors.aai.uri";
104
105     // Availability zones query
106     public static final String QUERY_PATH         = "org.onap.ccsdk.sli.adaptors.aai.path.query";
107
108     // Update
109     public static final String UPDATE_PATH          = "org.onap.ccsdk.sli.adaptors.aai.update";
110
111     // Service instance
112     public static final String SVC_INSTANCE_PATH  = "org.onap.ccsdk.sli.adaptors.aai.path.svcinst";
113     public static final String SVC_INST_QRY_PATH  = "org.onap.ccsdk.sli.adaptors.aai.path.svcinst.query";
114
115     // VServer
116     public static final String NETWORK_VSERVER_PATH  = "org.onap.ccsdk.sli.adaptors.aai.path.vserver";
117
118     public static final String VNF_IMAGE_QUERY_PATH      = "org.onap.ccsdk.sli.adaptors.aai.path.vnf.image.query";
119
120     public static final String PARAM_SERVICE_TYPE     = "org.onap.ccsdk.sli.adaptors.aai.param.service.type";
121     public static final String CERTIFICATE_HOST_ERROR = "org.onap.ccsdk.sli.adaptors.aai.host.certificate.ignore";
122
123     // UBB Notify
124     public static final String UBB_NOTIFY_PATH        = "org.onap.ccsdk.sli.adaptors.aai.path.notify";
125     public static final String SELFLINK_AVPN          = "org.onap.ccsdk.sli.adaptors.aai.notify.selflink.avpn";
126     public static final String SELFLINK_FQDN          = "org.onap.ccsdk.sli.adaptors.aai.notify.selflink.fqdn";
127
128     //Service
129     public static final String SERVICE_PATH              = "org.onap.ccsdk.sli.adaptors.aai.path.service";
130
131     // P-Interfaces
132     public static final String P_INTERFACE_PATH       = "org.onap.ccsdk.sli.adaptors.aai.path.pserver.pinterface";
133
134     // site-pair-sets
135     public static final String SITE_PAIR_SET_PATH     = "org.onap.ccsdk.sli.adaptors.aai.path.site.pair.set";
136
137     // node query (1602)
138     public static final String QUERY_NODES_PATH          = "org.onap.ccsdk.sli.adaptors.aai.query.nodes";
139
140
141     protected abstract Logger getLogger();
142     public abstract AAIExecutorInterface getExecutor();
143
144
145     @Override
146     public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
147         throws SvcLogicException {
148
149         getLogger().debug("AAIService.query \tresource = "+resource);
150
151         String vnfId;
152         String vnfName = null;
153         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
154         getLogger().debug("key = "+ nameValues.toString());
155
156         if(!AAIServiceUtils.isValidFormat(resource, nameValues)) {
157             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported. Key string contains invaid identifiers", resource));
158             return QueryStatus.FAILURE;
159         }
160
161         if(resource == null || resource.isEmpty() || AAIRequest.createRequest(resource, nameValues) == null) {
162             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported", resource));
163             return QueryStatus.FAILURE;
164         }
165
166         // process data using new model
167         boolean useNewModelProcessing = true;
168         // process server query by name the old way
169         if("vserver".equals(resource) || "vserver2".equals(resource)){
170             if(nameValues.containsKey("vserver_name") || nameValues.containsKey("vserver-name") || nameValues.containsKey("vserver.vserver_name") || nameValues.containsKey("vserver.vserver-name"))
171                 useNewModelProcessing = false;
172         }
173         if("generic-vnf".equals(resource)){
174             if(nameValues.containsKey("vnf_name") || nameValues.containsKey("vnf-name") || nameValues.containsKey("generic_vnf.vnf_name") || nameValues.containsKey("generic-vnf.vnf-name"))
175                 useNewModelProcessing = false;
176         }
177
178         // process data using new model
179         if(useNewModelProcessing && AAIRequest.createRequest(resource, nameValues) != null) {
180
181             try {
182                 return newModelQuery(resource, localOnly, select, key, prefix, orderBy, ctx);
183             } catch (Exception exc) {
184                 getLogger().warn("Failed query - returning FAILURE", exc);
185                 return QueryStatus.FAILURE;
186             }
187         }
188
189         ObjectMapper mapper = AAIService.getObjectMapper();
190         Map<String,Object> attributes = new HashMap<>();
191
192         String modifier = null;
193
194         if(resource.contains(":")) {
195             String[] tokens = resource.split(":");
196             resource = tokens[0];
197             if(tokens.length > 1) {
198                 modifier = tokens[1];
199             }
200         }
201
202         resource = resource.toLowerCase().replace("-", "_");
203
204         try {
205
206             switch(resource) {
207                 case "generic_vnf":
208                     vnfId = nameValues.get("vnf_id");
209                     if(nameValues.containsKey("vnf_id"))
210                         vnfId = nameValues.get("vnf_id");
211                     else if(nameValues.containsKey("generic_vnf.vnf_name"))
212                         vnfId = nameValues.get("generic_vnf.vserver_name");
213
214                     if(nameValues.containsKey("vnf_name"))
215                         vnfName = nameValues.get("vnf_name");
216                     else if(nameValues.containsKey("generic_vnf.vnf_name"))
217                         vnfName = nameValues.get("generic_vnf.vnf_name");
218
219                     if(vnfId != null && !vnfId.isEmpty()) {
220                         // at this point of the project this part should not be executed
221                         vnfId = vnfId.trim().replace("'", "").replace("$", "").replace("'", "");
222                         GenericVnf vnf = this.requestGenericVnfData(vnfId);
223                         if(vnf == null) {
224                             return QueryStatus.NOT_FOUND;
225                         }
226
227                         attributes = mapper.convertValue(vnf, attributes.getClass());
228                     } else if(vnfName != null && !vnfName.isEmpty()) {
229                         try {
230                             vnfName = vnfName.trim().replace("'", "").replace("$", "").replace("'", "");
231                             GenericVnf vnf = this.requestGenericVnfeNodeQuery(vnfName);
232                             if(vnf == null) {
233                                 return QueryStatus.NOT_FOUND;
234                             }
235                             vnfId=vnf.getVnfId();
236                             nameValues.put("vnf_id", vnfId);
237                             attributes = mapper.convertValue(vnf, attributes.getClass());
238                         } catch (AAIServiceException exc) {
239                             int errorCode = exc.getReturnCode();
240                             switch(errorCode) {
241                             case 400:
242                             case 404:
243                             case 412:
244                                 break;
245                             default:
246                                 getLogger().warn("Caught exception trying to refresh generic VNF", exc);
247                             }
248                             ctx.setAttribute(prefix + ".error.message", exc.getMessage());
249                             if(errorCode >= 300) {
250                                 ctx.setAttribute(prefix + ".error.http.response-code",
251                                                  Integer.toString(exc.getReturnCode()));
252                             }
253                             return QueryStatus.FAILURE;
254                         }
255                     } else {
256                         getLogger().warn("No arguments are available to process generic VNF");
257                         return QueryStatus.FAILURE;
258                     }
259                     break;
260                 case "vserver":
261                 case "vserver2":
262                     String vserverName = null;
263                     if(nameValues.containsKey("vserver_name"))
264                         vserverName = nameValues.get("vserver_name");
265                     else if(nameValues.containsKey("vserver.vserver_name"))
266                         vserverName = nameValues.get("vserver.vserver_name");
267
268                     String vserverId = null;
269                     if(nameValues.containsKey("vserver_id"))
270                         vserverId = nameValues.get("vserver_id");
271                     if(nameValues.containsKey("vserver.vserver_id"))
272                         vserverId = nameValues.get("vserver.vserver_id");
273                     String tenantId = nameValues.get("teannt_id");
274
275                     if(vserverName != null) vserverName = vserverName.trim().replace("'", "").replace("$", "").replace("'", "");
276                     if(vserverId != null) vserverId = vserverId.trim().replace("'", "").replace("$", "").replace("'", "");
277                     if(tenantId != null) tenantId = tenantId.trim().replace("'", "").replace("$", "").replace("'", "");
278
279                 if (vserverName != null) {
280                     URL vserverUrl = null;
281                     try {
282                         vserverUrl = this.requestVserverURLNodeQuery(vserverName);
283                     } catch (AAIServiceException aaiexc) {
284                         ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage());
285                         if (aaiexc.getReturnCode() >= 300) {
286                             ctx.setAttribute(prefix + ".error.http" + "" + ".response-code", Integer.toString(aaiexc.getReturnCode()));
287                         }
288
289                         if (aaiexc.getReturnCode() == 404)
290                             return QueryStatus.NOT_FOUND;
291                         else
292                             return QueryStatus.FAILURE;
293                     }
294                     if (vserverUrl == null) {
295                         return QueryStatus.NOT_FOUND;
296                     }
297
298                     tenantId = getTenantIdFromVserverUrl(vserverUrl);
299                             String cloudOwner = getCloudOwnerFromVserverUrl(vserverUrl);
300                             String cloudRegionId = getCloudRegionFromVserverUrl(vserverUrl);
301
302                     Vserver vserver = null;
303                     try {
304                         vserver = this.requestVServerDataByURL(vserverUrl);
305                     } catch (AAIServiceException aaiexc) {
306                         ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage());
307                         if (aaiexc.getReturnCode() >= 300) {
308                             ctx.setAttribute(prefix + ".error.http" + ".response-code", Integer.toString(aaiexc.getReturnCode()));
309                         }
310
311                         if (aaiexc.getReturnCode() == 404)
312                             return QueryStatus.NOT_FOUND;
313                         else
314                             return QueryStatus.FAILURE;
315                     }
316                     if (vserver == null) {
317                         return QueryStatus.NOT_FOUND;
318                     }
319                     attributes = mapper.convertValue(vserver, attributes.getClass());
320                     if (!attributes.containsKey("tenant-id") && tenantId != null) {
321                         attributes.put("tenant-id", tenantId);
322                     }
323                     if (!attributes.containsKey("cloud-owner") && cloudOwner != null) {
324                         attributes.put("cloud-owner", cloudOwner);
325                     }
326                     if (!attributes.containsKey("cloud-region-id") && cloudRegionId != null) {
327                         attributes.put("cloud-region-id", cloudRegionId);
328                     }
329                 } else if (vserverId != null && tenantId != null) {
330                         Vserver vserver = this.requestVServerData(tenantId, vserverId, "att-aic", "AAIAIC25");
331                         if(vserver == null) {
332                             return QueryStatus.NOT_FOUND;
333                         }
334                         attributes = mapper.convertValue(vserver, attributes.getClass());
335                         if(!attributes.containsKey("tenant-id") && tenantId != null){
336                             attributes.put("tenant-id", tenantId);
337                         }
338                     } else {
339                         return QueryStatus.FAILURE;
340                     }
341                     break;
342
343                 default:
344                     return QueryStatus.FAILURE;
345             }
346
347             QueryStatus retval = QueryStatus.SUCCESS;
348
349             if (attributes == null || attributes.isEmpty()) {
350                 retval = QueryStatus.NOT_FOUND;
351                 getLogger().debug("No data found");
352             } else {
353                 if (ctx != null) {
354                     if (prefix != null) {
355                         ArrayList<String> keys = new ArrayList<>(attributes.keySet());
356
357                         int numCols = keys.size();
358
359                         for (int i = 0; i < numCols; i++) {
360                             String colValue;
361                             String colName = keys.get(i);
362                             Object object = attributes.get(colName);
363
364                             if(object != null && object instanceof String) {
365                                 colValue = (String)object;
366
367                                 if (prefix != null) {
368                                     getLogger().debug("Setting "+prefix    + "." + colName.replaceAll("_", "-")+" = "+ colValue);
369                                     ctx.setAttribute(prefix    + "." + colName.replaceAll("_", "-"), colValue);
370                                 } else {
371                                     getLogger().debug("Setting " + colValue.replaceAll("_", "-")+" = "+colValue);
372                                     ctx.setAttribute(colValue.replaceAll("_", "-"), colValue);
373                                 }
374                             } else if(object != null && object instanceof Map) {
375                                 if(colName.equals(modifier) || "relationship-list".equals(colName)){
376                                     String localNodifier = modifier;
377                                     if(localNodifier == null)
378                                         localNodifier = "relationship-list";
379                                     Map<String, Object> properties = (Map<String, Object>)object;
380                                     writeMap(properties, prefix+"."+localNodifier,  ctx);
381                                 }
382                             }
383                         }
384                     }
385                 }
386             }
387             getLogger().debug("Query - returning " + retval);
388             return retval;
389
390         } catch (Exception exc) {
391             getLogger().warn("Failed query - returning FAILURE", exc);
392             return QueryStatus.FAILURE;
393         }
394     }
395
396
397     public void writeMap(Map<String, Object> properties, String prefix, SvcLogicContext ctx) {
398         Set<String> mapKeys = properties.keySet();
399
400         for(String mapKey : mapKeys) {
401             Object entity = properties.get(mapKey);
402             if(entity instanceof ArrayList) {
403                 writeList((ArrayList<?>)entity, prefix + "." + mapKey, ctx);
404             } else
405             if(entity instanceof String ||  entity instanceof Long || entity instanceof Integer || entity instanceof Boolean) {
406                 ctx.setAttribute(prefix + "." + mapKey, entity.toString());
407                 getLogger().debug(prefix + "." + mapKey + " : " + entity.toString());
408             } else if(entity instanceof Map) {
409                 String localPrefix = prefix;
410                 if(mapKey != null) {
411                     localPrefix = String.format("%s.%s", prefix, mapKey);
412                 }
413                 writeMap( (Map<String, Object>)entity,  localPrefix,  ctx);
414             }
415         }
416     }
417
418     private void writeList(ArrayList<?> list, String prefix, SvcLogicContext ctx) {
419         for(int i = 0; i < list.size(); i++ ) {
420             Object entity = list.get(i);
421             if(entity instanceof Map) {
422                 writeMap( (Map<String, Object>)entity,  prefix + "[" + i + "]",  ctx);
423             } else
424                 if(entity instanceof String ||  entity instanceof Long || entity instanceof Integer || entity instanceof Boolean) {
425                 ctx.setAttribute(prefix, entity.toString());
426                 getLogger().debug(prefix  + " : " + entity.toString());
427             }
428         }
429
430         if(!list.isEmpty()) {
431             ctx.setAttribute(prefix + "_length", Integer.toString(list.size()));
432             getLogger().debug(prefix + "_length"  + " : " + Integer.toString(list.size()));
433         }
434     }
435
436     @Override
437     public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
438             throws SvcLogicException {
439
440         getLogger().debug("AAIService.save\tresource="+resource);
441         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
442
443         if(!AAIServiceUtils.isValidFormat(resource, nameValues)) {
444             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported. Key string contains invaid identifiers", resource));
445             return QueryStatus.FAILURE;
446         }
447
448         if(resource == null || resource.isEmpty() || AAIRequest.createRequest(resource, nameValues) == null) {
449             getLogger().warn("AAIService.save has unspecified resource");
450             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported", resource));
451             return QueryStatus.FAILURE;
452         }
453         // keys passed
454         getLogger().debug("key = "+ Arrays.toString(nameValues.entrySet().toArray()));
455
456         // process params
457         if(params.containsKey("prefix")) {
458             Map<String, String> tmpParams = ctxGetBeginsWith(ctx, params.get("prefix"));
459             if(!tmpParams.isEmpty()) {
460                 params.putAll(tmpParams);
461 //                params.remove("prefix");
462             }
463         }
464         // params passed
465         getLogger().debug("parms = "+ Arrays.toString(params.entrySet().toArray()));
466
467         boolean useNewModelProcessing = true;
468         // process server query by name the old way
469         if("vserver".equals(resource) || "vserver2".equals(resource)){
470             if(nameValues.containsKey("vserver-name")) {
471                 useNewModelProcessing = false;
472             }
473
474             if(!params.containsKey("vserver-selflink")) {
475
476                 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
477                 URL path = null;
478                 try {
479                     request.processRequestPathValues(nameValues);
480                     path = request.getRequestUrl("GET", null);
481                     params.put("vserver-selflink", path.toString());
482                 } catch (UnsupportedEncodingException | MalformedURLException | URISyntaxException e) {
483                     params.put("vserver-selflink", "/vserver");
484                 }
485             }
486         }
487
488         // process data using new model
489         if(useNewModelProcessing && AAIRequest.createRequest(resource, nameValues) != null) {
490
491             try {
492                 if(!resource.contains(":")){
493                     return newModelSave(resource, force, key, params, prefix, ctx);
494                 } else {
495                     String[] tokens = resource.split(":");
496                     String localResource = tokens[0];
497                     String dependency = tokens[1];
498
499                     AAIDatum instance = newModelObjectRequest( localResource, nameValues, prefix, ctx);
500                     if(instance == null) {
501                         return QueryStatus.NOT_FOUND;
502                     }
503
504                     switch(dependency){
505                         case "relationship-list":
506                             newModelProcessRelationshipList(instance, params, prefix, ctx);
507                             break;
508                         case "metadata":
509                             newModelProcessMetadata(instance, params, prefix, ctx);
510                             break;
511                     }
512                     // create a method to update relationship-list
513                     AAIRequest request = AAIRequest.createRequest(localResource, nameValues);
514                     request.setRequestObject(instance);
515                     request.processRequestPathValues(nameValues);
516
517                     getExecutor().post(request);
518                     getLogger().debug("Save relationship list - returning SUCCESS");
519                     return QueryStatus.SUCCESS;
520                 }
521             } catch (Exception exc) {
522                 ctx.setAttribute(prefix + ".error.message", exc.getMessage());
523                 if(exc instanceof AAIServiceException) {
524                     AAIServiceException aaiexc = (AAIServiceException)exc;
525                     if(aaiexc.getReturnCode() >= 300) {
526                         ctx.setAttribute(prefix + ".error.http" + ".response-code", Integer.toString(aaiexc.getReturnCode()));
527                     }
528
529                     if(aaiexc.getReturnCode() == 404) {
530                         return QueryStatus.NOT_FOUND;
531                     }
532                 }
533                 getLogger().warn("Failed save() - returning FAILURE", exc);
534                 return QueryStatus.FAILURE;
535             }
536         } else {
537             getLogger().debug("Save() request for {} is not supported- returning FAILURE", resource);
538             return QueryStatus.FAILURE;
539         }
540     }
541
542     @Override
543     public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
544
545         resource = resource.toLowerCase();
546         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
547         getLogger().debug("key = "+ Arrays.toString(nameValues.entrySet().toArray()));
548         if(!AAIServiceUtils.isValidFormat(resource, nameValues)) {
549             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported. Key string contains invaid identifiers", resource));
550             return QueryStatus.FAILURE;
551         }
552
553         if(resource == null || resource.isEmpty() || AAIRequest.createRequest(resource, nameValues) == null) {
554             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not supported", resource));
555             return QueryStatus.FAILURE;
556         }
557
558         // check if request is for groups
559         if(!AAIServiceUtils.containsResource(resource, nameValues)) {
560             ctx.setAttribute(String.format("%s.error.message", prefix), String.format("Resource %s is not permitted in 'update' operation", resource));
561             return QueryStatus.FAILURE;
562         }
563
564         getLogger().debug("parms = "+ Arrays.toString(params.entrySet().toArray()));
565
566         AAIRequest request = AAIRequest.createRequest(resource, nameValues);
567         request = new UpdateRequest(request, params);
568
569         String[] arguments = request.getArgsList();
570         for(String name : arguments) {
571             String modifiedKey = name.replaceAll("-", "_");
572             if(nameValues.containsKey(modifiedKey)) {
573                 String argValue = nameValues.get(modifiedKey);
574                 if(argValue != null) argValue = argValue.trim().replace("'", "").replace("$", "").replace("'", "");
575                 request.addRequestProperty(name, argValue);
576             }
577         }
578
579         try {
580             QueryStatus retval = QueryStatus.SUCCESS;
581
582             retval = newModelQuery(resource, false, null, key, "tmpDelete", null,  ctx);
583
584             if(retval == null || retval != QueryStatus.SUCCESS) {
585                 return retval;
586             }
587
588             String resourceVersion = ctx.getAttribute("tmpDelete.resource-version");
589             if(resourceVersion == null) {
590                 return QueryStatus.NOT_FOUND;
591             }
592             params.put("resource-version", resourceVersion);
593
594             request.processRequestPathValues(nameValues);
595             getExecutor().patch(request, resourceVersion);
596         } catch(AAIServiceException aaiexc) {
597             if(aaiexc.getReturnCode() == 404)
598                 return QueryStatus.NOT_FOUND;
599             else
600                 return QueryStatus.FAILURE;
601         } catch (Exception exc) {
602             getLogger().warn("Failed update - returning FAILURE", exc);
603             return QueryStatus.FAILURE;
604         }
605
606         getLogger().debug("Update - returning SUCCESS");
607         return QueryStatus.SUCCESS;
608     }
609
610     @Override
611     public QueryStatus delete(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
612         getLogger().debug("AAIService.delete\tresource="+resource);
613         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
614         getLogger().debug("key = "+ Arrays.toString(nameValues.entrySet().toArray()));
615
616         if(!AAIServiceUtils.isValidFormat(resource, nameValues)) {
617             ctx.setAttribute(String.format("%s.error.message", "aaiData"), String.format("Resource %s is not supported. Key string contains invaid identifiers", resource));
618             return QueryStatus.FAILURE;
619         }
620
621         if(resource == null || resource.isEmpty() || AAIRequest.createRequest(resource, nameValues) == null) {
622             ctx.setAttribute(String.format("%s.error.message", "tmpDelete"), String.format("Resource %s is not supported", resource));
623             return QueryStatus.FAILURE;
624         }
625
626         // check if request is for groups
627         if(!AAIServiceUtils.containsResource(resource, nameValues)) {
628             ctx.setAttribute(String.format("%s.error.message", "tmpDelete"), String.format("Resource %s is not permitted in 'delete' operation", resource));
629             return QueryStatus.FAILURE;
630         }
631
632         if(AAIRequest.createRequest(resource, nameValues) != null) {
633             if(resource.contains(":")) {
634                 switch (resource.split(":")[1]){
635                     case "relationship-list":
636                         return processDeleteRelationshipList(resource, key, ctx, nameValues);
637                     case "metadata":
638                         return processDeleteMetadata(resource, key, ctx, nameValues);
639                 }
640             }
641
642
643             try {
644                 QueryStatus retval = QueryStatus.SUCCESS;
645
646                 retval = newModelQuery(resource, false, null, key, "tmpDelete", null,  ctx);
647
648                 if(retval == null || retval != QueryStatus.SUCCESS) {
649                     return retval;
650                 }
651
652                 String resourceVersion = ctx.getAttribute("tmpDelete.resource-version");
653                 if(resourceVersion == null) {
654                     return QueryStatus.NOT_FOUND;
655                 }
656
657                 try {
658                     AAIRequest request = AAIRequest.createRequest(resource, nameValues);
659                     if(request == null) {
660                         return QueryStatus.FAILURE;
661                     }
662
663                     request.processRequestPathValues(nameValues);
664
665                     if(getExecutor().delete(request, resourceVersion)) {
666                         return QueryStatus.SUCCESS;
667                     }
668                 } catch(AAIServiceException aaiexc) {
669                     if(aaiexc.getReturnCode() == 404)
670                         return QueryStatus.NOT_FOUND;
671                     else
672                         return QueryStatus.FAILURE;
673
674                 } catch (Exception exc) {
675                     getLogger().warn("requestGenericVnfData", exc);
676                     return QueryStatus.FAILURE;
677                 }
678
679             } catch (Exception exc) {
680                 getLogger().warn("Failed delete - returning FAILURE", exc);
681                 return QueryStatus.FAILURE;
682             }
683         } else {
684             String resourceName = resource;
685             String identifier = null;
686
687             if(resourceName.contains(":")) {
688                 String[] tokens = resourceName.split(":");
689                 if(tokens != null && tokens.length > 0) {
690                     resourceName = tokens[0];
691                     identifier = tokens[1];
692                 }
693             }
694             if("relationship-list".equals(identifier) || "relationshipList".equals(identifier)) {
695 //                RelationshipRequest relationshipRequest = new RelationshipRequest();
696                 if("generic-vnf".equals(resourceName)){
697                     String vnfId = nameValues.get("vnf_id");
698                     String relatedTo  = nameValues.get("related_to");
699                     vnfId = vnfId.trim().replace("'", "").replace("$", "").replace("'", "");
700                     relatedTo = relatedTo.trim().replace("'", "").replace("$", "").replace("'", "");
701
702                     GenericVnf vnf;
703                     try {
704                         vnf = this.requestGenericVnfData(vnfId);
705                         if(vnf == null)
706                             return QueryStatus.NOT_FOUND;
707                     } catch (AAIServiceException exc) {
708                         getLogger().warn("Failed delete - returning NOT_FOUND", exc);
709                         return QueryStatus.NOT_FOUND;
710                     }
711                     boolean itemRemoved = false;
712                     RelationshipList relationshipList = vnf.getRelationshipList();
713                     List<Relationship> relationships = relationshipList.getRelationship();
714                     List<Relationship> iterableList = new LinkedList<>(relationships);
715                     for(Relationship relationship : iterableList) {
716                         if(relationship.getRelatedTo().equals(relatedTo)) {
717                             relationships.remove(relationship);
718                             itemRemoved = true;
719                         }
720                     }
721
722                     if(!itemRemoved)
723                         return QueryStatus.NOT_FOUND;
724
725 //                    AAIRequest masterRequest = new GenericVnfRequest();
726 //                    masterRequest.addRequestProperty(GenericVnfRequest.VNF_ID, vnfId);
727 //                    relationshipRequest.addMasterRequest(masterRequest);
728 //                    Map<String, String> attributes = objectToProperties(vnf);
729 //                    try {
730 //                        Boolean result = getExecutor().delete(relationshipRequest, attributes.get(AAIRequest.RESOURCE_VERSION));
731 //                    } catch (AAIServiceException e) {
732 //                        return QueryStatus.FAILURE;
733 //                    }
734
735                     try {
736                         this.postGenericVnfData(vnf.getVnfId(), vnf);
737                     } catch (AAIServiceException exc) {
738                         if(exc.getReturnCode() == 404){
739                             return QueryStatus.NOT_FOUND;
740                         } else {
741                             getLogger().warn("Failed delete - returning FAILURE", exc);
742                             return QueryStatus.FAILURE;
743                         }
744                     }
745                     return QueryStatus.SUCCESS;
746                 }
747             }
748         }
749         return QueryStatus.FAILURE;
750     }
751
752     @Override
753     public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException {
754         return query(resource, false, null, key, prefix, null, ctx);
755     }
756
757     @Override
758     public QueryStatus isAvailable(String arg0, String arg1, String arg2, SvcLogicContext arg3)
759             throws SvcLogicException {
760         throw new SvcLogicException("Method AAIService.isAvailable() has not been implemented yet");
761     }
762
763     @Override
764     public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException {
765         throw new SvcLogicException("Method AAIService.notify() has not been implemented yet");
766     }
767
768 //    @Override
769     public QueryStatus newModelQuery(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) {
770
771         QueryStatus retval = QueryStatus.SUCCESS;
772         String modifier = null;
773
774         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
775         if(resource.contains(":")) {
776             modifier = resource.split(":")[1];
777         }
778
779         try {
780             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
781             if(request == null) {
782                 return QueryStatus.FAILURE;
783             }
784
785             Map<String, String> params = new HashMap<>();
786
787             request.processRequestPathValues(nameValues);
788             if(nameValues.containsKey("prefix")){
789                 Map<String, String> tmpParams = ctxGetBeginsWith(ctx, nameValues.get("prefix"));
790                 if(!tmpParams.isEmpty()) {
791                     params.putAll(tmpParams);
792                 }
793                 if("named-query".equals(resource))
794                     request.setRequestObject(extractNamedQueryDataFromQueryPrefix(nameValues, params));
795             }
796             String rv = getExecutor().get(request);
797
798             retval = processResponseData(rv, resource, request, prefix,  ctx, nameValues, modifier);
799
800         } catch(AAIServiceException aaiexc) {
801             int errorCode = aaiexc.getReturnCode();
802             ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage());
803             if(errorCode >= 300) {
804                 ctx.setAttribute(prefix + ".error.http.response-code",
805                         Integer.toString(aaiexc.getReturnCode()));
806             }
807
808             if(aaiexc.getReturnCode() == 404)
809                 return QueryStatus.NOT_FOUND;
810
811             return QueryStatus.FAILURE;
812         } catch (Exception exc) {
813             getLogger().warn("requestGenericVnfData", exc);
814             ctx.setAttribute(prefix + ".error.message", exc.getMessage());
815             return QueryStatus.FAILURE;
816         }
817
818         return retval;
819     }
820
821     public QueryStatus processResponseData(String rv, String resource, AAIRequest request, String prefix,  SvcLogicContext ctx, Map<String, String> nameValues, String modifier) throws JsonParseException, JsonMappingException, IOException, AAIServiceException
822     {
823         Object response;
824
825             if(rv == null) {
826                 return QueryStatus.NOT_FOUND;
827             }
828
829             response = request.jsonStringToObject(rv);
830             if(response == null) {
831                 return QueryStatus.NOT_FOUND;
832             }
833
834             if("generic-query".equals(resource)) {
835                 SearchResults rd = SearchResults.class.cast(response);
836                 List<ResultData> rdList = rd.getResultData();
837                 if(rdList == null || rdList.isEmpty()) {
838                     return QueryStatus.NOT_FOUND;
839                 }
840                 ResultData rDatum = rdList.get(0);
841                 nameValues.put("selflink", rDatum.getResourceLink());
842                 AAIRequest req2 = AAIRequest.createRequest(rDatum.getResourceType(), nameValues);
843                 req2.processRequestPathValues(nameValues);
844                 rv = getExecutor().get(req2);
845                 if(rv == null) {
846                     return QueryStatus.NOT_FOUND;
847                 }
848
849                 response = req2.jsonStringToObject(rv);
850                 if(response == null) {
851                     return QueryStatus.NOT_FOUND;
852                 }
853             }
854
855             if("named-query".equals(resource)) {
856                 InventoryResponseItems rd = InventoryResponseItems.class.cast(response);
857                 List<InventoryResponseItem> iRIlist = rd.getInventoryResponseItem();
858                 if(iRIlist == null || iRIlist.isEmpty()) {
859                     return QueryStatus.NOT_FOUND;
860                 }
861             }
862
863             if("nodes-query".equals(resource)) {
864                 SearchResults rd = SearchResults.class.cast(response);
865                 List<ResultData> rdList = rd.getResultData();
866                 if(rdList == null || rdList.isEmpty()) {
867                     return QueryStatus.NOT_FOUND;
868                 }
869                 ResultData rDatum = rdList.get(0);
870                 response = rDatum;
871             }
872
873         if("formatted-query".equals(resource) || "custom-query".equals(resource)) {
874             FormattedQueryResultList rd = FormattedQueryResultList.class.cast(response);
875             List<Result> iRIlist = rd.getResults();
876             if(iRIlist == null || iRIlist.isEmpty()) {
877                 return QueryStatus.NOT_FOUND;
878             }
879         }
880
881         // process relationship list
882         // this is a temporary soluton to address the realationship handling changes added in Release 17.07
883         try {
884             Class<?> clazz = response.getClass();
885             Method getter = clazz.getMethod("getRelationshipList");
886             Object obj = getter.invoke(response);
887             if(obj != null && obj instanceof RelationshipList) {
888                 RelationshipList list = RelationshipList.class.cast(obj);
889                 AAIServiceUtils.populateRelationshipDataFromPath(list);
890             }
891         } catch(Exception exc) {
892             getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
893         }
894
895             String preFix;
896             if(prefix == null || prefix.isEmpty()) {
897                 preFix = "";
898             } else {
899                 preFix = prefix + ".";
900             }
901
902             Map<String,Object> props = objectToProperties(response);
903             Set<String> keys = props.keySet();
904             for(String theKey: keys) {
905                 if(getLogger().isTraceEnabled())
906                     getLogger().trace(theKey);
907
908                 Object value = props.get(theKey);
909                 if(value == null)
910                     continue;
911                 Object type = value.getClass();
912                 if(value instanceof String) {
913                     ctx.setAttribute(preFix + theKey, value.toString());
914                     continue;
915                 }
916                 if(value instanceof Boolean) {
917                     ctx.setAttribute(preFix + theKey, value.toString());
918                     continue;
919                 }
920                 if(value instanceof Integer) {
921                     ctx.setAttribute(preFix + theKey, value.toString());
922                     continue;
923                 }
924                 if(value instanceof Long) {
925                     ctx.setAttribute(preFix + theKey, value.toString());
926                     continue;
927                 }
928
929                 if(value instanceof ArrayList) {
930                     ArrayList<?> array = ArrayList.class.cast(value);
931                     for(int i = 0; i < array.size(); i++) {
932                         writeList(array, String.format("%s.%s", prefix, theKey), ctx);
933                     }
934                     continue;
935                 }
936
937                 if("relationship-list".equals(theKey)){
938                     Map<String, Object> relationshipList = (Map<String, Object>)value;
939                     // we are interested in seeing just the selected relationship
940                     if(theKey.equals(modifier)) {
941                         List<?> relationships = (List<?>)relationshipList.get("relationship");
942                         if(relationships != null && !relationships.isEmpty()) {
943
944                             List newRelationships = new LinkedList();
945                             newRelationships.addAll(relationships);
946
947                             for(Object obj : newRelationships){
948                                 if(obj instanceof Map<?, ?>) {
949                                     Map<?, ?> relProperties = (Map<?, ?>)obj;
950                                     if(relProperties.containsKey("related-to")) {
951                                         Object relPropsRelatedTo = relProperties.get("related-to");
952
953                                         String relatedTo = nameValues.get("related_to");
954                                         if(relatedTo != null) {
955                                             relatedTo = relatedTo.trim().replace("'", "").replace("$", "").replace("'", "");
956                                             if(!relatedTo.equals(relPropsRelatedTo)) {
957                                                 relationships.remove(relProperties);
958                                             }
959                                             continue;
960                                         } else {
961                                             continue;
962                                         }
963                                     }
964                                 }
965                             }
966                         }
967                     }
968                     writeMap(relationshipList, String.format("%s.%s", prefix, theKey), ctx);
969                     continue;
970                 }
971
972                 if(value instanceof Map) {
973                     Map<String, Object> subnetsList = (Map<String, Object>)value;
974                     writeMap(subnetsList, String.format("%s.%s", prefix, theKey), ctx);
975                     continue;
976                 }
977
978             }
979         return QueryStatus.SUCCESS;
980     }
981
982
983     public QueryStatus newModelBackupRequest(String resource,  Map<String, String> params,  String prefix,  SvcLogicContext ctx) {
984
985         QueryStatus retval = QueryStatus.SUCCESS;
986         HashMap<String, String> nameValues = new HashMap<>();
987
988         try {
989             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
990             if(request == null) {
991                 return QueryStatus.FAILURE;
992             }
993
994             boolean argsFound = false;
995             String[] arguments = request.getArgsList();
996             for(String name : arguments) {
997                 String tmpName = name.replaceAll("-", "_");
998                 String value = params.get(tmpName);
999                 if(value != null && !value.isEmpty()) {
1000                     value = value.trim().replace("'", "").replace("$", "").replace("'", "");
1001                     request.addRequestProperty(name, value);
1002                     argsFound = true;
1003                 }
1004             }
1005             if(!argsFound) {
1006                 getLogger().warn("No arguments were found. Terminating backup request.");
1007                 return QueryStatus.FAILURE;
1008             }
1009
1010             String rv = getExecutor().get(request);
1011             ctx.setAttribute(prefix, rv);
1012         } catch(AAIServiceException aaiexc) {
1013             if(aaiexc.getReturnCode() == 404)
1014                 return QueryStatus.NOT_FOUND;
1015
1016             return QueryStatus.FAILURE;
1017         } catch (Exception exc) {
1018             getLogger().warn("newModelBackupRequest", exc);
1019             return QueryStatus.FAILURE;
1020         }
1021
1022         return retval;
1023     }
1024
1025     public AAIDatum newModelObjectRequest(String resource,  Map<String, String> params,  String prefix,  SvcLogicContext ctx)
1026             throws AAIServiceException {
1027
1028         AAIDatum response = null;
1029
1030         try {
1031             AAIRequest request = AAIRequest.createRequest(resource, params);
1032             if(request == null) {
1033                 return null;
1034             }
1035
1036             request.processRequestPathValues(params);
1037             String rv = getExecutor().get(request);
1038             response = request.jsonStringToObject(rv);
1039         } catch(AAIServiceException aaiexc) {
1040             throw aaiexc;
1041         } catch (Exception exc) {
1042             getLogger().warn("newModelBackupRequest", exc);
1043             throw new AAIServiceException(exc);
1044         }
1045
1046         return response;
1047     }
1048
1049
1050     @Override
1051     public QueryStatus release(String arg0, String arg1, SvcLogicContext arg2) throws SvcLogicException {
1052         throw new SvcLogicException("Method AAIService.release() has not been implemented yet");
1053     }
1054
1055     @Override
1056     public QueryStatus reserve(String arg0, String arg1, String arg2, String arg3, SvcLogicContext arg4)
1057             throws SvcLogicException {
1058         throw new SvcLogicException("Method AAIService.reserve() has not been implemented yet");
1059     }
1060
1061     private QueryStatus newModelSave(String resource, boolean force, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) {
1062         getLogger().debug("Executing newModelSave for resource : " + resource);
1063         HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1064
1065         try {
1066             ArrayList<String> subResources = new ArrayList<>();
1067             Set<String> set = params.keySet();
1068             Map<String, Method> setters = new HashMap<>();
1069             Map<String, Method> getters = new HashMap<>();
1070
1071             // 1. find class
1072             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1073             Class<? extends AAIDatum> resourceClass = request.getModelClass();
1074             getLogger().debug(resourceClass.getName());
1075             AAIDatum instance = resourceClass.newInstance();
1076
1077             {
1078                 Annotation[] annotations = resourceClass.getAnnotations();
1079                 for(Annotation annotation : annotations) {
1080                     Class<? extends Annotation> anotationType = annotation.annotationType();
1081                     String annotationName = anotationType.getName();
1082
1083                     // 2. find string property setters and getters for the lists
1084                     if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
1085                         XmlType order = (XmlType)annotation;
1086                         String[]  values = order.propOrder();
1087                         for(String value : values) {
1088                             String id = AAIServiceUtils.camelCaseToDashedString(value);
1089                             Field field = resourceClass.getDeclaredField(value);
1090                             Class<?> type = field.getType();
1091                             Method setter = null;
1092                             try {
1093                                 setter = resourceClass.getMethod("set"+StringUtils.capitalize(value), type);
1094                                 if(type.getName().startsWith("java.lang") || "boolean".equals(type.getName()) || "long".equals(type.getName())) {
1095                                     try {
1096                                         setter.setAccessible(true);
1097                                         Object arglist[] = new Object[1];
1098                                         arglist[0] = params.get(id);
1099
1100                                         if(arglist[0] != null) {
1101                                             if(!type.getName().equals("java.lang.String")) {
1102 //                                            getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
1103                                                 if("boolean".equals(type.getName())) {
1104                                                     arglist[0] = valueOf(Boolean.class, params.get(id));
1105                                                 } else if("long".equals(type.getName())) {
1106                                                         arglist[0] = valueOf(Long.class, params.get(id));
1107                                                 } else {
1108                                                     arglist[0] = valueOf(type, params.get(id));
1109                                                 }
1110                                             }
1111                                             Object obj = setter.invoke(instance, arglist);
1112                                         }
1113                                         set.remove(id);
1114
1115                                     } catch (Exception x) {
1116                                         Throwable cause = x.getCause();
1117                                         getLogger().warn("Failed process for " + resourceClass.getName(), x);
1118                                     }
1119                                 } else if("java.util.List".equals(type.getName())) {
1120                                     List<String> newValues = new ArrayList<>();
1121                                     String length = id+"_length";
1122                                     if(!params.isEmpty() && params.containsKey(length)) {
1123                                         String tmp = params.get(length);
1124                                         int count = Integer.parseInt(tmp);
1125                                         for(int i=0; i<count; i++) {
1126                                             String tmpValue = params.get(String.format("%s[%d]", id, i));
1127                                             newValues.add(tmpValue);
1128                                         }
1129                                         if(!newValues.isEmpty()) {
1130                                             Object o = setter.invoke(instance, newValues);
1131                                         }
1132                                     }
1133                                     set.remove(id);
1134                                 } else {
1135                                     setters.put(id, setter);
1136                                 }
1137                             } catch(Exception exc) {
1138
1139                             }
1140
1141                             Method getter;
1142                             try {
1143                                 getter = resourceClass.getMethod("get"+StringUtils.capitalize(value));
1144                                 if(!type.getName().equals("java.lang.String")) {
1145                                     getters.put(id, getter);
1146                                 }
1147                             } catch(Exception exc) {
1148
1149                             }
1150
1151                         }
1152                         subResources.addAll(Arrays.asList(values));
1153                     }
1154                 }
1155             }
1156
1157             // remove getters that have matching setter
1158             for(String setKey : setters.keySet()) {
1159                 if(getters.containsKey(setKey)) {
1160                     getters.remove(setKey);
1161                 }
1162             }
1163
1164             Set<String> relationshipKeys = new TreeSet<>();
1165             Set<String> vlansKeys = new TreeSet<>();
1166             Set<String> metadataKeys = new TreeSet<>();
1167
1168             for(String attribute : set) {
1169                 String value = params.get(attribute);
1170                 if(attribute.startsWith("relationship-list")) {
1171                     relationshipKeys.add(attribute);
1172                 } else if(attribute.startsWith("vlans")) {
1173                     vlansKeys.add(attribute);
1174                 } else if(attribute.startsWith("metadata")) {
1175                     metadataKeys.add(attribute);
1176                 }
1177             }
1178             // 3. find list property getters
1179             for(String attribute : set) {
1180                 String value = params.get(attribute);
1181                 Method method = getters.get(attribute);
1182                 if(method != null) {
1183                     try {
1184                         method.setAccessible(true);
1185                         Object arglist[] = new Object[0];
1186 //                        arglist[0] = value;
1187                         Class<?>[] types = method.getParameterTypes();
1188                         if(types.length == 0){
1189                             Object o = method.invoke(instance, arglist);
1190                             if(o instanceof ArrayList) {
1191                                 ArrayList<String> values = (ArrayList<String>)o;
1192 //                                getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
1193                                 value = value.replace("[", "").replace("]", "");
1194                                 List<String> items = Arrays.asList(value.split("\\s*,\\s*"));
1195                                 for(String s : items) {
1196                                     values.add(s.trim());
1197                                 }
1198                             }
1199                         }
1200                     } catch (Exception x) {
1201                         Throwable cause = x.getCause();
1202                         getLogger().warn("Failed process for " + resourceClass.getName(), x);
1203                     }
1204                 }
1205             }
1206             // 4. Process Relationships
1207             // add relationship list
1208             if( (subResources.contains("relationship-list") || subResources.contains("relationshipList")) &&  !relationshipKeys.isEmpty()) {
1209                 RelationshipList relationshipList = null;
1210                 Object obj = null;
1211                 Method getRelationshipListMethod = null;
1212                 try {
1213                      getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1214                 } catch(Exception exc) {
1215                     getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1216                 }
1217
1218                 if(getRelationshipListMethod != null){
1219                     try {
1220                         getRelationshipListMethod.setAccessible(true);
1221                         obj = getRelationshipListMethod.invoke(instance);
1222                     } catch (InvocationTargetException x) {
1223                         Throwable cause = x.getCause();
1224                     }
1225                 }
1226                 if(obj != null && obj instanceof RelationshipList){
1227                     relationshipList = (RelationshipList)obj;
1228                 } else {
1229                     relationshipList = new RelationshipList();
1230                     Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList", RelationshipList.class);
1231                     if(setRelationshipListMethod != null){
1232                         try {
1233                             setRelationshipListMethod.setAccessible(true);
1234                             Object arglist[] = new Object[1];
1235                             arglist[0] = relationshipList;
1236
1237                             obj = setRelationshipListMethod.invoke(instance, arglist);
1238                         } catch (InvocationTargetException x) {
1239                             Throwable cause = x.getCause();
1240                         }
1241                     }
1242                 }
1243
1244                 List<Relationship> relationships = relationshipList.getRelationship();
1245
1246                 int i = 0;
1247                 while(true){
1248                     String searchKey = "relationship-list.relationship[" + i + "].related-to";
1249                     if(!params.containsKey(searchKey))
1250                         break;
1251                     int j = 0;
1252                     String relatedTo = params.get(searchKey);
1253                     String relatedLinkKey = "relationship-list.relationship[" + i + "].related-link";
1254                     String relatedLink = null;
1255                     if(params.containsKey(relatedLinkKey)) {
1256                         relatedLink = params.get(relatedLinkKey);
1257                     }
1258                     Relationship relationship = new Relationship();
1259                     relationships.add(relationship);
1260                     relationship.setRelatedTo(relatedTo);
1261                     if(relatedLink != null) {
1262                         relationship.setRelatedLink(relatedLink);
1263                     } else {
1264                         Map<String, String> relParams = new HashMap<>();
1265
1266                             while(true) {
1267                                 String searchRelationshipKey = "relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-key";
1268                                 String searchRelationshipValue = "relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-value";
1269                                     if(!params.containsKey(searchRelationshipKey))
1270                                     break;
1271
1272                                     relParams.put(params.get(searchRelationshipKey), params.get(searchRelationshipValue));
1273                                 j++;
1274                             }
1275                         AAIRequest rlRequest = AAIRequest.createRequest(relatedTo, relParams);
1276                         for(Map.Entry<String,String> entry : relParams.entrySet()) {
1277                             rlRequest.addRequestProperty(entry.getKey(), entry.getValue());
1278                         }
1279                         String path = rlRequest.updatePathDataValues(null);
1280                         relationship.setRelatedLink(path);
1281                     }
1282                                 {
1283                                         int k = 0;
1284                                         // process related to properties
1285                                         Map<String, String> relParams = new HashMap<String, String>();
1286
1287                                         while(true) {
1288                                                 String searchRelatedToKey = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-key";
1289                                                 String searchRelatedToValue = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-value";
1290                                                 if(!params.containsKey(searchRelatedToKey))
1291                                                         break;
1292
1293                                                 RelatedToProperty relDatum = new RelatedToProperty();
1294                                                 relDatum.setPropertyKey(params.get(searchRelatedToKey));
1295                                                 relDatum.setPropertyValue(params.get(searchRelatedToValue));
1296                                                 relationship.getRelatedToProperty().add(relDatum);
1297
1298                                                 relParams.put(params.get(searchRelatedToKey), params.get(searchRelatedToValue));
1299                                                 k++;
1300                                         }
1301                                 }
1302                     i++;
1303                 }
1304             }
1305
1306             // 4. vlans
1307             if(subResources.contains("vlans") &&  !vlansKeys.isEmpty()) {
1308                 Object obj = null;
1309                 Vlans vlanList = null;
1310                 Method getVLansMethod = resourceClass.getMethod("getVlans");
1311                 if(getVLansMethod != null){
1312                     try {
1313                         getVLansMethod.setAccessible(true);
1314                         obj = getVLansMethod.invoke(instance);
1315                     } catch (InvocationTargetException x) {
1316                         Throwable cause = x.getCause();
1317                     }
1318                 }
1319                 if(obj != null && obj instanceof Vlans){
1320                     vlanList = (Vlans)obj;
1321                 } else {
1322                     vlanList = new Vlans();
1323                     Method setVlansMethod = resourceClass.getMethod("setVlans", Vlans.class);
1324                     if(setVlansMethod != null){
1325                         try {
1326                             setVlansMethod.setAccessible(true);
1327                             Object arglist[] = new Object[1];
1328                             arglist[0] = vlanList;
1329
1330                             obj = setVlansMethod.invoke(instance, arglist);
1331                         } catch (InvocationTargetException x) {
1332                             Throwable cause = x.getCause();
1333                         }
1334                     }
1335                 }
1336
1337                 int i = 0;
1338                 while(true){
1339                     String searchKey = "vlans.vlan[" + i + "].vlan-interface";
1340                     if(!params.containsKey(searchKey))
1341                         break;
1342
1343                     String vlanInterface = params.get("vlans.vlan[" + i + "].vlan-interface");
1344                     String vlanIdInner    = params.get("vlans.vlan[" + i + "].vlan-id-inner");
1345                     String vlanIdOute     = params.get("vlans.vlan[" + i + "].vlan-id-outer");
1346                     String speedValue     = params.get("vlans.vlan[" + i + "].speed-value");
1347                     String speedUnits     = params.get("vlans.vlan[" + i + "].speed-units");
1348
1349                     Vlan vlan = new Vlan();
1350                     vlan.setVlanInterface(vlanInterface);
1351
1352                     if(vlanIdInner != null) {
1353                     Long iVlanIdInner = Long.parseLong(vlanIdInner);
1354                     vlan.setVlanIdInner(iVlanIdInner);
1355                     }
1356
1357                     if(vlanIdOute != null) {
1358                         Long iVlanIdOuter = Long.parseLong(vlanIdOute);
1359                     vlan.setVlanIdOuter(iVlanIdOuter);
1360                     }
1361
1362                     if(speedValue != null) {
1363                     vlan.setSpeedValue(speedValue);
1364                     vlan.setSpeedUnits(speedUnits);
1365                     }
1366
1367                     vlanList.getVlan().add(vlan);
1368                     i++;
1369                 }
1370             }
1371
1372             // 5. metadata
1373             if(subResources.contains("metadata") &&  !metadataKeys.isEmpty()) {
1374                 Object obj = null;
1375                 Metadata metadataList = null;
1376                 Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1377                 if(getMetadataMethod != null){
1378                     try {
1379                         getMetadataMethod.setAccessible(true);
1380                         obj = getMetadataMethod.invoke(instance);
1381                     } catch (InvocationTargetException x) {
1382                         Throwable cause = x.getCause();
1383                     }
1384                 }
1385                 if(obj != null && obj instanceof Metadata){
1386                     metadataList = (Metadata)obj;
1387                 } else {
1388                     metadataList = new Metadata();
1389                     Method setMetadataMethod = resourceClass.getMethod("setMetadata", Metadata.class);
1390                     if(setMetadataMethod != null){
1391                         try {
1392                             setMetadataMethod.setAccessible(true);
1393                             Object arglist[] = new Object[1];
1394                             arglist[0] = metadataList;
1395
1396                             obj = setMetadataMethod.invoke(instance, arglist);
1397                         } catch (InvocationTargetException x) {
1398                             Throwable cause = x.getCause();
1399                         }
1400                     }
1401                 }
1402
1403                 // process data
1404                 int i = 0;
1405                 while(true){
1406                     String metaKey = "metadata.metadatum[" + i + "].meta-key";
1407                     if(!params.containsKey(metaKey))
1408                         break;
1409
1410                     String metaValue = params.get("metadata.metadatum[" + i + "].meta-value");
1411
1412                     Metadatum vlan = new Metadatum();
1413                     vlan.setMetaname(metaKey);
1414                     vlan.setMetaval(metaValue);
1415
1416                     metadataList.getMetadatum().add(vlan);
1417                     i++;
1418                 }
1419
1420             }
1421
1422
1423             // 6. Prepare AAI request
1424             String[] args = request.getArgsList();
1425             for(String arg : args) {
1426                 String modifiedKey = arg.replaceAll("-", "_");
1427                 if(nameValues.containsKey(modifiedKey)) {
1428                     String argValue = nameValues.get(modifiedKey);
1429                     if(argValue != null) argValue = argValue.trim().replace("'", "").replace("$", "").replace("'", "");
1430                     request.addRequestProperty(arg, argValue);
1431                 }
1432             }
1433
1434             request.processRequestPathValues(nameValues);
1435             request.setRequestObject(instance);
1436                 Object response = getExecutor().post(request);
1437                 if(request.expectsDataFromPUTRequest()){
1438                     if(response != null && response instanceof String) {
1439                         String rv = response.toString();
1440                         QueryStatus retval = processResponseData(rv, resource, request, prefix,  ctx, nameValues, null);
1441                         getLogger().debug("newModelSave - returning " + retval.toString());
1442                         return retval;
1443                     }
1444                 }
1445
1446         } catch(AAIServiceException exc){
1447             ctx.setAttribute(prefix + ".error.message", exc.getMessage());
1448             int returnCode = exc.getReturnCode();
1449             if(returnCode >= 300) {
1450                 ctx.setAttribute(prefix + ".error.http.response-code",
1451                         Integer.toString(exc.getReturnCode()));
1452             }
1453
1454             if(returnCode == 400 || returnCode == 412)
1455                 return QueryStatus.FAILURE;
1456             else if(returnCode == 404)
1457                 return QueryStatus.NOT_FOUND;
1458             else {
1459                 getLogger().warn("Failed newModelSave - returning FAILURE", exc);
1460                 return QueryStatus.FAILURE;
1461             }
1462         } catch(Exception exc){
1463             getLogger().warn("Failed newModelSave - returning FAILURE", exc);
1464             ctx.setAttribute(prefix + ".error.message", exc.getMessage());
1465             return QueryStatus.FAILURE;
1466         }
1467
1468         getLogger().debug("newModelSave - returning SUCCESS");
1469         return QueryStatus.SUCCESS;
1470     }
1471
1472     private QueryStatus newModelProcessRelationshipList(Object instance, Map<String, String> params, String prefix, SvcLogicContext ctx) throws Exception {
1473
1474         Class resourceClass = instance.getClass();
1475
1476         Set<String> relationshipKeys = new TreeSet<>();
1477
1478         Set<String> set = params.keySet();
1479
1480         for(String attribute : set) {
1481             String value = params.get(attribute);
1482
1483             if(attribute.startsWith("relationship-list")) {
1484                 relationshipKeys.add(attribute);
1485             }
1486         }
1487
1488         // 3. Process Relationships
1489         // add relationship list
1490         if(!relationshipKeys.isEmpty()) {
1491             RelationshipList relationshipList;
1492             Object obj = null;
1493             Method getRelationshipListMethod = null;
1494             try {
1495                  getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1496             } catch(Exception exc) {
1497                 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1498             }
1499             if(getRelationshipListMethod != null){
1500                 try {
1501                     getRelationshipListMethod.setAccessible(true);
1502                     obj = getRelationshipListMethod.invoke(instance);
1503                 } catch (InvocationTargetException x) {
1504                     Throwable cause = x.getCause();
1505                 }
1506             }
1507             if(obj != null && obj instanceof RelationshipList){
1508                 relationshipList = (RelationshipList)obj;
1509             } else {
1510                 relationshipList = new RelationshipList();
1511                 Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList", RelationshipList.class);
1512                 if(setRelationshipListMethod != null){
1513                     try {
1514                         setRelationshipListMethod.setAccessible(true);
1515                         Object arglist[] = new Object[1];
1516                         arglist[0] = relationshipList;
1517
1518                         obj = setRelationshipListMethod.invoke(instance, arglist);
1519                     } catch (InvocationTargetException x) {
1520                         Throwable cause = x.getCause();
1521                     }
1522                 }
1523             }
1524
1525             boolean createdNewRelationships = false;
1526             List<Relationship> relationships = relationshipList.getRelationship();
1527             if(relationships == null) {
1528                 relationships = new ArrayList<>();
1529                 createdNewRelationships = true;
1530             }
1531
1532             int i = 0;
1533             while(true){
1534                 String searchKey = "relationship-list.relationship[" + i + "].related-to";
1535                 if(!params.containsKey(searchKey))
1536                     break;
1537
1538                 String relatedTo = params.get(searchKey);
1539                 String relatedLinkKey = "relationship-list.relationship[" + i + "].related-link";
1540                 String relatedLink = null;
1541                 if(params.containsKey(relatedLinkKey)) {
1542                     relatedLink = params.get(relatedLinkKey);
1543                 }
1544
1545                                 Relationship relationship = new Relationship();
1546                                 relationships.add(relationship);
1547                                 relationship.setRelatedTo(relatedTo);
1548                                 if (relatedLink != null) {
1549                                         relationship.setRelatedLink(relatedLink);
1550                                 } else {
1551                                         Map<String, String> relParams = new HashMap<>();
1552                                         int j = 0;
1553
1554                                         while (true) {
1555                                                 String searchRelationshipKey = "relationship-list.relationship[" + i + "].relationship-data["
1556                                                                 + j + "].relationship-key";
1557                                                 String searchRelationshipValue = "relationship-list.relationship[" + i + "].relationship-data["
1558                                                                 + j + "].relationship-value";
1559                                                 if (!params.containsKey(searchRelationshipKey))
1560                                                         break;
1561
1562                                                 RelationshipData relDatum = new RelationshipData();
1563                                                 relDatum.setRelationshipKey(params.get(searchRelationshipKey));
1564                                                 relDatum.setRelationshipValue(params.get(searchRelationshipValue));
1565                                                 relationship.getRelationshipData().add(relDatum);
1566
1567                                                 relParams.put(params.get(searchRelationshipKey), params.get(searchRelationshipValue));
1568                                                 j++;
1569                                         }
1570                                         AAIRequest rlRequest = AAIRequest.createRequest(relatedTo, relParams);
1571                                         for (Map.Entry<String, String> entry : relParams.entrySet()) {
1572                                                 rlRequest.addRequestProperty(entry.getKey(), entry.getValue());
1573                                         }
1574                                         String path = rlRequest.updatePathDataValues(null);
1575                                         relationship.setRelatedLink(path);
1576                                 }
1577                                 {
1578                                         int k = 0;
1579                                         // process related to properties
1580                                         Map<String, String> relParams = new HashMap<String, String>();
1581
1582                                         while(true) {
1583                                                 String searchRelatedToKey = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-key";
1584                                                 String searchRelatedToValue = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-value";
1585                                                 if(!params.containsKey(searchRelatedToKey))
1586                                                         break;
1587
1588                                                 RelatedToProperty relDatum = new RelatedToProperty();
1589                                                 relDatum.setPropertyKey(params.get(searchRelatedToKey));
1590                                                 relDatum.setPropertyValue(params.get(searchRelatedToValue));
1591                                                 relationship.getRelatedToProperty().add(relDatum);
1592
1593                                                 relParams.put(params.get(searchRelatedToKey), params.get(searchRelatedToValue));
1594                                                 k++;
1595                                         }
1596                                 }
1597
1598                                 i++;
1599                         }
1600         }
1601
1602         return QueryStatus.SUCCESS;
1603     }
1604
1605     private QueryStatus newModelProcessMetadata(Object instance, Map<String, String> params, String prefix, SvcLogicContext ctx) throws Exception {
1606
1607         if (!(instance instanceof ServiceInstance) && !(instance instanceof Image)) {
1608             throw new IllegalArgumentException("request is not applicable for selected request");
1609         }
1610
1611         Class resourceClass = instance.getClass();
1612         Set<String> metadataKeys = new TreeSet<String>();
1613         Set<String> set = params.keySet();
1614         for(String attribute : set) {
1615             if(attribute.startsWith("metadata")) {
1616                 metadataKeys.add(attribute);
1617             }
1618         }
1619
1620         // 3. Process Metadata
1621         // add metadata
1622         if(!metadataKeys.isEmpty()) {
1623             Metadata metadata = null;
1624             Object obj = null;
1625             Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1626             if(getMetadataMethod != null){
1627                 try {
1628                     getMetadataMethod.setAccessible(true);
1629                     obj = getMetadataMethod.invoke(instance);
1630                 } catch (InvocationTargetException x) {
1631                     Throwable cause = x.getCause();
1632                 }
1633             }
1634             if(obj != null && obj instanceof Metadata){
1635                 metadata = (Metadata)obj;
1636             } else {
1637                 metadata = new Metadata();
1638                 Method setMetadataMethod = resourceClass.getMethod("setMetadata", Metadata.class);
1639                 if(setMetadataMethod != null){
1640                     try {
1641                         setMetadataMethod.setAccessible(true);
1642                         setMetadataMethod.invoke(instance, metadata);
1643                     } catch (InvocationTargetException x) {
1644                     }
1645                 }
1646             }
1647
1648             List<Metadatum> metadatumList = metadata.getMetadatum();
1649             int i = 0;
1650             while(true){
1651                 String metaNameKey = "metadata.metadatum[" + i + "].metaname";
1652                 String metaValueKey = "metadata.metadatum[" + i + "].metaval";
1653                 if(!params.containsKey(metaNameKey) || !params.containsKey(metaValueKey))
1654                     break;
1655
1656                 Metadatum metadatum = new Metadatum();
1657                 metadatum.setMetaname(params.get(metaNameKey));
1658                 metadatum.setMetaval(params.get(metaValueKey));
1659                 metadatumList.add(metadatum);
1660
1661                 i++;
1662             }
1663         }
1664
1665         return QueryStatus.SUCCESS;
1666     }
1667
1668     private Relationship findRelationship(List<Relationship> relationships, String relatedTo) {
1669         if(relatedTo == null)
1670             return null;
1671
1672         for(Relationship relationship : relationships) {
1673             if(relationship.getRelatedTo().equals(relatedTo)){
1674                 return relationship;
1675             }
1676         }
1677         return null;
1678     }
1679
1680
1681     public QueryStatus backup(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
1682         String resource = params.get("resource").toLowerCase();
1683         String prefix = params.get("data-key");
1684
1685         HashMap<String, String> nameValues = new HashMap<>();
1686         if(AAIRequest.createRequest(resource, nameValues) != null) {
1687
1688             try {
1689                 return newModelBackupRequest(resource, params, prefix, ctx);
1690             } catch (Exception exc) {
1691                 getLogger().warn("Failed backup - returning FAILURE", exc);
1692                 return QueryStatus.FAILURE;
1693             }
1694         }
1695
1696         return QueryStatus.NOT_FOUND;
1697     }
1698
1699     @Override
1700     public QueryStatus restore(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
1701
1702         QueryStatus retval = QueryStatus.SUCCESS;
1703         String resource = params.get("resource").toLowerCase();
1704         String prefix = params.get("data-key");
1705
1706         HashMap<String, String> nameValues = new HashMap<>();
1707         if(AAIRequest.createRequest(resource, nameValues) != null) {
1708
1709             try {
1710                 retval = newModelBackupRequest(resource, params, "tmpRestore", ctx);
1711                 if(retval == QueryStatus.SUCCESS) {
1712                     ctx.setAttribute("tmpRestore", null);
1713                 }
1714             } catch (Exception exc) {
1715                 getLogger().warn("Failed restore - returning FAILURE", exc);
1716                 return QueryStatus.FAILURE;
1717             }
1718         }
1719
1720         return QueryStatus.NOT_FOUND;
1721     }
1722
1723     protected Map<String, Object> objectToProperties(Object object) {
1724         ObjectMapper mapper = AAIService.getObjectMapper();
1725         return mapper.convertValue(object, Map.class);
1726     }
1727
1728     static <T> T valueOf(Class<T> klazz, String arg) {
1729         Exception cause = null;
1730         T ret = null;
1731         try {
1732             ret = klazz.cast(klazz.getDeclaredMethod("valueOf", String.class).invoke(null, arg));
1733         } catch (NoSuchMethodException exc) {
1734             LoggerFactory.getLogger(AAIService.class).warn("Wrong data type", exc);
1735             ret = klazz.cast(arg);
1736         } catch (IllegalAccessException e) {
1737             cause = e;
1738         } catch (InvocationTargetException e) {
1739             cause = e;
1740         }
1741         if (cause == null) {
1742             return ret;
1743         } else {
1744             throw new IllegalArgumentException(cause);
1745         }
1746     }
1747
1748     private QueryStatus processDeleteRelationshipList(String resource, String key, SvcLogicContext ctx, HashMap<String, String> nameValues) {
1749         try {
1750             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1751             if(request == null) {
1752                 return QueryStatus.FAILURE;
1753             }
1754
1755             request.processRequestPathValues(nameValues);
1756             URL url = request.getRequestUrl("GET", null);
1757
1758             Class resourceClass = request.getModelClass();
1759             Object instance = getResource(url.toString(), resourceClass);
1760             if(instance == null)
1761                 return QueryStatus.NOT_FOUND;
1762
1763             // get resource version
1764             String resourceVersion = null;
1765             Method getResourceVersionMethod = resourceClass.getMethod("getResourceVersion");
1766             if(getResourceVersionMethod != null){
1767                 try {
1768                     getResourceVersionMethod.setAccessible(true);
1769                     Object object = getResourceVersionMethod.invoke(instance);
1770                     if(object != null)
1771                         resourceVersion = object.toString();
1772                 } catch (InvocationTargetException exc) {
1773                     getLogger().warn("Retrieving resource version", exc);
1774                 }
1775             }
1776
1777             RelationshipList relationshipList = null;
1778             Object obj = null;
1779             Method getRelationshipListMethod = null;
1780             try {
1781                  getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1782             } catch(Exception exc) {
1783                 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1784             }
1785             if(getRelationshipListMethod != null){
1786                 try {
1787                     getRelationshipListMethod.setAccessible(true);
1788                     obj = getRelationshipListMethod.invoke(instance);
1789                 } catch (InvocationTargetException x) {
1790                     Throwable cause = x.getCause();
1791                 }
1792             }
1793             if(obj != null && obj instanceof RelationshipList){
1794                 relationshipList = (RelationshipList)obj;
1795             } else {
1796                 getLogger().debug("No relationships found to process.");
1797                 return QueryStatus.NOT_FOUND;
1798             }
1799
1800             if(relationshipList.getRelationship() == null || relationshipList.getRelationship().isEmpty()) {
1801                 return QueryStatus.NOT_FOUND;
1802             }
1803             String relatedTo = nameValues.get("related_to");
1804             if(relatedTo == null) {
1805                 return QueryStatus.FAILURE;
1806             }
1807
1808             relatedTo = relatedTo.replaceAll("_", "-");
1809
1810             String relatedLink = nameValues.get("relationship.related_link");
1811             if(relatedLink != null) {
1812                 relatedLink = URLDecoder.decode(relatedLink, "UTF-8");
1813             }
1814
1815             List<Relationship> relationships = relationshipList.getRelationship();
1816             List<Relationship> relationshipsToDelete = new LinkedList<>();
1817
1818             for(Relationship relationship : relationships) {
1819                 if(relatedTo.equals(relationship.getRelatedTo())) {
1820                     if(relatedLink != null) {
1821                         if(relationship.getRelatedLink() != null ) {
1822                             String localRelatedLink = relationship.getRelatedLink();
1823                             localRelatedLink = URLDecoder.decode(localRelatedLink, "UTF-8");
1824                             if(localRelatedLink.endsWith(relatedLink)) {
1825                                 getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'", relationship.getRelatedTo(),  relatedTo));
1826                                 relationshipsToDelete.add(relationship);
1827                         }
1828                     }
1829                     } else {
1830                     getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'", relationship.getRelatedTo(),  relatedTo));
1831                     relationshipsToDelete.add(relationship);
1832                 }
1833             }
1834             }
1835             if(relationshipsToDelete == null || relationshipsToDelete.isEmpty()) {
1836                 getLogger().info(String.format("Relationship has not been found for %s", key));
1837                 return QueryStatus.NOT_FOUND;
1838             }
1839
1840             String path = url.toString();
1841             path = path + "/relationship-list/relationship";
1842             URL deleteUrl = new URL(path);
1843
1844             ObjectMapper mapper = AAIService.getObjectMapper();
1845
1846             boolean cumulativeResponse = true;
1847
1848             for(Relationship targetRelationship : relationshipsToDelete) {
1849                 String json_text = mapper.writeValueAsString(targetRelationship);
1850                 boolean response = deleteList(deleteUrl, json_text);
1851                 if(!response)
1852                     cumulativeResponse = response;
1853
1854             }
1855
1856             if(!cumulativeResponse)
1857                 return QueryStatus.FAILURE;
1858
1859             return QueryStatus.SUCCESS;
1860
1861         } catch(Exception exc) {
1862             getLogger().warn("processDelete", exc);
1863             return QueryStatus.FAILURE;
1864         }
1865     }
1866
1867     private QueryStatus processDeleteMetadata(String resource, String key, SvcLogicContext ctx, HashMap<String, String> nameValues) {
1868         try {
1869             AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1870             if(request == null) {
1871                 return QueryStatus.FAILURE;
1872             }
1873
1874             request.processRequestPathValues(nameValues);
1875             URL url = request.getRequestUrl("GET", null);
1876
1877             Class<?> resourceClass = request.getModelClass();
1878             Object instance = getResource(url.toString(), resourceClass);
1879
1880             // get resource version
1881             String resourceVersion = null;
1882             Method getResourceVersionMethod = resourceClass.getMethod("getResourceVersion");
1883             if(getResourceVersionMethod != null){
1884                 try {
1885                     getResourceVersionMethod.setAccessible(true);
1886                     resourceVersion = (String) getResourceVersionMethod.invoke(instance);
1887                 } catch (InvocationTargetException x) {
1888                 }
1889             }
1890
1891             Metadata metadata = null;
1892             Object obj = null;
1893             Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1894             if(getMetadataMethod != null){
1895                 try {
1896                     getMetadataMethod.setAccessible(true);
1897                     obj = getMetadataMethod.invoke(instance);
1898                 } catch (InvocationTargetException x) {
1899                     Throwable cause = x.getCause();
1900                 }
1901             }
1902             if(obj != null && obj instanceof Metadata){
1903                 metadata = (Metadata)obj;
1904             } else {
1905                 getLogger().debug("No metadata found to process.");
1906                 return QueryStatus.NOT_FOUND;
1907             }
1908
1909             if(metadata.getMetadatum() == null || metadata.getMetadatum().isEmpty()) {
1910                 return QueryStatus.NOT_FOUND;
1911             }
1912
1913             List<Metadatum> metadatumList = metadata.getMetadatum();
1914             Metadatum metadatumToDelete = null;
1915
1916             final String metaname = nameValues.get("metaname");
1917
1918             for(Metadatum metadatum : metadatumList) {
1919                 getLogger().debug(String.format("Comparing existing metadatum of '%s' to keyword '%s'", metadatum.getMetaname(),  metaname));
1920                 if(metaname.equals(metadatum.getMetaname())) {
1921                     metadatumToDelete = metadatum;
1922                     break;
1923                 }
1924             }
1925             if(metadatumToDelete == null) {
1926                 getLogger().info(String.format("Metadatum has not been found for %s", key));
1927                 return QueryStatus.NOT_FOUND;
1928             }
1929
1930             String path = url.toString();
1931             path = path + "/metadata/metadatum/" + encodeQuery( metadatumToDelete.getMetaname() ) +
1932                     "?resource-version=" + metadatumToDelete.getResourceVersion();
1933             URL deleteUrl = new URL(path);
1934             boolean response = deleteList(deleteUrl, null);
1935
1936             if(!response)
1937                 return QueryStatus.FAILURE;
1938
1939             return QueryStatus.SUCCESS;
1940
1941         } catch(Exception exc) {
1942             getLogger().warn("processDelete", exc);
1943             return QueryStatus.FAILURE;
1944         }
1945     }
1946
1947     protected String encodeQuery(String param) throws UnsupportedEncodingException {
1948         return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
1949     }
1950
1951     static final Map<String, String> ctxGetBeginsWith( SvcLogicContext ctx, String prefix ) {
1952         Map<String, String> tmpPrefixMap = new HashMap<>();
1953
1954         if(prefix == null || prefix.isEmpty()){
1955             return tmpPrefixMap;
1956         }
1957
1958         for( String key : ctx.getAttributeKeySet() ) {
1959             if( key.startsWith(prefix) ) {
1960                 String tmpKey = key.substring(prefix.length() + 1);
1961                 tmpPrefixMap.put( tmpKey, ctx.getAttribute(key));
1962             }
1963         }
1964
1965         Map<String, String> prefixMap = new HashMap<>();
1966         Pattern p = Pattern.compile(".*\\[\\d\\]");
1967
1968         SortedSet<String> keys = new TreeSet<String>(tmpPrefixMap.keySet () );
1969         for(String key : keys) {
1970             Matcher m = p.matcher(key);
1971             if(m.matches()) {
1972                 continue;
1973             } else if(key.endsWith("_length")) {
1974                 String listKey = key.substring(0, key.indexOf("_length"));
1975                 int max = Integer.parseInt(tmpPrefixMap.get(key));
1976
1977                 ArrayList<String> data = new ArrayList<>();
1978                 for(int x = 0; x < max; x++){
1979                     String tmpKey = String.format("%s[%d]", listKey, x);
1980                     String tmpValue = tmpPrefixMap.get(tmpKey);
1981                     if(tmpValue != null && !tmpValue.isEmpty()) {
1982                         data.add(tmpValue);
1983                     }
1984                 }
1985                 if(!data.isEmpty()) {
1986                     prefixMap.put(listKey, data.toString());
1987                 } else {
1988                     prefixMap.put(key, tmpPrefixMap.get(key));
1989                 }
1990             } else {
1991                 prefixMap.put(key, tmpPrefixMap.get(key));
1992             }
1993         }
1994
1995         return prefixMap;
1996     }
1997
1998     /**
1999     */
2000     protected NamedQueryData extractNamedQueryDataFromQueryPrefix(HashMap<String, String> nameValues, Map<String, String> parms) {
2001         if(parms.isEmpty()) {
2002             return null;
2003         }
2004
2005         NamedQueryData data = new NamedQueryData();
2006
2007         // query parameters
2008         if(data.getQueryParameters() == null) {
2009             data.setQueryParameters(new QueryParameters());
2010         }
2011         String namedQueryUuid = nameValues.get("named-query-uuid".replaceAll("-", "_"));
2012         if(namedQueryUuid == null) {
2013             namedQueryUuid = parms.get("query-parameters.named-query.named-query-uuid");
2014         }
2015         NamedQuery namedQuery = new NamedQuery();
2016         namedQuery.setNamedQueryUuid(namedQueryUuid);
2017         data.getQueryParameters().setNamedQuery(namedQuery);
2018
2019         // instance filters
2020         if(data.getInstanceFilters() == null) {
2021             data.setInstanceFilters(new InstanceFilters());
2022         }
2023
2024
2025         String quantity = parms.get("instance-filters.instance-filter_length");
2026         if(quantity != null && StringUtils.isNumeric(quantity)) {
2027             int max = Integer.parseInt(quantity);
2028             for(int i = 0; i < max; i++) {
2029                 String keyPattern = String.format("instance-filters.instance-filter[%d].", i);
2030                 Set<String> keys = parms.keySet();
2031                 for(String key: keys) {
2032                     if(key.startsWith(keyPattern)){
2033                         String value = parms.get(key);
2034                         String remainder = key.substring(keyPattern.length());
2035                         String[] split = remainder.split("\\.");
2036                         getLogger().debug(String.format("%s", remainder));
2037                         if("logical-link".equals(split[0])) {
2038                             InstanceFilter insf = null;
2039                             if(data.getInstanceFilters().getInstanceFilter().isEmpty()) {
2040                                 insf = new InstanceFilter();
2041                                 data.getInstanceFilters().getInstanceFilter().add(insf);
2042                             } else {
2043                                 insf = data.getInstanceFilters().getInstanceFilter().get(0);
2044                             }
2045                             LogicalLink logicalLink = insf.getLogicalLink();
2046                             if(logicalLink == null) {
2047                                 logicalLink = new LogicalLink();
2048                                 insf.setLogicalLink(logicalLink);
2049                             }
2050
2051                             switch(split[1]) {
2052                             case "link-name":
2053                                 logicalLink.setLinkName(value);
2054                                 break;
2055                             case "link-type":
2056                                 logicalLink.setLinkType(value);
2057                                 break;
2058                             case "operational-state":
2059                                 logicalLink.setOperationalStatus(value);
2060                                 break;
2061                             }
2062
2063                         } else if("pnf".equals(split[0])) {
2064                             Pnf pnf = new Pnf();
2065                             pnf.setPnfName(value);
2066
2067                             InstanceFilter insf = new InstanceFilter();
2068                             insf.setPnf(pnf);
2069                             data.getInstanceFilters().getInstanceFilter().add(insf);
2070
2071                         } else if("service-instance".equals(split[0])) {
2072                             ServiceInstance serviceInstance = new ServiceInstance();
2073                             serviceInstance.setServiceInstanceId(value);
2074
2075                             InstanceFilter insf = new InstanceFilter();
2076                             insf.setServiceInstance(serviceInstance);
2077                             data.getInstanceFilters().getInstanceFilter().add(insf);
2078
2079                         } else if("l3-network".equals(split[0])) {
2080                             L3Network l3Network = new L3Network();
2081                             if("network-role".equals(split[1])) {
2082                                 l3Network.setNetworkRole(value);
2083                             }
2084
2085                             InstanceFilter insf = new InstanceFilter();
2086                             insf.setL3Network(l3Network);
2087                             data.getInstanceFilters().getInstanceFilter().add(insf);
2088                         } else if("generic-vnf".equals(split[0])) {
2089                             GenericVnf vnf = new GenericVnf();
2090                             if("vnf-id".equals(split[1])) {
2091                                 vnf.setVnfId(value);
2092                             }
2093
2094                             InstanceFilter insf = new InstanceFilter();
2095                             insf.setGenericVnf(vnf);
2096                             data.getInstanceFilters().getInstanceFilter().add(insf);
2097                         }
2098                     }
2099                 }
2100             }
2101         }
2102
2103         return data;
2104     }
2105
2106     public abstract <T> T getResource(String key, Class<T> type) throws AAIServiceException ;
2107     protected abstract boolean deleteList(URL url, String caller) throws AAIServiceException;
2108 }