2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.ccsdk.sli.adaptors.aai;
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;
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;
42 import java.util.SortedSet;
43 import java.util.TreeSet;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
47 import javax.xml.bind.annotation.XmlType;
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.v13.GenericVnf;
61 import org.openecomp.aai.inventory.v13.Image;
62 import org.openecomp.aai.inventory.v13.InventoryResponseItem;
63 import org.openecomp.aai.inventory.v13.InventoryResponseItems;
64 import org.openecomp.aai.inventory.v13.L3Network;
65 import org.openecomp.aai.inventory.v13.LogicalLink;
66 import org.openecomp.aai.inventory.v13.Metadata;
67 import org.openecomp.aai.inventory.v13.Metadatum;
68 import org.openecomp.aai.inventory.v13.Pnf;
69 import org.openecomp.aai.inventory.v13.RelatedToProperty;
70 import org.openecomp.aai.inventory.v13.Relationship;
71 import org.openecomp.aai.inventory.v13.RelationshipData;
72 import org.openecomp.aai.inventory.v13.RelationshipList;
73 import org.openecomp.aai.inventory.v13.ResultData;
74 import org.openecomp.aai.inventory.v13.SearchResults;
75 import org.openecomp.aai.inventory.v13.ServiceInstance;
76 import org.openecomp.aai.inventory.v13.Vlan;
77 import org.openecomp.aai.inventory.v13.Vlans;
78 import org.openecomp.aai.inventory.v13.Vserver;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
82 import com.fasterxml.jackson.core.JsonParseException;
83 import com.fasterxml.jackson.databind.JsonMappingException;
84 import com.fasterxml.jackson.databind.ObjectMapper;
87 public abstract class AAIDeclarations implements AAIClient {
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";
94 public static final String APPLICATION_ID = "org.onap.ccsdk.sli.adaptors.aai.application";
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";
100 public static final String CONNECTION_TIMEOUT = "connection.timeout";
101 public static final String READ_TIMEOUT = "read.timeout";
103 public static final String TARGET_URI = "org.onap.ccsdk.sli.adaptors.aai.uri";
105 // Availability zones query
106 public static final String QUERY_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.query";
109 public static final String UPDATE_PATH = "org.onap.ccsdk.sli.adaptors.aai.update";
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";
116 public static final String NETWORK_VSERVER_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.vserver";
118 public static final String VNF_IMAGE_QUERY_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.vnf.image.query";
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";
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";
129 public static final String SERVICE_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.service";
132 public static final String P_INTERFACE_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.pserver.pinterface";
135 public static final String SITE_PAIR_SET_PATH = "org.onap.ccsdk.sli.adaptors.aai.path.site.pair.set";
138 public static final String QUERY_NODES_PATH = "org.onap.ccsdk.sli.adaptors.aai.query.nodes";
141 protected abstract Logger getLogger();
142 public abstract AAIExecutorInterface getExecutor();
146 public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx)
147 throws SvcLogicException {
149 getLogger().debug("AAIService.query \tresource = "+resource);
152 String vnfName = null;
153 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
154 getLogger().debug("key = "+ nameValues.toString());
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;
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;
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;
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;
178 // process data using new model
179 if(useNewModelProcessing && AAIRequest.createRequest(resource, nameValues) != null) {
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;
189 ObjectMapper mapper = AAIService.getObjectMapper();
190 Map<String,Object> attributes = new HashMap<>();
192 String modifier = null;
194 if(resource.contains(":")) {
195 String[] tokens = resource.split(":");
196 resource = tokens[0];
197 if(tokens.length > 1) {
198 modifier = tokens[1];
202 resource = resource.toLowerCase().replace("-", "_");
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");
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");
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);
224 return QueryStatus.NOT_FOUND;
227 attributes = mapper.convertValue(vnf, attributes.getClass());
228 } else if(vnfName != null && !vnfName.isEmpty()) {
230 vnfName = vnfName.trim().replace("'", "").replace("$", "").replace("'", "");
231 GenericVnf vnf = this.requestGenericVnfeNodeQuery(vnfName);
233 return QueryStatus.NOT_FOUND;
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();
246 getLogger().warn("Caught exception trying to refresh generic VNF", exc);
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()));
253 return QueryStatus.FAILURE;
256 getLogger().warn("No arguments are available to process generic VNF");
257 return QueryStatus.FAILURE;
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");
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");
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("'", "");
279 if (vserverName != null) {
280 URL vserverUrl = null;
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()));
289 if (aaiexc.getReturnCode() == 404)
290 return QueryStatus.NOT_FOUND;
292 return QueryStatus.FAILURE;
294 if (vserverUrl == null) {
295 return QueryStatus.NOT_FOUND;
298 tenantId = getTenantIdFromVserverUrl(vserverUrl);
299 String cloudOwner = getCloudOwnerFromVserverUrl(vserverUrl);
300 String cloudRegionId = getCloudRegionFromVserverUrl(vserverUrl);
302 Vserver vserver = null;
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()));
311 if (aaiexc.getReturnCode() == 404)
312 return QueryStatus.NOT_FOUND;
314 return QueryStatus.FAILURE;
316 if (vserver == null) {
317 return QueryStatus.NOT_FOUND;
319 attributes = mapper.convertValue(vserver, attributes.getClass());
320 if (!attributes.containsKey("tenant-id") && tenantId != null) {
321 attributes.put("tenant-id", tenantId);
323 if (!attributes.containsKey("cloud-owner") && cloudOwner != null) {
324 attributes.put("cloud-owner", cloudOwner);
326 if (!attributes.containsKey("cloud-region-id") && cloudRegionId != null) {
327 attributes.put("cloud-region-id", cloudRegionId);
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;
334 attributes = mapper.convertValue(vserver, attributes.getClass());
335 if(!attributes.containsKey("tenant-id") && tenantId != null){
336 attributes.put("tenant-id", tenantId);
339 return QueryStatus.FAILURE;
344 return QueryStatus.FAILURE;
347 QueryStatus retval = QueryStatus.SUCCESS;
349 if (attributes == null || attributes.isEmpty()) {
350 retval = QueryStatus.NOT_FOUND;
351 getLogger().debug("No data found");
354 if (prefix != null) {
355 ArrayList<String> keys = new ArrayList<>(attributes.keySet());
357 int numCols = keys.size();
359 for (int i = 0; i < numCols; i++) {
361 String colName = keys.get(i);
362 Object object = attributes.get(colName);
364 if(object != null && object instanceof String) {
365 colValue = (String)object;
367 if (prefix != null) {
368 getLogger().debug("Setting "+prefix + "." + colName.replaceAll("_", "-")+" = "+ colValue);
369 ctx.setAttribute(prefix + "." + colName.replaceAll("_", "-"), colValue);
371 getLogger().debug("Setting " + colValue.replaceAll("_", "-")+" = "+colValue);
372 ctx.setAttribute(colValue.replaceAll("_", "-"), colValue);
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);
387 getLogger().debug("Query - returning " + retval);
390 } catch (Exception exc) {
391 getLogger().warn("Failed query - returning FAILURE", exc);
392 return QueryStatus.FAILURE;
397 public void writeMap(Map<String, Object> properties, String prefix, SvcLogicContext ctx) {
398 Set<String> mapKeys = properties.keySet();
400 for(String mapKey : mapKeys) {
401 Object entity = properties.get(mapKey);
402 if(entity instanceof ArrayList) {
403 writeList((ArrayList<?>)entity, prefix + "." + mapKey, ctx);
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;
411 localPrefix = String.format("%s.%s", prefix, mapKey);
413 writeMap( (Map<String, Object>)entity, localPrefix, ctx);
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);
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());
430 if(!list.isEmpty()) {
431 ctx.setAttribute(prefix + "_length", Integer.toString(list.size()));
432 getLogger().debug(prefix + "_length" + " : " + Integer.toString(list.size()));
437 public QueryStatus save(String resource, boolean force, boolean localOnly, String key, Map<String, String> params, String prefix, SvcLogicContext ctx)
438 throws SvcLogicException {
440 getLogger().debug("AAIService.save\tresource="+resource);
441 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
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;
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;
454 getLogger().debug("key = "+ Arrays.toString(nameValues.entrySet().toArray()));
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");
465 getLogger().debug("parms = "+ Arrays.toString(params.entrySet().toArray()));
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;
474 if(!params.containsKey("vserver-selflink")) {
476 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
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");
488 // process data using new model
489 if(useNewModelProcessing && AAIRequest.createRequest(resource, nameValues) != null) {
492 if(!resource.contains(":")){
493 return newModelSave(resource, force, key, params, prefix, ctx);
495 String[] tokens = resource.split(":");
496 String localResource = tokens[0];
497 String dependency = tokens[1];
499 AAIDatum instance = newModelObjectRequest( localResource, nameValues, prefix, ctx);
500 if(instance == null) {
501 return QueryStatus.NOT_FOUND;
505 case "relationship-list":
506 newModelProcessRelationshipList(instance, params, prefix, ctx);
509 newModelProcessMetadata(instance, params, prefix, ctx);
512 // create a method to update relationship-list
513 AAIRequest request = AAIRequest.createRequest(localResource, nameValues);
514 request.setRequestObject(instance);
515 request.processRequestPathValues(nameValues);
517 getExecutor().post(request);
518 getLogger().debug("Save relationship list - returning SUCCESS");
519 return QueryStatus.SUCCESS;
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()));
529 if(aaiexc.getReturnCode() == 404) {
530 return QueryStatus.NOT_FOUND;
533 getLogger().warn("Failed save() - returning FAILURE", exc);
534 return QueryStatus.FAILURE;
537 getLogger().debug("Save() request for {} is not supported- returning FAILURE", resource);
538 return QueryStatus.FAILURE;
543 public QueryStatus update(String resource, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) throws SvcLogicException {
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;
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;
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;
564 getLogger().debug("parms = "+ Arrays.toString(params.entrySet().toArray()));
566 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
567 request = new UpdateRequest(request, params);
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);
580 QueryStatus retval = QueryStatus.SUCCESS;
582 retval = newModelQuery(resource, false, null, key, "tmpDelete", null, ctx);
584 if(retval == null || retval != QueryStatus.SUCCESS) {
588 String resourceVersion = ctx.getAttribute("tmpDelete.resource-version");
589 if(resourceVersion == null) {
590 return QueryStatus.NOT_FOUND;
592 params.put("resource-version", resourceVersion);
594 request.processRequestPathValues(nameValues);
595 getExecutor().patch(request, resourceVersion);
596 } catch(AAIServiceException aaiexc) {
597 if(aaiexc.getReturnCode() == 404)
598 return QueryStatus.NOT_FOUND;
600 return QueryStatus.FAILURE;
601 } catch (Exception exc) {
602 getLogger().warn("Failed update - returning FAILURE", exc);
603 return QueryStatus.FAILURE;
606 getLogger().debug("Update - returning SUCCESS");
607 return QueryStatus.SUCCESS;
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()));
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;
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;
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;
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);
638 return processDeleteMetadata(resource, key, ctx, nameValues);
644 QueryStatus retval = QueryStatus.SUCCESS;
646 retval = newModelQuery(resource, false, null, key, "tmpDelete", null, ctx);
648 if(retval == null || retval != QueryStatus.SUCCESS) {
652 String resourceVersion = ctx.getAttribute("tmpDelete.resource-version");
653 if(resourceVersion == null) {
654 return QueryStatus.NOT_FOUND;
658 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
659 if(request == null) {
660 return QueryStatus.FAILURE;
663 request.processRequestPathValues(nameValues);
665 if(getExecutor().delete(request, resourceVersion)) {
666 return QueryStatus.SUCCESS;
668 } catch(AAIServiceException aaiexc) {
669 if(aaiexc.getReturnCode() == 404)
670 return QueryStatus.NOT_FOUND;
672 return QueryStatus.FAILURE;
674 } catch (Exception exc) {
675 getLogger().warn("requestGenericVnfData", exc);
676 return QueryStatus.FAILURE;
679 } catch (Exception exc) {
680 getLogger().warn("Failed delete - returning FAILURE", exc);
681 return QueryStatus.FAILURE;
684 String resourceName = resource;
685 String identifier = null;
687 if(resourceName.contains(":")) {
688 String[] tokens = resourceName.split(":");
689 if(tokens != null && tokens.length > 0) {
690 resourceName = tokens[0];
691 identifier = tokens[1];
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("'", "");
704 vnf = this.requestGenericVnfData(vnfId);
706 return QueryStatus.NOT_FOUND;
707 } catch (AAIServiceException exc) {
708 getLogger().warn("Failed delete - returning NOT_FOUND", exc);
709 return QueryStatus.NOT_FOUND;
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);
723 return QueryStatus.NOT_FOUND;
725 this.postGenericVnfData(vnf.getVnfId(), vnf);
726 } catch (AAIServiceException exc) {
727 if(exc.getReturnCode() == 404){
728 return QueryStatus.NOT_FOUND;
730 getLogger().warn("Failed delete - returning FAILURE", exc);
731 return QueryStatus.FAILURE;
734 return QueryStatus.SUCCESS;
738 return QueryStatus.FAILURE;
742 public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException {
743 return query(resource, false, null, key, prefix, null, ctx);
747 public QueryStatus isAvailable(String arg0, String arg1, String arg2, SvcLogicContext arg3)
748 throws SvcLogicException {
749 throw new SvcLogicException("Method AAIService.isAvailable() has not been implemented yet");
753 public QueryStatus notify(String resource, String action, String key, SvcLogicContext ctx) throws SvcLogicException {
754 throw new SvcLogicException("Method AAIService.notify() has not been implemented yet");
758 public QueryStatus newModelQuery(String resource, boolean localOnly, String select, String key, String prefix, String orderBy, SvcLogicContext ctx) {
760 QueryStatus retval = QueryStatus.SUCCESS;
761 String modifier = null;
763 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
764 if(resource.contains(":")) {
765 modifier = resource.split(":")[1];
769 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
770 if(request == null) {
771 return QueryStatus.FAILURE;
774 Map<String, String> params = new HashMap<>();
776 request.processRequestPathValues(nameValues);
777 if(nameValues.containsKey("prefix")){
778 Map<String, String> tmpParams = ctxGetBeginsWith(ctx, nameValues.get("prefix"));
779 if(!tmpParams.isEmpty()) {
780 params.putAll(tmpParams);
782 if("named-query".equals(resource))
783 request.setRequestObject(extractNamedQueryDataFromQueryPrefix(nameValues, params));
785 String rv = getExecutor().get(request);
787 retval = processResponseData(rv, resource, request, prefix, ctx, nameValues, modifier);
789 } catch(AAIServiceException aaiexc) {
790 int errorCode = aaiexc.getReturnCode();
791 ctx.setAttribute(prefix + ".error.message", aaiexc.getMessage());
792 if(errorCode >= 300) {
793 ctx.setAttribute(prefix + ".error.http.response-code",
794 Integer.toString(aaiexc.getReturnCode()));
797 if(aaiexc.getReturnCode() == 404)
798 return QueryStatus.NOT_FOUND;
800 return QueryStatus.FAILURE;
801 } catch (Exception exc) {
802 getLogger().warn("requestGenericVnfData", exc);
803 ctx.setAttribute(prefix + ".error.message", exc.getMessage());
804 return QueryStatus.FAILURE;
810 public QueryStatus processResponseData(String rv, String resource, AAIRequest request, String prefix, SvcLogicContext ctx, Map<String, String> nameValues, String modifier) throws JsonParseException, JsonMappingException, IOException, AAIServiceException
815 return QueryStatus.NOT_FOUND;
818 response = request.jsonStringToObject(rv);
819 if(response == null) {
820 return QueryStatus.NOT_FOUND;
823 if("generic-query".equals(resource)) {
824 SearchResults rd = SearchResults.class.cast(response);
825 List<ResultData> rdList = rd.getResultData();
826 if(rdList == null || rdList.isEmpty()) {
827 return QueryStatus.NOT_FOUND;
829 ResultData rDatum = rdList.get(0);
830 nameValues.put("selflink", rDatum.getResourceLink());
831 AAIRequest req2 = AAIRequest.createRequest(rDatum.getResourceType(), nameValues);
832 req2.processRequestPathValues(nameValues);
833 rv = getExecutor().get(req2);
835 return QueryStatus.NOT_FOUND;
838 response = req2.jsonStringToObject(rv);
839 if(response == null) {
840 return QueryStatus.NOT_FOUND;
844 if("named-query".equals(resource)) {
845 InventoryResponseItems rd = InventoryResponseItems.class.cast(response);
846 List<InventoryResponseItem> iRIlist = rd.getInventoryResponseItem();
847 if(iRIlist == null || iRIlist.isEmpty()) {
848 return QueryStatus.NOT_FOUND;
852 if("nodes-query".equals(resource)) {
853 SearchResults rd = SearchResults.class.cast(response);
854 List<ResultData> rdList = rd.getResultData();
855 if(rdList == null || rdList.isEmpty()) {
856 return QueryStatus.NOT_FOUND;
858 ResultData rDatum = rdList.get(0);
862 if("formatted-query".equals(resource) || "custom-query".equals(resource)) {
863 FormattedQueryResultList rd = FormattedQueryResultList.class.cast(response);
864 List<Result> iRIlist = rd.getResults();
865 if(iRIlist == null || iRIlist.isEmpty()) {
866 return QueryStatus.NOT_FOUND;
870 // process relationship list
871 // this is a temporary soluton to address the realationship handling changes added in Release 17.07
873 Class<?> clazz = response.getClass();
874 Method getter = clazz.getMethod("getRelationshipList");
875 Object obj = getter.invoke(response);
876 if(obj != null && obj instanceof RelationshipList) {
877 RelationshipList list = RelationshipList.class.cast(obj);
878 AAIServiceUtils.populateRelationshipDataFromPath(list);
880 } catch(Exception exc) {
881 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
885 if(prefix == null || prefix.isEmpty()) {
888 preFix = prefix + ".";
891 Map<String,Object> props = objectToProperties(response);
892 Set<String> keys = props.keySet();
893 for(String theKey: keys) {
894 if(getLogger().isTraceEnabled())
895 getLogger().trace(theKey);
897 Object value = props.get(theKey);
900 Object type = value.getClass();
901 if(value instanceof String) {
902 ctx.setAttribute(preFix + theKey, value.toString());
905 if(value instanceof Boolean) {
906 ctx.setAttribute(preFix + theKey, value.toString());
909 if(value instanceof Integer) {
910 ctx.setAttribute(preFix + theKey, value.toString());
913 if(value instanceof Long) {
914 ctx.setAttribute(preFix + theKey, value.toString());
918 if(value instanceof ArrayList) {
919 ArrayList<?> array = ArrayList.class.cast(value);
920 for(int i = 0; i < array.size(); i++) {
921 writeList(array, String.format("%s.%s", prefix, theKey), ctx);
926 if("relationship-list".equals(theKey)){
927 Map<String, Object> relationshipList = (Map<String, Object>)value;
928 // we are interested in seeing just the selected relationship
929 if(theKey.equals(modifier)) {
930 List<?> relationships = (List<?>)relationshipList.get("relationship");
931 if(relationships != null && !relationships.isEmpty()) {
933 List newRelationships = new LinkedList();
934 newRelationships.addAll(relationships);
936 for(Object obj : newRelationships){
937 if(obj instanceof Map<?, ?>) {
938 Map<?, ?> relProperties = (Map<?, ?>)obj;
939 if(relProperties.containsKey("related-to")) {
940 Object relPropsRelatedTo = relProperties.get("related-to");
942 String relatedTo = nameValues.get("related_to");
943 if(relatedTo != null) {
944 relatedTo = relatedTo.trim().replace("'", "").replace("$", "").replace("'", "");
945 if(!relatedTo.equals(relPropsRelatedTo)) {
946 relationships.remove(relProperties);
957 writeMap(relationshipList, String.format("%s.%s", prefix, theKey), ctx);
961 if(value instanceof Map) {
962 Map<String, Object> subnetsList = (Map<String, Object>)value;
963 writeMap(subnetsList, String.format("%s.%s", prefix, theKey), ctx);
968 return QueryStatus.SUCCESS;
972 public QueryStatus newModelBackupRequest(String resource, Map<String, String> params, String prefix, SvcLogicContext ctx) {
974 QueryStatus retval = QueryStatus.SUCCESS;
975 HashMap<String, String> nameValues = new HashMap<>();
978 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
979 if(request == null) {
980 return QueryStatus.FAILURE;
983 boolean argsFound = false;
984 String[] arguments = request.getArgsList();
985 for(String name : arguments) {
986 String tmpName = name.replaceAll("-", "_");
987 String value = params.get(tmpName);
988 if(value != null && !value.isEmpty()) {
989 value = value.trim().replace("'", "").replace("$", "").replace("'", "");
990 request.addRequestProperty(name, value);
995 getLogger().warn("No arguments were found. Terminating backup request.");
996 return QueryStatus.FAILURE;
999 String rv = getExecutor().get(request);
1000 ctx.setAttribute(prefix, rv);
1001 } catch(AAIServiceException aaiexc) {
1002 if(aaiexc.getReturnCode() == 404)
1003 return QueryStatus.NOT_FOUND;
1005 return QueryStatus.FAILURE;
1006 } catch (Exception exc) {
1007 getLogger().warn("newModelBackupRequest", exc);
1008 return QueryStatus.FAILURE;
1014 public AAIDatum newModelObjectRequest(String resource, Map<String, String> params, String prefix, SvcLogicContext ctx)
1015 throws AAIServiceException {
1017 AAIDatum response = null;
1020 AAIRequest request = AAIRequest.createRequest(resource, params);
1021 if(request == null) {
1025 request.processRequestPathValues(params);
1026 String rv = getExecutor().get(request);
1027 response = request.jsonStringToObject(rv);
1028 } catch(AAIServiceException aaiexc) {
1030 } catch (Exception exc) {
1031 getLogger().warn("newModelBackupRequest", exc);
1032 throw new AAIServiceException(exc);
1040 public QueryStatus release(String arg0, String arg1, SvcLogicContext arg2) throws SvcLogicException {
1041 throw new SvcLogicException("Method AAIService.release() has not been implemented yet");
1045 public QueryStatus reserve(String arg0, String arg1, String arg2, String arg3, SvcLogicContext arg4)
1046 throws SvcLogicException {
1047 throw new SvcLogicException("Method AAIService.reserve() has not been implemented yet");
1050 private QueryStatus newModelSave(String resource, boolean force, String key, Map<String, String> params, String prefix, SvcLogicContext ctx) {
1051 getLogger().debug("Executing newModelSave for resource : " + resource);
1052 HashMap<String, String> nameValues = AAIServiceUtils.keyToHashMap(key, ctx);
1055 ArrayList<String> subResources = new ArrayList<>();
1056 Set<String> set = params.keySet();
1057 Map<String, Method> setters = new HashMap<>();
1058 Map<String, Method> getters = new HashMap<>();
1061 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1062 Class<? extends AAIDatum> resourceClass = request.getModelClass();
1063 getLogger().debug(resourceClass.getName());
1064 AAIDatum instance = resourceClass.newInstance();
1067 Annotation[] annotations = resourceClass.getAnnotations();
1068 for(Annotation annotation : annotations) {
1069 Class<? extends Annotation> anotationType = annotation.annotationType();
1070 String annotationName = anotationType.getName();
1072 // 2. find string property setters and getters for the lists
1073 if("javax.xml.bind.annotation.XmlType".equals(annotationName)){
1074 XmlType order = (XmlType)annotation;
1075 String[] values = order.propOrder();
1076 for(String value : values) {
1077 String id = AAIServiceUtils.camelCaseToDashedString(value);
1078 Field field = resourceClass.getDeclaredField(value);
1079 Class<?> type = field.getType();
1080 Method setter = null;
1082 setter = resourceClass.getMethod("set"+StringUtils.capitalize(value), type);
1083 if(type.getName().startsWith("java.lang") || "boolean".equals(type.getName()) || "long".equals(type.getName()) || "int".equals(type.getName())) {
1085 Object arglist[] = new Object[1];
1086 arglist[0] = params.get(id);
1088 if(arglist[0] != null) {
1089 if(!type.getName().equals("java.lang.String")) {
1090 // getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
1091 if("java.lang.Long".equals(type.getName()) || "java.lang.Integer".equals(type.getName())) {
1092 String fv = params.get(id);
1093 if(fv == null || fv.isEmpty()) {
1096 arglist[0] = valueOf(type, params.get(id));
1098 } else if("boolean".equals(type.getName())) {
1099 arglist[0] = valueOf(Boolean.class, params.get(id));
1100 } else if("int".equals(type.getName())) {
1101 arglist[0] = valueOf(Integer.class, params.get(id));
1102 } else if("long".equals(type.getName())) {
1103 String fv = params.get(id);
1104 if(fv == null || fv.isEmpty()) {
1107 arglist[0] = valueOf(Long.class, params.get(id));
1110 arglist[0] = valueOf(type, params.get(id));
1113 Object obj = setter.invoke(instance, arglist);
1117 } catch (Exception x) {
1118 Throwable cause = x.getCause();
1119 getLogger().warn("Failed process for " + resourceClass.getName(), x);
1121 } else if("java.util.List".equals(type.getName())) {
1122 List<String> newValues = new ArrayList<>();
1123 String length = id+"_length";
1124 if(!params.isEmpty() && params.containsKey(length)) {
1125 String tmp = params.get(length);
1126 int count = Integer.parseInt(tmp);
1127 for(int i=0; i<count; i++) {
1128 String tmpValue = params.get(String.format("%s[%d]", id, i));
1129 newValues.add(tmpValue);
1131 if(!newValues.isEmpty()) {
1132 Object o = setter.invoke(instance, newValues);
1137 setters.put(id, setter);
1139 } catch(Exception exc) {
1145 getter = resourceClass.getMethod("get"+StringUtils.capitalize(value));
1146 if(!type.getName().equals("java.lang.String")) {
1147 getters.put(id, getter);
1149 } catch(Exception exc) {
1154 subResources.addAll(Arrays.asList(values));
1159 // remove getters that have matching setter
1160 for(String setKey : setters.keySet()) {
1161 if(getters.containsKey(setKey)) {
1162 getters.remove(setKey);
1166 Set<String> relationshipKeys = new TreeSet<>();
1167 Set<String> vlansKeys = new TreeSet<>();
1168 Set<String> metadataKeys = new TreeSet<>();
1170 for(String attribute : set) {
1171 String value = params.get(attribute);
1172 if(attribute.startsWith("relationship-list")) {
1173 relationshipKeys.add(attribute);
1174 } else if(attribute.startsWith("vlans")) {
1175 vlansKeys.add(attribute);
1176 } else if(attribute.startsWith("metadata")) {
1177 metadataKeys.add(attribute);
1180 // 3. find list property getters
1181 for(String attribute : set) {
1182 String value = params.get(attribute);
1183 Method method = getters.get(attribute);
1184 if(method != null) {
1186 Object arglist[] = new Object[0];
1187 // arglist[0] = value;
1188 Class<?>[] types = method.getParameterTypes();
1189 if(types.length == 0){
1190 Object o = method.invoke(instance, arglist);
1191 if(o instanceof ArrayList) {
1192 ArrayList<String> values = (ArrayList<String>)o;
1193 // getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
1194 value = value.replace("[", "").replace("]", "");
1195 List<String> items = Arrays.asList(value.split("\\s*,\\s*"));
1196 for(String s : items) {
1197 values.add(s.trim());
1201 } catch (Exception x) {
1202 Throwable cause = x.getCause();
1203 getLogger().warn("Failed process for " + resourceClass.getName(), x);
1207 // 4. Process Relationships
1208 // add relationship list
1209 if( (subResources.contains("relationship-list") || subResources.contains("relationshipList")) && !relationshipKeys.isEmpty()) {
1210 RelationshipList relationshipList = null;
1212 Method getRelationshipListMethod = null;
1214 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1215 } catch(Exception exc) {
1216 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1219 if(getRelationshipListMethod != null){
1221 obj = getRelationshipListMethod.invoke(instance);
1222 } catch (InvocationTargetException x) {
1223 Throwable cause = x.getCause();
1226 if(obj != null && obj instanceof RelationshipList){
1227 relationshipList = (RelationshipList)obj;
1229 relationshipList = new RelationshipList();
1230 Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList", RelationshipList.class);
1231 if(setRelationshipListMethod != null){
1233 Object arglist[] = new Object[1];
1234 arglist[0] = relationshipList;
1236 obj = setRelationshipListMethod.invoke(instance, arglist);
1237 } catch (InvocationTargetException x) {
1238 Throwable cause = x.getCause();
1243 List<Relationship> relationships = relationshipList.getRelationship();
1247 String searchKey = "relationship-list.relationship[" + i + "].related-to";
1248 if(!params.containsKey(searchKey))
1251 String relatedTo = params.get(searchKey);
1252 String relatedLinkKey = "relationship-list.relationship[" + i + "].related-link";
1253 String relatedLink = null;
1254 if(params.containsKey(relatedLinkKey)) {
1255 relatedLink = params.get(relatedLinkKey);
1257 Relationship relationship = new Relationship();
1258 relationships.add(relationship);
1259 relationship.setRelatedTo(relatedTo);
1260 String relationshipLabel = "relationship-list.relationship[" + i + "].relationship-label";
1261 if(params.containsKey(searchKey)) {
1262 relationship.setRelationshipLabel(params.get(relationshipLabel));
1264 getLogger().debug("About to process related link of {}", relatedLink);
1265 if(relatedLink != null) {
1266 if(relatedLink.contains("v$"))
1267 relatedLink = relatedLink.replace("v$", "v13");
1268 relationship.setRelatedLink(relatedLink);
1270 Map<String, String> relParams = new HashMap<>();
1273 String searchRelationshipKey = "relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-key";
1274 String searchRelationshipValue = "relationship-list.relationship[" + i + "].relationship-data[" + j + "].relationship-value";
1275 if(!params.containsKey(searchRelationshipKey))
1278 relParams.put(params.get(searchRelationshipKey), params.get(searchRelationshipValue));
1281 AAIRequest rlRequest = AAIRequest.createRequest(relatedTo, relParams);
1282 for(Map.Entry<String,String> entry : relParams.entrySet()) {
1283 rlRequest.addRequestProperty(entry.getKey(), entry.getValue());
1285 String path = rlRequest.updatePathDataValues(null);
1286 relationship.setRelatedLink(path);
1290 // process related to properties
1291 Map<String, String> relParams = new HashMap<String, String>();
1294 String searchRelatedToKey = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-key";
1295 String searchRelatedToValue = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-value";
1296 if(!params.containsKey(searchRelatedToKey))
1299 RelatedToProperty relDatum = new RelatedToProperty();
1300 relDatum.setPropertyKey(params.get(searchRelatedToKey));
1301 relDatum.setPropertyValue(params.get(searchRelatedToValue));
1302 relationship.getRelatedToProperty().add(relDatum);
1304 relParams.put(params.get(searchRelatedToKey), params.get(searchRelatedToValue));
1313 if(subResources.contains("vlans") && !vlansKeys.isEmpty()) {
1315 Vlans vlanList = null;
1316 Method getVLansMethod = resourceClass.getMethod("getVlans");
1317 if(getVLansMethod != null){
1319 obj = getVLansMethod.invoke(instance);
1320 } catch (InvocationTargetException x) {
1321 Throwable cause = x.getCause();
1324 if(obj != null && obj instanceof Vlans){
1325 vlanList = (Vlans)obj;
1327 vlanList = new Vlans();
1328 Method setVlansMethod = resourceClass.getMethod("setVlans", Vlans.class);
1329 if(setVlansMethod != null){
1331 Object arglist[] = new Object[1];
1332 arglist[0] = vlanList;
1334 obj = setVlansMethod.invoke(instance, arglist);
1335 } catch (InvocationTargetException x) {
1336 Throwable cause = x.getCause();
1343 String searchKey = "vlans.vlan[" + i + "].vlan-interface";
1344 if(!params.containsKey(searchKey))
1347 String vlanInterface = params.get("vlans.vlan[" + i + "].vlan-interface");
1348 String vlanIdInner = params.get("vlans.vlan[" + i + "].vlan-id-inner");
1349 String vlanIdOute = params.get("vlans.vlan[" + i + "].vlan-id-outer");
1350 String speedValue = params.get("vlans.vlan[" + i + "].speed-value");
1351 String speedUnits = params.get("vlans.vlan[" + i + "].speed-units");
1353 Vlan vlan = new Vlan();
1354 vlan.setVlanInterface(vlanInterface);
1356 if(vlanIdInner != null) {
1357 Long iVlanIdInner = Long.parseLong(vlanIdInner);
1358 vlan.setVlanIdInner(iVlanIdInner);
1361 if(vlanIdOute != null) {
1362 Long iVlanIdOuter = Long.parseLong(vlanIdOute);
1363 vlan.setVlanIdOuter(iVlanIdOuter);
1366 if(speedValue != null) {
1367 vlan.setSpeedValue(speedValue);
1368 vlan.setSpeedUnits(speedUnits);
1371 vlanList.getVlan().add(vlan);
1377 if(subResources.contains("metadata") && !metadataKeys.isEmpty()) {
1379 Metadata metadataList = null;
1380 Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1381 if(getMetadataMethod != null){
1383 obj = getMetadataMethod.invoke(instance);
1384 } catch (InvocationTargetException x) {
1385 Throwable cause = x.getCause();
1388 if(obj != null && obj instanceof Metadata){
1389 metadataList = (Metadata)obj;
1391 metadataList = new Metadata();
1392 Method setMetadataMethod = resourceClass.getMethod("setMetadata", Metadata.class);
1393 if(setMetadataMethod != null){
1395 Object arglist[] = new Object[1];
1396 arglist[0] = metadataList;
1398 obj = setMetadataMethod.invoke(instance, arglist);
1399 } catch (InvocationTargetException x) {
1400 Throwable cause = x.getCause();
1408 String metaKey = "metadata.metadatum[" + i + "].meta-key";
1409 if(!params.containsKey(metaKey))
1412 String metaValue = params.get("metadata.metadatum[" + i + "].meta-value");
1414 Metadatum vlan = new Metadatum();
1415 vlan.setMetaname(metaKey);
1416 vlan.setMetaval(metaValue);
1418 metadataList.getMetadatum().add(vlan);
1425 // 6. Prepare AAI request
1426 String[] args = request.getArgsList();
1427 for(String arg : args) {
1428 String modifiedKey = arg.replaceAll("-", "_");
1429 if(nameValues.containsKey(modifiedKey)) {
1430 String argValue = nameValues.get(modifiedKey);
1431 if(argValue != null) argValue = argValue.trim().replace("'", "").replace("$", "").replace("'", "");
1432 request.addRequestProperty(arg, argValue);
1436 request.processRequestPathValues(nameValues);
1437 request.setRequestObject(instance);
1438 Object response = getExecutor().post(request);
1439 if(request.expectsDataFromPUTRequest()){
1440 if(response != null && response instanceof String) {
1441 String rv = response.toString();
1442 QueryStatus retval = processResponseData(rv, resource, request, prefix, ctx, nameValues, null);
1443 getLogger().debug("newModelSave - returning " + retval.toString());
1448 } catch(AAIServiceException exc){
1449 ctx.setAttribute(prefix + ".error.message", exc.getMessage());
1450 int returnCode = exc.getReturnCode();
1451 if(returnCode >= 300) {
1452 ctx.setAttribute(prefix + ".error.http.response-code",
1453 Integer.toString(exc.getReturnCode()));
1456 if(returnCode == 400 || returnCode == 412)
1457 return QueryStatus.FAILURE;
1458 else if(returnCode == 404)
1459 return QueryStatus.NOT_FOUND;
1461 getLogger().warn("Failed newModelSave - returning FAILURE", exc);
1462 return QueryStatus.FAILURE;
1464 } catch(Exception exc){
1465 getLogger().warn("Failed newModelSave - returning FAILURE", exc);
1466 ctx.setAttribute(prefix + ".error.message", exc.getMessage());
1467 return QueryStatus.FAILURE;
1470 getLogger().debug("newModelSave - returning SUCCESS");
1471 return QueryStatus.SUCCESS;
1474 private QueryStatus newModelProcessRelationshipList(Object instance, Map<String, String> params, String prefix, SvcLogicContext ctx) throws Exception {
1476 Class resourceClass = instance.getClass();
1478 Set<String> relationshipKeys = new TreeSet<>();
1480 Set<String> set = params.keySet();
1482 for(String attribute : set) {
1483 String value = params.get(attribute);
1485 if(attribute.startsWith("relationship-list")) {
1486 relationshipKeys.add(attribute);
1490 // 3. Process Relationships
1491 // add relationship list
1492 if(!relationshipKeys.isEmpty()) {
1493 RelationshipList relationshipList;
1495 Method getRelationshipListMethod = null;
1497 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1498 } catch(Exception exc) {
1499 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1501 if(getRelationshipListMethod != null){
1503 obj = getRelationshipListMethod.invoke(instance);
1504 } catch (InvocationTargetException x) {
1505 Throwable cause = x.getCause();
1508 if(obj != null && obj instanceof RelationshipList){
1509 relationshipList = (RelationshipList)obj;
1511 relationshipList = new RelationshipList();
1512 Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList", RelationshipList.class);
1513 if(setRelationshipListMethod != null){
1515 Object arglist[] = new Object[1];
1516 arglist[0] = relationshipList;
1518 obj = setRelationshipListMethod.invoke(instance, arglist);
1519 } catch (InvocationTargetException x) {
1520 Throwable cause = x.getCause();
1525 boolean createdNewRelationships = false;
1526 List<Relationship> relationships = relationshipList.getRelationship();
1527 if(relationships == null) {
1528 relationships = new ArrayList<>();
1529 createdNewRelationships = true;
1534 String searchKey = "relationship-list.relationship[" + i + "].related-to";
1535 if(!params.containsKey(searchKey))
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);
1545 Relationship relationship = new Relationship();
1546 relationships.add(relationship);
1547 relationship.setRelatedTo(relatedTo);
1549 String relationshipLabel = "relationship-list.relationship[" + i + "].relationship-label";
1550 if(params.containsKey(searchKey)) {
1551 relationship.setRelationshipLabel(params.get(relationshipLabel));
1554 if (relatedLink != null) {
1555 if(relatedLink.contains("v$"))
1556 relatedLink = relatedLink.replace("v$", "v13");
1557 relationship.setRelatedLink(relatedLink);
1559 Map<String, String> relParams = new HashMap<>();
1563 String searchRelationshipKey = "relationship-list.relationship[" + i + "].relationship-data["
1564 + j + "].relationship-key";
1565 String searchRelationshipValue = "relationship-list.relationship[" + i + "].relationship-data["
1566 + j + "].relationship-value";
1567 if (!params.containsKey(searchRelationshipKey))
1570 RelationshipData relDatum = new RelationshipData();
1571 relDatum.setRelationshipKey(params.get(searchRelationshipKey));
1572 relDatum.setRelationshipValue(params.get(searchRelationshipValue));
1573 relationship.getRelationshipData().add(relDatum);
1575 relParams.put(params.get(searchRelationshipKey), params.get(searchRelationshipValue));
1578 AAIRequest rlRequest = AAIRequest.createRequest(relatedTo, relParams);
1579 for (Map.Entry<String, String> entry : relParams.entrySet()) {
1580 rlRequest.addRequestProperty(entry.getKey(), entry.getValue());
1582 String path = rlRequest.updatePathDataValues(null);
1583 relationship.setRelatedLink(path);
1587 // process related to properties
1588 Map<String, String> relParams = new HashMap<String, String>();
1591 String searchRelatedToKey = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-key";
1592 String searchRelatedToValue = "relationship-list.relationship[" + i + "].related-to-property[" + k + "].property-value";
1593 if(!params.containsKey(searchRelatedToKey))
1596 RelatedToProperty relDatum = new RelatedToProperty();
1597 relDatum.setPropertyKey(params.get(searchRelatedToKey));
1598 relDatum.setPropertyValue(params.get(searchRelatedToValue));
1599 relationship.getRelatedToProperty().add(relDatum);
1601 relParams.put(params.get(searchRelatedToKey), params.get(searchRelatedToValue));
1610 return QueryStatus.SUCCESS;
1613 private QueryStatus newModelProcessMetadata(Object instance, Map<String, String> params, String prefix, SvcLogicContext ctx) throws Exception {
1615 if (!(instance instanceof ServiceInstance) && !(instance instanceof Image)) {
1616 throw new IllegalArgumentException("request is not applicable for selected request");
1619 Class resourceClass = instance.getClass();
1620 Set<String> metadataKeys = new TreeSet<String>();
1621 Set<String> set = params.keySet();
1622 for(String attribute : set) {
1623 if(attribute.startsWith("metadata")) {
1624 metadataKeys.add(attribute);
1628 // 3. Process Metadata
1630 if(!metadataKeys.isEmpty()) {
1631 Metadata metadata = null;
1633 Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1634 if(getMetadataMethod != null){
1636 obj = getMetadataMethod.invoke(instance);
1637 } catch (InvocationTargetException x) {
1638 Throwable cause = x.getCause();
1641 if(obj != null && obj instanceof Metadata){
1642 metadata = (Metadata)obj;
1644 metadata = new Metadata();
1645 Method setMetadataMethod = resourceClass.getMethod("setMetadata", Metadata.class);
1646 if(setMetadataMethod != null){
1648 setMetadataMethod.invoke(instance, metadata);
1649 } catch (InvocationTargetException x) {
1654 List<Metadatum> metadatumList = metadata.getMetadatum();
1657 String metaNameKey = "metadata.metadatum[" + i + "].metaname";
1658 String metaValueKey = "metadata.metadatum[" + i + "].metaval";
1659 if(!params.containsKey(metaNameKey) || !params.containsKey(metaValueKey))
1662 Metadatum metadatum = new Metadatum();
1663 metadatum.setMetaname(params.get(metaNameKey));
1664 metadatum.setMetaval(params.get(metaValueKey));
1665 metadatumList.add(metadatum);
1671 return QueryStatus.SUCCESS;
1674 private Relationship findRelationship(List<Relationship> relationships, String relatedTo) {
1675 if(relatedTo == null)
1678 for(Relationship relationship : relationships) {
1679 if(relationship.getRelatedTo().equals(relatedTo)){
1680 return relationship;
1687 public QueryStatus backup(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
1688 String resource = params.get("resource").toLowerCase();
1689 String prefix = params.get("data-key");
1691 HashMap<String, String> nameValues = new HashMap<>();
1692 if(AAIRequest.createRequest(resource, nameValues) != null) {
1695 return newModelBackupRequest(resource, params, prefix, ctx);
1696 } catch (Exception exc) {
1697 getLogger().warn("Failed backup - returning FAILURE", exc);
1698 return QueryStatus.FAILURE;
1702 return QueryStatus.NOT_FOUND;
1706 public QueryStatus restore(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
1708 QueryStatus retval = QueryStatus.SUCCESS;
1709 String resource = params.get("resource").toLowerCase();
1710 String prefix = params.get("data-key");
1712 HashMap<String, String> nameValues = new HashMap<>();
1713 if(AAIRequest.createRequest(resource, nameValues) != null) {
1716 retval = newModelBackupRequest(resource, params, "tmpRestore", ctx);
1717 if(retval == QueryStatus.SUCCESS) {
1718 ctx.setAttribute("tmpRestore", null);
1720 } catch (Exception exc) {
1721 getLogger().warn("Failed restore - returning FAILURE", exc);
1722 return QueryStatus.FAILURE;
1726 return QueryStatus.NOT_FOUND;
1729 protected Map<String, Object> objectToProperties(Object object) {
1730 ObjectMapper mapper = AAIService.getObjectMapper();
1731 return mapper.convertValue(object, Map.class);
1734 static <T> T valueOf(Class<T> klazz, String arg) {
1735 Exception cause = null;
1738 ret = klazz.cast(klazz.getDeclaredMethod("valueOf", String.class).invoke(null, arg));
1739 } catch (NoSuchMethodException exc) {
1740 LoggerFactory.getLogger(AAIService.class).warn("Wrong data type", exc);
1741 ret = klazz.cast(arg);
1742 } catch (IllegalAccessException e) {
1744 } catch (InvocationTargetException e) {
1747 if (cause == null) {
1750 throw new IllegalArgumentException(cause);
1754 private QueryStatus processDeleteRelationshipList(String resource, String key, SvcLogicContext ctx, HashMap<String, String> nameValues) {
1756 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1757 if(request == null) {
1758 return QueryStatus.FAILURE;
1761 request.processRequestPathValues(nameValues);
1762 URL url = request.getRequestUrl("GET", null);
1764 Class resourceClass = request.getModelClass();
1765 Object instance = getResource(url.toString(), resourceClass);
1766 if(instance == null)
1767 return QueryStatus.NOT_FOUND;
1769 // get resource version
1770 String resourceVersion = null;
1771 Method getResourceVersionMethod = resourceClass.getMethod("getResourceVersion");
1772 if(getResourceVersionMethod != null){
1774 Object object = getResourceVersionMethod.invoke(instance);
1776 resourceVersion = object.toString();
1777 } catch (InvocationTargetException exc) {
1778 getLogger().warn("Retrieving resource version", exc);
1782 RelationshipList relationshipList = null;
1784 Method getRelationshipListMethod = null;
1786 getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
1787 } catch(Exception exc) {
1788 getLogger().debug("Retrofiting relationship data: " + exc.getMessage());
1790 if(getRelationshipListMethod != null){
1792 obj = getRelationshipListMethod.invoke(instance);
1793 } catch (InvocationTargetException x) {
1794 Throwable cause = x.getCause();
1797 if(obj != null && obj instanceof RelationshipList){
1798 relationshipList = (RelationshipList)obj;
1800 getLogger().debug("No relationships found to process.");
1801 return QueryStatus.NOT_FOUND;
1804 if(relationshipList.getRelationship() == null || relationshipList.getRelationship().isEmpty()) {
1805 return QueryStatus.NOT_FOUND;
1807 String relatedTo = nameValues.get("related_to");
1808 if(relatedTo == null) {
1809 return QueryStatus.FAILURE;
1812 relatedTo = relatedTo.replaceAll("_", "-");
1814 String relatedLink = nameValues.get("relationship.related_link");
1815 if(relatedLink != null) {
1816 relatedLink = URLDecoder.decode(relatedLink, "UTF-8");
1819 List<Relationship> relationships = relationshipList.getRelationship();
1820 List<Relationship> relationshipsToDelete = new LinkedList<>();
1822 for(Relationship relationship : relationships) {
1823 if(relatedTo.equals(relationship.getRelatedTo())) {
1824 if(relatedLink != null) {
1825 if(relationship.getRelatedLink() != null ) {
1826 String localRelatedLink = relationship.getRelatedLink();
1827 localRelatedLink = URLDecoder.decode(localRelatedLink, "UTF-8");
1828 if(localRelatedLink.endsWith(relatedLink)) {
1829 getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'", relationship.getRelatedTo(), relatedTo));
1830 relationshipsToDelete.add(relationship);
1834 getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'", relationship.getRelatedTo(), relatedTo));
1835 relationshipsToDelete.add(relationship);
1839 if(relationshipsToDelete == null || relationshipsToDelete.isEmpty()) {
1840 getLogger().info(String.format("Relationship has not been found for %s", key));
1841 return QueryStatus.NOT_FOUND;
1844 String path = url.toString();
1845 path = path + "/relationship-list/relationship";
1846 URL deleteUrl = new URL(path);
1848 ObjectMapper mapper = AAIService.getObjectMapper();
1850 boolean cumulativeResponse = true;
1852 for(Relationship targetRelationship : relationshipsToDelete) {
1853 String json_text = mapper.writeValueAsString(targetRelationship);
1854 boolean response = deleteList(deleteUrl, json_text);
1856 cumulativeResponse = response;
1860 if(!cumulativeResponse)
1861 return QueryStatus.FAILURE;
1863 return QueryStatus.SUCCESS;
1865 } catch(Exception exc) {
1866 getLogger().warn("processDelete", exc);
1867 return QueryStatus.FAILURE;
1871 private QueryStatus processDeleteMetadata(String resource, String key, SvcLogicContext ctx, HashMap<String, String> nameValues) {
1873 AAIRequest request = AAIRequest.createRequest(resource, nameValues);
1874 if(request == null) {
1875 return QueryStatus.FAILURE;
1878 request.processRequestPathValues(nameValues);
1879 URL url = request.getRequestUrl("GET", null);
1881 Class<?> resourceClass = request.getModelClass();
1882 Object instance = getResource(url.toString(), resourceClass);
1884 // get resource version
1885 String resourceVersion = null;
1886 Method getResourceVersionMethod = resourceClass.getMethod("getResourceVersion");
1887 if(getResourceVersionMethod != null){
1889 resourceVersion = (String) getResourceVersionMethod.invoke(instance);
1890 } catch (InvocationTargetException x) {
1894 Metadata metadata = null;
1896 Method getMetadataMethod = resourceClass.getMethod("getMetadata");
1897 if(getMetadataMethod != null){
1899 obj = getMetadataMethod.invoke(instance);
1900 } catch (InvocationTargetException x) {
1901 Throwable cause = x.getCause();
1904 if(obj != null && obj instanceof Metadata){
1905 metadata = (Metadata)obj;
1907 getLogger().debug("No metadata found to process.");
1908 return QueryStatus.NOT_FOUND;
1911 if(metadata.getMetadatum() == null || metadata.getMetadatum().isEmpty()) {
1912 return QueryStatus.NOT_FOUND;
1915 List<Metadatum> metadatumList = metadata.getMetadatum();
1916 Metadatum metadatumToDelete = null;
1918 final String metaname = nameValues.get("metaname");
1920 for(Metadatum metadatum : metadatumList) {
1921 getLogger().debug(String.format("Comparing existing metadatum of '%s' to keyword '%s'", metadatum.getMetaname(), metaname));
1922 if(metaname.equals(metadatum.getMetaname())) {
1923 metadatumToDelete = metadatum;
1927 if(metadatumToDelete == null) {
1928 getLogger().info(String.format("Metadatum has not been found for %s", key));
1929 return QueryStatus.NOT_FOUND;
1932 String path = url.toString();
1933 path = path + "/metadata/metadatum/" + encodeQuery( metadatumToDelete.getMetaname() ) +
1934 "?resource-version=" + metadatumToDelete.getResourceVersion();
1935 URL deleteUrl = new URL(path);
1936 boolean response = deleteList(deleteUrl, null);
1939 return QueryStatus.FAILURE;
1941 return QueryStatus.SUCCESS;
1943 } catch(Exception exc) {
1944 getLogger().warn("processDelete", exc);
1945 return QueryStatus.FAILURE;
1949 protected String encodeQuery(String param) throws UnsupportedEncodingException {
1950 return URLEncoder.encode(param, "UTF-8").replace("+", "%20");
1953 static final Map<String, String> ctxGetBeginsWith( SvcLogicContext ctx, String prefix ) {
1954 Map<String, String> tmpPrefixMap = new HashMap<>();
1956 if(prefix == null || prefix.isEmpty()){
1957 return tmpPrefixMap;
1960 for( String key : ctx.getAttributeKeySet() ) {
1961 if( key.startsWith(prefix) ) {
1962 String tmpKey = key.substring(prefix.length() + 1);
1963 tmpPrefixMap.put( tmpKey, ctx.getAttribute(key));
1967 Map<String, String> prefixMap = new HashMap<>();
1968 Pattern p = Pattern.compile(".*\\[\\d\\]");
1970 SortedSet<String> keys = new TreeSet<String>(tmpPrefixMap.keySet () );
1971 for(String key : keys) {
1972 Matcher m = p.matcher(key);
1975 } else if(key.endsWith("_length")) {
1976 String listKey = key.substring(0, key.indexOf("_length"));
1977 int max = Integer.parseInt(tmpPrefixMap.get(key));
1979 ArrayList<String> data = new ArrayList<>();
1980 for(int x = 0; x < max; x++){
1981 String tmpKey = String.format("%s[%d]", listKey, x);
1982 String tmpValue = tmpPrefixMap.get(tmpKey);
1983 if(tmpValue != null && !tmpValue.isEmpty()) {
1987 if(!data.isEmpty()) {
1988 prefixMap.put(listKey, data.toString());
1990 prefixMap.put(key, tmpPrefixMap.get(key));
1993 prefixMap.put(key, tmpPrefixMap.get(key));
2002 protected NamedQueryData extractNamedQueryDataFromQueryPrefix(HashMap<String, String> nameValues, Map<String, String> parms) {
2003 if(parms.isEmpty()) {
2007 NamedQueryData data = new NamedQueryData();
2010 if(data.getQueryParameters() == null) {
2011 data.setQueryParameters(new QueryParameters());
2013 String namedQueryUuid = nameValues.get("named-query-uuid".replaceAll("-", "_"));
2014 if(namedQueryUuid == null) {
2015 namedQueryUuid = parms.get("query-parameters.named-query.named-query-uuid");
2017 NamedQuery namedQuery = new NamedQuery();
2018 namedQuery.setNamedQueryUuid(namedQueryUuid);
2019 data.getQueryParameters().setNamedQuery(namedQuery);
2022 if(data.getInstanceFilters() == null) {
2023 data.setInstanceFilters(new InstanceFilters());
2027 String quantity = parms.get("instance-filters.instance-filter_length");
2028 if(quantity != null && StringUtils.isNumeric(quantity)) {
2029 int max = Integer.parseInt(quantity);
2030 for(int i = 0; i < max; i++) {
2031 String keyPattern = String.format("instance-filters.instance-filter[%d].", i);
2032 Set<String> keys = parms.keySet();
2033 for(String key: keys) {
2034 if(key.startsWith(keyPattern)){
2035 String value = parms.get(key);
2036 String remainder = key.substring(keyPattern.length());
2037 String[] split = remainder.split("\\.");
2038 getLogger().debug(String.format("%s", remainder));
2039 if("logical-link".equals(split[0])) {
2040 InstanceFilter insf = null;
2041 if(data.getInstanceFilters().getInstanceFilter().isEmpty()) {
2042 insf = new InstanceFilter();
2043 data.getInstanceFilters().getInstanceFilter().add(insf);
2045 insf = data.getInstanceFilters().getInstanceFilter().get(0);
2047 LogicalLink logicalLink = insf.getLogicalLink();
2048 if(logicalLink == null) {
2049 logicalLink = new LogicalLink();
2050 insf.setLogicalLink(logicalLink);
2055 logicalLink.setLinkName(value);
2058 logicalLink.setLinkType(value);
2060 case "operational-state":
2061 logicalLink.setOperationalStatus(value);
2065 } else if("pnf".equals(split[0])) {
2066 Pnf pnf = new Pnf();
2067 pnf.setPnfName(value);
2069 InstanceFilter insf = new InstanceFilter();
2071 data.getInstanceFilters().getInstanceFilter().add(insf);
2073 } else if("service-instance".equals(split[0])) {
2074 ServiceInstance serviceInstance = new ServiceInstance();
2075 serviceInstance.setServiceInstanceId(value);
2077 InstanceFilter insf = new InstanceFilter();
2078 insf.setServiceInstance(serviceInstance);
2079 data.getInstanceFilters().getInstanceFilter().add(insf);
2081 } else if("l3-network".equals(split[0])) {
2082 L3Network l3Network = new L3Network();
2083 if("network-role".equals(split[1])) {
2084 l3Network.setNetworkRole(value);
2087 InstanceFilter insf = new InstanceFilter();
2088 insf.setL3Network(l3Network);
2089 data.getInstanceFilters().getInstanceFilter().add(insf);
2090 } else if("generic-vnf".equals(split[0])) {
2091 GenericVnf vnf = new GenericVnf();
2092 if("vnf-id".equals(split[1])) {
2093 vnf.setVnfId(value);
2096 InstanceFilter insf = new InstanceFilter();
2097 insf.setGenericVnf(vnf);
2098 data.getInstanceFilters().getInstanceFilter().add(insf);
2108 public abstract <T> T getResource(String key, Class<T> type) throws AAIServiceException ;
2109 protected abstract boolean deleteList(URL url, String caller) throws AAIServiceException;