diff options
55 files changed, 2320 insertions, 1488 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java index ef37f9f719..5d16a95e5f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/cloud/CloudConfig.java @@ -46,7 +46,6 @@ import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound; * * This class also contains methods to query cloud sites and/or identity * services by ID. - * */ @JsonRootName("cloud_config") @@ -89,21 +88,20 @@ public class CloudConfig { * individual entries to try and find one with a CLLI that matches the ID * and an AIC version of 2.5. * - * @param id - * the ID to match - * @return a CloudSite, or null of no match found + * @param id the ID to match + * @return an Optional of CloudSite object. */ - public synchronized CloudSite getCloudSite(String id) { - if (id != null) { - if (cloudSites.containsKey(id)) { - return cloudSites.get(id); - } - // check for id == CLLI now as well - return getCloudSiteWithClli(id); + public synchronized Optional<CloudSite> getCloudSite(String id) { + if (id == null) { + return Optional.empty(); } - return null; + if (cloudSites.containsKey(id)) { + return Optional.ofNullable(cloudSites.get(id)); + } + return Optional.ofNullable(getCloudSiteWithClli(id)); } + private CloudSite getCloudSiteWithClli(String clli) { Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs -> cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAic_version()))) @@ -111,7 +109,6 @@ public class CloudConfig { return cloudSiteOptional.orElse(getDefaultCloudSite(clli)); } - // TODO in future the result will be optional private CloudSite getDefaultCloudSite(String clli) { Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream() .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny(); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/HeatStatus.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/HeatStatus.java index 8e223b7bcb..3e4ea27d5f 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/HeatStatus.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/HeatStatus.java @@ -20,7 +20,6 @@ package org.openecomp.mso.openstack.beans; - /* * Enum status values to mirror the Openstack Heat stack status values */ diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/NetworkInfo.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/NetworkInfo.java index 9f2c275670..2cda8f99e2 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/NetworkInfo.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/NetworkInfo.java @@ -20,8 +20,6 @@ package org.openecomp.mso.openstack.beans; - - import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -35,7 +33,6 @@ import com.woorea.openstack.quantum.model.Segment; * * This bean is returned by all Network-specific adapter operations (create, query, delete) */ - public class NetworkInfo { // Set defaults for everything private String name = ""; @@ -44,7 +41,6 @@ public class NetworkInfo { private String provider = ""; private List<Integer> vlans = new ArrayList<>(); private List<String> subnets = new ArrayList<>(); - private String shared = ""; static Map<String,NetworkStatus> NetworkStatusMap; static { @@ -55,15 +51,6 @@ public class NetworkInfo { NetworkStatusMap.put("ERROR", NetworkStatus.ERROR); } - public NetworkInfo () { - } - - public NetworkInfo (String name, NetworkStatus status) { - this.name = name; - this.id = name; // Don't have an ID, so just use name - this.status = status; - } - /** * Capture the data from a Neutron Network object. * @@ -75,41 +62,35 @@ public class NetworkInfo { * * @param network */ - public NetworkInfo (Network network) - { - if (network == null) { - this.status = NetworkStatus.NOTFOUND; - return; + public NetworkInfo(Network network) { + if (network != null) { + initFieldsWithDataFromNetwork(network); + } else { + status = NetworkStatus.NOTFOUND; } + } - this.name = network.getName(); - this.id = network.getId(); + private void initFieldsWithDataFromNetwork(Network network){ + name = network.getName(); + id = network.getId(); - if (network.getStatus() == null) { - // Can this happen on a newly created network? - this.status = NetworkStatus.UNKNOWN; - } else if (NetworkStatusMap.containsKey(network.getStatus())) { - this.status = NetworkStatusMap.get(network.getStatus()); - } else { - this.status = NetworkStatus.UNKNOWN; + if (network.getStatus() != null && NetworkStatusMap.containsKey(network.getStatus())) { + status = NetworkStatusMap.get(network.getStatus()); } - if (network.getProviderPhysicalNetwork() != null) { - this.provider = network.getProviderPhysicalNetwork(); + provider = network.getProviderPhysicalNetwork(); if ("vlan".equals(network.getProviderNetworkType())) { - this.vlans.add(network.getProviderSegmentationId()); + vlans.add(network.getProviderSegmentationId()); } } else if (network.getSegments() != null && !network.getSegments().isEmpty()) { Segment s = network.getSegments().get(0); - this.provider = s.getProviderPhysicalNetwork(); + provider = s.getProviderPhysicalNetwork(); if ("vlan".equals(s.getProviderNetworkType())) { - for (Segment s1 : network.getSegments()) { - this.vlans.add(s1.getProviderSegmentationId()); - } + network.getSegments().forEach(segment -> vlans.add(segment.getProviderSegmentationId())); } } - this.subnets = network.getSubnets(); + subnets = network.getSubnets(); } public String getName() { @@ -156,22 +137,17 @@ public class NetworkInfo { return subnets; } - public void setSubnets (List<String> subnets) { - this.subnets = subnets; - } - - public String getShared() { - return shared; - } - - public void setShared(String shared) { - this.shared = shared; - } - @Override - public String toString () { - return "Network: name=" + name + ",id=" + id + ",status=" + status + - ",provider=" + provider + ",vlans=" + vlans + ",subnets=" + subnets + ",shared=" + shared; + public String toString() { + final StringBuilder sb = new StringBuilder("NetworkInfo{"); + sb.append("name='").append(name).append('\''); + sb.append(", id='").append(id).append('\''); + sb.append(", status=").append(status); + sb.append(", provider='").append(provider).append('\''); + sb.append(", vlans=").append(vlans); + sb.append(", subnets=").append(subnets); + sb.append('}'); + return sb.toString(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/StackInfo.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/StackInfo.java index 83e1484257..600985e310 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/StackInfo.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/beans/StackInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,136 +20,89 @@ package org.openecomp.mso.openstack.beans; - -import java.util.Map; -import java.util.HashMap; - import com.woorea.openstack.heat.model.Stack; +import java.util.HashMap; +import java.util.Map; /* * This Java bean class relays Heat stack status information to ActiveVOS processes. - * + * * This bean is returned by all Heat-specific adapter operations (create, query, delete) */ - public class StackInfo { - // Set defaults for everything private String name = ""; private String canonicalName = ""; - private HeatStatus status = HeatStatus.UNKNOWN; - private String statusMessage = ""; - private Map<String,Object> outputs = new HashMap<String,Object>(); - private Map<String,Object> parameters = new HashMap<String,Object>(); - - static Map<String,HeatStatus> HeatStatusMap; - static { - HeatStatusMap = new HashMap<String,HeatStatus>(); - HeatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING); - HeatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED); - HeatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED); - HeatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING); - HeatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND); - HeatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED); - HeatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING); - HeatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED); - HeatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED); - } + private HeatStatus status; + private Map<String, Object> outputs = new HashMap<>(); + private Map<String,Object> parameters = new HashMap<>(); + static private Map<String, HeatStatus> heatStatusMap; - public StackInfo () { + static { + heatStatusMap = new HashMap<>(); + heatStatusMap.put("CREATE_IN_PROGRESS", HeatStatus.BUILDING); + heatStatusMap.put("CREATE_COMPLETE", HeatStatus.CREATED); + heatStatusMap.put("CREATE_FAILED", HeatStatus.FAILED); + heatStatusMap.put("DELETE_IN_PROGRESS", HeatStatus.DELETING); + heatStatusMap.put("DELETE_COMPLETE", HeatStatus.NOTFOUND); + heatStatusMap.put("DELETE_FAILED", HeatStatus.FAILED); + heatStatusMap.put("UPDATE_IN_PROGRESS", HeatStatus.UPDATING); + heatStatusMap.put("UPDATE_FAILED", HeatStatus.FAILED); + heatStatusMap.put("UPDATE_COMPLETE", HeatStatus.UPDATED); } - - public StackInfo (String name, HeatStatus status, String statusMessage, Map<String,Object> outputs) { - this.name = name; - this.canonicalName = name; // Don't have an ID, so just use name - this.status = status; - if (statusMessage != null) this.statusMessage = statusMessage; - if (outputs != null) this.outputs = outputs; - } - public StackInfo (String name, HeatStatus status) { this.name = name; this.canonicalName = name; // Don't have an ID, so just use name this.status = status; } - + public StackInfo (Stack stack) { if (stack == null) { this.status = HeatStatus.NOTFOUND; return; } - this.name = stack.getStackName(); this.canonicalName = stack.getStackName() + "/" + stack.getId(); if (stack.getStackStatus() == null) { this.status = HeatStatus.INIT; - } else if (HeatStatusMap.containsKey(stack.getStackStatus())) { - this.status = HeatStatusMap.get(stack.getStackStatus()); + } else if (heatStatusMap.containsKey(stack.getStackStatus())) { + this.status = heatStatusMap.get(stack.getStackStatus()); } else { this.status = HeatStatus.UNKNOWN; } - - this.statusMessage = stack.getStackStatusReason(); - if (stack.getOutputs() != null) { - this.outputs = new HashMap<String,Object>(); - for (Stack.Output output : stack.getOutputs()) { - this.outputs.put(output.getOutputKey(), output.getOutputValue()); - } + this.outputs = new HashMap<>(); + stack.getOutputs().forEach(output -> outputs.put(output.getOutputKey(), output.getOutputValue())); } - + this.parameters = stack.getParameters(); } - + public String getName() { return name; } - + public void setName (String name) { this.name = name; } - + public String getCanonicalName() { return canonicalName; } - - public void setCanonicalName (String name) { - this.canonicalName = name; - } - + public HeatStatus getStatus() { return status; } - - public void setStatus (HeatStatus status) { - this.status = status; - } - - public String getStatusMessage() { - return statusMessage; - } - - public void setStatusMessage (String statusMessage) { - this.statusMessage = statusMessage; - } - - public Map<String,Object> getOutputs () { + + public Map<String, Object> getOutputs() { return outputs; } - - public void setOutputs (Map<String,Object> outputs) { - this.outputs = outputs; - } - + public Map<String,Object> getParameters () { return parameters; } - - public void setParameters (Map<String,Object> parameters) { - this.parameters = parameters; - } - + } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java index 3aa77c2c7a..69da437797 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntry.java @@ -21,212 +21,83 @@ package org.openecomp.mso.openstack.utils; - - -import java.util.HashSet; -import java.util.ArrayList; import java.util.Set; -import org.openecomp.mso.db.catalog.beans.HeatTemplateParam; import org.openecomp.mso.logger.MsoLogger; public class MsoHeatEnvironmentEntry { - private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); - - private Set<MsoHeatEnvironmentParameter> parameters = null; - private Set<MsoHeatEnvironmentResource> resources = null; - private StringBuilder rawEntry = null; + private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA); + private Set<MsoHeatEnvironmentParameter> parameters; + private String rawEntry; private boolean valid = true; - private String errorString = null; - private StringBuilder resourceRegistryEntryRaw = null; - - public MsoHeatEnvironmentEntry() { - super(); - } - - public MsoHeatEnvironmentEntry(StringBuilder sb) { - this(); - this.rawEntry = sb; - this.processRawEntry(); + private String errorString; + private String resourceRegistryEntryRaw; + + private MsoHeatEnvironmentEntry(String rawEntry) { + this.rawEntry = rawEntry; } - - private void processRawEntry() { - try { - if (this.rawEntry == null || "".equals(this.rawEntry)) - return; - byte[] b = this.rawEntry.toString().getBytes(); - MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b); - this.parameters = yaml.getParameterListFromEnvt(); - //this.resources = yaml.getResourceListFromEnvt(); - StringBuilder sb = this.getResourceRegistryRawEntry(); - if (sb == null) { - this.resourceRegistryEntryRaw = new StringBuilder(""); - } else { - this.resourceRegistryEntryRaw = sb; - } - } catch (Exception e) { - LOGGER.debug("Exception:", e); - this.valid = false; - this.errorString = e.getMessage(); - //e.printStackTrace(); - } + + private MsoHeatEnvironmentEntry(Set<MsoHeatEnvironmentParameter> parameters, String rawEntry, boolean valid, + String errorString, String resourceRegistryEntryRaw) { + this.parameters = parameters; + this.rawEntry = rawEntry; + this.valid = valid; + this.errorString = errorString; + this.resourceRegistryEntryRaw = resourceRegistryEntryRaw; } - + public boolean isValid() { return this.valid; } public String getErrorString() { return this.errorString; } - - public Set<MsoHeatEnvironmentParameter> getParameters() { - return this.parameters; - } - public Set<MsoHeatEnvironmentResource> getResources() { - return this.resources; - } - public void setParameters(Set<MsoHeatEnvironmentParameter> paramSet) { - if (paramSet == null) { - this.parameters = null; - } else { - this.parameters = paramSet; - } - } - public void setResources(Set<MsoHeatEnvironmentResource> resourceSet) { - if (resourceSet == null) { - this.resources = null; - } else { - this.resources = resourceSet; - } - } - - public void addParameter(MsoHeatEnvironmentParameter hep) { - if (this.parameters == null) { - this.parameters = new HashSet<>(); - } - this.parameters.add(hep); - } - public void addResource(MsoHeatEnvironmentResource her) { - if (this.resources == null) { - this.resources = new HashSet<>(); - } - this.resources.add(her); - } - - public int getNumberOfParameters() { - return this.parameters.size(); - } - public int getNumberOfResources() { - return this.resources.size(); - } - - public boolean hasResources() { - if (this.resources != null && this.resources.size() > 0) { - return true; - } - return false; - } - public boolean hasParameters() { - if (this.parameters != null && this.parameters.size() > 0) { - return true; - } - return false; - } - + public boolean containsParameter(String paramName) { - boolean contains = false; if (this.parameters == null || this.parameters.size() < 1) { return false; } if (this.parameters.contains(new MsoHeatEnvironmentParameter(paramName))) { - contains = true; - } - return contains; - } - - public boolean containsParameter(String paramName, String paramAlias) { - if (this.containsParameter(paramName)) { - return true; - } - if (this.containsParameter(paramAlias)) { return true; } return false; } - - public StringBuilder toFullStringExcludeNonParams(Set<HeatTemplateParam> params) { - // Basically give back the envt - but exclude the params that aren't in the HeatTemplate - - StringBuilder sb = new StringBuilder(); - ArrayList<String> paramNameList = new ArrayList<String>(params.size()); - for (HeatTemplateParam htp : params) { - paramNameList.add(htp.getParamName()); - } - - if (this.hasParameters()) { - sb.append("parameters:\n"); - for (MsoHeatEnvironmentParameter hep : this.parameters) { - String paramName = hep.getName(); - if (paramNameList.contains(paramName)) { - // This parameter *is* in the Heat Template - so include it: - sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n"); - // New - 1607 - if any of the params mapped badly - JUST RETURN THE ORIGINAL ENVT! - if (hep.getValue().startsWith("_BAD")) { - return this.rawEntry; - } - } - } - sb.append("\n"); - } -// if (this.hasResources()) { -// sb.append("resource_registry:\n"); -// for (MsoHeatEnvironmentResource her : this.resources) { -// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n"); -// } -// } - sb.append("\n"); - sb.append(this.resourceRegistryEntryRaw); - return sb; + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("MsoHeatEnvironmentEntry{"); + sb.append("parameters=").append(parameters); + sb.append(", resourceRegistryEntryRaw='").append(resourceRegistryEntryRaw).append('\''); + sb.append('}'); + return sb.toString(); + } + + public String getRawEntry() { + return rawEntry; } - public StringBuilder toFullString() { - StringBuilder sb = new StringBuilder(); - - if (this.hasParameters()) { - sb.append("parameters:\n"); - for (MsoHeatEnvironmentParameter hep : this.parameters) { - sb.append(" " + hep.getName() + ": " + hep.getValue() + "\n"); - } - sb.append("\n"); + private static String getResourceRegistryRawEntry(String rawEntry) { + int indexOf = rawEntry.indexOf("resource_registry:"); + if (indexOf < 0) { + return ""; } -// if (this.hasResources()) { -// sb.append("resource_registry:\n"); -// for (MsoHeatEnvironmentResource her : this.resources) { -// sb.append(" \"" + her.getName() + "\": " + her.getValue() + "\n"); -// } -// } - sb.append("\n"); - sb.append(this.resourceRegistryEntryRaw); - return sb; + return rawEntry.substring(indexOf); } - public StringBuilder getRawEntry() { - return this.rawEntry; - } - - private StringBuilder getResourceRegistryRawEntry() { - - if (this.rawEntry == null) { - return null; + public static MsoHeatEnvironmentEntry create(String rawEntry) { + if (rawEntry == null || rawEntry.isEmpty()) { + return new MsoHeatEnvironmentEntry(rawEntry); } - - StringBuilder sb = new StringBuilder(); - int indexOf = this.rawEntry.indexOf("resource_registry:"); - if (indexOf < 0) { // no resource_registry: - return null; + try { + Set<MsoHeatEnvironmentParameter> parameters = new MsoYamlEditorWithEnvt(rawEntry.getBytes()) + .getParameterListFromEnvt(); + return new MsoHeatEnvironmentEntry(parameters, rawEntry, true, null, + getResourceRegistryRawEntry(rawEntry)); + } catch (Exception e) { + LOGGER.debug(String.format("An exception occurred during processing the following raw entry: %s", rawEntry), + e); + return new MsoHeatEnvironmentEntry(null, rawEntry, false, e.getMessage(), null); } - sb.append(this.rawEntry.substring(indexOf)); - return sb; } - + } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java index 08ea84d85d..acc6d72f63 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtils.java @@ -258,7 +258,7 @@ public class MsoHeatUtils extends MsoCommonUtils { * @param cloudSiteId The cloud (may be a region) in which to create the stack. * @param tenantId The Openstack ID of the tenant in which to create the Stack * @param stackName The name of the stack to create - * @param stackTemplate The Heat template + * @param heatTemplate The Heat template * @param stackInputs A map of key/value inputs * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client * @param environment An optional yaml-format string to specify environmental parameters @@ -309,10 +309,8 @@ public class MsoHeatUtils extends MsoCommonUtils { } // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); LOGGER.debug("Found: " + cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) @@ -632,10 +630,8 @@ public class MsoHeatUtils extends MsoCommonUtils { LOGGER.debug ("Query HEAT stack: " + stackName + " in tenant " + tenantId); // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); LOGGER.debug("Found: " + cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) @@ -648,7 +644,7 @@ public class MsoHeatUtils extends MsoCommonUtils { } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); - return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "OpenStack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); @@ -662,7 +658,7 @@ public class MsoHeatUtils extends MsoCommonUtils { if (heatStack == null) { // Stack does not exist. Return a StackInfo with status NOTFOUND - StackInfo stackInfo = new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + StackInfo stackInfo = new StackInfo (stackName, HeatStatus.NOTFOUND); return stackInfo; } @@ -696,10 +692,8 @@ public class MsoHeatUtils extends MsoCommonUtils { String stackName, boolean pollForCompletion) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); LOGGER.debug("Found: " + cloudSite.toString()); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) @@ -712,7 +706,7 @@ public class MsoHeatUtils extends MsoCommonUtils { } catch (MsoTenantNotFound e) { // Tenant doesn't exist, so stack doesn't either LOGGER.debug ("Tenant with id " + tenantId + "not found.", e); - return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + return new StackInfo (stackName, HeatStatus.NOTFOUND); } catch (MsoException me) { // Got an Openstack error. Propagate it LOGGER.error (MessageEnum.RA_CONNECTION_EXCEPTION, "Openstack", "Openstack Exception on Token request: " + me, "Openstack", "", MsoLogger.ErrorCode.AvailabilityError, "Connection Exception"); @@ -724,7 +718,7 @@ public class MsoHeatUtils extends MsoCommonUtils { Stack heatStack = queryHeatStack (heatClient, stackName); if (heatStack == null || "DELETE_COMPLETE".equals (heatStack.getStackStatus ())) { // Not found. Return a StackInfo with status NOTFOUND - return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + return new StackInfo (stackName, HeatStatus.NOTFOUND); } // Delete the stack. @@ -747,7 +741,7 @@ public class MsoHeatUtils extends MsoCommonUtils { } catch (OpenStackResponseException e) { if (e.getStatus () == 404) { // Not found. We are OK with this. Return a StackInfo with status NOTFOUND - return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + return new StackInfo (stackName, HeatStatus.NOTFOUND); } else { // Convert the OpenStackResponseException to an MsoOpenstackException throw heatExceptionToMsoException (e, DELETE_STACK); @@ -813,7 +807,7 @@ public class MsoHeatUtils extends MsoCommonUtils { } // The stack is gone when this point is reached - return new StackInfo (stackName, HeatStatus.NOTFOUND, null, null); + return new StackInfo (stackName, HeatStatus.NOTFOUND); } // Return the current status (if not polling, the delete may still be in progress) @@ -838,11 +832,8 @@ public class MsoHeatUtils extends MsoCommonUtils { */ public List <StackInfo> queryAllStacks (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } - + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) Heat heatClient = getHeatClient (cloudSite, tenantId); @@ -950,8 +941,6 @@ public class MsoHeatUtils extends MsoCommonUtils { * tenantID + cloudId so that it can be reused without reauthenticating with * Openstack every time. * - * @param tenantName - * @param cloudId * @return an authenticated Heat object */ public Heat getHeatClient (CloudSite cloudSite, String tenantId) throws MsoException { @@ -1038,8 +1027,6 @@ public class MsoHeatUtils extends MsoCommonUtils { * the same Tenant Name is repeatedly used for creation/deletion. * <p> * - * @param tenantName - * @param cloudId */ public static void expireHeatClient (String tenantId, String cloudId) { String cacheKey = cloudId + ":" + tenantId; diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java index dba52d4306..2465b30eca 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoHeatUtilsWithUpdate.java @@ -21,7 +21,6 @@ package org.openecomp.mso.openstack.utils; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -160,7 +159,7 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { * @param tenantId The Openstack ID of the tenant in which to create the Stack * @param cloudSiteId The cloud identifier (may be a region) in which to create the tenant. * @param stackName The name of the stack to update - * @param stackTemplate The Heat template + * @param heatTemplate The Heat template * @param stackInputs A map of key/value inputs * @param pollForCompletion Indicator that polling should be handled in Java vs. in the client * @param environment An optional yaml-format string to specify environmental parameters @@ -194,10 +193,8 @@ public class MsoHeatUtilsWithUpdate extends MsoHeatUtils { } // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); // Get a Heat client. They are cached between calls (keyed by tenantId:cloudId) // This could throw MsoTenantNotFound or MsoOpenstackException (both propagated) Heat heatClient = getHeatClient (cloudSite, tenantId); diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java index ee89840c50..be36d67e0b 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoKeystoneUtils.java @@ -26,6 +26,7 @@ import java.util.Calendar; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import org.openecomp.mso.cloud.CloudIdentity; import org.openecomp.mso.cloud.CloudSite; import org.openecomp.mso.logger.MsoAlarmLogger; @@ -58,7 +59,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // token will be used until it expires. // // The cache key is "cloudId" - private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap <String, KeystoneCacheEntry> (); + private static Map <String, KeystoneCacheEntry> adminClientCache = new HashMap<>(); private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); String msoPropID; @@ -92,13 +93,12 @@ public class MsoKeystoneUtils extends MsoTenantUtils { Map <String, String> metadata, boolean backout) throws MsoException { // Obtain the cloud site information where we will create the tenant - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); + if (!cloudSiteOpt.isPresent()) { LOGGER.error(MessageEnum.RA_CREATE_TENANT_ERR, "MSOCloudSite not found", "", "", MsoLogger.ErrorCode.DataError, "MSOCloudSite not found"); throw new MsoCloudSiteNotFound (cloudSiteId); } - Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); - + Keystone keystoneAdminClient = getKeystoneAdminClient(cloudSiteOpt.get()); Tenant tenant = null; try { // Check if the tenant already exists @@ -129,7 +129,7 @@ public class MsoKeystoneUtils extends MsoTenantUtils { // Add MSO User to the tenant as a member and // apply tenant metadata if supported by the cloud site try { - CloudIdentity cloudIdentity = cloudSite.getIdentityService (); + CloudIdentity cloudIdentity = cloudSiteOpt.get().getIdentityService (); User msoUser = findUserByNameOrId (keystoneAdminClient, cloudIdentity.getMsoId ()); Role memberRole = findRoleByNameOrId (keystoneAdminClient, cloudIdentity.getMemberRole ()); @@ -197,10 +197,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public MsoTenant queryTenant (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); @@ -247,10 +245,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public MsoTenant queryTenantByName (String tenantName, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); try { @@ -294,10 +290,8 @@ public class MsoKeystoneUtils extends MsoTenantUtils { */ public boolean deleteTenant (String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); try { @@ -326,59 +320,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils { return true; } - /** - * Delete the specified Tenant (by Name) in the given cloud. This method returns true or - * false, depending on whether the tenant existed and was successfully deleted, or if - * the tenant already did not exist. Both cases are treated as success (no Exceptions). - * <p> - * Note for the AIC Cloud (DCP/LCP): all admin requests go to the centralized identity - * service in DCP. So deleting a tenant from one cloudSiteId will remove it from all - * sites managed by that identity service. - * <p> - * - * @param tenantName The name of the tenant to delete - * @param cloudSiteId The cloud identifier from which to delete the tenant. - * @return true if the tenant was deleted, false if the tenant did not exist. - * @throws MsoOpenstackException If the Openstack API call returns an exception. - */ - public boolean deleteTenantByName (String tenantName, String cloudSiteId) throws MsoException { - // Obtain the cloud site information where we will query the tenant - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound (cloudSiteId); - } - Keystone keystoneAdminClient = getKeystoneAdminClient (cloudSite); - - try { - // Need the Tenant ID to delete (can't directly delete by name) - Tenant tenant = findTenantByName (keystoneAdminClient, tenantName); - if (tenant == null) { - // OK if tenant already doesn't exist. - LOGGER.error(MessageEnum.RA_TENANT_NOT_FOUND, tenantName, cloudSiteId, "", "", MsoLogger.ErrorCode.DataError, "Tenant not found"); - return false; - } - - // Execute the Delete. It has no return value. - OpenStackRequest <Void> request = keystoneAdminClient.tenants ().delete (tenant.getId ()); - executeAndRecordOpenstackRequest (request, msoProps); - - LOGGER.debug ("Deleted Tenant " + tenant.getId () + " (" + tenant.getName () + ")"); - - // Clear any cached clients. Not really needed, ID will not be reused. - MsoHeatUtils.expireHeatClient (tenant.getId (), cloudSiteId); - MsoNeutronUtils.expireNeutronClient (tenant.getId (), cloudSiteId); - } catch (OpenStackBaseException e) { - // Note: It doesn't seem to matter if tenant doesn't exist, no exception is thrown. - // Convert Keystone OpenStackResponseException to MsoOpenstackException - throw keystoneErrorToMsoException (e, "DeleteTenant"); - } catch (RuntimeException e) { - // Catch-all - throw runtimeExceptionToMsoException (e, "DeleteTenant"); - } - - return true; - } - // ------------------------------------------------------------------- // PRIVATE UTILITY FUNCTIONS FOR USE WITHIN THIS CLASS @@ -463,29 +404,6 @@ public class MsoKeystoneUtils extends MsoTenantUtils { } /* - * Find a tenant (or query its existance) by its Name or Id. Check first against the - * ID. If that fails, then try by name. - * - * @param adminClient an authenticated Keystone object - * - * @param tenantName the tenant name or ID to query - * - * @return a Tenant object or null if not found - */ - public Tenant findTenantByNameOrId (Keystone adminClient, String tenantNameOrId) { - if (tenantNameOrId == null) { - return null; - } - - Tenant tenant = findTenantById (adminClient, tenantNameOrId); - if (tenant == null) { - tenant = findTenantByName (adminClient, tenantNameOrId); - } - - return tenant; - } - - /* * Find a tenant (or query its existance) by its Id. * * @param adminClient an authenticated Keystone object diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java index ad3eae4b01..50a594663e 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoNeutronUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -43,7 +43,6 @@ import org.openecomp.mso.openstack.exceptions.MsoIOException; import org.openecomp.mso.openstack.exceptions.MsoNetworkAlreadyExists; import org.openecomp.mso.openstack.exceptions.MsoNetworkNotFound; import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.exceptions.MsoTenantNotFound; import com.woorea.openstack.base.client.OpenStackBaseException; import com.woorea.openstack.base.client.OpenStackConnectException; import com.woorea.openstack.base.client.OpenStackRequest; @@ -71,7 +70,7 @@ public class MsoNeutronUtils extends MsoCommonUtils private static MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); private String msoPropID; - + public enum NetworkType { BASIC, PROVIDER, MULTI_PROVIDER }; @@ -99,13 +98,11 @@ public class MsoNeutronUtils extends MsoCommonUtils * @throws MsoCloudSiteNotFound Thrown if the cloudSite is invalid or unknown */ public NetworkInfo createNetwork (String cloudSiteId, String tenantId, NetworkType type, String networkName, String provider, List<Integer> vlans) - throws MsoException, MsoNetworkAlreadyExists, MsoCloudSiteNotFound + throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound(cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); @@ -177,19 +174,15 @@ public class MsoNeutronUtils extends MsoCommonUtils * @throws MsoOpenstackException Thrown if the Openstack API call returns an exception * @throws MsoCloudSiteNotFound */ - public NetworkInfo queryNetwork (String networkNameOrId, String tenantId, String cloudSiteId) - throws MsoException, MsoCloudSiteNotFound + public NetworkInfo queryNetwork(String networkNameOrId, String tenantId, String cloudSiteId) throws MsoException { LOGGER.debug("In queryNetwork"); // Obtain the cloud site information - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound(cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); - // Check if the network exists and return its info try { Network network = findNetworkByNameOrId (neutronClient, networkNameOrId); @@ -215,24 +208,20 @@ public class MsoNeutronUtils extends MsoCommonUtils * Delete the specified Network (by ID) in the given cloud. * If the network does not exist, success is returned. * <p> - * @param networkNameOrId The name or Openstack ID of the network to delete - * @param cloudId The cloud identifier (may be a region) from which to delete the network. + * @param networkId Openstack ID of the network to delete + * @param tenantId The Openstack tenant. + * @param cloudSiteId The cloud identifier (may be a region) from which to delete the network. * @return true if the network was deleted, false if the network did not exist * @throws MsoOpenstackException If the Openstack API call returns an exception, this local * exception will be thrown. * @throws MsoCloudSiteNotFound */ - public boolean deleteNetwork (String networkId, String tenantId, String cloudSiteId) - throws MsoException, MsoCloudSiteNotFound + public boolean deleteNetwork(String networkId, String tenantId, String cloudSiteId) throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound(cloudSiteId); - } - + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); - try { // Check that the network exists. Network network = findNetworkById (neutronClient, networkId); @@ -273,7 +262,7 @@ public class MsoNeutronUtils extends MsoCommonUtils * to manage the virtual networking). * * @param cloudSiteId The cloud site ID (may be a region) in which to update the network. - * @param the Openstack ID of the tenant in which to update the network + * @param tenantId Openstack ID of the tenant in which to update the network * @param networkId The unique Openstack ID of the network to be updated * @param type The network type (Basic, Provider, Multi-Provider) * @param provider The provider network name. This should not change. @@ -284,15 +273,12 @@ public class MsoNeutronUtils extends MsoCommonUtils * @throws MsoCloudSiteNotFound */ public NetworkInfo updateNetwork (String cloudSiteId, String tenantId, String networkId, NetworkType type, String provider, List<Integer> vlans) - throws MsoException, MsoNetworkNotFound, MsoCloudSiteNotFound + throws MsoException { // Obtain the cloud site information where we will create the stack - CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite == null) { - throw new MsoCloudSiteNotFound(cloudSiteId); - } + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); Quantum neutronClient = getNeutronClient (cloudSite, tenantId); - // Check that the network exists Network network = findNetworkById (neutronClient, networkId); @@ -359,8 +345,7 @@ public class MsoNeutronUtils extends MsoCommonUtils * @param tenantId - Openstack tenant ID * @return an authenticated Quantum object */ - private Quantum getNeutronClient (CloudSite cloudSite, String tenantId) - throws MsoTenantNotFound, MsoException + private Quantum getNeutronClient(CloudSite cloudSite, String tenantId) throws MsoException { String cloudId = cloudSite.getId(); @@ -440,9 +425,6 @@ public class MsoNeutronUtils extends MsoCommonUtils * the KeystoneClient in case where a tenant is deleted. In that case, * all cached credentials must be purged so that fresh authentication is * done on subsequent calls. - * <p> - * @param tenantName - * @param cloudId */ public static void expireNeutronClient (String tenantId, String cloudId) { String cacheKey = cloudId + ":" + tenantId; @@ -602,6 +584,6 @@ public class MsoNeutronUtils extends MsoCommonUtils * This may be useful if cached credentials get out of sync. */ public static void neutronCacheReset () { - neutronClientCache = new HashMap<String,NeutronCacheEntry>(); + neutronClientCache = new HashMap<>(); } } diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java index 4a19828897..2cd4597c18 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtils.java @@ -21,27 +21,18 @@ package org.openecomp.mso.openstack.utils; -import java.io.Serializable; -import java.util.Calendar; -import java.util.HashMap; import java.util.Map; - import org.openecomp.mso.cloud.CloudConfig; import org.openecomp.mso.cloud.CloudConfigFactory; import org.openecomp.mso.cloud.CloudIdentity; -import org.openecomp.mso.logger.MsoAlarmLogger; -import org.openecomp.mso.logger.MsoLogger; import org.openecomp.mso.logger.MessageEnum; +import org.openecomp.mso.logger.MsoLogger; import org.openecomp.mso.openstack.beans.MsoTenant; -import org.openecomp.mso.openstack.exceptions.MsoAdapterException; import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; import org.openecomp.mso.openstack.exceptions.MsoException; -import org.openecomp.mso.openstack.exceptions.MsoOpenstackException; -import org.openecomp.mso.openstack.exceptions.MsoTenantAlreadyExists; import org.openecomp.mso.properties.MsoJavaProperties; import org.openecomp.mso.properties.MsoPropertiesException; import org.openecomp.mso.properties.MsoPropertiesFactory; -import com.woorea.openstack.keystone.Keystone; public abstract class MsoTenantUtils extends MsoCommonUtils { diff --git a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java index a659fb629e..e36d46841d 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java +++ b/adapters/mso-adapter-utils/src/main/java/org/openecomp/mso/openstack/utils/MsoTenantUtilsFactory.java @@ -26,6 +26,7 @@ import org.openecomp.mso.cloud.CloudIdentity; import org.openecomp.mso.cloud.CloudSite; import java.lang.reflect.InvocationTargetException; +import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; public class MsoTenantUtilsFactory { @@ -39,12 +40,11 @@ public class MsoTenantUtilsFactory { } //based on Cloud IdentityServerType returns ORM or KEYSTONE Utils - public MsoTenantUtils getTenantUtils(String cloudSiteId) { - + public MsoTenantUtils getTenantUtils(String cloudSiteId) throws MsoCloudSiteNotFound { // Obtain the cloud site information cloudConfig = cloudConfigFactory.getCloudConfig(); - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - + CloudSite cloudSite = cloudConfig.getCloudSite(cloudSiteId).orElseThrow( + () -> new MsoCloudSiteNotFound(cloudSiteId)); return getTenantUtilsByServerType(cloudSite.getIdentityService().getIdentityServerType().toString()); } diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/AdapterBeansTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/AdapterBeansTest.java index f231c75211..250211845f 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/AdapterBeansTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/AdapterBeansTest.java @@ -26,21 +26,14 @@ import java.util.ArrayList; import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import org.junit.Test;
import org.openecomp.mso.entity.MsoRequest;
-import org.openecomp.mso.openstack.beans.HeatStatus;
import org.openecomp.mso.openstack.beans.MsoTenant;
-import org.openecomp.mso.openstack.beans.NetworkInfo;
import org.openecomp.mso.openstack.beans.NetworkRollback;
-import org.openecomp.mso.openstack.beans.NetworkStatus;
import org.openecomp.mso.openstack.beans.Pool;
-import org.openecomp.mso.openstack.beans.StackInfo;
import org.openecomp.mso.openstack.beans.Subnet;
import org.openecomp.mso.openstack.beans.VnfRollback;
-import com.woorea.openstack.heat.model.Stack;
-
public class AdapterBeansTest {
@Test
public final void msoTenantTest() {
@@ -58,33 +51,6 @@ public class AdapterBeansTest { }
@Test
- public final void networkInfoTest() {
- NetworkInfo networkInfo = new NetworkInfo();
- networkInfo.setName("name");
- assertTrue(networkInfo.getName().equalsIgnoreCase("name"));
- networkInfo.setId("1");
- assertTrue(networkInfo.getId().equalsIgnoreCase("1"));
- networkInfo.setStatus(NetworkStatus.ACTIVE);
- assertTrue(networkInfo.getStatus().equals(NetworkStatus.ACTIVE));
- networkInfo.setProvider("provider");
- networkInfo.getProvider().equalsIgnoreCase("provider");
- List<Integer> al = new ArrayList<>();
- al.add(1);
- al.add(2);
- networkInfo.setVlans(al);
- assertTrue(networkInfo.getVlans() != null);
- networkInfo.setShared("shared");
- assertTrue(networkInfo.getShared().equalsIgnoreCase("shared"));
- List<String> als = new ArrayList<>();
- als.add("1");
- als.add("2");
- networkInfo.setSubnets(als);
- assertTrue(networkInfo.getSubnets() != null);
- new NetworkInfo("string", NetworkStatus.ACTIVE);
- assertTrue(networkInfo.toString() != null);
- }
-
- @Test
public final void networkRollbackTest() {
NetworkRollback networkRollback = new NetworkRollback();
networkRollback.setCloudId("cloudId");
@@ -130,26 +96,6 @@ public class AdapterBeansTest { }
@Test
- public final void stackInfoTest() {
- StackInfo stackInfo = new StackInfo();
- new StackInfo(new Stack());
- new StackInfo("name", HeatStatus.CREATED, "statusmessage", new HashMap<>());
- new StackInfo("name", HeatStatus.CREATED);
- stackInfo.setCanonicalName("Canonicalname");
- stackInfo.getCanonicalName();
- stackInfo.setName("name");
- stackInfo.getName();
- stackInfo.setOutputs(new HashMap<>());
- stackInfo.getOutputs();
- stackInfo.setParameters(new HashMap<>());
- stackInfo.getParameters();
- stackInfo.setStatus(HeatStatus.CREATED);
- stackInfo.getStatus();
- stackInfo.setStatusMessage("statusMessage");
- stackInfo.getStatusMessage();
- }
-
- @Test
public final void subnetTest() {
Subnet subnet = new Subnet();
subnet.setAllocationPools(new ArrayList<>());
diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java index 714bb66e18..62043e83b8 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/adapter_utils/tests/MsoHeatUtilsWithUpdateTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.when; import java.util.HashMap; import java.util.Map; +import java.util.Optional; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -68,8 +69,8 @@ public class MsoHeatUtilsWithUpdateTest { cloudIdentity.setKeystoneUrl ("toto"); cloudIdentity.setMsoPass (CloudIdentity.encryptPassword ("mockId")); cloudSite.setIdentityService (cloudIdentity); - when (cloudConfig.getCloudSite ("cloud")).thenReturn (cloudSite); - when (cloudConfig.getCloudSite ("none")).thenReturn (null); + when(cloudConfig.getCloudSite("cloud")).thenReturn (Optional.of(cloudSite)); + when(cloudConfig.getCloudSite("none")).thenReturn (Optional.empty()); } @Test diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java index a73e4359fc..1c2501e8e4 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/cloud/CloudConfigTest.java @@ -26,6 +26,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import java.util.Optional; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -112,29 +113,29 @@ public class CloudConfigTest { @Test public void cloudSiteIsGotById_when_IdFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("MT"); - assertNotNull(cloudSite); - assertEquals("regionOne", cloudSite.getRegionId()); - assertEquals("MT_KEYSTONE", cloudSite.getIdentityServiceId()); + Optional<CloudSite> cloudSite = con.getCloudSite("MT"); + assertTrue(cloudSite.isPresent()); + assertEquals("regionOne", cloudSite.get().getRegionId()); + assertEquals("MT_KEYSTONE", cloudSite.get().getIdentityServiceId()); } @Test public void cloudSiteIsGotByClli_when_IdNotFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("CS_clli"); - assertNotNull(cloudSite); - assertEquals("clliRegion", cloudSite.getRegionId()); - assertEquals("CS_clli", cloudSite.getClli()); - assertEquals("CS_service", cloudSite.getIdentityServiceId()); + Optional<CloudSite> cloudSite = con.getCloudSite("CS_clli"); + assertTrue(cloudSite.isPresent()); + assertEquals("clliRegion", cloudSite.get().getRegionId()); + assertEquals("CS_clli", cloudSite.get().getClli()); + assertEquals("CS_service", cloudSite.get().getIdentityServiceId()); } @Test public void cloudSiteIsGotByDefault_when_IdAndClliNotFound() throws MsoCloudIdentityNotFound { CloudConfig con = createTestObject(cloudDefaultConfigJsonFilePath); - CloudSite cloudSite = con.getCloudSite("not_existing_id"); - assertNotNull(cloudSite); - assertEquals("not_existing_id", cloudSite.getId()); - assertEquals("not_existing_id", cloudSite.getRegionId()); + Optional<CloudSite> cloudSite = con.getCloudSite("not_existing_id"); + assertTrue(cloudSite.isPresent()); + assertEquals("not_existing_id", cloudSite.get().getId()); + assertEquals("not_existing_id", cloudSite.get().getRegionId()); } @Test diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/NetworkInfoTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/NetworkInfoTest.java new file mode 100644 index 0000000000..0f357e5555 --- /dev/null +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/NetworkInfoTest.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.openstack.beans; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.woorea.openstack.quantum.model.Network; +import com.woorea.openstack.quantum.model.Segment; +import java.util.ArrayList; +import java.util.List; +import org.junit.Test; + +public class NetworkInfoTest { + + private static final String NETWORK_STATUS_ACTIVE = "ACTIVE"; + private static final String NETWORK_STATUS_ID = "networkIdTest"; + private static final String NETWORK_STATUS_NAME = "networkNameTest"; + private static final String SUBNET_NAME = "subnetTest"; + private static final String PROVIDER = "providerTest"; + private static final String PROVIDER_NETWORK_TYPE_VLAN = "vlan"; + private static final String PROVIDER_NETWORK_TYPE_OTHER = "providerTypeTest"; + private static final Integer PROVIDER_SEGMENTATION_ID = 777; + private static final String PROVIDER_FOR_SEGMENT = "providerSegmentTest"; + private static final Integer PROVIDER_SEGMENTATION_ID_FOR_SEGMENT = 123; + + @Test + public void networkStatusUnknownWhenIsNullInNetwork() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetwork(null)); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.UNKNOWN); + checkCommonPartWhenProviderIsNotPresent(networkInfo); + } + + @Test + public void networkStatusUnknownWhenNotFoundInNetworkStatusMap() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetwork("notExistingNetworkStatus")); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.UNKNOWN); + checkCommonPartWhenProviderIsNotPresent(networkInfo); + } + + @Test + public void setNetworkStatusWhenNetworkStatusFoundInNetworkStatusMap() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetwork(NETWORK_STATUS_ACTIVE)); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.ACTIVE); + checkCommonPartWhenProviderIsNotPresent(networkInfo); + } + + @Test + public void setVLANProviderFromTheNetwork() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetworkWithProvider(NETWORK_STATUS_ACTIVE, PROVIDER, + PROVIDER_NETWORK_TYPE_VLAN)); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.ACTIVE); + assertThat(networkInfo.getProvider()).isEqualTo(PROVIDER); + assertThat(networkInfo.getVlans()).hasSize(1).contains(PROVIDER_SEGMENTATION_ID); + checkCommonPart(networkInfo); + } + + @Test + public void setOtherProviderFromTheNetwork() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetworkWithProvider(NETWORK_STATUS_ACTIVE, PROVIDER, + PROVIDER_NETWORK_TYPE_OTHER)); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.ACTIVE); + assertThat(networkInfo.getProvider()).isEqualTo(PROVIDER); + assertThat(networkInfo.getVlans()).isEmpty(); + checkCommonPart(networkInfo); + } + + @Test + public void setVLANProviderFromTheNetworkSegments() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetworkWithSegments(NETWORK_STATUS_ACTIVE, + prepareSegment(PROVIDER_NETWORK_TYPE_VLAN))); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.ACTIVE); + assertThat(networkInfo.getProvider()).isEqualTo(PROVIDER_FOR_SEGMENT); + assertThat(networkInfo.getVlans()).hasSize(1).contains(PROVIDER_SEGMENTATION_ID_FOR_SEGMENT); + checkCommonPart(networkInfo); + } + + @Test + public void setOtherProviderFromTheNetworkSegments() { + NetworkInfo networkInfo = new NetworkInfo(prepareNetworkWithSegments(NETWORK_STATUS_ACTIVE, + prepareSegment(PROVIDER_NETWORK_TYPE_OTHER))); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.ACTIVE); + assertThat(networkInfo.getProvider()).isEqualTo(PROVIDER_FOR_SEGMENT); + assertThat(networkInfo.getVlans()).isEmpty(); + checkCommonPart(networkInfo); + } + + @Test + public void setNetworkStatusNotFoundWhenNetworkIsNull() { + NetworkInfo networkInfo = new NetworkInfo(null); + assertThat(networkInfo.getStatus()).isEqualTo(NetworkStatus.NOTFOUND); + } + + private void checkCommonPartWhenProviderIsNotPresent(NetworkInfo networkInfo) { + assertThat(networkInfo.getProvider()).isEmpty(); + assertThat(networkInfo.getVlans()).isEmpty(); + checkCommonPart(networkInfo); + } + + private void checkCommonPart(NetworkInfo networkInfo) { + assertThat(networkInfo.getId()).isEqualTo(NETWORK_STATUS_ID); + assertThat(networkInfo.getName()).isEqualTo(NETWORK_STATUS_NAME); + assertThat(networkInfo.getSubnets()).hasSize(1).contains(SUBNET_NAME); + } + + private Network prepareNetwork(String networkStatus) { + Network network = new Network(); + network.setId(NETWORK_STATUS_ID); + network.setName(NETWORK_STATUS_NAME); + network.setStatus(networkStatus); + List<String> subnets = new ArrayList<>(); + subnets.add(SUBNET_NAME); + network.setSubnets(subnets); + return network; + } + + private Network prepareNetworkWithProvider(String networkStatus, String providerPhysicalNetwork, String providerNetworkType) { + Network network = prepareNetwork(networkStatus); + network.setProviderPhysicalNetwork(providerPhysicalNetwork); + network.setProviderNetworkType(providerNetworkType); + network.setProviderSegmentationId(PROVIDER_SEGMENTATION_ID); + return network; + } + + private Network prepareNetworkWithSegments(String networkStatus, Segment segment) { + Network network = prepareNetwork(networkStatus); + List<Segment> segments = new ArrayList<>(); + segments.add(segment); + network.setSegments(segments); + return network; + } + + private Segment prepareSegment(String providerNetworkType) { + Segment segment = new Segment(); + segment.setProviderPhysicalNetwork(PROVIDER_FOR_SEGMENT); + segment.setProviderNetworkType(providerNetworkType); + segment.setProviderSegmentationId(PROVIDER_SEGMENTATION_ID_FOR_SEGMENT); + return segment; + } + +} diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java new file mode 100644 index 0000000000..9c7911ef89 --- /dev/null +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/beans/StackInfoTest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.openstack.beans; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.woorea.openstack.heat.model.Stack; +import java.io.IOException; +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Test; + +public class StackInfoTest { + + private static final String STACK_NAME = "stackNameTest"; + private static final String STACK_STATUS = "CREATE_COMPLETE"; + private static final String STACK_OUTPUT_KEY = "outputKeyTest"; + private static final String STACK_OUTPUT_VALUE = "outputValueTest"; + private static final String STACK_PARAM_KEY = "paramKeyTest"; + private static final String STACK_PARAM_VALUE = "paramValueTest"; + + @Test + public void setStatusNotFoundWhenStackIsNull() { + StackInfo stackInfo = new StackInfo(null); + assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.NOTFOUND); + assertThat(stackInfo.getOutputs()).isEmpty(); + assertThat(stackInfo.getParameters()).isEmpty(); + } + + @Test + public void createObjectWhenStackStatusIsNull() { + StackInfo stackInfo = new StackInfo(createStackWithStatus(null)); + assertThat(stackInfo.getName()).isEqualTo(STACK_NAME); + assertThat(stackInfo.getOutputs()).isEmpty(); + assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.INIT); + assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE); + } + + @Test + public void createObjectWhenStackStatusIsFound() { + StackInfo stackInfo = new StackInfo(createStackWithStatus(STACK_STATUS)); + assertThat(stackInfo.getName()).isEqualTo(STACK_NAME); + assertThat(stackInfo.getOutputs()).isEmpty(); + assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.CREATED); + assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE); + } + + @Test + public void createObjectWhenStackStatusIsUnknown() { + StackInfo stackInfo = new StackInfo(createStackWithStatus("unknownStatus")); + assertThat(stackInfo.getName()).isEqualTo(STACK_NAME); + assertThat(stackInfo.getOutputs()).isEmpty(); + assertThat(stackInfo.getStatus()).isEqualTo(HeatStatus.UNKNOWN); + assertThat(stackInfo.getParameters()).hasSize(1).containsEntry(STACK_PARAM_KEY, STACK_PARAM_VALUE); + } + + @Test + public void createStackWhenOutputsListIsNotNull() throws IOException { + StackInfo stackInfo = new StackInfo(createStackWithOutputs()); + assertThat(stackInfo.getOutputs()).isNotEmpty().hasSize(1); + assertThat(stackInfo.getOutputs()).hasSize(1).containsEntry(STACK_OUTPUT_KEY, STACK_OUTPUT_VALUE); + } + + private Stack createStackWithStatus(String stackStatus) { + Stack stack = new Stack(); + stack.setStackName(STACK_NAME); + stack.setStackStatus(stackStatus); + stack.getParameters().put(STACK_PARAM_KEY, STACK_PARAM_VALUE); + return stack; + } + + private Stack createStackWithOutputs() throws IOException { + String json = "{\"outputs\":[{\"output_key\" : \"" + STACK_OUTPUT_KEY + "\", \"output_value\" : \"" + + STACK_OUTPUT_VALUE + "\" }]}"; + JsonNode node = new ObjectMapper().readTree(json); + Stack stack = new ObjectMapper().readValue(node, Stack.class); + return stack; + } + +} diff --git a/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java new file mode 100644 index 0000000000..60faa760ba --- /dev/null +++ b/adapters/mso-adapter-utils/src/test/java/org/openecomp/mso/openstack/utils/MsoHeatEnvironmentEntryTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.openstack.utils; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class MsoHeatEnvironmentEntryTest { + + private static final String PARAMETER_NAME = "keyTest"; + private static final String VALUE_NAME = "valueTest"; + private static final String NOT_EXISTING_PARAM = "notExistingParam"; + private static final String RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY = "parameters: {" + + PARAMETER_NAME + ": " + VALUE_NAME + "}"; + private static final String RAW_ENTRY_WITH_RESOURCE_REGISTRY = "resource_registry: resourceTest"; + private static final String RAW_ENTRY_INVALID = "invalidRawEntry"; + private static final String WHITESPACE = " "; + + @Test + public void createObjectWithNullStringBuilder() { + MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(null); + assertThat(testedObject.getRawEntry()).isNull(); + assertThat(testedObject.containsParameter(PARAMETER_NAME)).isFalse(); + assertThat(testedObject.isValid()).isTrue(); + } + + @Test + public void toFullString_ResourceRegistryNotPresentInRawEntry() { + MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY); + assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY); + assertThat(testedObject.isValid()).isTrue(); + assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue(); + assertThat(testedObject.toString()).contains(PARAMETER_NAME).contains(VALUE_NAME); + } + + @Test + public void toFullString_ResourceRegistryPresentInRawEntry() { + MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_RESOURCE_REGISTRY); + assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_WITH_RESOURCE_REGISTRY); + assertThat(testedObject.containsParameter(PARAMETER_NAME)).isFalse(); + assertThat(testedObject.isValid()).isTrue(); + assertThat(testedObject.toString()).contains(RAW_ENTRY_WITH_RESOURCE_REGISTRY); + } + + @Test + public void toFullString_ExceptionOccurred() { + MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_INVALID); + assertThat(testedObject.getRawEntry()).isEqualTo(RAW_ENTRY_INVALID); + assertThat(testedObject.isValid()).isFalse(); + assertThat(testedObject.getErrorString()).isNotNull().isNotEmpty(); + } + + @Test + public void checkIfContainsTheParameter() { + MsoHeatEnvironmentEntry testedObject = MsoHeatEnvironmentEntry.create(RAW_ENTRY_WITH_NO_RESOURCE_REGISTRY); + assertThat(testedObject.containsParameter(PARAMETER_NAME)).isTrue(); + assertThat(testedObject.containsParameter(NOT_EXISTING_PARAM)).isFalse(); + } + +} diff --git a/adapters/mso-adapters-rest-interface/pom.xml b/adapters/mso-adapters-rest-interface/pom.xml index bbf614a644..f10500d2ca 100644 --- a/adapters/mso-adapters-rest-interface/pom.xml +++ b/adapters/mso-adapters-rest-interface/pom.xml @@ -54,11 +54,5 @@ <version>1.10.19</version> <scope>test</scope> </dependency> - <dependency> - <groupId>org.assertj</groupId> - <artifactId>assertj-core</artifactId> - <version>3.8.0</version> - <scope>test</scope> - </dependency> </dependencies> </project> diff --git a/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java index 687930673b..2c04ae9d6b 100644 --- a/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-network-adapter/src/main/java/org/openecomp/mso/adapters/network/MsoNetworkAdapterImpl.java @@ -26,6 +26,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import javax.jws.WebService; import javax.xml.ws.Holder; @@ -271,8 +272,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { // So this is just catching that error in a bit more obvious way up front. cloudConfig = cloudConfigFactory.getCloudConfig (); - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); + if (!cloudSiteOpt.isPresent()) { String error = "Configuration Error. Stack " + networkName + " in " + cloudSiteId @@ -299,7 +300,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { physicalNetworkName, vlans, routeTargets, - cloudSite); + cloudSiteOpt.get()); String mode = networkResource.getOrchestrationMode (); NetworkType neutronNetworkType = NetworkType.valueOf (networkResource.getNeutronNetworkType ()); @@ -787,8 +788,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { networkRollback.setMsoRequest (msoRequest); cloudConfig = cloudConfigFactory.getCloudConfig (); - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) { + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite (cloudSiteId); + if (!cloudSiteOpt.isPresent()) { String error = "UpdateNetwork: Configuration Error. Stack " + networkName + " in " + cloudSiteId + "/" @@ -814,7 +815,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { physicalNetworkName, vlans, routeTargets, - cloudSite); + cloudSiteOpt.get()); String mode = networkResource.getOrchestrationMode(); NetworkType neutronNetworkType = NetworkType.valueOf(networkResource.getNeutronNetworkType()); @@ -1233,7 +1234,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { Holder <NetworkStatus> status, Holder <List <Integer>> vlans, Holder <Map <String, String>> subnetIdMap) throws NetworkException { - queryNetwork (cloudSiteId, + queryNetworkInfo(cloudSiteId, tenantId, networkNameOrId, msoRequest, @@ -1242,7 +1243,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { neutronNetworkId, status, vlans, - null, subnetIdMap); } @@ -1257,7 +1257,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { Holder <NetworkStatus> status, Holder <List <String>> routeTargets, Holder <Map <String, String>> subnetIdMap) throws NetworkException { - queryNetwork (cloudSiteId, + queryNetworkInfo(cloudSiteId, tenantId, networkNameOrId, msoRequest, @@ -1266,18 +1266,17 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { neutronNetworkId, status, null, - routeTargets, subnetIdMap); } /** - * This is the queryNetwork method. It returns the existence and status of + * This is the queryNetworkInfo method. It returns the existence and status of * the specified network, along with its Neutron UUID and list of VLANs. * This method attempts to find the network using both Heat and Neutron. * Heat stacks are first searched based on the provided network name/id. * If none is found, the Neutron is directly queried. */ - private void queryNetwork (String cloudSiteId, + private void queryNetworkInfo(String cloudSiteId, String tenantId, String networkNameOrId, MsoRequest msoRequest, @@ -1286,7 +1285,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { Holder <String> neutronNetworkId, Holder <NetworkStatus> status, Holder <List <Integer>> vlans, - Holder <List <String>> routeTargets, Holder <Map <String, String>> subnetIdMap) throws NetworkException { MsoLogger.setLogContext (msoRequest); MsoLogger.setServiceName ("QueryNetwork"); @@ -1309,9 +1307,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { throw new NetworkException (error, MsoExceptionCategory.USERDATA); } - cloudConfig = cloudConfigFactory.getCloudConfig (); - CloudSite cloudSite = cloudConfig.getCloudSite (cloudSiteId); - if (cloudSite == null) + cloudConfig = cloudConfigFactory.getCloudConfig(); + Optional<CloudSite> cloudSiteOpt = cloudConfig.getCloudSite(cloudSiteId); + if (!cloudSiteOpt.isPresent()) { String error = "Configuration Error. Stack " + networkNameOrId + " in " + cloudSiteId @@ -1414,7 +1412,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { status.value = NetworkStatus.NOTFOUND; neutronNetworkId.value = null; if (vlans != null) - vlans.value = new ArrayList <Integer> (); + vlans.value = new ArrayList<>(); LOGGER.debug ("Network " + networkNameOrId + " not found"); } diff --git a/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java b/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java index 29f5630586..58169f6f92 100644 --- a/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java +++ b/adapters/mso-tenant-adapter/src/main/java/org/openecomp/mso/adapters/tenant/MsoTenantAdapterImpl.java @@ -28,6 +28,7 @@ import javax.jws.WebService; import javax.xml.ws.Holder; import javax.xml.ws.WebServiceContext; +import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; import org.openecomp.mso.properties.MsoPropertiesFactory; import org.openecomp.mso.adapters.tenant.exceptions.TenantAlreadyExists; import org.openecomp.mso.adapters.tenant.exceptions.TenantException; @@ -84,7 +85,7 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter { Boolean backout, MsoRequest msoRequest, Holder <String> tenantId, - Holder <TenantRollback> rollback) throws TenantException, TenantAlreadyExists { + Holder <TenantRollback> rollback) throws TenantException { MsoLogger.setLogContext (msoRequest); MsoLogger.setServiceName (CREATE_TENANT); @@ -99,15 +100,16 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter { TenantRollback tenantRollback = new TenantRollback (); tenantRollback.setCloudId (cloudSiteId); tenantRollback.setMsoRequest (msoRequest); - - MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId); + MsoTenantUtils tUtils; MsoTenant newTenant = null; String newTenantId; long queryTenantStartTime = System.currentTimeMillis (); try { + tUtils = tFactory.getTenantUtils (cloudSiteId); newTenant = tUtils.queryTenantByName (tenantName, cloudSiteId); logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null); + } catch (MsoException me) { logger.recordMetricEvent (queryTenantStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with Open Stack", OPENSTACK, QUERY_TENANT, null); String error = "Create Tenant " + tenantName + ": " + me; @@ -166,11 +168,11 @@ public class MsoTenantAdapterImpl implements MsoTenantAdapter { // Will capture execution time for metrics long startTime = System.currentTimeMillis (); - MsoTenantUtils tUtils = tFactory.getTenantUtils (cloudSiteId); - + MsoTenantUtils tUtils = null; MsoTenant qTenant = null; long subStartTime = System.currentTimeMillis (); try { + tUtils = tFactory.getTenantUtils (cloudSiteId); qTenant = tUtils.queryTenant (tenantNameOrId, cloudSiteId); logger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from Open Stack", OPENSTACK, QUERY_TENANT, null); if (qTenant == null) { diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java index 2a5c305926..b4827d0f45 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/model/NsParameters.java @@ -35,7 +35,7 @@ public class NsParameters { private List<LocationConstraint> locationConstraints; - private Map<String, Object> additionalParamForNs = new HashMap<String,Object>(); + private Map<String, Object> additionalParamForNs = new HashMap<>(); /** * @return Returns the locationConstraints. */ diff --git a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java index 7690d80609..afee1bbfaa 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/openecomp/mso/adapters/vfc/util/RestfulUtil.java @@ -63,20 +63,27 @@ public class RestfulUtil { private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger(); private static final int DEFAULT_TIME_OUT = 60000; + + private static final String ONAP_IP = "ONAP_IP"; + + private static final String DEFAULT_MSB_IP = "127.0.0.1"; + + private static final String DEFAULT_MSB_PORT = "80"; private static final MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory(); public static String getMsbHost() { - String msbIp = "10.229.32.131"; - String msbPort = "8090"; + String msbPort = DEFAULT_MSB_PORT; + // MSB_IP will be set as ONAP_IP environment parameter in install flow. + String msbIp = System.getenv().get(ONAP_IP); try { - msbIp = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-ip", - "10.229.32.131"); - msbPort = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-port", "8099"); - + // if ONAP IP is not set. get it from config file. + if(null == msbIp || msbIp.isEmpty()) { + msbIp = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-ip", DEFAULT_MSB_IP); + msbPort = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-port", DEFAULT_MSB_PORT); + } } catch(MsoPropertiesException e) { - LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, - "Get msb properties failed"); + LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, "Get msb properties failed"); e.printStackTrace(); } return "http://" + msbIp + ":" + msbPort; diff --git a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java index fb86b8c520..7fe09be2b6 100644 --- a/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-vnf-adapter/src/main/java/org/openecomp/mso/adapters/vnf/MsoVnfAdapterImpl.java @@ -21,7 +21,7 @@ package org.openecomp.mso.adapters.vnf; - +import java.util.Optional; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.ObjectMapper; @@ -953,15 +953,14 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (minVersionVnf != null && maxVersionVnf != null) { MavenLikeVersioning aicV = new MavenLikeVersioning(); - CloudSite cloudSite = null; if (this.cloudConfig == null) { this.cloudConfig = this.cloudConfigFactory.getCloudConfig(); } // double check if (this.cloudConfig != null) { - cloudSite = this.cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite != null) { - aicV.setVersion(cloudSite.getAic_version()); + Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); + if (cloudSiteOpt.isPresent()) { + aicV.setVersion(cloudSiteOpt.get().getAic_version()); // Add code to handle unexpected values in here boolean moreThanMin = true; boolean equalToMin = true; @@ -980,10 +979,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (!doNotTest) { if ((moreThanMin || equalToMin) // aic >= min && (equalToMax || !(moreThanMax))) { //aic <= max - LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version()); + LOGGER.debug("VNF Resource " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version()); } else { // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version(); + String error = "VNF Resource type: " + vnfResource.getModelName() + ", ModelUuid=" + vnfResource.getModelUuid() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version(); LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion"); LOGGER.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); @@ -1200,9 +1199,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (heatEnvironmentString != null && heatEnvironmentString.contains ("parameters:")) { //LOGGER.debug ("Have an Environment argument with a parameters: section - will bypass checking for valid params - but will still check for aliases"); LOGGER.debug("Enhanced environment checking enabled - 1604"); - StringBuilder sb = new StringBuilder(heatEnvironmentString); - //LOGGER.debug("About to create MHEE with " + sb); - mhee = new MsoHeatEnvironmentEntry(sb); + mhee = MsoHeatEnvironmentEntry.create(heatEnvironmentString); StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n"); for (HeatTemplateParam parm : heatTemplate.getParameters()) { sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); @@ -1211,7 +1208,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { sb2.append("Environment says it's not valid! " + mhee.getErrorString()); } else { sb2.append("\nEnvironment:"); - sb2.append(mhee.toFullString()); + sb2.append(mhee); } LOGGER.debug(sb2.toString()); } else { @@ -1292,7 +1289,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // and it causes problems with json that has arrays String newEnvironmentString = null; if (mhee != null) { - newEnvironmentString = mhee.getRawEntry().toString(); + newEnvironmentString = mhee.getRawEntry(); } // "Fix" the template if it has CR/LF (getting this from Oracle) @@ -1703,26 +1700,25 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (minVersionVnf != null && maxVersionVnf != null) { MavenLikeVersioning aicV = new MavenLikeVersioning(); - CloudSite cloudSite = null; //String aicVersion = ""; if (this.cloudConfig == null) { this.cloudConfig = this.cloudConfigFactory.getCloudConfig(); } // double check if (this.cloudConfig != null) { - cloudSite = this.cloudConfig.getCloudSite(cloudSiteId); - if (cloudSite != null) { - aicV.setVersion(cloudSite.getAic_version()); + Optional<CloudSite> cloudSiteOpt = this.cloudConfig.getCloudSite(cloudSiteId); + if (cloudSiteOpt.isPresent()) { + aicV.setVersion(cloudSiteOpt.get().getAic_version()); if ((aicV.isMoreRecentThan(minVersionVnf) || aicV.isTheSameVersion(minVersionVnf)) // aic >= min && (aicV.isTheSameVersion(maxVersionVnf) || !(aicV.isMoreRecentThan(maxVersionVnf)))) { //aic <= max - LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version()); + LOGGER.debug("VNF Resource " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version()); } else { // ERROR - String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSite.getId() + " with AIC_Version:" + cloudSite.getAic_version(); + String error = "VNF Resource type: " + vnfResource.getModelName() + " VersionMin=" + minVersionVnf + " VersionMax:" + maxVersionVnf + " NOT supported on Cloud: " + cloudSiteOpt.get().getId() + " with AIC_Version:" + cloudSiteOpt.get().getAic_version(); LOGGER.error(MessageEnum.RA_CONFIG_EXC, error, "OpenStack", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - setVersion"); LOGGER.debug(error); throw new VnfException(error, MsoExceptionCategory.USERDATA); - } + } } // let this error out downstream to avoid introducing uncertainty at this stage } else { LOGGER.debug("cloudConfig is NULL - cannot check cloud site version"); @@ -1904,10 +1900,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { MsoHeatEnvironmentEntry mhee = null; if (heatEnvironmentString != null && heatEnvironmentString.toLowerCase ().contains ("parameters:")) { LOGGER.debug("Enhanced environment checking enabled - 1604"); - haveEnvironmentParameters = true; - StringBuilder sb = new StringBuilder(heatEnvironmentString); - //LOGGER.debug("About to create MHEE with " + sb); - mhee = new MsoHeatEnvironmentEntry(sb); + mhee = MsoHeatEnvironmentEntry.create(heatEnvironmentString); StringBuilder sb2 = new StringBuilder("\nHeat Template Parameters:\n"); for (HeatTemplateParam parm : heatTemplate.getParameters()) { sb2.append("\t" + parm.getParamName() + ", required=" + parm.isRequired()); @@ -1916,7 +1909,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { sb2.append("Environment says it's not valid! " + mhee.getErrorString()); } else { sb2.append("\nEnvironment:"); - sb2.append(mhee.toFullString()); + sb2.append(mhee); } LOGGER.debug(sb2.toString()); } else { @@ -2041,7 +2034,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Just submit the envt entry as received from the database String newEnvironmentString = null; if (mhee != null) { - newEnvironmentString = mhee.getRawEntry().toString(); + newEnvironmentString = mhee.getRawEntry(); } // Remove any extraneous parameters (don't throw an error) diff --git a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterAsyncImplTest.java b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterAsyncImplTest.java index b680170abe..a045b00699 100644 --- a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterAsyncImplTest.java +++ b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterAsyncImplTest.java @@ -22,18 +22,10 @@ package org.openecomp.mso.adapters.vnf.test; import java.util.HashMap;
import java.util.Map;
-
import org.junit.Test;
import org.openecomp.mso.adapters.vnf.MsoVnfAdapterAsyncImpl;
import org.openecomp.mso.entity.MsoRequest;
-import org.openecomp.mso.openstack.beans.HeatStatus;
-import org.openecomp.mso.openstack.beans.StackInfo;
import org.openecomp.mso.openstack.beans.VnfRollback;
-import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.utils.MsoHeatUtils;
-
-import mockit.Mock;
-import mockit.MockUp;
public class MsoVnfAdapterAsyncImplTest {
@@ -45,15 +37,6 @@ public class MsoVnfAdapterAsyncImplTest { @Test
public void createVNFTest() {
- new MockUp<MsoHeatUtils>() {
- @Mock
- public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
- StackInfo info = new StackInfo();
- info.setStatus(HeatStatus.CREATED);
- return info;
- }
- };
-
MsoVnfAdapterAsyncImpl instance = new MsoVnfAdapterAsyncImpl();
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
diff --git a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterImplTest.java b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterImplTest.java index 77879089e9..6f01954db3 100644 --- a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterImplTest.java +++ b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/MsoVnfAdapterImplTest.java @@ -22,24 +22,11 @@ package org.openecomp.mso.adapters.vnf.test; import java.util.HashMap;
import java.util.Map;
-
import javax.xml.ws.Holder;
-
import org.junit.Test;
import org.openecomp.mso.adapters.vnf.MsoVnfAdapterImpl;
-import org.openecomp.mso.db.catalog.CatalogDatabase;
-import org.openecomp.mso.db.catalog.beans.VfModule;
-import org.openecomp.mso.db.catalog.beans.VfModuleCustomization;
-import org.openecomp.mso.db.catalog.beans.VnfResource;
import org.openecomp.mso.entity.MsoRequest;
-import org.openecomp.mso.openstack.beans.HeatStatus;
-import org.openecomp.mso.openstack.beans.StackInfo;
import org.openecomp.mso.openstack.beans.VnfRollback;
-import org.openecomp.mso.openstack.exceptions.MsoException;
-import org.openecomp.mso.openstack.utils.MsoHeatUtils;
-
-import mockit.Mock;
-import mockit.MockUp;
public class MsoVnfAdapterImplTest {
@@ -51,16 +38,6 @@ public class MsoVnfAdapterImplTest { @Test
public void createVnfTest() {
-
- new MockUp<MsoHeatUtils>() {
- @Mock
- public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
- StackInfo info = new StackInfo();
- info.setStatus(HeatStatus.CREATED);
- return info;
- }
- };
-
MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
@@ -80,37 +57,6 @@ public class MsoVnfAdapterImplTest { @Test
public void updateVnfTest() {
-
- new MockUp<MsoHeatUtils>() {
- @Mock
- public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException {
- StackInfo info = new StackInfo();
- info.setStatus(HeatStatus.CREATED);
- return info;
- }
- };
-
- new MockUp<CatalogDatabase>() {
- @Mock
- public VfModuleCustomization getVfModuleCustomizationByModelCustomizationId(String modelCustomizationUuid) {
- VfModuleCustomization vfcModule = new VfModuleCustomization();
- VfModule vfm = new VfModule();
- vfm.setVnfResourceModelUUId("88a6ca3ee0394ade9403f075db23167e");
- vfcModule.setVfModule(vfm);
- return vfcModule;
- }
- };
-
- new MockUp<CatalogDatabase>() {
- @Mock
- public VnfResource getVnfResourceByModelUuid(String modelUuid) {
- VnfResource vnfResource = new VnfResource();
- vnfResource.setAicVersionMin("1");
- vnfResource.setAicVersionMax("2");
- return vnfResource;
- }
- };
-
MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
@@ -130,17 +76,6 @@ public class MsoVnfAdapterImplTest { @Test
public void deleteVnfTest() {
- new MockUp<MsoHeatUtils>() {
- @Mock
- public Map<String, Object> queryStackForOutputs(String cloudSiteId, String tenantId, String stackName)
- throws MsoException {
-
- Map<String, Object> outputs = new HashMap<>();
- outputs.put("Key1", "value1");
- return outputs;
- }
- };
-
MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl();
MsoRequest msoRequest = new MsoRequest();
msoRequest.setRequestId("12345");
diff --git a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/QueryTest.java b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/QueryTest.java index 315db2eb83..f6e79e12a0 100644 --- a/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/QueryTest.java +++ b/adapters/mso-vnf-adapter/src/test/java/org/openecomp/mso/adapters/vnf/test/QueryTest.java @@ -21,26 +21,23 @@ package org.openecomp.mso.adapters.vnf.test; -import java.util.Map; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import java.util.Map; import javax.xml.ws.Holder; - import mockit.Mock; import mockit.MockUp; import org.junit.Test; import org.openecomp.mso.adapters.vnf.MsoVnfAdapter; import org.openecomp.mso.adapters.vnf.MsoVnfAdapterImpl; +import org.openecomp.mso.adapters.vnf.exceptions.VnfException; import org.openecomp.mso.openstack.beans.HeatStatus; import org.openecomp.mso.openstack.beans.StackInfo; import org.openecomp.mso.openstack.beans.VnfStatus; -import org.openecomp.mso.adapters.vnf.exceptions.VnfException; -import org.openecomp.mso.openstack.exceptions.MsoCloudSiteNotFound; import org.openecomp.mso.openstack.exceptions.MsoException; import org.openecomp.mso.openstack.utils.MsoHeatUtils; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class QueryTest { @Test @@ -49,8 +46,7 @@ public class QueryTest { new MockUp<MsoHeatUtils>() { @Mock public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException { - StackInfo info = new StackInfo(); - info.setStatus(HeatStatus.CREATED); + StackInfo info = new StackInfo("stackName", HeatStatus.CREATED); return info; } }; @@ -77,8 +73,7 @@ public class QueryTest { new MockUp<MsoHeatUtils>() { @Mock public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException { - StackInfo info = new StackInfo(); - info.setStatus(HeatStatus.NOTFOUND); + StackInfo info = new StackInfo("stackName", HeatStatus.NOTFOUND); return info; } }; @@ -102,13 +97,6 @@ public class QueryTest { @Test(expected = VnfException.class) public void testQueryVnfWithException() throws VnfException { { - new MockUp<MsoHeatUtils>() { - @Mock - public StackInfo queryStack(String cloudSiteId, String tenantId, String stackName) throws MsoException { - throw new MsoCloudSiteNotFound(cloudSiteId); - } - }; - MsoVnfAdapter vnfAdapter = new MsoVnfAdapterImpl(); String cloudId = "MT"; String tenantId = "MSO_Test"; diff --git a/adapters/pom.xml b/adapters/pom.xml index 80244a62cc..97c2506bcc 100644 --- a/adapters/pom.xml +++ b/adapters/pom.xml @@ -28,7 +28,6 @@ <module>mso-workflow-message-adapter</module> <module>mso-vfc-adapter</module> </modules> - <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> @@ -38,5 +37,11 @@ <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>3.9.0</version> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DecomposeService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DecomposeService.groovy index 06cc284620..2645ea3c02 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DecomposeService.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/DecomposeService.groovy @@ -17,7 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.openecomp.mso.bpmn.common.scripts; +package org.openecomp.mso.bpmn.common.scripts + +import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil; import static org.apache.commons.lang3.StringUtils.*; @@ -96,12 +98,12 @@ public class DecomposeService extends AbstractServiceTaskProcessor { // check for input String serviceModelInvariantId = execution.getVariable("DDS_serviceModelInvariantId") String modelVersion = execution.getVariable("DDS_modelVersion") - + utils.log("DEBUG", "serviceModelInvariantId: " + serviceModelInvariantId, isDebugEnabled) - utils.log("DEBUG", "modelVersion: " + modelVersion, isDebugEnabled) - + utils.log("DEBUG", "modelVersion: " + modelVersion, isDebugEnabled) + JSONObject catalogDbResponse = null - + if (modelVersion != null && modelVersion.length() > 0) catalogDbResponse = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidAndServiceModelVersion(execution, serviceModelInvariantId, modelVersion, "v2") else @@ -140,7 +142,7 @@ public class DecomposeService extends AbstractServiceTaskProcessor { utils.log("DEBUG", "getting service decomposition", isDebugEnabled) String catalogDbResponse = execution.getVariable("DDS_catalogDbResponse") - ServiceDecomposition serviceDecomposition = new ServiceDecomposition(catalogDbResponse, serviceInstanceId) + ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.jsonToServiceDecomposition(catalogDbResponse, serviceInstanceId) execution.setVariable("serviceDecomposition", serviceDecomposition) execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString()) diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy index 14f9135826..cfc5171dca 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/openecomp/mso/bpmn/common/scripts/GenericGetService.groovy @@ -20,14 +20,14 @@ package org.openecomp.mso.bpmn.common.scripts
-import static org.apache.commons.lang3.StringUtils.*
-
-import org.apache.commons.lang3.*
+import org.apache.commons.lang3.StringEscapeUtils
import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.runtime.Execution
import org.openecomp.mso.rest.APIResponse
import org.springframework.web.util.UriUtils
+import static org.apache.commons.lang3.StringUtils.isBlank
+
/**
* This class supports the GenericGetService Sub Flow.
@@ -301,7 +301,9 @@ class GenericGetService extends AbstractServiceTaskProcessor{ if(responseCode == 200){
utils.log("DEBUG", " Query for Service Instance Url Received a Good Response Code", isDebugEnabled)
execution.setVariable("GENGS_SuccessIndicator", true)
- if(utils.nodeExists(aaiResponse, "result-data")){
+ String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
+ boolean nodeExists = isBlank(globalCustomerId) ? utils.nodeExists(aaiResponse, "result-data") : hasCustomerServiceInstance(aaiResponse, globalCustomerId)
+ if(nodeExists){
utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled)
execution.setVariable("GENGS_FoundIndicator", true)
String resourceLink = utils.getNodeText1(aaiResponse, "resource-link")
@@ -439,4 +441,30 @@ class GenericGetService extends AbstractServiceTaskProcessor{ utils.log("DEBUG", " *** COMPLETED GenericGetService GetServiceObject Process*** ", isDebugEnabled)
}
+ /**
+ * An utility method which check whether a service(by name) is already present within a globalCustomerId or not.
+ * @param jsonResponse raw response received from AAI by searching ServiceInstance by Name.
+ * @param globalCustomerId
+ * @return {@code true} if globalCustomerId is found at 6th position within "resource-link", {@code false} in any other cases.
+ */
+ public boolean hasCustomerServiceInstance(String aaiResponse, final String globalCustomerId) {
+ if (isBlank(aaiResponse)) {
+ return false
+ }
+ aaiResponse = utils.removeXmlNamespaces(aaiResponse)
+ ArrayList<String> linksArray = utils.getMultNodeObjects(aaiResponse, "resource-link")
+ if (linksArray == null || linksArray.size() == 0) {
+ return false
+ }
+ for (String resourceLink : linksArray) {
+ int custStart = resourceLink.indexOf("customer/")
+ int custEnd = resourceLink.indexOf("/service-subscriptions/")
+ String receivedCustomerId = resourceLink.substring(custStart + 9, custEnd)
+ if (globalCustomerId.equals(receivedCustomerId)) {
+ return true
+ }
+ }
+ return false
+ }
+
}
\ No newline at end of file diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java index ca815cf904..214be060e3 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClient.java @@ -32,13 +32,9 @@ import com.fasterxml.jackson.databind.JsonMappingException; public interface AAIRestClient { - Pservers getPhysicalServers(String hostName, String uuid); - - List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException; - - void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws Exception; - - void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws Exception; - - GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception; +Pservers getPhysicalServers(String hostName, String uuid); +List<Pserver> getPhysicalServerByVnfId(String vnfId, String transactionLoggingUuid) throws UnsupportedEncodingException, JsonParseException, JsonMappingException, IOException; +void updateMaintenceFlag(String vnfId,boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException; +void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; +GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException , IOException; } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java index ae8638f0b7..af1eddf491 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/aai/AAIRestClientImpl.java @@ -139,14 +139,14 @@ public class AAIRestClientImpl implements AAIRestClient { } @Override - public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws Exception { + public void updateMaintenceFlag(String vnfName, boolean inMaint, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { GenericVnfs genericVnfs = webTarget.register(AAIResourcesObjectMapperProvider.class).path(ENDPOINT_GET_ALL_VNFS) .queryParam("vnf-name", vnfName).request().header("X-FromAppId", "MSO") .header("X-TransactionId", transactionLoggingUuid).header("Content-Type", "application/json") .accept(MediaType.APPLICATION_JSON_TYPE).get().readEntity(GenericVnfs.class); if (genericVnfs.getGenericVnf().size() > 1) - throw new Exception("Multiple Generic Vnfs Returned"); + throw new IndexOutOfBoundsException ("Multiple Generic Vnfs Returned"); GenericVnf genericVnf = genericVnfs.getGenericVnf().get(0); updateMaintenceFlagVnfId(genericVnf.getVnfId(), inMaint, transactionLoggingUuid); @@ -154,7 +154,7 @@ public class AAIRestClientImpl implements AAIRestClient { @Override public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) - throws Exception { + throws JsonParseException, JsonMappingException, IOException { GenericVnf genericVnf = new GenericVnf(); genericVnf.setInMaint(inMaint); webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() @@ -165,7 +165,7 @@ public class AAIRestClientImpl implements AAIRestClient { } @Override - public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception { + public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws JsonParseException, JsonMappingException, IOException { return webTarget.register(AAIResourcesObjectMapperProvider.class).path(GENERIC_VNF_PATH + "/" + vnfId).request() .header("X-FromAppId", "MSO").header("X-TransactionId", transactionLoggingUuid) .header("Content-Type", "application/json").accept(MediaType.APPLICATION_JSON_TYPE).get() diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java index 26c1c4acd2..f66034f5e9 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/openecomp/mso/client/appc/ApplicationControllerClient.java @@ -76,7 +76,7 @@ public class ApplicationControllerClient { private LifeCycleManagerStateful client; public Status runCommand(Action action, ActionIdentifiers identifier, Flags flags, Payload payload, - String requestID) throws Exception { + String requestID) throws IllegalAccessException,NoSuchMethodException,AppcClientException,JsonProcessingException,InvocationTargetException { Object requestObject = createRequest(action, identifier, flags, payload, requestID); client = getAppCClient(); Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, false); @@ -118,7 +118,7 @@ public class ApplicationControllerClient { } public Object createRequest(Action action, ActionIdentifiers identifier, Flags flags, Payload payload, - String requestId) throws Exception { + String requestId) throws IllegalAccessException,NoSuchMethodException,InvocationTargetException { Object requestObject = appCSupport.getInput(action.name()); try { org.openecomp.appc.client.lcm.model.CommonHeader commonHeader = buildCommonHeader(requestId); @@ -129,7 +129,7 @@ public class ApplicationControllerClient { .invoke(requestObject, identifier); } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { LOGGER.debug("Exception:", e); - throw new Exception("Error Building AppC Request: " + e.getMessage()); + throw new IllegalAccessException("Error Building AppC Request: " + e.getMessage()); } return requestObject; } diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java index b1172837cf..82cceb0b70 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/GenericGetServiceTest.java @@ -482,6 +482,61 @@ public class GenericGetServiceTest extends WorkflowTest { assertEquals(expectedWorkflowException, workflowException);
}
+ @Test
+ @Deployment(resources = {"subprocess/GenericGetService.bpmn"})
+ public void testGenericGetService_success_serviceInstance_byNameServicePresent() throws Exception{
+
+ MockNodeQueryServiceInstanceByName("1604-MVM-26", "GenericFlows/getSIUrlByNameMultiCustomer.xml");
+ MockGetServiceInstance("XyCorporation", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml");
+
+ Map<String, String> variables = new HashMap<String, String>();
+ setVariablesInstance(variables, null, "1604-MVM-26", "XyCorporation", null);
+
+ WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables);
+ waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID());
+
+ String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator");
+ String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator");
+ String resourceLink = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_resourceLink");
+ String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse");
+ String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException");
+ String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode");
+
+ assertEquals("true", successIndicator);
+ assertEquals("true", found);
+ assertNotNull(resourceLink);
+ assertNotNull(response);
+ assertEquals("200", siUrlResponseCode);
+ assertEquals(null, workflowException);
+ }
+
+ @Test
+ @Deployment(resources = {"subprocess/GenericGetService.bpmn"})
+ public void testGenericGetService_success_serviceInstance_byNameServiceNotPresent() throws Exception{
+
+ MockNodeQueryServiceInstanceByName("1604-MVM-26", "GenericFlows/getSIUrlByNameMultiCustomer.xml");
+ MockGetServiceInstance("CorporationNotPresent", "123456789", "MIS%252F1604%252F0026%252FSW_INTERNET", "GenericFlows/getServiceInstance.xml");
+
+ Map<String, String> variables = new HashMap<String, String>();
+ setVariablesInstance(variables, null, "1604-MVM-26", "CorporationNotPresent", null);
+
+ WorkflowResponse workflowResponse = executeWorkFlow(processEngineRule, "GenericGetService", variables);
+ waitForWorkflowToFinish(processEngineRule, workflowResponse.getProcessInstanceID());
+
+ String successIndicator = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_SuccessIndicator");
+ String found = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_FoundIndicator");
+ String resourceLink = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_resourceLink");
+ String response = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowResponse");
+ String workflowException = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "WorkflowException");
+ String siUrlResponseCode = BPMNUtil.getVariable(processEngineRule, "GenericGetService", "GENGS_obtainSIUrlResponseCode");
+
+ assertEquals("true", successIndicator);
+ assertEquals("false", found);
+ assertEquals(null, resourceLink);
+ assertEquals(" ", response);
+ assertEquals("200", siUrlResponseCode);
+ assertEquals(null, workflowException);
+ }
private void setVariablesInstance(Map<String, String> variables, String siId, String siName, String globalCustId, String serviceType) {
variables.put("isDebugLogEnabled", "true");
diff --git a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java index 15dc4f4609..ce8eb7afec 100644 --- a/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java +++ b/bpmn/MSOCommonBPMN/src/test/java/org/openecomp/mso/bpmn/common/WorkflowTest.java @@ -61,7 +61,6 @@ import org.custommonkey.xmlunit.DetailedDiff; import org.custommonkey.xmlunit.XMLUnit;
import org.jboss.resteasy.spi.AsynchronousResponse;
import org.json.JSONArray;
-import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.openecomp.mso.bpmn.common.adapter.sdnc.CallbackHeader;
@@ -78,7 +77,7 @@ import org.openecomp.mso.bpmn.common.workflow.service.VnfAdapterNotifyServiceImp import org.openecomp.mso.bpmn.common.workflow.service.WorkflowAsyncResource;
import org.openecomp.mso.bpmn.common.workflow.service.WorkflowMessageResource;
import org.openecomp.mso.bpmn.common.workflow.service.WorkflowResponse;
-import org.openecomp.mso.bpmn.core.CamundaDBSetup;
+import org.openecomp.mso.bpmn.core.utils.CamundaDBSetup;
import org.openecomp.mso.bpmn.core.PropertyConfigurationSetup;
import org.openecomp.mso.bpmn.core.domain.Resource;
import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
diff --git a/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml new file mode 100644 index 0000000000..fce47fcd0d --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/test/resources/__files/GenericFlows/getSIUrlByNameMultiCustomer.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="UTF-8"?> +<search-results xmlns="http://org.openecomp.aai.inventory/v11"> + <result-data> + <resource-type>service-instance</resource-type> + <resource-link>/aai/v11/business/customers/customer/AbcBank/service-subscriptions/service-subscription/ABC-ST/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET</resource-link> + </result-data> + <result-data> + <resource-type>service-instance</resource-type> + <resource-link>/aai/v11/business/customers/customer/XyCorporation/service-subscriptions/service-subscription/XY-ST/service-instances/service-instance/MIS%252F1604%252F0026%252FSW_INTERNET</resource-link> + </result-data> +</search-results>
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/pom.xml b/bpmn/MSOCoreBPMN/pom.xml index 6884c1e33b..267f175533 100644 --- a/bpmn/MSOCoreBPMN/pom.xml +++ b/bpmn/MSOCoreBPMN/pom.xml @@ -158,9 +158,10 @@ <version>20160212</version> </dependency> <dependency> - <groupId>xmlunit</groupId> - <artifactId>xmlunit</artifactId> - <version>1.6</version> + <groupId>org.xmlunit</groupId> + <artifactId>xmlunit-core</artifactId> + <version>2.5.1</version> + <scope>test</scope> </dependency> <dependency> <groupId>org.openecomp.so</groupId> diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/RollbackData.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/RollbackData.java index 66edaaae3c..64068d2b90 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/RollbackData.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/RollbackData.java @@ -23,6 +23,7 @@ package org.openecomp.mso.bpmn.core; import java.io.Serializable; import java.util.HashMap; import java.util.Map; +import java.util.stream.Collectors; /** * An object that stores data for rollbacks. Data is organized by type. A @@ -30,79 +31,72 @@ import java.util.Map; * in the same object for separate rollback operations. */ public class RollbackData implements Serializable { - private static final long serialVersionUID = 1L; - private Map<String, Map<String, Serializable>> dictionary = - new HashMap<String, Map<String, Serializable>>(); - - /** - * Returns true if the specified type is stored in this object. - * @param type the data type - */ - public boolean hasType(String type) { - return dictionary.containsKey(type); - } + private static final long serialVersionUID = 1L; - /** - * Stores a single item. - * @param type the data type - * @param key the key - * @param value the value - */ - public void put(String type, String key, String value) { - Map<String, Serializable> mapForType = dictionary.get(type); + private Map<String, Map<String, Serializable>> dictionary = + new HashMap<String, Map<String, Serializable>>(); - if (mapForType == null) { - mapForType = new HashMap<String, Serializable>(); - dictionary.put(type, mapForType); - } + /** + * Returns true if the specified type is stored in this object. + * + * @param type the data type + */ + public boolean hasType(String type) { + return dictionary.containsKey(type); + } - mapForType.put(key, value); - } + /** + * Stores a single item. + * + * @param type the data type + * @param key the key + * @param value the value + */ + public void put(String type, String key, String value) { + Map<String, Serializable> mapForType = dictionary.get(type); - /** - * Gets a single item. - * @param type the data type - * @param key the key - * @return the item or null if there is no item for the specified type and key - */ - public Serializable get(String type, String key) { - Map<String, Serializable> mapForType = dictionary.get(type); + if (mapForType == null) { + mapForType = new HashMap<String, Serializable>(); + dictionary.put(type, mapForType); + } - if (mapForType == null) { - return null; - } + mapForType.put(key, value); + } - return mapForType.get(key); - } + /** + * Gets a single item. + * + * @param type the data type + * @param key the key + * @return the item or null if there is no item for the specified type and key + */ + public Serializable get(String type, String key) { + Map<String, Serializable> mapForType = dictionary.get(type); - /** - * Gets a map containing all items associated with the specified data type. - * @param type the data type - * @return a map, or null if there are no items associated with the specified - * data type - */ - public Map<String, Serializable> get(String type) { - return dictionary.get(type); - } + if (mapForType == null) { + return null; + } - /** - * Returns a string representation of this object. - */ - public String toString() { - StringBuilder out = new StringBuilder(); - out.append(getClass().getSimpleName()); - out.append('['); - boolean hasOne = false; - for (String type : dictionary.keySet()) { - if (hasOne) { - out.append(','); - } - out.append(type); - out.append(dictionary.get(type)); - hasOne = true; - } - out.append(']'); - return out.toString(); - } + return mapForType.get(key); + } + + /** + * Gets a map containing all items associated with the specified data type. + * + * @param type the data type + * @return a map, or null if there are no items associated with the specified data type + */ + public Map<String, Serializable> get(String type) { + return dictionary.get(type); + } + + /** + * Returns a string representation of this object. + */ + @Override + public String toString() { + return dictionary.entrySet().stream().map(entry -> entry.getKey() + entry.getValue()) + .collect(Collectors.joining(",", "[", "]")); + } } diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/JsonWrapper.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/JsonWrapper.java index ce66e06089..4d895f3279 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/JsonWrapper.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/JsonWrapper.java @@ -142,6 +142,7 @@ public abstract class JsonWrapper implements Serializable { /**
* Returns a string representation of this object.
*/
+ @Override
public String toString() {
return this.toJsonString();
}
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/ServiceDecomposition.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/ServiceDecomposition.java index 1e68c84878..0e985cc8f1 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/ServiceDecomposition.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/domain/ServiceDecomposition.java @@ -31,9 +31,8 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
-import org.json.JSONObject;
import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil;
-
+import org.openecomp.mso.bpmn.core.json.JsonDecomposingException;
/**
@@ -50,7 +49,6 @@ import org.openecomp.mso.bpmn.core.json.DecomposeJsonUtil; public class ServiceDecomposition extends JsonWrapper implements Serializable {
private static final long serialVersionUID = 1L;
- DecomposeJsonUtil jsonUtils = new DecomposeJsonUtil();
@JsonProperty("modelInfo")
private ModelInfo modelInfo;
@@ -67,48 +65,6 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { private List <AllottedResource> allottedResources;
public ServiceDecomposition () {
- super();
- }
-
- public ServiceDecomposition (String catalogRestOutput) {
-
- ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.JsonToServiceDecomposition(catalogRestOutput);
- this.modelInfo = serviceDecomposition.getModelInfo();
- this.vnfResources = serviceDecomposition.getServiceVnfs();
- this.allottedResources = serviceDecomposition.getServiceAllottedResources();
- this.networkResources = serviceDecomposition.getServiceNetworks();
- this.serviceRole = serviceDecomposition.getServiceRole();
- this.serviceType = serviceDecomposition.getServiceType();
- }
-
- /**
- * Constructor taking Catalog DB Adapter REST output (serviceResources model) + service Instance ID
- * @param catalogRestOutput
- * @param serviceInstanceId
- */
- public ServiceDecomposition (String catalogRestOutput, String serviceInstanceId) {
-
- ServiceDecomposition serviceDecomposition = DecomposeJsonUtil.JsonToServiceDecomposition(catalogRestOutput);
- this.modelInfo = serviceDecomposition.getModelInfo();
- this.vnfResources = serviceDecomposition.getServiceVnfs();
- this.allottedResources = serviceDecomposition.getServiceAllottedResources();
- this.networkResources = serviceDecomposition.getServiceNetworks();
-
- this.serviceRole = serviceDecomposition.getServiceRole();
- this.serviceType = serviceDecomposition.getServiceType();
-
- this.serviceInstance = new ServiceInstance();
- this.serviceInstance.setInstanceId(serviceInstanceId);
- }
-
- /**
- * Constructor taking a Service Decomposition JSON serialization
- * @param catalogRestOutput
- * @param serviceInstanceId
- */
- public ServiceDecomposition (JSONObject jsonServiceDecomposition, String serviceInstanceId) {
- //TODO provide constructor implementation
-
}
//*****
@@ -278,7 +234,7 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { * Add resource to the list
* Given a ResourceDecomposition (subclass) object, add it to the Service Decomposition (in the appropriate category, e.g. as a VNF, Network, or Allotted Resource).
* As dependencies are not currently supported, add it to the end of any ordered lists.
- * @param Resource
+ * @param resource
*/
public void addResource(Resource resource) {
//create resource based upon type
@@ -299,36 +255,36 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { /**
* Add resource to the list
- * @param Resource
+ * @param jsonResource
*/
- public void addVnfResource(String jsonResource) {
+ public void addVnfResource(String jsonResource) throws JsonDecomposingException {
VnfResource vnfResource = null;
- vnfResource = DecomposeJsonUtil.JsonToVnfResource(jsonResource);
+ vnfResource = DecomposeJsonUtil.jsonToVnfResource(jsonResource);
this.addVnfResource(vnfResource);
}
/**
* Add resource to the list
- * @param Resource
+ * @param jsonResource
*/
- public void addNetworkResource(String jsonResource) {
+ public void addNetworkResource(String jsonResource) throws JsonDecomposingException {
NetworkResource networkResource = null;
- networkResource = DecomposeJsonUtil.JsonToNetworkResource(jsonResource);
+ networkResource = DecomposeJsonUtil.jsonToNetworkResource(jsonResource);
this.addVnfResource(networkResource);
}
/**
* Add resource to the list
- * @param Resource
+ * @param jsonResource
*/
- public void addAllottedResource(String jsonResource) {
+ public void addAllottedResource(String jsonResource) throws JsonDecomposingException {
AllottedResource allottedResource = null;
- allottedResource = DecomposeJsonUtil.JsonToAllottedResource(jsonResource);
+ allottedResource = DecomposeJsonUtil.jsonToAllottedResource(jsonResource);
this.addVnfResource(allottedResource);
}
/**
* Given a ResourceDecomposition (subclass) object, locate it in the Service Decomposition by its unique ID, and replace the current version with the new one.
* This method should support concurrency control via an auto-incrementing field in the ResourceDecomposition class.
- * @param Resource
+ * @param newResource
* @return TRUE if replacement was a success
*/
public boolean replaceResource(Resource newResource){
@@ -365,7 +321,7 @@ public class ServiceDecomposition extends JsonWrapper implements Serializable { /**
* Given a resource object ID, locate it in the Service Decomposition by its unique ID, and delete it.
- * @param Resource
+ * @param resource
* @return TRUE if delete was a success
*/
public boolean deleteResource(Resource resource){
diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/DecomposeJsonUtil.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/DecomposeJsonUtil.java index 71ef09ce33..dcd9e3b39a 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/DecomposeJsonUtil.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/DecomposeJsonUtil.java @@ -20,139 +20,102 @@ package org.openecomp.mso.bpmn.core.json;
-import java.io.Serializable;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-
-
import org.openecomp.mso.bpmn.core.domain.AllottedResource;
import org.openecomp.mso.bpmn.core.domain.NetworkResource;
import org.openecomp.mso.bpmn.core.domain.ServiceDecomposition;
+import org.openecomp.mso.bpmn.core.domain.ServiceInstance;
import org.openecomp.mso.bpmn.core.domain.VnfResource;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
+public class DecomposeJsonUtil {
-import org.openecomp.mso.logger.MsoLogger;
+ private static final ObjectMapper OBJECT_MAPPER = createObjectMapper();
-public class DecomposeJsonUtil implements Serializable {
- private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL);
- /**
- *
- */
- private static final long serialVersionUID = 1L;
+ private DecomposeJsonUtil() {
+ }
- /**
- * Method to construct Service Decomposition object converting
- * JSON structure
- *
- * @param jsonString - input in JSON format confirming ServiceDecomposition
- * @return - ServiceDecomposition object
- * @throws IOException
- * @throws JsonMappingException
- * @throws JsonParseException
- */
- public static ServiceDecomposition JsonToServiceDecomposition(String jsonString) {
-
- ServiceDecomposition serviceDecomposition = new ServiceDecomposition();
- ObjectMapper om = new ObjectMapper();
- om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
-
- try {
- serviceDecomposition = om.readValue(jsonString, ServiceDecomposition.class);
- } catch (JsonParseException e) {
- LOGGER.debug("JsonParseException :",e);
- } catch (JsonMappingException e) {
- LOGGER.debug("JsonMappingException :",e);
- } catch (IOException e) {
- LOGGER.debug("IOException :",e);
- }
-
- return serviceDecomposition;
- }
-
- /**
- * Method to construct Resource Decomposition object converting
- * JSON structure
- *
- * @param jsonString - input in JSON format confirming ResourceDecomposition
- * @return - ServiceDecomposition object
- * @throws IOException
- * @throws JsonMappingException
- * @throws JsonParseException
- */
- public static VnfResource JsonToVnfResource(String jsonString) {
-
- VnfResource vnfResource = new VnfResource();
+ private static ObjectMapper createObjectMapper() {
ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
-
- try {
- vnfResource = om.readValue(jsonString, VnfResource.class);
- } catch (JsonParseException e) {
- LOGGER.debug("JsonParseException :",e);
- } catch (JsonMappingException e) {
- LOGGER.debug("JsonMappingException :",e);
- } catch (IOException e) {
- LOGGER.debug("IOException :",e);
- }
- return vnfResource;
- }
-
- /**
- * Method to construct Resource Decomposition object converting
- * JSON structure
- *
- * @param jsonString - input in JSON format confirming ResourceDecomposition
- * @return - ServiceDecomposition object
- * @throws IOException
- * @throws JsonMappingException
- * @throws JsonParseException
- */
- public static NetworkResource JsonToNetworkResource(String jsonString) {
-
- NetworkResource networkResource = new NetworkResource();
- ObjectMapper om = new ObjectMapper();
- om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
-
- try {
- networkResource = om.readValue(jsonString, NetworkResource.class);
- } catch (JsonParseException e) {
- LOGGER.debug("Exception :",e);
- } catch (JsonMappingException e) {
- LOGGER.debug("Exception :",e);
- } catch (IOException e) {
- LOGGER.debug("Exception :",e);
- }
- return networkResource;
- }
-
- /**
- * Method to construct Resource Decomposition object converting
- * JSON structure
- *
- * @param jsonString - input in JSON format confirming ResourceDecomposition
- * @return - ServiceDecomposition object
- * @throws IOException
- * @throws JsonMappingException
- * @throws JsonParseException
- */
- public static AllottedResource JsonToAllottedResource(String jsonString) {
-
- AllottedResource allottedResource = new AllottedResource();
- ObjectMapper om = new ObjectMapper();
- om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
-
- try {
- allottedResource = om.readValue(jsonString, AllottedResource.class);
- } catch (JsonParseException e) {
- LOGGER.debug("Exception :",e);
- } catch (JsonMappingException e) {
- LOGGER.debug("Exception :",e);
- } catch (IOException e) {
- LOGGER.debug("Exception :",e);
- }
- return allottedResource;
- }
+ return om;
+ }
+
+ /**
+ * Method to construct Service Decomposition object converting JSON structure
+ *
+ * @param jsonString input in JSON format confirming ServiceDecomposition
+ * @return decoded object
+ * @throws JsonDecomposingException thrown when decoding json fails
+ */
+ public static ServiceDecomposition jsonToServiceDecomposition(String jsonString) throws JsonDecomposingException {
+ try {
+ return OBJECT_MAPPER.readValue(jsonString, ServiceDecomposition.class);
+ } catch (IOException e) {
+ throw new JsonDecomposingException("Exception while converting json to service decomposition", e);
+ }
+ }
+
+ /**
+ * Method to construct Service Decomposition object converting JSON structure
+ *
+ * @param jsonString input in JSON format confirming ServiceDecomposition
+ * @param serviceInstanceId service instance id to be put in decoded ServiceDecomposition
+ * @return decoded object
+ * @throws JsonDecomposingException thrown when decoding json fails
+ */
+ public static ServiceDecomposition jsonToServiceDecomposition(String jsonString, String serviceInstanceId)
+ throws JsonDecomposingException {
+ ServiceDecomposition serviceDecomposition = jsonToServiceDecomposition(jsonString);
+ ServiceInstance serviceInstance = new ServiceInstance();
+ serviceInstance.setInstanceId(serviceInstanceId);
+ serviceDecomposition.setServiceInstance(serviceInstance);
+ return serviceDecomposition;
+ }
+
+ /**
+ * Method to construct Resource Decomposition object converting JSON structure
+ *
+ * @param jsonString input in JSON format confirming ResourceDecomposition
+ * @return decoded object
+ * @throws JsonDecomposingException thrown when decoding json fails
+ */
+ public static VnfResource jsonToVnfResource(String jsonString) throws JsonDecomposingException {
+ try {
+ return OBJECT_MAPPER.readValue(jsonString, VnfResource.class);
+ } catch (IOException e) {
+ throw new JsonDecomposingException("Exception while converting json to vnf resource", e);
+ }
+ }
+
+ /**
+ * Method to construct Resource Decomposition object converting JSON structure
+ *
+ * @param jsonString input in JSON format confirming ResourceDecomposition
+ * @return decoded object
+ * @throws JsonDecomposingException thrown when decoding json fails
+ */
+ public static NetworkResource jsonToNetworkResource(String jsonString) throws JsonDecomposingException {
+ try {
+ return OBJECT_MAPPER.readValue(jsonString, NetworkResource.class);
+ } catch (IOException e) {
+ throw new JsonDecomposingException("Exception while converting json to network resource", e);
+ }
+ }
+
+ /**
+ * Method to construct Resource Decomposition object converting JSON structure
+ *
+ * @param jsonString - input in JSON format confirming ResourceDecomposition
+ * @return decoded object
+ * @throws JsonDecomposingException thrown when decoding json fails
+ */
+ public static AllottedResource jsonToAllottedResource(String jsonString) throws JsonDecomposingException {
+ try {
+ return OBJECT_MAPPER.readValue(jsonString, AllottedResource.class);
+ } catch (IOException e) {
+ throw new JsonDecomposingException("Exception while converting json to allotted resource", e);
+ }
+ }
}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java new file mode 100644 index 0000000000..352979e7dd --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/json/JsonDecomposingException.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.core.json; + +import java.io.IOException; + +public class JsonDecomposingException extends IOException { + + public JsonDecomposingException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java index 71ed0eae5e..c346308e2b 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java +++ b/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/plugins/LoggingAndURNMappingPlugin.java @@ -323,6 +323,7 @@ public class LoggingAndURNMappingPlugin extends AbstractProcessEnginePlugin { private void loadFromDB(DelegateExecution execution, ProcessEngineConfigurationImpl processEngineConfiguration) { Command<List<URNMapping>> command = new Command<List<URNMapping>>() { @SuppressWarnings("unchecked") + @Override public List<URNMapping> execute(CommandContext commandContext) { return (List<URNMapping>) commandContext.getDbSqlSession().selectList( "mso.urnMapping.selectAll", null); diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/JsonUtilsTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/JsonUtilsTest.java index 7f922ce30e..58f1ae264d 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/JsonUtilsTest.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/JsonUtilsTest.java @@ -36,26 +36,24 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= - */ + */ package org.openecomp.mso.bpmn.core; -import java.io.BufferedReader; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.CharBuffer; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import org.junit.BeforeClass; import org.junit.Test; -import org.xml.sax.SAXException; -import org.custommonkey.xmlunit.Diff; - import org.openecomp.mso.bpmn.core.json.JsonUtils; import org.openecomp.mso.bpmn.core.xml.XmlTool; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.diff.DefaultNodeMatcher; +import org.xmlunit.diff.Diff; +import org.xmlunit.diff.ElementSelectors; /** * @version 1.0 @@ -63,8 +61,8 @@ import org.openecomp.mso.bpmn.core.xml.XmlTool; public class JsonUtilsTest { private static final String EOL = "\n"; - private String xmlReq = - "<vnf-request xmlns=\"http://org.openecomp/mso/infra/vnf-request/v1\">" + EOL + + private static final String XML_REQ = + "<vnf-request xmlns=\"http://org.openecomp/mso/infra/vnf-request/v1\">" + EOL + " <request-info>" + EOL + " <request-id>DEV-VF-0021</request-id>" + EOL + " <action>CREATE_VF_MODULE</action>" + EOL + @@ -93,9 +91,9 @@ public class JsonUtilsTest { " <param name=\"server\">server1111</param>" + EOL + " </vnf-params> " + EOL + "</vnf-request>" + EOL; - - private String xmlReqNoAttrs = - "<vnf-request xmlns=\"http://org.openecomp/mso/infra/vnf-request/v1\">" + EOL + + + private static final String XML_REQ_NO_ATTRS = + "<vnf-request xmlns=\"http://org.openecomp/mso/infra/vnf-request/v1\">" + EOL + " <request-info>" + EOL + " <action>DELETE_VF_MODULE</action>" + EOL + " <source>PORTAL</source>" + EOL + @@ -115,246 +113,214 @@ public class JsonUtilsTest { " <vnf-params xmlns:tns=\"http://org.openecomp/mso/infra/vnf-request/v1\"/>" + EOL + "</vnf-request>" + EOL; - private String xmlArrayReq = - "<ucpeInfo>" + EOL + + private static final String XML_ARRAY_REQ = + "<ucpeInfo>" + EOL + " <outOfBandManagementModem>BROADBAND</outOfBandManagementModem>" + EOL + - " <internetTopology>IVLAN</internetTopology>" + EOL + - " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL + - " <wanList>" + EOL + - " <wanInfo>" + EOL + - " <wanType>AVPN</wanType>" + EOL + - " <interfaceType>1000BASE-T</interfaceType>" + EOL + - " <transportProviderName>ATT</transportProviderName>" + EOL + - " <circuitId>BT/SLIR/70911</circuitId>" + EOL + - " <dualMode>Active</dualMode>" + EOL + - " <wanPortNumber>WAN1</wanPortNumber>" + EOL + - " <transportManagementOption>ATT</transportManagementOption>" + EOL + - " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL + - " <mediaType>ELECTRICAL</mediaType>" + EOL + - " </wanInfo>" + EOL + - " <wanInfo>" + EOL + - " <wanType>AVPN</wanType>" + EOL + - " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL + - " <transportProviderName>ATT</transportProviderName>" + EOL + - " <circuitId>AS/KRFN/34611</circuitId>" + EOL + - " <dualMode>Active</dualMode>" + EOL + - " <wanPortNumber>WAN2</wanPortNumber>" + EOL + - " <transportManagementOption>ATT</transportManagementOption>" + EOL + - " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL + - " <mediaType>MMF</mediaType>" + EOL + - " </wanInfo>" + EOL + - " </wanList>" + EOL + - " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL + - " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL + - " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL + + " <internetTopology>IVLAN</internetTopology>" + EOL + + " <ucpeAliasHostName>SHELLUCPE31</ucpeAliasHostName>" + EOL + + " <wanList>" + EOL + + " <wanInfo>" + EOL + + " <wanType>AVPN</wanType>" + EOL + + " <interfaceType>1000BASE-T</interfaceType>" + EOL + + " <transportProviderName>ATT</transportProviderName>" + EOL + + " <circuitId>BT/SLIR/70911</circuitId>" + EOL + + " <dualMode>Active</dualMode>" + EOL + + " <wanPortNumber>WAN1</wanPortNumber>" + EOL + + " <transportManagementOption>ATT</transportManagementOption>" + EOL + + " <transportVendorTotalBandwidth>100</transportVendorTotalBandwidth>" + EOL + + " <mediaType>ELECTRICAL</mediaType>" + EOL + + " </wanInfo>" + EOL + + " <wanInfo>" + EOL + + " <wanType>AVPN</wanType>" + EOL + + " <interfaceType>10/100/1000BASE-T</interfaceType>" + EOL + + " <transportProviderName>ATT</transportProviderName>" + EOL + + " <circuitId>AS/KRFN/34611</circuitId>" + EOL + + " <dualMode>Active</dualMode>" + EOL + + " <wanPortNumber>WAN2</wanPortNumber>" + EOL + + " <transportManagementOption>ATT</transportManagementOption>" + EOL + + " <transportVendorTotalBandwidth>10000</transportVendorTotalBandwidth>" + EOL + + " <mediaType>MMF</mediaType>" + EOL + + " </wanInfo>" + EOL + + " </wanList>" + EOL + + " <ucpeActivationCode>ASD-987-M31</ucpeActivationCode>" + EOL + + " <ucpeHostName>USOSTCDALTX0101UJZZ31</ucpeHostName>" + EOL + + " <ucpePartNumber>FG-VM00*</ucpePartNumber>" + EOL + "</ucpeInfo>"; // JSON request w/ embedded XML will be read from a file - private String jsonReq = null; - private String jsonReqArray = null; - - @Before - public void initialize() { - File file = new File("src/test/resources/request.json"); - File file2 = new File("src/test/resources/requestArray.json"); - FileInputStream fis = null; + private static String jsonReq; + private static String jsonReqArray; + + @BeforeClass + public static void initialize() throws Exception { + jsonReq = readFileToString("src/test/resources/request.json"); + jsonReqArray = readFileToString("src/test/resources/requestArray.json"); + } - try { - fis = new FileInputStream(file); - BufferedReader br = new BufferedReader(new InputStreamReader(fis)); - CharBuffer cbuf = CharBuffer.allocate((int)file.length()+1); - br.read(cbuf); - cbuf.flip(); - jsonReq = cbuf.toString(); - if (jsonReq != null) { - System.out.println("initialize(): json request: " + jsonReq); - } else { - System.out.println("initialize(): failed to read json request from src/test/resources/request.json"); - } - fis.close(); - fis = new FileInputStream(file2); - br = new BufferedReader(new InputStreamReader(fis)); - cbuf = CharBuffer.allocate((int)file.length()+1); - br.read(cbuf); - cbuf.flip(); - jsonReqArray = cbuf.toString(); - if (jsonReq != null) { - System.out.println("initialize(): json request w/ array: " + jsonReqArray); - } else { - System.out.println("initialize(): failed to read json request from src/test/resources/request2.json"); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (fis != null) - fis.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } + private static String readFileToString(String path) throws IOException { + File file = new File(path); + return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); } - - @After - public void cleanup(){ + + @Test + public void shouldConvertXmlToJsonAndBackToSameXml() throws Exception { + // Note: the current version of the JsonUtils.json2xml() method + // does not support converting the JSONObject representation + // of XML attributes (JSONArray) back to XML. So this test will + // only succeed if the original XML does not contain attributes + + // given + String xmlIn = XmlTool.removeNamespaces(XML_REQ_NO_ATTRS); + // when + String json = JsonUtils.xml2json(XML_REQ_NO_ATTRS); + String xmlOut = JsonUtils.json2xml(json); + // then + Diff diffXml = DiffBuilder.compare(xmlIn).withTest(xmlOut).ignoreWhitespace() + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); + + assertThat(diffXml.hasDifferences()).withFailMessage(diffXml.toString()).isFalse(); } @Test -// @Ignore - public void testConversion() { - // Note: the current version of the JsonUtils.json2xml() method - // does not support converting the JSONObject representation - // of XML attributes (JSONArray) back to XML. So this test will - // only succeed if the original XML does not contain attributes - - // save a copy of the xml with the namespaces removed - String xmlIn = XmlTool.removeNamespaces(xmlReqNoAttrs); - // strip all the non-data whitespace - xmlIn = xmlIn.replaceAll(">\\s*<", "><"); - String json = JsonUtils.xml2json(xmlReqNoAttrs); - System.out.println("testConversion(): xml request to json: " + json); - String xmlOut = JsonUtils.json2xml(json); - System.out.println("testConversion(): json request back to xml: " + xmlOut); - - // strip all the non-data whitespace - xmlOut = xmlOut.replaceAll(">\\s*<", "><"); + public void shouldReadValuesForAbsoluteJsonPaths() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + // when, then + assertThat(JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.vnf-name")).isEqualTo("STMTN5MMSC21"); + assertThat(JsonUtils.getJsonValue(json, "vnf-request.request-info.action")).isEqualTo("CREATE_VF_MODULE"); + assertThat(JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.persona-model-version")).isEqualTo("1"); + assertThat(JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.vnf-persona-model-version")).isEqualTo("1.5"); + assertThat(JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.is-base-module")).isEqualTo("true"); + } - Diff diffXml; - try { - diffXml = new Diff(xmlIn, xmlOut); - Assert.assertTrue(diffXml.similar()); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } + @Test + public void shouldReturnValueForJsonKey() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + // when, then + assertThat(JsonUtils.getJsonValueForKey(json, "source")).isEqualTo("PORTAL"); } @Test -// @Ignore - public void testRetrieval() { - String json = JsonUtils.xml2json(xmlReq); - System.out.println("testRetrieval(): xml request to json: " + json); - // full JSON path - String value = JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.vnf-name"); - Assert.assertEquals(value, "STMTN5MMSC21"); - value = JsonUtils.getJsonValue(json, "vnf-request.request-info.action"); - Assert.assertEquals(value, "CREATE_VF_MODULE"); - // retrieving an integer - value = JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.persona-model-version"); - Assert.assertEquals(value, "1"); - // retrieving a float - value = JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.vnf-persona-model-version"); - Assert.assertEquals(value, "1.5"); - // retrieving a boolean - value = JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.is-base-module"); - Assert.assertEquals(value, "true"); - // attempt to retrieve a value for a non-existent field - value = JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.bad"); - Assert.assertEquals(value, null); - // retrieving a parameter/array value (originally a XML attribute) - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name"); - Assert.assertEquals(value, "network"); - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "content"); - Assert.assertEquals(value, "network1111"); - // retrieving a parameter/array value by index - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "content", 1); - Assert.assertEquals(value, "server1111"); - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 1); - Assert.assertEquals(value, "server"); - // failure due to invalid parameter name - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "badParam"); - Assert.assertEquals(value, null); - // failure due to array index out of bounds - value = JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 2); - Assert.assertEquals(value, null); - // by field name/key - value = JsonUtils.getJsonValueForKey(json, "source"); - Assert.assertEquals(value, "PORTAL"); - value = JsonUtils.getJsonValueForKey(json, "vnf-module"); - Assert.assertEquals(value, null); + public void shouldReturnNullForNonexistentJsonNode() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + // when, then + assertThat(JsonUtils.getJsonValueForKey(json, "nonexistent-node")).isNull(); } @Test -// @Ignore - public void testUpdate() { - String json = JsonUtils.xml2json(xmlReq); - System.out.println("testUpdate(): xml request to json: " + json); - // the add should be successful - String jsonUpd = JsonUtils.addJsonValue(json, "vnf-request.request-info.comment", "Some comment"); - String value = JsonUtils.getJsonValue(jsonUpd, "vnf-request.request-info.comment"); - Assert.assertEquals(value, "Some comment"); - // the add should be ignored as the field already exists - jsonUpd = JsonUtils.addJsonValue(jsonUpd, "vnf-request.vnf-inputs.vnf-name", "STMTN5MMSC22"); - value = JsonUtils.getJsonValue(jsonUpd, "vnf-request.vnf-inputs.vnf-name"); - Assert.assertEquals(value, "STMTN5MMSC21"); - // the update should be successful - jsonUpd = JsonUtils.updJsonValue(jsonUpd, "vnf-request.vnf-inputs.vnf-name", "STMTN5MMSC22"); - value = JsonUtils.getJsonValue(jsonUpd, "vnf-request.vnf-inputs.vnf-name"); - Assert.assertEquals(value, "STMTN5MMSC22"); - // the delete should be successful - jsonUpd = JsonUtils.delJsonValue(jsonUpd, "vnf-request.request-info.comment"); - value = JsonUtils.getJsonValue(jsonUpd, "vnf-request.request-info.comment"); - Assert.assertEquals(value, null); - // the delete should fail as field 'vnf-model' does not exist - String jsonCur = jsonUpd; - jsonUpd = JsonUtils.delJsonValue(jsonUpd, "vnf-request.vnf-inputs.vnf-module"); - Assert.assertEquals(jsonCur, jsonUpd); + public void shouldReturnNullForNonExistentParameter() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + // when, then + assertThat(JsonUtils.getJsonValue(json, "vnf-request.vnf-inputs.bad")).isNull(); } - + @Test -// @Ignore - public void testEmbededXmlRetrievalConversion() { - try { - // extract the embedded XML from the request - String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value"); - String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value)); - System.out.println("testEmbededXmlRetrievalConversion(): xml payload: " + xmlReq); - String json = JsonUtils.xml2json(xmlReq); - System.out.println("testEmbededXmlRetrievalConversion(): xml request to json: " + json); - String xmlOut = JsonUtils.json2xml(json); - System.out.println("testEmbededXmlRetrievalConversion(): json request back to xml: " + xmlOut); - Diff diffXml; - try { - // compare the XML before and after - diffXml = new Diff(xmlReq, xmlOut); - Assert.assertTrue(diffXml.similar()); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - } catch (Exception e) { - e.printStackTrace(); - } + public void shouldGetJasonParametersFromArray() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + // when, then + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name")).isEqualTo("network"); + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "content")) + .isEqualTo("network1111"); + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 1)).isEqualTo("server"); + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "content", 1)) + .isEqualTo("server1111"); + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "badParam")) + .withFailMessage("Expected null for nonexistent param").isNull(); + assertThat(JsonUtils.getJsonParamValue(json, "vnf-request.vnf-params.param", "name", 2)) + .withFailMessage("Expected null for index out of bound").isNull(); } @Test -// @Ignore - // Tests the conversion of a JSON Doc containing a JSON Array to XML - public void testConversionArray() { - try { - String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo"); - System.out.println("testConversionArray(): json value: " + JsonUtils.prettyJson(jsonParm)); - String xmlOut = JsonUtils.json2xml(jsonParm); - System.out.println("testConversionArray(): json parameters to xml: " + xmlOut); - // strip all the non-data whitespace - xmlOut = xmlOut.replaceAll(">\\s*<", "><"); - System.out.println("testConversionArray(): XML after removing whitespace:" + xmlOut); - String xmlTest = xmlArrayReq.replaceAll(">\\s*<", "><"); + public void shouldAddJsonValue() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + String key = "vnf-request.request-info.comment"; + String value = "Some comment"; + // when + String jsonUpd = JsonUtils.addJsonValue(json, key, value); + // then + String extractedValue = JsonUtils.getJsonValue(jsonUpd, key); + assertThat(extractedValue).isEqualTo(value); + } - Diff diffXml; - try { - diffXml = new Diff(xmlTest, xmlOut); - Assert.assertTrue(diffXml.similar()); - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } + @Test + public void shouldIgnoreAddIfFieldAlreadyExists() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + String key = "vnf-request.vnf-inputs.vnf-name"; + String newValue = "STMTN5MMSC22"; + String oldValue = JsonUtils.getJsonValue(json, key); + // when + String jsonUpd = JsonUtils.addJsonValue(json, key, newValue); + // then + String extractedValue = JsonUtils.getJsonValue(jsonUpd, key); + assertThat(extractedValue).isEqualTo(oldValue).isNotEqualTo(newValue); + } + + @Test + public void shouldUpdateValueInJson() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + String key = "vnf-request.vnf-inputs.vnf-name"; + String newValue = "STMTN5MMSC22"; + String oldValue = JsonUtils.getJsonValue(json, key); + // when + String jsonUpd = JsonUtils.updJsonValue(json, key, newValue); + // then + String extractedValue = JsonUtils.getJsonValue(jsonUpd, key); + assertThat(extractedValue).isNotEqualTo(oldValue).isEqualTo(newValue); + } + + @Test + public void shouldDeleteValue() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + String key = "vnf-request.vnf-inputs.vnf-name"; + String oldValue = JsonUtils.getJsonValue(json, key); + // when + String jsonUpd = JsonUtils.delJsonValue(json, key); + // then + String extractedValue = JsonUtils.getJsonValue(jsonUpd, key); + assertThat(extractedValue).isNotEqualTo(oldValue).isNull(); + } + + @Test + public void shouldReturnOriginalJsonWhenTryingToRemoveNonexistentField() throws Exception { + // given + String json = JsonUtils.xml2json(XML_REQ); + String key = "vnf-request.vnf-inputs.does-not-exist"; + // when + String jsonUpd = JsonUtils.delJsonValue(json, key); + // then + assertThat(jsonUpd).isEqualTo(json); + } + + @Test + public void shouldConvertXmlToJsonAndBackToSameXmlExtractedFromTheRequest() throws Exception { + // given + String value = JsonUtils.getJsonValue(jsonReq, "variables.bpmnRequest.value"); + String xmlReq = XmlTool.removeNamespaces(XmlTool.normalize(value)); + // when + String json = JsonUtils.xml2json(xmlReq); + String xmlOut = JsonUtils.json2xml(json); + // then + Diff diffXml = DiffBuilder.compare(xmlReq).withTest(xmlOut).ignoreWhitespace() + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); + assertThat(diffXml.hasDifferences()).withFailMessage(diffXml.toString()).isFalse(); + } + + @Test + public void shouldConvertJsonContainingArrayToXml() throws Exception { + // when + String jsonParm = JsonUtils.getJsonNodeValue(jsonReqArray, "requestDetails.requestParameters.ucpeInfo"); + String xmlOut = JsonUtils.json2xml(jsonParm); + // then + Diff diffXml = DiffBuilder.compare(XML_ARRAY_REQ).withTest(xmlOut).ignoreWhitespace() + .withNodeMatcher(new DefaultNodeMatcher(ElementSelectors.byName)).checkForSimilar().build(); + assertThat(diffXml.hasDifferences()).withFailMessage(diffXml.toString()).isFalse(); } } diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java new file mode 100644 index 0000000000..c51af23e30 --- /dev/null +++ b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/RollbackDataTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.mso.bpmn.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +import org.junit.Test; + +public class RollbackDataTest { + + private final static String TYPE_A = "typeA"; + private final static String TYPE_B = "typeB"; + private static final String KEY_1 = "key1"; + private static final String VALUE_1 = "value1"; + private static final String VALUE_2 = "value2"; + + @Test + public void shouldReturnStringRepresentationOfDataInAnyPermutation() throws Exception { + // given + RollbackData data = new RollbackData(); + data.put(TYPE_A, KEY_1, VALUE_1); + data.put(TYPE_A, "key2", "value2"); + data.put(TYPE_B, "key3", "value3"); + // when, then + assertThat(data.toString()).isIn( + "[typeB{key3=value3},typeA{key1=value1, key2=value2}]", + "[typeB{key3=value3},typeA{key2=value2, key1=value1}]", + "[typeA{key1=value1, key2=value2},typeB{key3=value3}]", + "[typeA{key2=value2, key1=value1},typeB{key3=value3}]"); + } + + @Test + public void shouldBeEmptyOnCreation() throws Exception { + // given + RollbackData data = new RollbackData(); + // then + assertThat(data.hasType(TYPE_A)).isFalse(); + assertThat(data.get(TYPE_A, KEY_1)).isNull(); + } + + @Test + public void shouldHaveTypeAfterPuttingDataOfThatType() throws Exception { + // given + RollbackData data = new RollbackData(); + // when + data.put(TYPE_A, KEY_1, VALUE_1); + // then + assertThat(data.hasType(TYPE_A)).isTrue(); + assertThat(data.hasType(TYPE_B)).isFalse(); + assertThat(data.get(TYPE_A, KEY_1)).isEqualTo(VALUE_1); + } + + @Test + public void shouldKeepTwoValuesWithSameKeysButDifferentTypes() throws Exception { + // given + RollbackData data = new RollbackData(); + // when + data.put(TYPE_A, KEY_1, VALUE_1); + data.put(TYPE_B, KEY_1, VALUE_2); + // then + assertThat(data.get(TYPE_A, KEY_1)).isEqualTo(VALUE_1); + assertThat(data.get(TYPE_A)).containsExactly(entry(KEY_1, VALUE_1)); + assertThat(data.get(TYPE_B, KEY_1)).isEqualTo(VALUE_2); + assertThat(data.get(TYPE_B)).containsExactly(entry(KEY_1, VALUE_2)); + } +}
\ No newline at end of file diff --git a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/TestBaseTask.java b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/TestBaseTask.java index 862cb76146..9730b129be 100644 --- a/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/TestBaseTask.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/TestBaseTask.java @@ -35,6 +35,7 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; +import org.openecomp.mso.bpmn.core.utils.CamundaDBSetup; import org.openecomp.mso.logger.MsoLogger; /** diff --git a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/utils/CamundaDBSetup.java index 9a8cad6b86..f29ccc75e0 100644 --- a/bpmn/MSOCoreBPMN/src/main/java/org/openecomp/mso/bpmn/core/CamundaDBSetup.java +++ b/bpmn/MSOCoreBPMN/src/test/java/org/openecomp/mso/bpmn/core/utils/CamundaDBSetup.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.mso.bpmn.core; +package org.openecomp.mso.bpmn.core.utils; import java.sql.Connection; import java.sql.DriverManager; @@ -35,9 +35,6 @@ public class CamundaDBSetup { private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL); private CamundaDBSetup() { - /** - * Constructor. - */ } public static synchronized void configure() throws SQLException { diff --git a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy index 862c46ad19..308834038e 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy +++ b/bpmn/MSOInfrastructureBPMN/src/main/groovy/org/openecomp/mso/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy @@ -54,7 +54,6 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { JsonUtils jsonUtil = new JsonUtils() VidUtils vidUtils = new VidUtils(this) CatalogDbUtils cutils = new CatalogDbUtils() - DecomposeJsonUtil decomposeJsonUtil = new DecomposeJsonUtil() /** * This method gets and validates the incoming @@ -185,7 +184,7 @@ class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { utils.log("DEBUG", "obtained VNF list") // Only one match here JSONObject vnfObject = vnfs[0] - vnf = decomposeJsonUtil.JsonToVnfResource(vnfObject.toString()) + vnf = DecomposeJsonUtil.jsonToVnfResource(vnfObject.toString()) } utils.log("DEBUG", "Read vnfResource", isDebugLogEnabled) if (vnf == null) { diff --git a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java index 823223fbd8..dfa390c296 100644 --- a/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java +++ b/bpmn/MSOInfrastructureBPMN/src/main/java/org/openecomp/mso/bpmn/infrastructure/workflow/serviceTask/AbstractSdncOperationTask.java @@ -115,14 +115,11 @@ public abstract class AbstractSdncOperationTask extends BaseTask { protected String httpPost(String url, HttpPost httpPost) throws RouteException { logger.info("AbstractSdncOperationTask.httpPost begin!"); - CloseableHttpClient httpClient = HttpClients.createDefault(); String result = null; - boolean var15 = false; String errorMsg; label91: { - try { - var15 = true; + try(CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost); result = EntityUtils.toString(closeableHttpResponse.getEntity()); logger.info("result = {}", result); @@ -133,42 +130,14 @@ public abstract class AbstractSdncOperationTask extends BaseTask { } closeableHttpResponse.close(); - var15 = false; break label91; - } catch (IOException var19) { + } catch (IOException e) { errorMsg = url + ":httpPostWithJSON connect faild"; logger.info("exception: POST_CONNECT_FAILD : {}", errorMsg); - throwsRouteException(errorMsg, var19, "POST_CONNECT_FAILD"); - var15 = false; - } finally { - if(var15) { - try { - httpClient.close(); - } catch (IOException var16) { - String errorMsg1 = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg1); - throwsRouteException(errorMsg1, var16, "CLOSE_CONNECT_FAILD"); - } - - } - } - - try { - httpClient.close(); - } catch (IOException var17) { - errorMsg = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg); - throwsRouteException(errorMsg, var17, "CLOSE_CONNECT_FAILD"); + throwsRouteException(errorMsg, e, "POST_CONNECT_FAILD"); } } - try { - httpClient.close(); - } catch (IOException var18) { - errorMsg = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD : {}", errorMsg); - throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD"); - } logger.info("AbstractSdncOperationTask.httpPost end!"); return result; } @@ -223,78 +192,27 @@ public abstract class AbstractSdncOperationTask extends BaseTask { private String httpGet(String url, HttpGet httpGet) throws RouteException { logger.info("AbstractSdncOperationTask.httpGet begin!"); - boolean var16 = false; - CloseableHttpClient httpClient = HttpClients.createDefault(); String result = ""; String errorMsg; - label109: - { - label110: - { - try { - var16 = true; - CloseableHttpResponse e = httpClient.execute(httpGet); - result = EntityUtils.toString(e.getEntity()); - logger.info("result = {}", result); - if (e.getStatusLine().getStatusCode() != 200) { - logger.info("exception: fail for status code = {}", e.getStatusLine().getStatusCode()); + try(CloseableHttpClient httpClient = HttpClients.createDefault()) { + CloseableHttpResponse e = httpClient.execute(httpGet); + result = EntityUtils.toString(e.getEntity()); + logger.info("result = {}", result); + if (e.getStatusLine().getStatusCode() != 200) { + logger.info("exception: fail for status code = {}", e.getStatusLine().getStatusCode()); throw new RouteException(result, "SERVICE_GET_ERR"); } - e.close(); - var16 = false; - break label110; - } catch (ClientProtocolException var21) { - errorMsg = url + ":httpGetWithJSON connect faild"; - logger.info("exception: GET_CONNECT_FAILD {}", errorMsg); - throwsRouteException(errorMsg, var21, "GET_CONNECT_FAILD"); - var16 = false; - } catch (IOException var22) { - errorMsg = url + ":httpGetWithJSON connect faild"; - logger.info("exception: GET_CONNECT_FAILD {}", errorMsg); - throwsRouteException(errorMsg, var22, "GET_CONNECT_FAILD"); - var16 = false; - break label109; - } finally { - if (var16) { - try { - httpClient.close(); - } catch (IOException var17) { - String errorMsg1 = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg1); - throwsRouteException(errorMsg1, var17, "CLOSE_CONNECT_FAILD"); - } - - } - } + } catch (ClientProtocolException e) { + errorMsg = url + ":httpGetWithJSON connect faild"; + logger.info("exception: GET_CONNECT_FAILD {}", errorMsg); + throwsRouteException(errorMsg, e, "GET_CONNECT_FAILD"); + } catch (IOException e) { + errorMsg = url + ":httpGetWithJSON connect faild"; + logger.info("exception: GET_CONNECT_FAILD {}", errorMsg); + throwsRouteException(errorMsg, e, "GET_CONNECT_FAILD"); + } - try { - httpClient.close(); - } catch (IOException var19) { - errorMsg = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg); - throwsRouteException(errorMsg, var19, "CLOSE_CONNECT_FAILD"); - } - - } - - try { - httpClient.close(); - } catch (IOException var20) { - errorMsg = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg); - throwsRouteException(errorMsg, var20, "CLOSE_CONNECT_FAILD"); - } - - } - - try { - httpClient.close(); - } catch (IOException var18) { - errorMsg = url + ":close httpClient faild"; - logger.info("exception: CLOSE_CONNECT_FAILD {}", errorMsg); - throwsRouteException(errorMsg, var18, "CLOSE_CONNECT_FAILD"); - } logger.info("AbstractSdncOperationTask.httpGet end!"); return result; } diff --git a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateGenericALaCarteServiceInstanceTest.java b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateGenericALaCarteServiceInstanceTest.java index 21c00918d3..571db76399 100644 --- a/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateGenericALaCarteServiceInstanceTest.java +++ b/bpmn/MSOInfrastructureBPMN/src/test/java/org/openecomp/mso/bpmn/infrastructure/CreateGenericALaCarteServiceInstanceTest.java @@ -79,8 +79,8 @@ public class CreateGenericALaCarteServiceInstanceTest extends WorkflowTest { MockGetCustomer("MCBH-1610", "CreateServiceInstance/createServiceInstance_queryGlobalCustomerId_AAIResponse_Success.xml"); MockPutServiceInstance("MCBH-1610", "viprsvc", "RaaTest-1-id", ""); MockGetServiceInstance("MCBH-1610", "viprsvc", "RaaTest-1-id", "GenericFlows/getServiceInstance.xml"); - MockNodeQueryServiceInstanceByName("RAATest-1", ""); - MockNodeQueryServiceInstanceById("RaaTest-1-id", ""); + MockNodeQueryServiceInstanceByName("RAATest-1", null); + MockNodeQueryServiceInstanceById("RaaTest-1-id", null); //SDNC mockSDNCAdapter(200); //DB diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/OrchestrationRequests.java index 2f32e80dc1..d60915bf43 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/OrchestrationRequests.java @@ -160,7 +160,7 @@ public class OrchestrationRequests { orchestrationList = new GetOrchestrationListResponse(); - List<RequestList> requestLists = new ArrayList<RequestList>(); + List<RequestList> requestLists = new ArrayList<>(); for (InfraActiveRequests infraActive : activeRequests) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/ServiceInstances.java index 3c40003dd0..6f6d2972d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/openecomp/mso/apihandlerinfra/ServiceInstances.java @@ -757,12 +757,16 @@ public class ServiceInstances { // } // TODO need to make this a configurable property - String defaultServiceModelName = msoRequest.getRequestInfo().getSource() + "_DEFAULT"; + String defaultServiceModelName = "*"; + String defaultSourceServiceModelName = msoRequest.getRequestInfo().getSource() + "_DEFAULT"; Service serviceRecord; ModelInfo modelInfo = msoRequest.getModelInfo(); if(msoRequest.getALaCarteFlag()){ - serviceRecord = db.getServiceByModelName(defaultServiceModelName); + serviceRecord = db.getServiceByModelName(defaultSourceServiceModelName); + if (serviceRecord == null) { + serviceRecord = db.getServiceByModelName(defaultServiceModelName); + } }else{ serviceRecord = db.getServiceByModelUUID(modelInfo.getModelVersionId()); // ModelVersionId is not required in v3 if(serviceRecord == null) { @@ -778,12 +782,16 @@ public class ServiceInstances { RequestParameters reqParam = msoRequest.getServiceInstancesRequest().getRequestDetails().getRequestParameters(); if(reqParam!=null && reqParam.isaLaCarteSet() && recipe==null){ return null; - }else if (recipe == null) { //aLaCarte wasn't sent, so we'll try the default + } + + //aLaCarte wasn't sent, so we'll try the default + serviceRecord = db.getServiceByModelName(defaultSourceServiceModelName); + if (serviceRecord == null) { serviceRecord = db.getServiceByModelName(defaultServiceModelName); - recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name()); } - if(modelInfo.getModelVersionId() == null) { + recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name()); + if(modelInfo.getModelVersionId() == null) { modelInfo.setModelVersionId(serviceRecord.getModelUUID()); } if(recipe==null){ diff --git a/mso-api-handlers/mso-requests-db/pom.xml b/mso-api-handlers/mso-requests-db/pom.xml index 6a4941e53e..cdfa0fa8db 100644 --- a/mso-api-handlers/mso-requests-db/pom.xml +++ b/mso-api-handlers/mso-requests-db/pom.xml @@ -55,6 +55,12 @@ </exclusions> </dependency> <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <version>4.12</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.6.Final</version> @@ -101,6 +107,12 @@ <artifactId>common</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.jmockit</groupId> + <artifactId>jmockit</artifactId> + <version>1.19</version> + <scope>test</scope> + </dependency> </dependencies> <packaging>jar</packaging> <build> diff --git a/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java b/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java new file mode 100644 index 0000000000..0bb126fa42 --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/test/java/org/openecomp/mso/requestsdb/RequestsDatabaseTest.java @@ -0,0 +1,283 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.openecomp.mso.requestsdb; + + +import mockit.Expectations; +import mockit.Mocked; +import mockit.integration.junit4.JMockit; +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.mso.db.AbstractSessionFactoryManager; + +import java.util.Arrays; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +@RunWith(JMockit.class) +public class RequestsDatabaseTest { + + RequestsDatabase requestsDatabase = RequestsDatabase.getInstance(); + + @Test + public void getInstanceTest() throws Exception { + RequestsDatabase instance = RequestsDatabase.getInstance(); + assertEquals(RequestsDatabase.class, instance.getClass()); + } + + @Test + public void healthCheckTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked SQLQuery query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createSQLQuery(" show tables "); result = query; + query.list(); result = Arrays.asList("table1", "table2"); + }}; + + assertTrue(requestsDatabase.healthCheck()); + } + + @Test + public void updateInfraStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", "unknown")); + } + + @Test + public void updateInfraStatus1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraStatus("123", "unknown", 0, "unknown")); + } + + @Test + public void updateInfraFinalStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.executeUpdate(); result = 1; + }}; + assertEquals(1, requestsDatabase.updateInfraFinalStatus("123", + "unknown", + "statusMessage", + 0, + "responsebody", + "lastmodifiedby")); + } + + @Test + public void getRequestFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + query.uniqueResult(); result = new InfraActiveRequests("123", "action"); + }}; + assertEquals("123", + requestsDatabase.getRequestFromInfraActive("123").getRequestId()); + } + + @Test + public void getOrchestrationFiltersFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Criteria criteria) throws Exception { + + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createCriteria(InfraActiveRequests.class); result = criteria; + criteria.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals(1, + requestsDatabase.getRequestListFromInfraActive("queryattr", + "queryvalue", + "type").size()); + } + + @Test + public void getRequestListFromInfraActiveTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType"); result = query; + query.uniqueResult(); result = new InfraActiveRequests("123", "action"); + }}; + assertEquals("123", + requestsDatabase.getRequestFromInfraActive("123", "requestType").getRequestId()); + } + + @Test + public void getRequestFromInfraActive1Test(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Criteria criteria) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createCriteria(InfraActiveRequests.class); result = criteria; + criteria.list(); result = Arrays.asList(new InfraActiveRequests()); + }}; + assertEquals(1, + requestsDatabase.getRequestListFromInfraActive("queryAttr", + "queryvalue", + "type").size()); + } + + @Test + public void checkDuplicateByVnfNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query; + query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals("123", + requestsDatabase.checkDuplicateByVnfName("vnfname", + "action", + "requesttype").getRequestId()); + } + + @Test + public void checkDuplicateByVnfIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT') and requestType = :requestType ORDER BY startTime DESC"); result = query; + query.list(); result = Arrays.asList(new InfraActiveRequests("123", "action")); + }}; + assertEquals("123", + requestsDatabase.checkDuplicateByVnfId("vnfname", + "action", + "requesttype").getRequestId()); + } + + @Test + public void setMockDBTest() throws Exception { + requestsDatabase.setMockDB(null); + } + + @Test + public void getSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query; + query.uniqueResult(); result = new SiteStatus(); + }}; + assertEquals(SiteStatus.class, + requestsDatabase.getSiteStatus("site").getClass()); + } + + @Test + public void updateSiteStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM SiteStatus WHERE siteName = :site_name"); result = query; + query.uniqueResult(); result = new SiteStatus(); + }}; + requestsDatabase.updateSiteStatus("site", true); + } + + @Test + public void getOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatus("123", + "Unknown").getClass()); + } + + @Test + public void getOperationStatusByServiceIdTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatusByServiceId("123").getClass()); + } + + @Test + public void getOperationStatusByServiceNameTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_NAME = :service_name"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + assertEquals(OperationStatus.class, + requestsDatabase.getOperationStatusByServiceName("servicename").getClass()); + } + + @Test + public void updateOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM OperationStatus WHERE SERVICE_ID = :service_id and OPERATION_ID = :operation_id"); result = query; + query.uniqueResult(); result = new OperationStatus(); + }}; + requestsDatabase.updateOperationStatus(new OperationStatus()); + } + + @Test + public void getResourceOperationStatusTest(@Mocked AbstractSessionFactoryManager sessionFactoryManager, + @Mocked Session session, + @Mocked Query query) throws Exception { + new Expectations() {{ + sessionFactoryManager.getSessionFactory().openSession(); result = session; + session.createQuery("FROM ResourceOperationStatus WHERE serviceId = :service_id and operationId = :operation_id and resourceTemplateUUID= :uuid"); result = query; + query.uniqueResult(); result = new ResourceOperationStatus(); + }}; + assertEquals(ResourceOperationStatus.class, + requestsDatabase.getResourceOperationStatus("serviceId", + "operationid", + "123-uuid").getClass()); + } +} diff --git a/mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/CatalogDatabase.java b/mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/CatalogDatabase.java index 0219e304cb..aefe0d5a8b 100644 --- a/mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/CatalogDatabase.java +++ b/mso-catalog-db/src/main/java/org/openecomp/mso/db/catalog/CatalogDatabase.java @@ -958,43 +958,43 @@ public class CatalogDatabase implements Closeable { * Return the newest version of a vfModule - 1607 * */ - public VfModule getVfModuleModelName (String modelName) { + public VfModule getVfModuleModelName(String modelName) { - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get vfModuleModelName with name " + modelName); + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get vfModuleModelName with name " + modelName); String hql = "FROM VfModule WHERE modelName = :model_name"; - Query query = getSession ().createQuery (hql); - query.setParameter ("model_name", modelName); + Query query = getSession().createQuery(hql); + query.setParameter("model_name", modelName); @SuppressWarnings("unchecked") - List <VfModule> resultList = query.list (); + List<VfModule> resultList = query.list(); // See if something came back. Name is unique, so - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleModelName", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VF not found", "CatalogDB", "getVfModuleModelName", null); return null; } - Collections.sort (resultList, new MavenLikeVersioningComparator ()); - Collections.reverse (resultList); + Collections.sort(resultList, new MavenLikeVersioningComparator()); + Collections.reverse(resultList); - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null); - return resultList.get (0); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null); + return resultList.get(0); } - public VfModule getVfModuleModelName (String modelName, String model_version) { + public VfModule getVfModuleModelName(String modelName, String model_version) { - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get vfModuleModelName with type='" + modelName + "' and asdc_service_model_version='" + model_version + "'"); + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get vfModuleModelName with type='" + modelName + "' and asdc_service_model_version='" + model_version + "'"); String hql = "FROM VfModule WHERE Name = :model_name and version = :model_version"; - Query query = getSession ().createQuery (hql); - query.setParameter ("modelName", modelName); - query.setParameter ("model_version", model_version); + Query query = getSession().createQuery(hql); + query.setParameter("modelName", modelName); + query.setParameter("model_version", model_version); VfModule module = null; try { - module = (VfModule) query.uniqueResult (); + module = (VfModule) query.uniqueResult(); } catch (org.hibernate.NonUniqueResultException nure) { LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: type='" + modelName + "', asdc_service_model_version='" + model_version + "'"); LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for type=" + modelName + " and version=" + model_version, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for type=" + modelName); @@ -1012,9 +1012,9 @@ public class CatalogDatabase implements Closeable { throw e; } if (module == null) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleModelName", null); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleModelName", null); } else { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleModelName", null); } return module; } @@ -1026,21 +1026,21 @@ public class CatalogDatabase implements Closeable { *@author cb645j * */ - public VfModuleCustomization getVfModuleCustomizationByModelName (String modelName) { + public VfModuleCustomization getVfModuleCustomizationByModelName(String modelName) { - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get VfModuleCustomization By VfModule's ModelName: " + modelName); + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get VfModuleCustomization By VfModule's ModelName: " + modelName); String hql = "SELECT VfModuleCustomization FROM VfModuleCustomization as vfmc LEFT OUTER JOIN VfModule as vfm on vfm.modelUUID = vfmc.vfModuleModelUuid where vfm.modelName = :model_name"; - Query query = getSession ().createQuery (hql); - query.setParameter ("model_name", modelName); + Query query = getSession().createQuery(hql); + query.setParameter("model_name", modelName); @SuppressWarnings("unchecked") List<VfModuleCustomization> resultList = query.list(); // See if something came back. Name is unique, so - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful query but Vf module NOT found", "CatalogDB", "getVfModuleCustomizationByModelName", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful query but Vf module NOT found", "CatalogDB", "getVfModuleCustomizationByModelName", null); return null; } @@ -1055,28 +1055,28 @@ public class CatalogDatabase implements Closeable { * @param networkType * @return NetworkResource object or null if none found */ - public NetworkResource getNetworkResource (String networkType) { + public NetworkResource getNetworkResource(String networkType) { - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get network resource with type " + networkType); + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get network resource with type " + networkType); String hql = "FROM NetworkResource WHERE model_name = :network_type"; - Query query = getSession ().createQuery (hql); - query.setParameter ("network_type", networkType); + Query query = getSession().createQuery(hql); + query.setParameter("network_type", networkType); @SuppressWarnings("unchecked") - List <NetworkResource> resultList = query.list (); + List <NetworkResource> resultList = query.list(); // See if something came back. Name is unique, so - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Network Resource not found", "CatalogDB", "getNetworkResource", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. Network Resource not found", "CatalogDB", "getNetworkResource", null); return null; } - Collections.sort (resultList, new MavenLikeVersioningComparator ()); - Collections.reverse (resultList); - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResource", null); - return resultList.get (0); + Collections.sort(resultList, new MavenLikeVersioningComparator()); + Collections.reverse(resultList); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getNetworkResource", null); + return resultList.get(0); } /** @@ -1087,46 +1087,46 @@ public class CatalogDatabase implements Closeable { * @param serviceType The service Name, if null or empty is provided, it won't be taken into account * @return VnfRecipe object or null if none found */ - public VnfRecipe getVnfRecipe (String vnfType, String action, String serviceType) { + public VnfRecipe getVnfRecipe(String vnfType, String action, String serviceType) { boolean withServiceType = false; - StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action "); + StringBuilder hql = new StringBuilder("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action "); // If query c - if (serviceType == null || serviceType.isEmpty ()) { - hql.append ("AND serviceType is NULL "); + if (serviceType == null || serviceType.isEmpty()) { + hql.append("AND serviceType is NULL "); } else { - hql.append ("AND serviceType = :serviceType "); + hql.append("AND serviceType = :serviceType "); withServiceType = true; } - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get VNF recipe with name " + vnfType + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get VNF recipe with name " + vnfType + " and action " + action + " and service type " + serviceType); - Query query = getSession ().createQuery (hql.toString ()); - query.setParameter (VNF_TYPE, vnfType); - query.setParameter (ACTION, action); + Query query = getSession().createQuery(hql.toString()); + query.setParameter(VNF_TYPE, vnfType); + query.setParameter(ACTION, action); if (withServiceType) { - query.setParameter (SERVICE_TYPE, serviceType); + query.setParameter(SERVICE_TYPE, serviceType); } @SuppressWarnings("unchecked") - List <VnfRecipe> resultList = query.list (); + List <VnfRecipe> resultList = query.list(); - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null); return null; } - Collections.sort (resultList, new MavenLikeVersioningComparator ()); - Collections.reverse (resultList); + Collections.sort(resultList, new MavenLikeVersioningComparator()); + Collections.reverse(resultList); - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null); - return resultList.get (0); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null); + return resultList.get(0); } /** @@ -1136,31 +1136,31 @@ public class CatalogDatabase implements Closeable { * @param action * @return VnfRecipe object or null if none found */ - public VnfRecipe getVnfRecipe (String vnfType, String action) { - StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action "); + public VnfRecipe getVnfRecipe(String vnfType, String action) { + StringBuilder hql = new StringBuilder("FROM VnfRecipe WHERE vnfType = :vnfType AND action = :action "); - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get VNF recipe with name " + vnfType + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get VNF recipe with name " + vnfType + " and action " + action); - Query query = getSession ().createQuery (hql.toString ()); - query.setParameter (VNF_TYPE, vnfType); - query.setParameter (ACTION, action); + Query query = getSession().createQuery(hql.toString()); + query.setParameter(VNF_TYPE, vnfType); + query.setParameter(ACTION, action); @SuppressWarnings("unchecked") - List <VnfRecipe> resultList = query.list (); + List <VnfRecipe> resultList = query.list(); - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe not found", "CatalogDB", "getVnfRecipe", null); return null; } - Collections.sort (resultList, new MavenLikeVersioningComparator ()); - Collections.reverse (resultList); + Collections.sort(resultList, new MavenLikeVersioningComparator()); + Collections.reverse(resultList); - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null); - return resultList.get (0); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVnfRecipe", null); + return resultList.get(0); } /** @@ -1170,30 +1170,30 @@ public class CatalogDatabase implements Closeable { * @param action * @return VnfRecipe object or null if none found */ - public VnfRecipe getVnfRecipeByVfModuleId (String vnfType, String vfModuleId, String action) { + public VnfRecipe getVnfRecipeByVfModuleId(String vnfType, String vfModuleId, String action) { - StringBuilder hql = new StringBuilder ("FROM VnfRecipe WHERE vfModuleId = :vfModuleId and action = :action "); + StringBuilder hql = new StringBuilder("FROM VnfRecipe WHERE vfModuleId = :vfModuleId and action = :action "); - long startTime = System.currentTimeMillis (); - LOGGER.debug ("Catalog database - get VNF Recipe with vfModuleId " + vfModuleId); + long startTime = System.currentTimeMillis(); + LOGGER.debug("Catalog database - get VNF Recipe with vfModuleId " + vfModuleId); - Query query = getSession ().createQuery (hql.toString ()); - query.setParameter (VF_MODULE_MODEL_UUID, vfModuleId); - query.setParameter (ACTION, action); + Query query = getSession().createQuery(hql.toString ()); + query.setParameter(VF_MODULE_MODEL_UUID, vfModuleId); + query.setParameter(ACTION, action); @SuppressWarnings("unchecked") - List <VnfRecipe> resultList = query.list (); + List <VnfRecipe> resultList = query.list(); - if (resultList.isEmpty ()) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe Entry not found", "CatalogDB", "getVnfRecipeByVfModuleId", null); + if (resultList.isEmpty()) { + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF recipe Entry not found", "CatalogDB", "getVnfRecipeByVfModuleId", null); return null; } - Collections.sort (resultList, new MavenLikeVersioningComparator ()); - Collections.reverse (resultList); + Collections.sort(resultList, new MavenLikeVersioningComparator()); + Collections.reverse(resultList); - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF Recipe Entry found", "CatalogDB", "getVnfRecipeByVfModuleId", null); - return resultList.get (0); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully. VNF Recipe Entry found", "CatalogDB", "getVnfRecipeByVfModuleId", null); + return resultList.get(0); } public VfModule getVfModuleTypeByUuid(String modelCustomizationUuid) { @@ -1299,7 +1299,7 @@ public class CatalogDatabase implements Closeable { query.setParameter ("serviceModelInvariantUuid", serviceModelInvariantUuid); VnfResource vnfResource = null; try { - vnfResource = (VnfResource) query.uniqueResult (); + vnfResource = (VnfResource) query.uniqueResult(); } catch (org.hibernate.NonUniqueResultException nure) { LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: serviceModelInvariantUuid='" + serviceModelInvariantUuid); LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for serviceModelInvariantUuid=" + serviceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for serviceModelInvariantUuid==" + serviceModelInvariantUuid); @@ -1317,23 +1317,23 @@ public class CatalogDatabase implements Closeable { throw e; } if (vnfResource == null) { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "NotFound", "CatalogDB", "getVfModuleType", null); } else { - LOGGER.recordMetricEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null); + LOGGER.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully", "CatalogDB", "getVfModuleType", null); } return vnfResource; } public VnfResource getVnfResourceByVnfUuid(String vnfResourceModelInvariantUuid) { long startTime = System.currentTimeMillis(); - LOGGER.debug ("Catalog database - get vfModuleType with vnfResourceModelInvariantUuid " + vnfResourceModelInvariantUuid); + LOGGER.debug("Catalog database - get vfModuleType with vnfResourceModelInvariantUuid " + vnfResourceModelInvariantUuid); String hql = "FROM VnfResource WHERE vnfResourceModelInvariantUuid = :vnfResourceModelInvariantUuid"; Query query = getSession().createQuery(hql); - query.setParameter ("vnfResourceModelInvariantUuid", vnfResourceModelInvariantUuid); + query.setParameter("vnfResourceModelInvariantUuid", vnfResourceModelInvariantUuid); VnfResource vnfResource = null; try { - vnfResource = (VnfResource) query.uniqueResult (); + vnfResource = (VnfResource) query.uniqueResult(); } catch (org.hibernate.NonUniqueResultException nure) { LOGGER.debug("Non Unique Result Exception - the Catalog Database does not match a unique row - data integrity error: vnfResourceModelInvariantUuid='" + vnfResourceModelInvariantUuid); LOGGER.error(MessageEnum.GENERAL_EXCEPTION, " non unique result for vnfResourceModelInvariantUuid=" + vnfResourceModelInvariantUuid, "", "", MsoLogger.ErrorCode.DataError, "Non unique result for vnfResourceModelInvariantUuid==" + vnfResourceModelInvariantUuid); diff --git a/mso-catalog-db/src/test/java/org/openecomp/mso/db/catalog/test/CatalogDatabaseTest.java b/mso-catalog-db/src/test/java/org/openecomp/mso/db/catalog/test/CatalogDatabaseTest.java index 219e70ea87..e9f080b1dd 100644 --- a/mso-catalog-db/src/test/java/org/openecomp/mso/db/catalog/test/CatalogDatabaseTest.java +++ b/mso-catalog-db/src/test/java/org/openecomp/mso/db/catalog/test/CatalogDatabaseTest.java @@ -53,12 +53,7 @@ import org.openecomp.mso.db.catalog.beans.VnfResourceCustomization; import org.openecomp.mso.db.catalog.utils.RecordNotFoundException; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -1443,39 +1438,445 @@ public class CatalogDatabaseTest { VnfResource vnf = cd.getVnfResourceById(19299); } - @Test(expected = Exception.class) - public void getVfModuleModelNameTestException(){ - VfModule vnf = cd.getVfModuleModelName("tetes"); + @Test + public void getVfModuleModelName(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VfModule> list() throws Exception { + VfModule vfModule = new VfModule(); + vfModule.setModelUUID("123-uuid"); + return Arrays.asList(vfModule); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VfModule vfModule = cd.getVfModuleModelName("vfmodule"); + assertEquals("123-uuid", vfModule.getModelUUID()); } - @Test(expected = Exception.class) - public void getVfModuleModelName2TestException(){ - VfModule vnf = cd.getVfModuleModelName("tetes","4kidsl"); + @Test + public void getVfModuleModelNameExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VfModule> list() throws Exception { + return Arrays.asList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VfModule vfModule = cd.getVfModuleModelName("vfmodule"); + assertEquals(null, vfModule); } - @Test(expected = Exception.class) - public void ggetVfModuleCustomizationByModelNameTestException(){ - VfModuleCustomization vnf = cd.getVfModuleCustomizationByModelName("tetes"); + @Test + public void getVfModuleModelNameTest() { + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + VfModule vfModule = new VfModule(); + vfModule.setModelUUID("123-uuid"); + return vfModule; + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleModelName("tetes","4kidsl"); + assertEquals("123-uuid", vfModule.getModelUUID()); } - @Test(expected = Exception.class) - public void getNetworkResourceTestException(){ - NetworkResource vnf = cd.getNetworkResource("tetes"); + @Test(expected = NonUniqueResultException.class) + public void getVfModuleModelNameNURExceptionTest() { + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new NonUniqueResultException(-1); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleModelName("tetes","4kidsl"); } - @Test(expected = Exception.class) - public void getVnfRecipeTestException(){ - VnfRecipe vnf = cd.getVnfRecipe("tetes","ergfedrf","4993493"); + @Test(expected = HibernateException.class) + public void getVfModuleModelNameHibernateExceptionTest() { + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new HibernateException("hibernate exception"); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleModelName("tetes","4kidsl"); } @Test(expected = Exception.class) - public void getVnfRecipe2TestException(){ - VnfRecipe vnf = cd.getVnfRecipe("tetes","4993493"); + public void getVfModuleModelNameGenericExceptionTest() { + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() throws Exception { + throw new Exception(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleModelName("tetes","4kidsl"); } - @Test(expected = Exception.class) - public void getVnfRecipeByVfModuleIdTestException(){ - VnfRecipe vnf = cd.getVnfRecipeByVfModuleId("tetes","4993493","vnf"); + @Test + public void ggetVfModuleCustomizationByModelNameTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VfModuleCustomization> list() throws Exception { + VfModuleCustomization vfModuleCustomization = new VfModuleCustomization(); + vfModuleCustomization.setVfModuleModelUuid("123-uuid"); + return Arrays.asList(vfModuleCustomization); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VfModuleCustomization vfModuleCustomization = cd.getVfModuleCustomizationByModelName("tetes"); + assertEquals("123-uuid", vfModuleCustomization.getVfModuleModelUuid()); + } + + @Test + public void ggetVfModuleCustomizationByModelNameEmptyTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VfModuleCustomization> list() throws Exception { + return Arrays.asList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VfModuleCustomization vfModuleCustomization = cd.getVfModuleCustomizationByModelName("tetes"); + assertEquals(null, vfModuleCustomization); + } + + @Test + public void getNetworkResourceTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<NetworkResource> list() throws Exception { + NetworkResource networkResource = new NetworkResource(); + networkResource.setModelUUID("123-uuid"); + return Arrays.asList(networkResource); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + NetworkResource networkResource = cd.getNetworkResource("tetes"); + assertEquals("123-uuid", networkResource.getModelUUID()); + } + + @Test + public void getNetworkResourceTestEmptyException(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<NetworkResource> list() throws Exception { + return Arrays.asList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + NetworkResource networkResource = cd.getNetworkResource("tetes"); + assertEquals(null, networkResource); + } + + @Test + public void getVnfRecipeTest(){ + + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + VnfRecipe vnfRecipe = new VnfRecipe(); + vnfRecipe.setVfModuleId("123-id"); + return Arrays.asList(vnfRecipe); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfRecipe vnfRecipe = cd.getVnfRecipe("tetes","ergfedrf","4993493"); + assertEquals("123-id", vnfRecipe.getVfModuleId()); + } + + @Test + public void getVnfRecipeEmptyTest(){ + + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + return Collections.emptyList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfRecipe vnfRecipe = cd.getVnfRecipe("tetes","ergfedrf","4993493"); + assertEquals(null, vnfRecipe); + } + + @Test + public void getVnfRecipe2Test(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + VnfRecipe vnfRecipe = new VnfRecipe(); + vnfRecipe.setId(1); + return Arrays.asList(vnfRecipe); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfRecipe vnfRecipe = cd.getVnfRecipe("tetes","4993493"); + assertEquals(1, vnfRecipe.getId()); + } + + @Test + public void getVnfRecipe2EmptyTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + return Collections.emptyList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfRecipe vnfRecipe = cd.getVnfRecipe("tetes","4993493"); + assertEquals(null, vnfRecipe); + } + + @Test + public void getVnfRecipeByVfModuleIdTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + VnfRecipe vnfRecipe = new VnfRecipe(); + vnfRecipe.setId(1); + return Arrays.asList(vnfRecipe); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfRecipe vnfRecipe = cd.getVnfRecipeByVfModuleId("tetes","4993493","vnf"); + assertEquals(1, vnfRecipe.getId()); + } + + @Test + public void getVnfRecipeByVfModuleIdEmptyTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + @Mock + public List<VnfRecipe> list() throws Exception { + return Collections.emptyList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfRecipe vnfRecipe = cd.getVnfRecipeByVfModuleId("tetes","4993493","vnf"); + assertEquals(null, vnfRecipe); } @Test(expected = Exception.class) @@ -1487,18 +1888,284 @@ public class CatalogDatabaseTest { public void getVfModuleType2TestException(){ VfModule vnf = cd.getVfModuleType("4993493","vnf"); } - @Test(expected = Exception.class) - public void getVnfResourceByServiceUuidTestException(){ - VnfResource vnf = cd.getVnfResourceByServiceUuid("4993493"); + @Test + public void getVnfResourceByServiceUuidTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + VnfResource vnfResource = new VnfResource(); + vnfResource.setModelUuid("123-uuid"); + return vnfResource; + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfResource vnfResource = cd.getVnfResourceByServiceUuid("4993493"); + assertEquals("123-uuid", vnfResource.getModelUuid()); + } + + @Test(expected = NonUniqueResultException.class) + public void getVnfResourceByServiceUuidNURExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new NonUniqueResultException(-1); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfResource vnfResource = cd.getVnfResourceByServiceUuid("4993493"); + } + + @Test(expected = HibernateException.class) + public void getVnfResourceByServiceUuidHibernateExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new HibernateException("hibernate exception"); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfResource vnfResource = cd.getVnfResourceByServiceUuid("4993493"); } + @Test(expected = Exception.class) - public void getVnfResourceByVnfUuidTestException(){ - VnfResource vnf = cd.getVnfResourceByVnfUuid("4993493"); + public void getVnfResourceByServiceUuidExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() throws Exception { + throw new Exception(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + VnfResource vnfResource = cd.getVnfResourceByServiceUuid("4993493"); + } + + @Test + public void getVnfResourceByVnfUuidTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + VnfResource vnfResource = new VnfResource(); + vnfResource.setModelUuid("123-uuid"); + return vnfResource; + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfResource vnfResource = cd.getVnfResourceByVnfUuid("4993493"); + assertEquals("123-uuid", vnfResource.getModelUuid()); } + + @Test(expected = NonUniqueResultException.class) + public void getVnfResourceByVnfUuidNURExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new NonUniqueResultException(-1); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfResource vnfResource = cd.getVnfResourceByVnfUuid("4993493"); + } + + @Test(expected = HibernateException.class) + public void getVnfResourceByVnfUuidHibernateExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() { + throw new HibernateException("hibernate exception"); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfResource vnfResource = cd.getVnfResourceByVnfUuid("4993493"); + } + @Test(expected = Exception.class) - public void getVfModuleByModelInvariantUuidTestException(){ - VfModule vnf = cd.getVfModuleByModelInvariantUuid("4993493"); + public void getVnfResourceByVnfUuidExceptionTest(){ + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public Object uniqueResult() throws Exception { + throw new Exception(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VnfResource vnfResource = cd.getVnfResourceByVnfUuid("4993493"); + } + + @Test + public void getVfModuleByModelInvariantUuidTest(){ + + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public List<VfModule> list() throws Exception { + VfModule vfModule = new VfModule(); + vfModule.setModelUUID("123-uuid"); + return Arrays.asList(vfModule); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleByModelInvariantUuid("4993493"); + assertEquals("123-uuid", vfModule.getModelUUID()); } + + @Test + public void getVfModuleByModelInvariantUuidEmptyTest(){ + + MockUp<Query> mockUpQuery = new MockUp<Query>() { + + @Mock + public List<VfModule> list() throws Exception { + return Collections.emptyList(); + } + }; + + MockUp<Session> mockedSession = new MockUp<Session>() { + @Mock + public Query createQuery(String hql) { + return mockUpQuery.getMockInstance(); + } + }; + + new MockUp<CatalogDatabase>() { + @Mock + private Session getSession() { + return mockedSession.getMockInstance(); + } + }; + + VfModule vfModule = cd.getVfModuleByModelInvariantUuid("4993493"); + assertEquals(null, vfModule); + } + @Test(expected = Exception.class) public void getVfModuleByModelCustomizationUuidTestException(){ VfModuleCustomization vnf = cd.getVfModuleByModelCustomizationUuid("4993493"); |