diff options
Diffstat (limited to 'common/src')
80 files changed, 912 insertions, 1114 deletions
diff --git a/common/src/main/java/org/onap/so/client/HttpClient.java b/common/src/main/java/org/onap/so/client/HttpClient.java index b991e79d8c..6f13a86237 100644 --- a/common/src/main/java/org/onap/so/client/HttpClient.java +++ b/common/src/main/java/org/onap/so/client/HttpClient.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. @@ -24,15 +24,20 @@ import java.net.URL; import java.util.Map; import java.util.Optional; +import static org.apache.commons.lang3.StringUtils.*; + import org.onap.so.utils.TargetEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HttpClient extends RestClient { + protected final Logger log = LoggerFactory.getLogger(HttpClient.class); private TargetEntity targetEntity; - public HttpClient(URL host, String contentType, TargetEntity targetEntity) { + + HttpClient(URL host, String contentType, TargetEntity targetEntity) { super(host, contentType); this.targetEntity = targetEntity; - } @Override @@ -49,4 +54,34 @@ public class HttpClient extends RestClient { return Optional.empty(); } + /** + * Adds a basic authentication header to the request. + * @param auth the encrypted credentials + * @param key the key for decrypting the credentials + */ + @Override + public void addBasicAuthHeader(String auth, String key) { + if(isNotBlank(auth) && isNotBlank(key)){ + super.addBasicAuthHeader(auth, key); + }else{ + log.warn("Not adding basic auth to headers."); + } + } + + /** + * Adds an additional header to the header map + * @param encoded basic auth value + */ + public void addAdditionalHeader(String name, String value) { + try { + if(isNotBlank(name) && isNotBlank(value)){ + headerMap.put(name, value); + }else{ + log.warn("Not adding " + name + " to headers."); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + } diff --git a/common/src/main/java/org/onap/so/client/grm/GRMDefaultPropertiesImpl.java b/common/src/main/java/org/onap/so/client/HttpClientFactory.java index b38072e769..d02c18ff56 100644 --- a/common/src/main/java/org/onap/so/client/grm/GRMDefaultPropertiesImpl.java +++ b/common/src/main/java/org/onap/so/client/HttpClientFactory.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. * ================================================================================ * 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. @@ -17,47 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ +package org.onap.so.client; -package org.onap.so.client.grm; - -import java.net.MalformedURLException; import java.net.URL; - import javax.ws.rs.core.MediaType; +import org.onap.so.utils.TargetEntity; -public class GRMDefaultPropertiesImpl implements GRMProperties { - - public GRMDefaultPropertiesImpl() { - } - - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL("http://localhost:47389"); - } - - @Override - public String getSystemName() { - return "MSO"; - } - - @Override - public String getDefaultVersion() { - return "v1"; - } - - @Override - public String getUsername() { - return "gmruser"; - } +public class HttpClientFactory { - @Override - public String getPassword() { - return "cGFzc3dvcmQ="; - } + public HttpClient newJsonClient(URL host, TargetEntity targetEntity) { + return new HttpClient(host, MediaType.APPLICATION_JSON, targetEntity); + } - @Override - public String getContentType() { - return MediaType.APPLICATION_JSON; - } + public HttpClient newXmlClient(URL host, TargetEntity targetEntity) { + return new HttpClient(host, MediaType.APPLICATION_XML, targetEntity); + } + public HttpClient newTextXmlClient(URL host, TargetEntity targetEntity) { + return new HttpClient(host, MediaType.TEXT_XML, targetEntity); + } } diff --git a/common/src/main/java/org/onap/so/client/RestClient.java b/common/src/main/java/org/onap/so/client/RestClient.java index 1a453c6b2f..76134a42f4 100644 --- a/common/src/main/java/org/onap/so/client/RestClient.java +++ b/common/src/main/java/org/onap/so/client/RestClient.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. @@ -61,7 +61,7 @@ public abstract class RestClient { private static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json"; public static final String ECOMP_COMPONENT_NAME = "MSO"; - + private static final int MAX_PAYLOAD_SIZE = 1024 * 1024; private WebTarget webTarget; @@ -76,12 +76,12 @@ public abstract class RestClient { protected RestProperties props; protected RestClient(RestProperties props, Optional<URI> path) { - + headerMap = new HashMap<>(); try { host = props.getEndpoint(); } catch (MalformedURLException e) { - + throw new RuntimeException(e); } this.props = props; @@ -105,23 +105,23 @@ public abstract class RestClient { /** * Override method to return false to disable logging. - * + * * @return true - to enable logging, false otherwise */ protected boolean enableLogging() { return true; } - + /** * Override method to return custom value for max payload size. - * + * * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024 */ protected int getMaxPayloadSize() { return MAX_PAYLOAD_SIZE; } - + protected Builder getBuilder() { if (webTarget == null) { @@ -134,7 +134,7 @@ public abstract class RestClient { } return builder; } - + protected WebTarget getWebTarget() { return this.webTarget; } @@ -148,7 +148,7 @@ public abstract class RestClient { protected CommonObjectMapperProvider getCommonObjectMapperProvider() { return new CommonObjectMapperProvider(); } - + /** * Adds a basic authentication header to the request. * @param auth the encrypted credentials @@ -188,7 +188,7 @@ public abstract class RestClient { } CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider(); client.register(new JacksonJsonProvider(provider.getMapper())); - + jaxRsClientLogging = new JaxRsClientLogging(); jaxRsClientLogging.setTargetService(getTargetEntity()); client.register(jaxRsClientLogging); @@ -205,11 +205,11 @@ public abstract class RestClient { this.contentType = MediaType.APPLICATION_JSON; } } - + protected List<Predicate<Throwable>> retryOn() { - + List<Predicate<Throwable>> result = new ArrayList<>(); - + result.add(e -> { return e.getCause() instanceof SocketTimeoutException; }); @@ -266,26 +266,26 @@ public abstract class RestClient { public <T> T delete(Class<T> resultClass) { return format(method("DELETE", null), resultClass).orElse(null); } - + public <T> T delete(Object obj, Class<T> resultClass) { return format(method("DELETE", obj), resultClass).orElse(null); } - + public Response method(String method, Object entity) { RetryPolicy policy = new RetryPolicy(); - + List<Predicate<Throwable>> items = retryOn(); - + Predicate<Throwable> pred = items.stream().reduce(Predicate::or).orElse(x -> false); policy.retryOn(error -> pred.test(error)); - + policy.withDelay(this.props.getDelayBetweenRetries(), TimeUnit.MILLISECONDS) .withMaxRetries(this.props.getRetries()); - + return Failsafe.with(policy).get(buildRequest(method, entity)); } - + protected RestRequest buildRequest(String method, Object entity) { return new RestRequest(this, method, entity); } @@ -295,7 +295,7 @@ public abstract class RestClient { } return Optional.of(response.readEntity(resultClass)); } - + private <T> Optional<T> format(Response response, GenericType<T> resultClass) { if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) { return Optional.empty(); diff --git a/common/src/main/java/org/onap/so/client/RestClientSSL.java b/common/src/main/java/org/onap/so/client/RestClientSSL.java index ac4a8d1a7c..8369eba859 100644 --- a/common/src/main/java/org/onap/so/client/RestClientSSL.java +++ b/common/src/main/java/org/onap/so/client/RestClientSSL.java @@ -22,6 +22,7 @@ package org.onap.so.client; import java.io.FileInputStream; import java.net.URI; +import java.nio.file.Paths; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.util.Optional; @@ -72,7 +73,7 @@ public abstract class RestClientSSL extends RestClient { private KeyStore getKeyStore() { KeyStore ks = null; char[] password = System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY).toCharArray(); - try(FileInputStream fis = new FileInputStream(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY))) { + try(FileInputStream fis = new FileInputStream(Paths.get(System.getProperty(RestClientSSL.SSL_KEY_STORE_KEY)).normalize().toString())) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(fis, password); diff --git a/common/src/main/java/org/onap/so/client/aai/AAINamespaceConstants.java b/common/src/main/java/org/onap/so/client/aai/AAINamespaceConstants.java index 242fd41b19..9d2c3a8b1b 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAINamespaceConstants.java +++ b/common/src/main/java/org/onap/so/client/aai/AAINamespaceConstants.java @@ -22,10 +22,10 @@ package org.onap.so.client.aai; public class AAINamespaceConstants { - protected static final String CLOUD_INFRASTRUCTURE = "/cloud-infrastructure"; - protected static final String NETWORK = "/network"; - protected static final String BUSINESS = "/business"; - protected static final String SERVICE_DESIGN_AND_CREATION = "/service-design-and-creation"; + public static final String CLOUD_INFRASTRUCTURE = "/cloud-infrastructure"; + public static final String NETWORK = "/network"; + public static final String BUSINESS = "/business"; + public static final String SERVICE_DESIGN_AND_CREATION = "/service-design-and-creation"; } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java index 4f3816ad90..12e0ebe691 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java @@ -20,37 +20,43 @@ package org.onap.so.client.aai; -import org.onap.aai.domain.yang.NetworkTechnologies; +import java.io.Serializable; + import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals; import org.onap.so.constants.Defaults; import com.google.common.base.CaseFormat; -public enum AAIObjectPlurals implements GraphInventoryObjectPlurals { +public class AAIObjectPlurals implements GraphInventoryObjectPlurals, Serializable { - CUSTOMER(AAINamespaceConstants.BUSINESS, "/customers"), - GENERIC_VNF(AAINamespaceConstants.NETWORK, "/generic-vnfs"), - PSERVER(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/pservers"), - P_INTERFACE(AAIObjectType.PSERVER.uriTemplate(), "/p-interfaces"), - L3_NETWORK(AAINamespaceConstants.NETWORK, "/l3-networks"), - NETWORK_POLICY(AAINamespaceConstants.NETWORK, "/network-policies"), - VPN_BINDING(AAINamespaceConstants.NETWORK, "/vpn-bindings"), - SERVICE_SUBSCRIPTION(AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions"), - SERVICE_INSTANCE(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances"), - OWNING_ENTITY(AAINamespaceConstants.BUSINESS, "/owning-entities"), - VOLUME_GROUP(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups"), - AVAILIBILITY_ZONE(AAIObjectType.CLOUD_REGION.uriTemplate(), "/availability-zones"), - VF_MODULE(AAIObjectType.GENERIC_VNF.uriTemplate(), "/vf-modules"), - CONFIGURATION(AAINamespaceConstants.NETWORK, "/configurations"), - DEFAULT_TENANT(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants"), - NETWORK_TECHNOLOGY(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/network-technologies"), - LOGICAL_LINK(AAINamespaceConstants.NETWORK, "/logical-links"); + private static final long serialVersionUID = 5312713297525740746L; + + public static final AAIObjectPlurals CUSTOMER = new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/customers", "customer"); + public static final AAIObjectPlurals GENERIC_VNF = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/generic-vnfs", "generic-vnf"); + public static final AAIObjectPlurals PORT_GROUP = new AAIObjectPlurals(AAIObjectType.VCE.uriTemplate(), "/port-groups", "port-group"); + public static final AAIObjectPlurals PSERVER = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/pservers", "pserver"); + public static final AAIObjectPlurals P_INTERFACE = new AAIObjectPlurals(AAIObjectType.PSERVER.uriTemplate(), "/p-interfaces", "p-interface"); + public static final AAIObjectPlurals L3_NETWORK = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/l3-networks", "l3-network"); + public static final AAIObjectPlurals NETWORK_POLICY = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/network-policies", "network-policy"); + public static final AAIObjectPlurals VPN_BINDING = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/vpn-bindings", "vpn-binding"); + public static final AAIObjectPlurals SERVICE_SUBSCRIPTION = new AAIObjectPlurals(AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions", "service-subscription"); + public static final AAIObjectPlurals SERVICE_INSTANCE = new AAIObjectPlurals(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances", "service-instance"); + public static final AAIObjectPlurals OWNING_ENTITY = new AAIObjectPlurals(AAINamespaceConstants.BUSINESS, "/owning-entities", "owning-entity"); + public static final AAIObjectPlurals VOLUME_GROUP = new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups", "volume-group"); + public static final AAIObjectPlurals AVAILIBILITY_ZONE = new AAIObjectPlurals(AAIObjectType.CLOUD_REGION.uriTemplate(), "/availability-zones", "availability-zone"); + public static final AAIObjectPlurals VF_MODULE = new AAIObjectPlurals(AAIObjectType.GENERIC_VNF.uriTemplate(), "/vf-modules", "vf-module"); + public static final AAIObjectPlurals CONFIGURATION = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/configurations", "configuration"); + public static final AAIObjectPlurals DEFAULT_TENANT = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants", "default-tenant"); + public static final AAIObjectPlurals NETWORK_TECHNOLOGY = new AAIObjectPlurals(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/network-technologies", "network-technology"); + public static final AAIObjectPlurals LOGICAL_LINK = new AAIObjectPlurals(AAINamespaceConstants.NETWORK, "/logical-links", "logical-link"); private final String uriTemplate; private final String partialUri; - private AAIObjectPlurals(String parentUri, String partialUri) { + private final String name; + protected AAIObjectPlurals(String parentUri, String partialUri, String name) { this.uriTemplate = parentUri + partialUri; this.partialUri = partialUri; + this.name = name; } @Override @@ -74,6 +80,6 @@ public enum AAIObjectPlurals implements GraphInventoryObjectPlurals { } @Override public String typeName(CaseFormat format) { - return CaseFormat.UPPER_UNDERSCORE.to(format, this.name()); + return CaseFormat.LOWER_HYPHEN.to(format, this.name); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index 51d09006db..a6a9acfadd 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -20,10 +20,17 @@ package org.onap.so.client.aai; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.net.URL; import java.util.HashMap; import java.util.Map; +import java.util.Set; + +import javax.annotation.Priority; import org.onap.aai.annotations.Metadata; +import org.onap.aai.domain.yang.AggregateRoute; import org.onap.aai.domain.yang.AllottedResource; import org.onap.aai.domain.yang.CloudRegion; import org.onap.aai.domain.yang.Collection; @@ -31,6 +38,7 @@ import org.onap.aai.domain.yang.Complex; import org.onap.aai.domain.yang.Configuration; import org.onap.aai.domain.yang.Connector; import org.onap.aai.domain.yang.Customer; +import org.onap.aai.domain.yang.Device; import org.onap.aai.domain.yang.ExtAaiNetwork; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.InstanceGroup; @@ -44,13 +52,14 @@ import org.onap.aai.domain.yang.OwningEntity; import org.onap.aai.domain.yang.PInterface; import org.onap.aai.domain.yang.PhysicalLink; import org.onap.aai.domain.yang.Platform; +import org.onap.aai.domain.yang.Pnf; +import org.onap.aai.domain.yang.PortGroup; import org.onap.aai.domain.yang.Project; import org.onap.aai.domain.yang.Pserver; -import org.onap.aai.domain.yang.RouteTableReferences; +import org.onap.aai.domain.yang.RouteTableReference; import org.onap.aai.domain.yang.ServiceInstance; import org.onap.aai.domain.yang.ServiceSubscription; import org.onap.aai.domain.yang.SpPartner; -import org.onap.aai.domain.yang.Device; import org.onap.aai.domain.yang.Subnet; import org.onap.aai.domain.yang.Tenant; import org.onap.aai.domain.yang.TunnelXconnect; @@ -63,75 +72,115 @@ import org.onap.aai.domain.yang.VpnBinding; import org.onap.aai.domain.yang.Vserver; import org.onap.so.client.graphinventory.GraphInventoryObjectType; import org.onap.so.constants.Defaults; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; import com.google.common.base.CaseFormat; -public enum AAIObjectType implements GraphInventoryObjectType { +public class AAIObjectType implements GraphInventoryObjectType, Serializable { + + private static final long serialVersionUID = -2877184776691514600L; + private static Map<String, AAIObjectType> map = new HashMap<>(); - DEFAULT_CLOUD_REGION(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/{cloud-region-id}"), - CUSTOMER(AAINamespaceConstants.BUSINESS, Customer.class), - GENERIC_QUERY("/search", "/generic-query"), - BULK_PROCESS("/bulkprocess", ""), - SINGLE_TRANSACTION("/bulk/single-transaction", ""), - GENERIC_VNF(AAINamespaceConstants.NETWORK, GenericVnf.class), - VF_MODULE(AAIObjectType.GENERIC_VNF.uriTemplate(), VfModule.class), - L3_NETWORK(AAINamespaceConstants.NETWORK, L3Network.class), - NETWORK_POLICY(AAINamespaceConstants.NETWORK, NetworkPolicy.class), - NODES_QUERY("/search", "/nodes-query"), - CUSTOM_QUERY("/query", ""), - ROUTE_TABLE_REFERENCE(AAINamespaceConstants.NETWORK, RouteTableReferences.class), - DEFAULT_TENANT(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants/tenant/{tenant-id}"), - VCE(AAINamespaceConstants.NETWORK, Vce.class), - VPN_BINDING(AAINamespaceConstants.NETWORK, VpnBinding.class), - CONFIGURATION(AAINamespaceConstants.NETWORK, Configuration.class), - PSERVER(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Pserver.class), - SERVICE_SUBSCRIPTION(AAIObjectType.CUSTOMER.uriTemplate(), ServiceSubscription.class), - SERVICE_INSTANCE(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), ServiceInstance.class), - PROJECT(AAINamespaceConstants.BUSINESS, Project.class), - LINE_OF_BUSINESS(AAINamespaceConstants.BUSINESS, LineOfBusiness.class), - PLATFORM(AAINamespaceConstants.BUSINESS, Platform.class), - OWNING_ENTITY(AAINamespaceConstants.BUSINESS, OwningEntity.class), - ALLOTTED_RESOURCE(AAIObjectType.SERVICE_INSTANCE.uriTemplate(), AllottedResource.class), - PNF(AAINamespaceConstants.NETWORK, "/pnfs/pnf/{pnf-name}"), - OPERATIONAL_ENVIRONMENT(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, OperationalEnvironment.class), - CLOUD_REGION(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, CloudRegion.class), - TENANT(AAIObjectType.CLOUD_REGION.uriTemplate(), Tenant.class), - VOLUME_GROUP(AAIObjectType.CLOUD_REGION.uriTemplate(), VolumeGroup.class), - VSERVER(AAIObjectType.TENANT.uriTemplate(), Vserver.class), - MODEL_VER(AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", ModelVer.class), - TUNNEL_XCONNECT(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), TunnelXconnect.class), - P_INTERFACE(AAIObjectType.PSERVER.uriTemplate(), PInterface.class), - PHYSICAL_LINK(AAINamespaceConstants.NETWORK, PhysicalLink.class), - INSTANCE_GROUP(AAINamespaceConstants.NETWORK, InstanceGroup.class), - COLLECTION(AAINamespaceConstants.NETWORK, Collection.class), - VNFC(AAINamespaceConstants.NETWORK, Vnfc.class), - VLAN_TAG(AAINamespaceConstants.NETWORK, VlanTag.class), - COMPLEX(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Complex.class), - CONNECTOR(AAINamespaceConstants.BUSINESS, Connector.class), - NETWORK_TECHNOLOGY(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, NetworkTechnology.class), - SUBNET(AAIObjectType.L3_NETWORK.uriTemplate(), Subnet.class), - SP_PARTNER(AAINamespaceConstants.BUSINESS, SpPartner.class), - DEVICE(AAINamespaceConstants.NETWORK, Device.class), - EXT_AAI_NETWORK(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class), - UNKNOWN("", ""); + public static final AAIObjectType DEFAULT_CLOUD_REGION = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/{cloud-region-id}", "default-cloud-region"); + public static final AAIObjectType CUSTOMER = new AAIObjectType(AAINamespaceConstants.BUSINESS, Customer.class); + public static final AAIObjectType GENERIC_QUERY = new AAIObjectType("/search", "/generic-query", "generic-query"); + public static final AAIObjectType BULK_PROCESS = new AAIObjectType("/bulkprocess", "", "bulkprocess"); + public static final AAIObjectType SINGLE_TRANSACTION = new AAIObjectType("/bulk/single-transaction", "", "single-transaction"); + public static final AAIObjectType GENERIC_VNF = new AAIObjectType(AAINamespaceConstants.NETWORK, GenericVnf.class); + public static final AAIObjectType VF_MODULE = new AAIObjectType(AAIObjectType.GENERIC_VNF.uriTemplate(), VfModule.class); + public static final AAIObjectType L3_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, L3Network.class); + public static final AAIObjectType NETWORK_POLICY = new AAIObjectType(AAINamespaceConstants.NETWORK, NetworkPolicy.class); + public static final AAIObjectType NODES_QUERY = new AAIObjectType("/search", "/nodes-query", "nodes-query"); + public static final AAIObjectType CUSTOM_QUERY = new AAIObjectType("/query", "", "query"); + public static final AAIObjectType ROUTE_TABLE_REFERENCE = new AAIObjectType(AAINamespaceConstants.NETWORK, RouteTableReference.class); + public static final AAIObjectType DEFAULT_TENANT = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/" + Defaults.CLOUD_OWNER + "/AAIAIC25", "/tenants/tenant/{tenant-id}", "default-tenant"); + public static final AAIObjectType VCE = new AAIObjectType(AAINamespaceConstants.NETWORK, Vce.class); + public static final AAIObjectType PORT_GROUP = new AAIObjectType(AAIObjectType.VCE.uriTemplate(), PortGroup.class); + public static final AAIObjectType VPN_BINDING = new AAIObjectType(AAINamespaceConstants.NETWORK, VpnBinding.class); + public static final AAIObjectType CONFIGURATION = new AAIObjectType(AAINamespaceConstants.NETWORK, Configuration.class); + public static final AAIObjectType PSERVER = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Pserver.class); + public static final AAIObjectType SERVICE_SUBSCRIPTION = new AAIObjectType(AAIObjectType.CUSTOMER.uriTemplate(), ServiceSubscription.class); + public static final AAIObjectType SERVICE_INSTANCE = new AAIObjectType(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), ServiceInstance.class); + public static final AAIObjectType PROJECT = new AAIObjectType(AAINamespaceConstants.BUSINESS, Project.class); + public static final AAIObjectType LINE_OF_BUSINESS = new AAIObjectType(AAINamespaceConstants.BUSINESS, LineOfBusiness.class); + public static final AAIObjectType PLATFORM = new AAIObjectType(AAINamespaceConstants.BUSINESS, Platform.class); + public static final AAIObjectType OWNING_ENTITY = new AAIObjectType(AAINamespaceConstants.BUSINESS, OwningEntity.class); + public static final AAIObjectType ALLOTTED_RESOURCE = new AAIObjectType(AAIObjectType.SERVICE_INSTANCE.uriTemplate(), AllottedResource.class); + public static final AAIObjectType PNF = new AAIObjectType(AAINamespaceConstants.NETWORK, Pnf.class); + public static final AAIObjectType OPERATIONAL_ENVIRONMENT = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, OperationalEnvironment.class); + public static final AAIObjectType CLOUD_REGION = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, CloudRegion.class); + public static final AAIObjectType TENANT = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Tenant.class); + public static final AAIObjectType VOLUME_GROUP = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), VolumeGroup.class); + public static final AAIObjectType VSERVER = new AAIObjectType(AAIObjectType.TENANT.uriTemplate(), Vserver.class); + public static final AAIObjectType MODEL_VER = new AAIObjectType(AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", ModelVer.class); + public static final AAIObjectType TUNNEL_XCONNECT = new AAIObjectType(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), TunnelXconnect.class); + public static final AAIObjectType P_INTERFACE = new AAIObjectType(AAIObjectType.PSERVER.uriTemplate(), PInterface.class); + public static final AAIObjectType PHYSICAL_LINK = new AAIObjectType(AAINamespaceConstants.NETWORK, PhysicalLink.class); + public static final AAIObjectType INSTANCE_GROUP = new AAIObjectType(AAINamespaceConstants.NETWORK, InstanceGroup.class); + public static final AAIObjectType COLLECTION = new AAIObjectType(AAINamespaceConstants.NETWORK, Collection.class); + public static final AAIObjectType VNFC = new AAIObjectType(AAINamespaceConstants.NETWORK, Vnfc.class); + public static final AAIObjectType VLAN_TAG = new AAIObjectType(AAINamespaceConstants.NETWORK, VlanTag.class); + public static final AAIObjectType COMPLEX = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, Complex.class); + public static final AAIObjectType CONNECTOR = new AAIObjectType(AAINamespaceConstants.BUSINESS, Connector.class); + public static final AAIObjectType NETWORK_TECHNOLOGY = new AAIObjectType(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, NetworkTechnology.class); + public static final AAIObjectType SUBNET = new AAIObjectType(AAIObjectType.L3_NETWORK.uriTemplate(), Subnet.class); + public static final AAIObjectType SP_PARTNER = new AAIObjectType(AAINamespaceConstants.BUSINESS, SpPartner.class); + public static final AAIObjectType DEVICE = new AAIObjectType(AAINamespaceConstants.NETWORK, Device.class); + public static final AAIObjectType EXT_AAI_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class); + public static final AAIObjectType AGGREGATE_ROUTE = new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class); + public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown"); private final String uriTemplate; private final String parentUri; private final String partialUri; private final Class<?> aaiObjectClass; - private static Map<String, AAIObjectType> map = new HashMap<>(); - private AAIObjectType(String parentUri, String partialUri) { + private final String name; + + static { + /* Locate any AAIObjectTypes on the classpath and add them to our map */ + java.util.Collection<URL> packages = ClasspathHelper.forPackage(""); + Reflections r = new Reflections(new ConfigurationBuilder().setUrls(packages).setScanners(new SubTypesScanner())); + + Set<Class<? extends AAIObjectType>> resources = + r.getSubTypesOf(AAIObjectType.class); + try { + for (Class<? extends AAIObjectType> customTypeClass : resources) { + AAIObjectType customType; + customType = customTypeClass.newInstance(); + } + } catch (InstantiationException | IllegalAccessException e) { + } + } + protected AAIObjectType() { + this.parentUri = null; + this.partialUri = null; + this.uriTemplate = null; + this.aaiObjectClass = null; + this.name = null; + } + protected AAIObjectType(String parentUri, String partialUri, String name) { this.parentUri = parentUri; this.partialUri = partialUri; this.uriTemplate = parentUri + partialUri; this.aaiObjectClass = null; + this.name = name; + if (!AAIObjectType.map.containsKey(name)) { + AAIObjectType.map.put(name, this); + } } - private AAIObjectType(String parentUri, Class<?> aaiObjectClass) { + protected AAIObjectType(String parentUri, Class<?> aaiObjectClass) { this.parentUri = parentUri; this.partialUri = removeParentUri(aaiObjectClass, parentUri); this.uriTemplate = parentUri + partialUri; this.aaiObjectClass = aaiObjectClass; + this.name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, aaiObjectClass.getSimpleName()); + if (!AAIObjectType.map.containsKey(name)) { + AAIObjectType.map.put(name, this); + } } @Override @@ -140,12 +189,6 @@ public enum AAIObjectType implements GraphInventoryObjectType { } public static AAIObjectType fromTypeName(String name) { - if (map.isEmpty()) { - for (AAIObjectType type : AAIObjectType.values()) { - map.put(type.typeName(), type); - } - } - if (map.containsKey(name)) { return map.get(name); } else { @@ -158,12 +201,7 @@ public enum AAIObjectType implements GraphInventoryObjectType { } @Override public String typeName(CaseFormat format) { - String enumName = this.name(); - if (this.equals(AAIObjectType.DEFAULT_CLOUD_REGION) || this.equals(AAIObjectType.DEFAULT_TENANT)) { - enumName = enumName.replace("DEFAULT_", ""); - } - - return CaseFormat.UPPER_UNDERSCORE.to(format, enumName); + return CaseFormat.LOWER_HYPHEN.to(format, this.name.replace("default-", "")); } @Override diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java index ac6e939e9e..4f235c35f1 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClient.java @@ -20,25 +20,17 @@ package org.onap.so.client.aai; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; - import java.net.URI; -import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.regex.Pattern; import javax.ws.rs.core.Response; import org.onap.so.client.ResponseExceptionMapper; import org.onap.so.client.RestClientSSL; -import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException; import org.onap.so.client.policy.CommonObjectMapperProvider; -import org.onap.so.jsonpath.JsonPathUtil; import org.onap.so.utils.TargetEntity; -import com.fasterxml.jackson.core.JsonProcessingException; - public class AAIRestClient extends RestClientSSL { private final AAIProperties aaiProperties; @@ -58,7 +50,7 @@ public class AAIRestClient extends RestClientSSL { @Override protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("X-FromAppId", "MSO"); + headerMap.put("X-FromAppId", aaiProperties.getSystemName()); headerMap.put("X-TransactionId", requestId); String auth = aaiProperties.getAuth(); String key = aaiProperties.getKey(); diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java index 831e43841a..62d7d565ac 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClientI.java @@ -31,11 +31,11 @@ public interface AAIRestClientI { List<Pserver> getPhysicalServerByVnfId(String vnfId) throws IOException; - void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) throws Exception; + void updateMaintenceFlagVnfId(String vnfId, boolean inMaint); - GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) throws Exception; + GenericVnf getVnfByName(String vnfId); - Optional<Pnf> getPnfByName(String pnfId, String transactionLoggingUuid) throws Exception; + Optional<Pnf> getPnfByName(String pnfId); - void createPnf(String pnfId, String transactionLoggingUuid, Pnf pnf) throws IOException; + void createPnf(String pnfId, Pnf pnf); } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java index bcc7d8ba16..b2c7fcc062 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIRestClientImpl.java @@ -39,14 +39,13 @@ import org.onap.so.client.graphinventory.Format; public class AAIRestClientImpl implements AAIRestClientI { - private static final AAIVersion ENDPOINT_VERSION = AAIVersion.V10; private static final String PSERVER_VNF_QUERY = "pservers-fromVnf"; @Override public List<Pserver> getPhysicalServerByVnfId(String vnfId) throws IOException { List<AAIResourceUri> startNodes = new ArrayList<>(); startNodes.add(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); - String jsonInput = new AAIQueryClient(ENDPOINT_VERSION) + String jsonInput = new AAIQueryClient() .query(Format.RESOURCE, new CustomQuery(startNodes, PSERVER_VNF_QUERY)); return this.getListOfPservers(jsonInput); @@ -66,23 +65,23 @@ public class AAIRestClientImpl implements AAIRestClientI { } @Override - public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint, String transactionLoggingUuid) { + public void updateMaintenceFlagVnfId(String vnfId, boolean inMaint) { GenericVnf genericVnf = new GenericVnf(); genericVnf.setInMaint(inMaint); - new AAIResourcesClient(ENDPOINT_VERSION) + new AAIResourcesClient() .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId), genericVnf); } @Override - public GenericVnf getVnfByName(String vnfId, String transactionLoggingUuid) { - return new AAIResourcesClient(ENDPOINT_VERSION) + public GenericVnf getVnfByName(String vnfId) { + return new AAIResourcesClient() .get(GenericVnf.class, AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)).orElse(null); } @Override - public Optional<Pnf> getPnfByName(String pnfId, String transactionLoggingUuid) { - Response response = new AAIResourcesClient(ENDPOINT_VERSION) + public Optional<Pnf> getPnfByName(String pnfId) { + Response response = new AAIResourcesClient() .getFullResponse(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId)); if (response.getStatus() != 200) { return Optional.empty(); @@ -92,8 +91,8 @@ public class AAIRestClientImpl implements AAIRestClientI { } @Override - public void createPnf(String pnfId, String transactionLoggingUuid, Pnf pnf) { - new AAIResourcesClient(ENDPOINT_VERSION) + public void createPnf(String pnfId, Pnf pnf) { + new AAIResourcesClient() .createIfNotExists(AAIUriFactory.createResourceUri(AAIObjectType.PNF, pnfId), Optional.of(pnf)); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java b/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java index 8921e4bbbe..f7c9fe8362 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIUpdator.java @@ -20,12 +20,10 @@ package org.onap.so.client.aai; -import java.io.IOException; - public interface AAIUpdator { - void updateVnfToLocked(String vnfName, String uuid) throws IOException, Exception; + void updateVnfToLocked(String vnfName) throws Exception; - void updateVnfToUnLocked(String vnfName, String uuid) throws IOException, Exception; + void updateVnfToUnLocked(String vnfName) throws Exception; } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java index a971fded0e..2697e4a9e8 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIUpdatorImpl.java @@ -23,7 +23,6 @@ package org.onap.so.client.aai; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - public class AAIUpdatorImpl implements AAIUpdator { @Autowired @@ -39,13 +38,13 @@ public class AAIUpdatorImpl implements AAIUpdator { } @Override - public void updateVnfToLocked(String vnfId, String uuid) throws Exception { - client.updateMaintenceFlagVnfId(vnfId, true, uuid); + public void updateVnfToLocked(String vnfId) throws Exception { + client.updateMaintenceFlagVnfId(vnfId, true); } @Override - public void updateVnfToUnLocked(String vnfId, String uuid) throws Exception { - client.updateMaintenceFlagVnfId(vnfId, false, uuid); + public void updateVnfToUnLocked(String vnfId) throws Exception { + client.updateMaintenceFlagVnfId(vnfId, false); } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidator.java b/common/src/main/java/org/onap/so/client/aai/AAIValidator.java index bf6485a631..18252d548b 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIValidator.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIValidator.java @@ -24,9 +24,9 @@ import java.io.IOException; public interface AAIValidator { - boolean isPhysicalServerLocked(String hostName, String transactionLoggingUuid) throws IOException; + boolean isPhysicalServerLocked(String hostName) throws IOException; - boolean isVNFLocked(String vnfId, String transactionLoggingUuid) throws IOException, Exception; + boolean isVNFLocked(String vnfId); }
\ No newline at end of file diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java index e416da172c..6ece8a2620 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java @@ -46,7 +46,7 @@ public class AAIValidatorImpl implements AAIValidator { } @Override - public boolean isPhysicalServerLocked(String vnfId, String transactionLoggingUuid) throws IOException { + public boolean isPhysicalServerLocked(String vnfId) throws IOException { List<Pserver> pservers; boolean isLocked = false; pservers = client.getPhysicalServerByVnfId(vnfId); @@ -58,9 +58,9 @@ public class AAIValidatorImpl implements AAIValidator { } @Override - public boolean isVNFLocked(String vnfId, String transactionLoggingUuid) throws Exception { + public boolean isVNFLocked(String vnfId) { boolean isLocked = false; - GenericVnf genericVnf = client.getVnfByName(vnfId, transactionLoggingUuid); + GenericVnf genericVnf = client.getVnfByName(vnfId); if (genericVnf.isInMaint()) isLocked = true; diff --git a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java index de418f32c0..d93d656403 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java @@ -23,13 +23,9 @@ package org.onap.so.client.aai; import org.onap.so.client.graphinventory.GraphInventoryVersion; public enum AAIVersion implements GraphInventoryVersion { - V8("v8"), - V9("v9"), - V10("v10"), - V11("v11"), - V12("v12"), V13("v13"), - V14("v14"); + V14("v14"), + V15("v15"); public final static AAIVersion LATEST = AAIVersion.values()[AAIVersion.values().length - 1]; private final String value; diff --git a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java index 45621f09a6..77ea9bcdfe 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java @@ -26,9 +26,11 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; -import org.apache.log4j.Logger; + import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.onap.so.jsonpath.JsonPathUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; @@ -39,7 +41,7 @@ public class AAIResultWrapper implements Serializable { private static final long serialVersionUID = 5895841925807816737L; private final String jsonBody; private final ObjectMapper mapper; - private final transient Logger logger = Logger.getLogger(AAIResultWrapper.class); + private final transient Logger logger = LoggerFactory.getLogger(AAIResultWrapper.class); public AAIResultWrapper(String json) { this.jsonBody = json; diff --git a/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java b/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java index bab145b3fd..e907bc97d7 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/Relationships.java @@ -91,11 +91,7 @@ public class Relationships { final String relatedTo = (String)relationship.get("related-to"); if (p.test(relatedTo)) { AAIObjectType type; - try { - type = AAIObjectType.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, relatedTo)); - } catch (IllegalArgumentException e) { - type = AAIObjectType.UNKNOWN; - } + type = AAIObjectType.fromTypeName(relatedTo); final String relatedLink = (String)relationship.get("related-link"); result.add(AAIUriFactory.createResourceFromExistingURI(type, UriBuilder.fromPath(relatedLink).build())); diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java index 884f8c6ac4..324bb8abad 100644 --- a/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java +++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java @@ -22,7 +22,6 @@ package org.onap.so.client.aai.entities.uri; import java.io.IOException; import java.net.URI; -import java.util.Arrays; import java.util.Map; import java.util.Optional; @@ -38,6 +37,7 @@ import org.onap.so.client.graphinventory.entities.uri.HttpAwareUri; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriComputationException; import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException; +import org.onap.so.client.graphinventory.exceptions.IncorrectNumberOfUriKeys; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -118,6 +118,18 @@ public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri @Override public abstract HttpLookupUri clone(); + @Override + public void validateValuesSize(String template, Object... values) { + try { + super.validateValuesSize(template, values); + } catch (IncorrectNumberOfUriKeys e) { + if (values.length == 1) { + //Special case where we perform an http look up + } else { + throw e; + } + } + } public AAIResourcesClient getResourcesClient() { return new AAIResourcesClient(); } diff --git a/common/src/main/java/org/onap/so/client/aai/objects/AAIOperationalEnvironment.java b/common/src/main/java/org/onap/so/client/aai/objects/AAIOperationalEnvironment.java deleted file mode 100644 index 02d8d56867..0000000000 --- a/common/src/main/java/org/onap/so/client/aai/objects/AAIOperationalEnvironment.java +++ /dev/null @@ -1,159 +0,0 @@ -/*- - * ============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.onap.so.client.aai.objects; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ -"operational-environment-id", -"operational-environment-name", -"operational-environment-type", -"operational-environment-status", -"tenant-context", -"workload-context", -"resource-version" -}) -public class AAIOperationalEnvironment { - -@JsonProperty("operational-environment-id") -private String operationalEnvironmentId; -@JsonProperty("operational-environment-name") -private String operationalEnvironmentName; -@JsonProperty("operational-environment-type") -private String operationalEnvironmentType; -@JsonProperty("operational-environment-status") -private String operationalEnvironmentStatus; -@JsonProperty("tenant-context") -private String tenantContext; -@JsonProperty("workload-context") -private String workloadContext; -@JsonProperty("resource-version") -private String resourceVersion; - -@JsonProperty("operational-environment-id") -public String getOperationalEnvironmentId() { -return operationalEnvironmentId; - } - -@JsonProperty("operational-environment-id") -public void setOperationalEnvironmentId(String operationalEnvironmentId) { -this.operationalEnvironmentId = operationalEnvironmentId; - } - -public AAIOperationalEnvironment withOperationalEnvironmentId(String operationalEnvironmentId) { -this.operationalEnvironmentId = operationalEnvironmentId; -return this; - } - -@JsonProperty("operational-environment-name") -public String getOperationalEnvironmentName() { -return operationalEnvironmentName; - } - -@JsonProperty("operational-environment-name") -public void setOperationalEnvironmentName(String operationalEnvironmentName) { -this.operationalEnvironmentName = operationalEnvironmentName; - } - -public AAIOperationalEnvironment withOperationalEnvironmentName(String operationalEnvironmentName) { -this.operationalEnvironmentName = operationalEnvironmentName; -return this; - } - -@JsonProperty("operational-environment-type") -public String getOperationalEnvironmentType() { -return operationalEnvironmentType; - } - -@JsonProperty("operational-environment-type") -public void setOperationalEnvironmentType(String operationalEnvironmentType) { -this.operationalEnvironmentType = operationalEnvironmentType; - } - -public AAIOperationalEnvironment withOperationalEnvironmentType(String operationalEnvironmentType) { -this.operationalEnvironmentType = operationalEnvironmentType; -return this; - } - -@JsonProperty("operational-environment-status") -public String getOperationalEnvironmentStatus() { -return operationalEnvironmentStatus; - } - -@JsonProperty("operational-environment-status") -public void setOperationalEnvironmentStatus(String operationalEnvironmentStatus) { -this.operationalEnvironmentStatus = operationalEnvironmentStatus; - } - -public AAIOperationalEnvironment withOperationalEnvironmentStatus(String operationalEnvironmentStatus) { -this.operationalEnvironmentStatus = operationalEnvironmentStatus; -return this; - } - -@JsonProperty("tenant-context") -public String getTenantContext() { -return tenantContext; - } - -@JsonProperty("tenant-context") -public void setTenantContext(String tenantContext) { -this.tenantContext = tenantContext; - } - -public AAIOperationalEnvironment withTenantContext(String tenantContext) { -this.tenantContext = tenantContext; -return this; - } - -@JsonProperty("workload-context") -public String getWorkloadContext() { -return workloadContext; - } - -@JsonProperty("workload-context") -public void setWorkloadContext(String workloadContext) { -this.workloadContext = workloadContext; - } - -public AAIOperationalEnvironment withWorkloadContext(String workloadContext) { -this.workloadContext = workloadContext; -return this; - } - -@JsonProperty("resource-version") -public String getResourceVersion() { -return resourceVersion; - } - -@JsonProperty("resource-version") -public void setResourceVersion(String resourceVersion) { -this.resourceVersion = resourceVersion; - } - -public AAIOperationalEnvironment withResourceVersion(String resourceVersion) { -this.resourceVersion = resourceVersion; -return this; - } - -} diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java index 874b06e192..93de9139f9 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java @@ -24,11 +24,11 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; -import java.io.UnsupportedEncodingException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; +import java.util.Set; import javax.ws.rs.core.UriBuilder; @@ -39,6 +39,7 @@ import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals; import org.onap.so.client.graphinventory.GraphInventoryObjectType; import org.onap.so.client.graphinventory.entities.uri.parsers.UriParser; import org.onap.so.client.graphinventory.entities.uri.parsers.UriParserSpringImpl; +import org.onap.so.client.graphinventory.exceptions.IncorrectNumberOfUriKeys; import org.springframework.web.util.UriUtils; public class SimpleUri implements GraphInventoryResourceUri, Serializable { @@ -56,6 +57,7 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { this.pluralType = null; this.internalURI = UriBuilder.fromPath(this.getTemplate(type)); this.values = values; + validateValuesSize(this.getTemplate(type), values); } protected SimpleUri(GraphInventoryObjectType type, URI uri) { this.type = type; @@ -86,12 +88,14 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { this.pluralType = type; this.internalURI = UriBuilder.fromPath(this.getTemplate(type)); this.values = values; + validateValuesSize(this.getTemplate(type), values); } protected SimpleUri(GraphInventoryResourceUri parentUri, GraphInventoryObjectType childType, Object... childValues) { this.type = childType; this.pluralType = null; this.internalURI = UriBuilder.fromUri(parentUri.build()).path(childType.partialUri()); this.values = childValues; + validateValuesSize(childType.partialUri(), values); } protected void setInternalURI(UriBuilder builder) { @@ -158,12 +162,8 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { protected URI build(Object... values) { //This is a workaround because resteasy does not encode URIs correctly final String[] encoded = new String[values.length]; - for (int i = 0; i < values.length; i++) { - try { - encoded[i] = UriUtils.encode(values[i].toString(), StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - encoded[i] = values[i].toString(); - } + for (int i = 0; i < values.length; i++) { + encoded[i] = UriUtils.encode(values[i].toString(), StandardCharsets.UTF_8.toString()); } return internalURI.buildFromEncoded(encoded); } @@ -236,6 +236,14 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable { return this; } + public void validateValuesSize(String template, Object... values) { + UriParser parser = new UriParserSpringImpl(template); + Set<String> variables = parser.getVariables(); + if (variables.size() != values.length) { + throw new IncorrectNumberOfUriKeys(String.format("Expected %s variables: %s", variables.size(), variables)); + } + } + protected String getTemplate(GraphInventoryObjectType type) { return type.uriTemplate(); } diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java index aeaa923d1b..b4cf8eb949 100644 --- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java +++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/parsers/UriParserSpringImpl.java @@ -56,11 +56,7 @@ public class UriParserSpringImpl implements UriParser { final Map<String, String> result = new LinkedHashMap<>(); for (Entry<String, String> entry : map.entrySet()) { - try { - result.put(entry.getKey(), UriUtils.decode(entry.getValue(), "UTF-8")); - } catch (UnsupportedEncodingException e) { - result.put(entry.getKey(), ""); - } + result.put(entry.getKey(), UriUtils.decode(entry.getValue(), "UTF-8")); } return result; diff --git a/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java new file mode 100644 index 0000000000..c94e561274 --- /dev/null +++ b/common/src/main/java/org/onap/so/client/graphinventory/exceptions/IncorrectNumberOfUriKeys.java @@ -0,0 +1,11 @@ +package org.onap.so.client.graphinventory.exceptions; + +public class IncorrectNumberOfUriKeys extends RuntimeException { + + private static final long serialVersionUID = 2189285428827817518L; + + public IncorrectNumberOfUriKeys(String message) { + super(message); + } + +} diff --git a/common/src/main/java/org/onap/so/client/grm/GRMClient.java b/common/src/main/java/org/onap/so/client/grm/GRMClient.java index 84e25b9ce4..653e1cc7b3 100644 --- a/common/src/main/java/org/onap/so/client/grm/GRMClient.java +++ b/common/src/main/java/org/onap/so/client/grm/GRMClient.java @@ -53,7 +53,7 @@ public class GRMClient { } } - protected ServiceEndPointLookupRequest buildServiceEndPointlookupRequest(String name, int majorVersion, String env) { + public ServiceEndPointLookupRequest buildServiceEndPointlookupRequest(String name, int majorVersion, String env) { VersionLookup version = new VersionLookup(); version.setMajor(majorVersion); diff --git a/common/src/main/java/org/onap/so/client/grm/GRMProperties.java b/common/src/main/java/org/onap/so/client/grm/GRMProperties.java index da9f215aac..1206896bf9 100644 --- a/common/src/main/java/org/onap/so/client/grm/GRMProperties.java +++ b/common/src/main/java/org/onap/so/client/grm/GRMProperties.java @@ -24,7 +24,7 @@ import org.onap.so.client.RestProperties; public interface GRMProperties extends RestProperties { public String getDefaultVersion(); - public String getUsername(); - public String getPassword(); + public String getAuth(); + public String getKey(); public String getContentType(); } diff --git a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java index ce16ccaaaa..0bb55e627a 100644 --- a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java +++ b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java @@ -32,13 +32,11 @@ import org.onap.so.utils.TargetEntity; public class GRMRestClient extends RestClient { - private final String username; - private final String password; + private final GRMProperties properties; - public GRMRestClient(RestProperties props, URI path, String username, String password) { - super(props, Optional.of(path)); - this.username = username; - this.password = password; + public GRMRestClient(GRMProperties props, URI path) { + super(props, Optional.of(path)); + this.properties = props; } @Override @@ -48,7 +46,12 @@ public class GRMRestClient extends RestClient { @Override protected void initializeHeaderMap(Map<String, String> headerMap) { - headerMap.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(new String(username + ":" + password).getBytes())); + String auth = properties.getAuth(); + String key = properties.getKey(); + + if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) { + addBasicAuthHeader(auth, key); + } } } diff --git a/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java b/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java index 3045cb35f4..0c95a66979 100644 --- a/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java +++ b/common/src/main/java/org/onap/so/client/grm/GRMRestInvoker.java @@ -21,7 +21,6 @@ package org.onap.so.client.grm; import java.net.URI; -import java.util.Base64; import javax.ws.rs.core.UriBuilder; @@ -34,11 +33,8 @@ public class GRMRestInvoker { public GRMRestInvoker(GRMAction action) { GRMProperties props = GRMPropertiesLoader.getInstance().getImpl(); - if (props == null) { - props = new GRMDefaultPropertiesImpl(); - } this.properties = props; - this.client = new GRMRestClient(this.properties, this.createURI(action), this.properties.getUsername(), this.decode(this.properties.getPassword())); + this.client = new GRMRestClient(properties, this.createURI(action)); } private URI createURI(GRMAction action) { @@ -49,15 +45,6 @@ public class GRMRestInvoker { .build(); } - private String decode(String cred) { - try { - return new String(Base64.getDecoder().decode(cred.getBytes())); - } - catch(IllegalArgumentException iae) { - return cred; - } - } - private RestClient getClient() { return this.client; } diff --git a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java index 19bbe69cf2..2b7a81d590 100644 --- a/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java +++ b/common/src/main/java/org/onap/so/client/grm/beans/ServiceEndPointList.java @@ -22,27 +22,21 @@ package org.onap.so.client.grm.beans; import java.util.List; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -@JsonPropertyOrder({ "serviceEndPointList" }) +//@JsonIgnoreProperties(ignoreUnknown = true) public class ServiceEndPointList { - @JsonProperty("serviceEndPointList") + @JsonAlias("ServiceEndPointList") private List<ServiceEndPoint> serviceEndPointList = null; - @JsonProperty("serviceEndPointList") public List<ServiceEndPoint> getServiceEndPointList() { return serviceEndPointList; } - @JsonProperty("serviceEndPointList") public void setServiceEndPointList(List<ServiceEndPoint> serviceEndPointList) { this.serviceEndPointList = serviceEndPointList; } - } diff --git a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java index b11003ed1e..882a390c7b 100644 --- a/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java +++ b/common/src/main/java/org/onap/so/client/sdno/SDNOValidatorImpl.java @@ -53,7 +53,7 @@ public class SDNOValidatorImpl implements SDNOValidator { public boolean healthDiagnostic(String vnfId, UUID uuid, String requestingUserId) throws IOException, Exception { AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId); - AAIResourcesClient client = new AAIResourcesClient(AAIVersion.V10); + AAIResourcesClient client = new AAIResourcesClient(); GenericVnf vnf = client.get(GenericVnf.class, uri).orElseThrow(() -> new NotFoundException(vnfId + " not found in A&AI")); SDNO requestDiagnostic = buildRequestDiagnostic(vnf, uuid, requestingUserId); @@ -77,17 +77,17 @@ public class SDNOValidatorImpl implements SDNOValidator { protected SDNO buildRequestDiagnostic(GenericVnf vnf, UUID uuid, String requestingUserId) { - Optional<String> vnfType; - if (vnf.getVnfType() == null) { - vnfType = Optional.empty(); + Optional<String> nfRole; + if (vnf.getNfRole() == null) { + nfRole = Optional.empty(); } else { - vnfType = Optional.of(vnf.getVnfType()); + nfRole = Optional.of(vnf.getNfRole()); } Input input = new Input(); SDNO parentRequest = new SDNO(); Body body = new Body(); parentRequest.setBody(body); - parentRequest.setNodeType(vnfType.orElse("NONE").toUpperCase()); + parentRequest.setNodeType(nfRole.orElse("NONE").toUpperCase()); parentRequest.setOperation("health-diagnostic"); body.setInput(input); @@ -97,6 +97,7 @@ public class SDNOValidatorImpl implements SDNOValidator { request.setRequestClientName(clientName); request.setRequestNodeName(vnf.getVnfName()); request.setRequestNodeUuid(vnf.getVnfId()); + request.setRequestNodeType(nfRole.orElse("NONE").toUpperCase()); request.setRequestNodeIp(vnf.getIpv4OamAddress()); //generic-vnf oam ip request.setRequestUserId(requestingUserId); //mech id? request.setRequestId(uuid.toString()); //something to identify this request by for polling diff --git a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java index 6f415af8b0..8154b9137d 100644 --- a/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java +++ b/common/src/main/java/org/onap/so/client/sdno/dmaap/SDNOHealthCheckDmaapConsumer.java @@ -154,6 +154,6 @@ public class SDNOHealthCheckDmaapConsumer extends DmaapConsumer { @Override public int getMaximumElapsedTime() { - return 300000; + return 600000; } } diff --git a/common/src/main/java/org/onap/so/constants/Defaults.java b/common/src/main/java/org/onap/so/constants/Defaults.java index 13a378eadb..5117f4de95 100644 --- a/common/src/main/java/org/onap/so/constants/Defaults.java +++ b/common/src/main/java/org/onap/so/constants/Defaults.java @@ -31,7 +31,7 @@ public enum Defaults { private final String propName; private final String defaultValue; - + private Defaults(String propName, String defaultValue) { this.defaultValue = defaultValue; this.propName = propName; diff --git a/common/src/main/java/org/onap/so/exceptions/ValidationException.java b/common/src/main/java/org/onap/so/exceptions/ValidationException.java index 713fac70f3..b91c30c598 100644 --- a/common/src/main/java/org/onap/so/exceptions/ValidationException.java +++ b/common/src/main/java/org/onap/so/exceptions/ValidationException.java @@ -32,9 +32,9 @@ public class ValidationException extends Exception { private static final long serialVersionUID = 1L; private static final String VALIDATION_FAIL = "No valid $ELEMENT is specified"; - private static final String INVALID_ELEMENT = "$ELEMENT is not valid in the $VERSION version"; + private static final String UNMATCHED_ELEMENTS = "$ELEMENT does not match $SECOND_ELEMENT"; private static final String REPLACE_ELEMENT_KEY = "\\$ELEMENT"; - private static final String REPLACE_VERSION_KEY = "\\$VERSION"; + private static final String REPLACE_SECOND_ELEMENT_KEY = "\\$SECOND_ELEMENT"; @Deprecated public ValidationException (String msg) { @@ -48,7 +48,7 @@ public class ValidationException extends Exception { public ValidationException (String msg, Exception cause) { super (VALIDATION_FAIL.replaceAll (REPLACE_ELEMENT_KEY, msg), cause); } - public ValidationException(String msg, String version) { - super(INVALID_ELEMENT.replaceAll(REPLACE_ELEMENT_KEY, msg).replaceAll(REPLACE_VERSION_KEY, version)); + public ValidationException(String firstElement, String secondElement) { + super(UNMATCHED_ELEMENTS.replaceAll(REPLACE_ELEMENT_KEY, firstElement).replaceAll(REPLACE_SECOND_ELEMENT_KEY, secondElement)); } -} +}
\ No newline at end of file diff --git a/common/src/main/java/org/onap/so/logger/LogConstants.java b/common/src/main/java/org/onap/so/logger/LogConstants.java index ea3c8e2c4a..3c8b7f7d56 100644 --- a/common/src/main/java/org/onap/so/logger/LogConstants.java +++ b/common/src/main/java/org/onap/so/logger/LogConstants.java @@ -23,4 +23,6 @@ package org.onap.so.logger; public class LogConstants { public static final String TARGET_ENTITY_HEADER="X-Target-Entity"; public static final String UNKNOWN_TARGET_ENTITY="Unknown-Target-Entity"; + public static final String HTTP_URL="Http-Url"; + public static final String URI_BASE="Uri-Base"; } diff --git a/common/src/main/java/org/onap/so/logger/MsoAlarmLogger.java b/common/src/main/java/org/onap/so/logger/MsoAlarmLogger.java deleted file mode 100644 index 890aac93c0..0000000000 --- a/common/src/main/java/org/onap/so/logger/MsoAlarmLogger.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============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.onap.so.logger; - - -import java.io.File; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.slf4j.LoggerFactory; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.rolling.RollingFileAppender; -import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; - -/** - * Wrapper around log4j and Nagios NRDP passive alarming for MSO. - * - * For local alarm logging, this class will look for an alarm log file name - * in the servlet context parameter "mso.alarms.file". If none is found, - * it will look for an MsoProperty of the same name. As a last resort, - * it will use the default path "/var/log/ecomp/MSO/alarms/alarm.log". - * It is expected that all alarms within an application will use the same - * alarm file, so there is no way to dynamically add other alarm files. - * - * Alarms are logged as a simple pipe-delimited string of the format: - * <dateTime>|<alarmType>|<state>|<detailMessage> - * - * This class also supports real-time Nagios NRDP alarming. If enabled via - * MsoProperties, all alarms generated and logged to the local alarm file will - * also be transmitted to a Nagios NRDP instance. NRDP requires 4 parameters - * in service alarm events (all Mso Alarms will be Service Alarms): - * hostname, servicename, state, detail - * - * The log file format is also intended to be compatible with Nagios NRDP for - * non-real-time reporting. The command-line tool for sending alarms is - * is "send_nrdp.php", which takes the same 4 parameters as input. - * It will be easy enough to translate entries from an alarm.log file to - * NRDP if real-time NRDP alarming is not enabled. - * - * For Nagios integration, the alarmTypes should all match "service names" - * configured in the receiving Nagios server. Also, the alarm state will - * be limited to the 4 values defined by Nagios: - * 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown - * - * - */ -public class MsoAlarmLogger implements ServletContextListener { - - private Logger alarmLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(MSO_ALARM_CONTEXT); - private static RollingFileAppender<ILoggingEvent> fileAppender = null; - public static final String DEFAULT_MSO_ALARM_FILE = "/var/log/ecomp/MSO/alarms/alarm.log"; - public static final String MSO_ALARM_CONTEXT = "mso.alarms"; - - public static final int OK = 0; - public static final int WARNING = 1; - public static final int CRITICAL = 2; - public static final int UNKNOWN = 3; - - /** - * Get the default MSO Alarm Logger - */ - public MsoAlarmLogger () { - - initializeAlarmLogger(null); - - } - - public MsoAlarmLogger (String alarmFile) { - initializeAlarmLogger(alarmFile); - - } - - /** - * Method to record an alarm. - * - * @param alarm - the alarm identifier (Nagios "service") - * @param state - the alarm state/severity, based on Nagios service - * state values: 0 = OK, 1 = Warning, 2 = Critical, 3 = Unknown - * @param detail - detail message (may contain additional internal - * structure per alarm type) - */ - public void sendAlarm (String alarm, int state, String detail) { - // Write the alarm to Log file - if (alarmLogger != null) { - String output = alarm + "|" + state + "|" + detail; - alarmLogger.info (output); - } - - } - - @Override - public void contextDestroyed (ServletContextEvent event) { - // Nothing to do... - } - - @Override - public void contextInitialized (ServletContextEvent event) { - String msoAlarmFile = event.getServletContext ().getInitParameter ("mso.alarm.file"); - if (msoAlarmFile == null) { - msoAlarmFile = DEFAULT_MSO_ALARM_FILE; - } - - initializeAlarmLogger (msoAlarmFile); - } - - private void initializeAlarmLogger (String alarmFile) { - synchronized (MsoAlarmLogger.class) { - if (fileAppender == null) { - if (alarmFile != null) { - fileAppender = MsoAlarmLogger.getAppender (alarmFile); - } else { - fileAppender = MsoAlarmLogger.getAppender (DEFAULT_MSO_ALARM_FILE); - } - } - } - // The alarmLogger was static originally. - // The initialization of the alarmLogger was fine, but not sure why, it lost its appender info later - // Due to that issue, the alarmLogger is not static any more. - // Instead static attribute fileAppender is added and will be assigned to the alarmLogger every time new MsoAlarmLogger is created. - alarmLogger.setLevel (Level.INFO); - alarmLogger.addAppender (fileAppender); - alarmLogger.setAdditive (false); - } - - public void resetAppender() { - synchronized (MsoAlarmLogger.class) { - fileAppender = null; - } - } - - private static RollingFileAppender<ILoggingEvent> getAppender (String msoAlarmFile) { - // Create a Logger for alarms. Just use a default Pattern that outputs - // a message. MsoAlarmLogger will handle the formatting. - File alarmFile = new File (msoAlarmFile); - File alarmDir = alarmFile.getParentFile (); - if (!alarmDir.exists ()) { - alarmDir.mkdirs (); - } - - String logPattern = "%d{yyyy-MM-dd HH:mm:ss}|%m%n"; - - LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); - PatternLayoutEncoder encoder=new PatternLayoutEncoder(); - encoder.setPattern(logPattern); - encoder.setContext(context); - encoder.start(); - RollingFileAppender<ILoggingEvent> fileAppender= new RollingFileAppender<>(); - TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy= new TimeBasedRollingPolicy<>(); - rollingPolicy.setContext(context); - rollingPolicy.setFileNamePattern(msoAlarmFile + ".%d"); - rollingPolicy.setParent(fileAppender); - rollingPolicy.start(); - fileAppender.setFile(msoAlarmFile); - fileAppender.setAppend(true); - fileAppender.setEncoder(encoder); - fileAppender.setRollingPolicy(rollingPolicy); - fileAppender.setContext(context); - fileAppender.start(); - - return fileAppender; - } - -} diff --git a/common/src/main/java/org/onap/so/logger/MsoLogger.java b/common/src/main/java/org/onap/so/logger/MsoLogger.java index c4fba671bb..39a23b5c3e 100644 --- a/common/src/main/java/org/onap/so/logger/MsoLogger.java +++ b/common/src/main/java/org/onap/so/logger/MsoLogger.java @@ -74,6 +74,7 @@ public class MsoLogger { public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; public static final String CLIENT_ID = "X-ClientID"; public static final String INVOCATION_ID_HEADER = "X-InvocationID"; + public static final String REQUESTOR_ID = "X-RequestorID"; //Default values for not found public static final String UNKNOWN_PARTNER = "UnknownPartner"; diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java index 85a6498748..7a99594d19 100644 --- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java +++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java @@ -40,6 +40,7 @@ import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.LogConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; @@ -77,6 +78,7 @@ public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerRespo mdcSetup.setInstanceUUID(); mdcSetup.setEntryTimeStamp(); MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString()); logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); } catch (Exception e) { logger.warn("Error in incoming JAX-RS Inteceptor", e); diff --git a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java index 4084ad3ff0..9aa4e4c9b5 100644 --- a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java +++ b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java @@ -30,6 +30,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Providers; import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.LogConstants; import org.onap.so.logging.jaxrs.filter.MDCSetup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -109,7 +110,7 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { protected void setServiceName(HttpServletRequest request) { MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); } - + protected void setRequestId(Map<String, String> headers) { String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase()); if(requestId == null || requestId.isEmpty()) diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java index 69d21c41ac..72374e0580 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/InstanceReferences.java @@ -39,6 +39,8 @@ public class InstanceReferences { protected String networkInstanceId; protected String networkInstanceName; protected String requestorId; + protected String instanceGroupId; + protected String instanceGroupName; public String getServiceInstanceId() { @@ -109,6 +111,18 @@ public class InstanceReferences { public void setRequestorId(String requestorId) { this.requestorId = requestorId; } + public String getInstanceGroupId() { + return instanceGroupId; + } + public void setInstanceGroupId(String instanceGroupId) { + this.instanceGroupId = instanceGroupId; + } + public String getInstanceGroupName() { + return instanceGroupName; + } + public void setInstanceGroupName(String instanceGroupName) { + this.instanceGroupName = instanceGroupName; + } @Override public String toString() { return new ToStringBuilder(this).append("serviceInstanceId", serviceInstanceId) @@ -118,6 +132,7 @@ public class InstanceReferences { .append("volumeGroupInstanceId", volumeGroupInstanceId) .append("volumeGroupInstanceName", volumeGroupInstanceName) .append("networkInstanceId", networkInstanceId).append("networkInstanceName", networkInstanceName) - .append("requestorId", requestorId).toString(); + .append("requestorId", requestorId).append("instanceGroupId", instanceGroupId) + .append("instanceGroupName", instanceGroupName).toString(); } } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java index 1e5124bf1f..754a70ee94 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ModelType.java @@ -32,5 +32,6 @@ public enum ModelType { configuration, connectionPoint, pnf, - networkInstanceGroup + networkInstanceGroup, + instanceGroup } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java index 8e7e5e945e..d39efddf43 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java @@ -22,6 +22,8 @@ package org.onap.so.serviceinstancebeans; import java.util.List; +import org.apache.commons.lang3.builder.ToStringBuilder; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @@ -31,6 +33,7 @@ public class Request { protected String requestId; protected String startTime; + protected String finishTime; protected String requestScope; protected String requestType; protected RequestDetails requestDetails; @@ -51,6 +54,12 @@ public class Request { public void setStartTime(String startTime) { this.startTime = startTime; } + public String getFinishTime() { + return finishTime; + } + public void setFinishTime(String finishTime) { + this.finishTime = finishTime; + } public String getRequestScope() { return requestScope; } @@ -89,11 +98,9 @@ public class Request { } @Override public String toString() { - return "Request [requestId=" + requestId + ", startTime=" + startTime - + ", requestScope=" + requestScope + ", requestType=" + requestType - + ", requestDetails=" + requestDetails + ", instanceReferences=" + instanceReferences - + ", requestStatus=" + requestStatus + ", requestProcessingData=" + requestProcessingData + "]"; + return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime) + .append("finishTime", finishTime).append("requestScope", requestScope).append("requestType", requestType) + .append("requestDetails", requestDetails).append("instanceReferences", instanceReferences) + .append("requestStatus", requestStatus).append("requestProcessingData", requestProcessingData).toString(); } - - } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java index 158ca7a819..fd7877822b 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java @@ -162,9 +162,6 @@ public class RequestInfo implements Serializable { * */ public String getSource() { - if(null == source || source.isEmpty()){ - source = "VID"; - } return source; } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java index 87cb481dec..4dfa1d4130 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java @@ -20,13 +20,12 @@ package org.onap.so.serviceinstancebeans; +import java.beans.Transient; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; -import javax.persistence.Transient; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java index c30e39a028..088e414094 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java @@ -20,6 +20,8 @@ package org.onap.so.serviceinstancebeans; +import java.net.URL; + import org.apache.commons.lang3.builder.ToStringBuilder; import com.fasterxml.jackson.annotation.JsonInclude; @@ -32,7 +34,7 @@ public class RequestReferences { String requestId; String instanceId; - + URL requestSelfLink; public String getRequestId() { return requestId; @@ -46,9 +48,15 @@ public class RequestReferences { public void setInstanceId(String instanceId) { this.instanceId = instanceId; } + public URL getRequestSelfLink() { + return requestSelfLink; + } + public void setRequestSelfLink(URL requestSelfLink) { + this.requestSelfLink = requestSelfLink; + } @Override public String toString() { - return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId).toString(); + return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId).append("requestSelfLink", requestSelfLink).toString(); } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java index 527aa037ed..4c3597b2c1 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java @@ -30,7 +30,7 @@ public class RequestStatus { protected String requestState; protected String statusMessage; protected Integer percentProgress; - protected String finishTime; + protected String timeStamp; public String getRequestState() { @@ -51,15 +51,15 @@ public class RequestStatus { public void setPercentProgress(Integer percentProgress) { this.percentProgress = percentProgress; } - public String getFinishTime() { - return finishTime; + public String getTimeStamp() { + return timeStamp; } - public void setFinishTime(String finishTime) { - this.finishTime = finishTime; + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; } @Override public String toString() { return new ToStringBuilder(this).append("requestState", requestState).append("statusMessage", statusMessage) - .append("percentProgress", percentProgress).append("finishTime", finishTime).toString(); + .append("percentProgress", percentProgress).append("timeStamp", timeStamp).toString(); } } diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java index 3ccf29127f..b6bfda159d 100644 --- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java +++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java @@ -43,6 +43,8 @@ public class ServiceInstancesRequest implements Serializable { private String configurationId; @JsonProperty("correlationId") private String correlationId; + @JsonProperty("instanceGroupId") + private String instanceGroupId; public RequestDetails getRequestDetails() { return requestDetails; @@ -107,6 +109,14 @@ public class ServiceInstancesRequest implements Serializable { public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } + + public String getInstanceGroupId() { + return instanceGroupId; + } + + public void setInstanceGroupId(String instanceGroupId) { + this.instanceGroupId = instanceGroupId; + } @Override public String toString() { diff --git a/common/src/main/java/org/onap/so/utils/CryptoUtils.java b/common/src/main/java/org/onap/so/utils/CryptoUtils.java index 11d464a85c..c35ced531d 100644 --- a/common/src/main/java/org/onap/so/utils/CryptoUtils.java +++ b/common/src/main/java/org/onap/so/utils/CryptoUtils.java @@ -21,15 +21,15 @@ package org.onap.so.utils; - -import java.security.GeneralSecurityException; -import java.security.NoSuchAlgorithmException; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; - -import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoLogger; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; /** @@ -40,8 +40,12 @@ public final class CryptoUtils { private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, CryptoUtils.class); - public static final String AES = "AES"; + private static final String AES = "AES"; private static final String CLOUD_KEY = "aa3871669d893c7fb8abbcda31b88b4f"; + private static final int GCM_TAG_LENGTH = 16; + private static final int GCM_IV_LENGTH = 12; + private static final String AES_GCM_NO_PADDING = "AES/GCM/NoPadding"; + /** * encrypt a value and generate a keyfile * if the keyfile is not found then a new one is created @@ -50,10 +54,16 @@ public final class CryptoUtils { */ public static String encrypt (String value, String keyString) throws GeneralSecurityException { SecretKeySpec sks = getSecretKeySpec (keyString); - Cipher cipher = Cipher.getInstance (CryptoUtils.AES); - cipher.init (Cipher.ENCRYPT_MODE, sks, cipher.getParameters ()); - byte[] encrypted = cipher.doFinal (value.getBytes ()); - return byteArrayToHexString (encrypted); + Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING); + byte[] initVector = new byte[GCM_IV_LENGTH]; + (new SecureRandom()).nextBytes(initVector); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); + cipher.init(Cipher.ENCRYPT_MODE, sks, spec); + byte[] encoded = value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] cipherText = new byte[initVector.length + cipher.getOutputSize(encoded.length)]; + System.arraycopy(initVector, 0, cipherText, 0, initVector.length); + cipher.doFinal(encoded, 0, encoded.length, cipherText, initVector.length); + return byteArrayToHexString(cipherText); } /** @@ -63,29 +73,18 @@ public final class CryptoUtils { */ public static String decrypt (String message, String keyString) throws GeneralSecurityException { SecretKeySpec sks = getSecretKeySpec (keyString); - Cipher cipher = Cipher.getInstance (CryptoUtils.AES); - cipher.init (Cipher.DECRYPT_MODE, sks); - byte[] decrypted = cipher.doFinal (hexStringToByteArray (message)); - return new String (decrypted); + byte[] cipherText = hexStringToByteArray(message); + Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING); + byte[] initVector = Arrays.copyOfRange(cipherText, 0, GCM_IV_LENGTH); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); + cipher.init(Cipher.DECRYPT_MODE, sks, spec); + byte[] plaintext = cipher.doFinal(cipherText, GCM_IV_LENGTH, cipherText.length - GCM_IV_LENGTH); + return new String(plaintext); } - - /** - * decrypt a value or return defaultValue - * - */ - public static String decryptProperty (String prop, String defaultValue, String encryptionKey) { - try { - return CryptoUtils.decrypt(prop, encryptionKey); - } - catch (GeneralSecurityException e) { - LOGGER.debug("Security exception", e); - } - return defaultValue; - } public static String encryptCloudConfigPassword(String message) { try { - return CryptoUtils.encrypt(message, CryptoUtils.CLOUD_KEY); + return CryptoUtils.encrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e); return null; @@ -93,16 +92,15 @@ public final class CryptoUtils { } public static String decryptCloudConfigPassword(String message) { try { - return CryptoUtils.decrypt(message, CryptoUtils.CLOUD_KEY); + return CryptoUtils.decrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { LOGGER.error (MessageEnum.RA_GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception in encryptPassword", e); return null; } } - private static SecretKeySpec getSecretKeySpec (String keyString) throws NoSuchAlgorithmException { + private static SecretKeySpec getSecretKeySpec (String keyString) { byte[] key = hexStringToByteArray (keyString); - SecretKeySpec sks = new SecretKeySpec (key, CryptoUtils.AES); - return sks; + return new SecretKeySpec (key, AES); } public static String byteArrayToHexString (byte[] b) { diff --git a/common/src/main/java/org/onap/so/utils/TargetEntity.java b/common/src/main/java/org/onap/so/utils/TargetEntity.java index 4d48d349b5..a4480f2d95 100644 --- a/common/src/main/java/org/onap/so/utils/TargetEntity.java +++ b/common/src/main/java/org/onap/so/utils/TargetEntity.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. @@ -24,14 +24,14 @@ import java.util.EnumSet; public enum TargetEntity { OPENSTACK_ADAPTER, BPMN, GRM ,AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB, - VNF_ADAPTER, SDNC_ADAPTER, NARAD, MULTICLOUD; + VNF_ADAPTER, SDNC_ADAPTER, SNIRO, SDC, EXTERNAL, MULTICLOUD; private static final String PREFIX = "SO"; - + public static EnumSet<TargetEntity> getSOInternalComponents() { return EnumSet.of(OPENSTACK_ADAPTER, BPMN,CATALOG_DB,REQUEST_DB,VNF_ADAPTER,SDNC_ADAPTER); } - + @Override public String toString(){ if(getSOInternalComponents().contains(this)) @@ -39,4 +39,4 @@ public enum TargetEntity { else return this.name(); } -}
\ No newline at end of file +} diff --git a/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java b/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java index 72e609acbd..9ddfd0592c 100644 --- a/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java +++ b/common/src/main/java/org/onap/so/web/exceptions/RuntimeExceptionMapper.java @@ -25,20 +25,20 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; -import org.onap.so.logger.MsoAlarmLogger; + import org.onap.so.logger.MsoLogger; public class RuntimeExceptionMapper implements ExceptionMapper<RuntimeException> { private static MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, RuntimeExceptionMapper.class); - private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger(); + @Override public Response toResponse(RuntimeException exception) { if (exception instanceof NotFoundException) { return Response.status(Status.NOT_FOUND).build(); } else { - alarmLogger.sendAlarm("MsoApplicationError", MsoAlarmLogger.CRITICAL, exception.getMessage()); + logger.error(exception); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(new ExceptionResponse("Unexpected Internal Exception")).build(); } diff --git a/common/src/test/java/org/onap/so/BeansTest.java b/common/src/test/java/org/onap/so/BeansTest.java index 2e825cf8c7..54cbced563 100644 --- a/common/src/test/java/org/onap/so/BeansTest.java +++ b/common/src/test/java/org/onap/so/BeansTest.java @@ -63,7 +63,6 @@ public class BeansTest { @Test public void pojoStructure() { - test("org.onap.so.client.aai.objects"); test("org.onap.so.client.policy.entities"); test("org.onap.so.client.grm.beans"); test("org.onap.so.client.ruby.beans"); diff --git a/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java b/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java index 587e4841d7..418220778a 100644 --- a/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java +++ b/common/src/test/java/org/onap/so/adapter_utils/tests/CryptoTest.java @@ -71,8 +71,6 @@ public class CryptoTest { String encode2String = CryptoUtils.encrypt(testData, testKey); assertNotNull(encode2String); - assertEquals(encodeString,encode2String); - assertEquals(CryptoUtils.decrypt(encodeString, testKey),CryptoUtils.decrypt(encode2String, testKey)); encodeString = CryptoUtils.encryptCloudConfigPassword(testData); diff --git a/common/src/test/java/org/onap/so/adapter_utils/tests/MsoAlarmLoggerTest.java b/common/src/test/java/org/onap/so/adapter_utils/tests/MsoAlarmLoggerTest.java deleted file mode 100644 index 6756bc98ad..0000000000 --- a/common/src/test/java/org/onap/so/adapter_utils/tests/MsoAlarmLoggerTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============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.onap.so.adapter_utils.tests; - - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.so.logger.MsoAlarmLogger; - - -/** - * This junit test very roughly the alarm logger - * - */ -public class MsoAlarmLoggerTest { - - public static MsoAlarmLogger msoAlarmLogger; - - @BeforeClass - public static final void createObjects() throws IOException - { - - File outputFile = new File ("./target/alarm-test.log"); - if (outputFile.exists()) { - outputFile.delete(); - } else { - outputFile.createNewFile(); - } - msoAlarmLogger = new MsoAlarmLogger("./target/alarm-test.log"); - } - - @AfterClass - public static void tearDown() { - msoAlarmLogger.resetAppender(); - } - @Test - public void testAlarmConfig() throws IOException { - - msoAlarmLogger.sendAlarm("test", 0, "detail message"); - - FileInputStream inputStream = new FileInputStream("./target/alarm-test.log"); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - - String line = reader.readLine(); - String[] splitLine = line.split("\\|"); - assertTrue(splitLine.length==4); - assertTrue("test".equals(splitLine[1])); - assertTrue("0".equals(splitLine[2])); - assertTrue("detail message".equals(splitLine[3])); - - line = reader.readLine(); - assertNull(line); - reader.close(); - inputStream.close(); - - // Reset the file for others tests - PrintWriter writer = new PrintWriter(new File("./target/alarm-test.log")); - writer.print(""); - writer.close(); - - } - - @Test - public void testAlarm() throws IOException { - - msoAlarmLogger.sendAlarm("test", 0, "detail message"); - msoAlarmLogger.sendAlarm("test2", 1, "detail message2"); - msoAlarmLogger.sendAlarm("test3", 2, "detail message3"); - - FileInputStream inputStream = new FileInputStream("./target/alarm-test.log"); - BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); - - String line = reader.readLine(); - String[] splitLine = line.split("\\|"); - assertTrue(splitLine.length==4); - assertTrue("test".equals(splitLine[1])); - assertTrue("0".equals(splitLine[2])); - assertTrue("detail message".equals(splitLine[3])); - - line = reader.readLine(); - splitLine = line.split("\\|"); - assertTrue(splitLine.length==4); - assertTrue("test2".equals(splitLine[1])); - assertTrue("1".equals(splitLine[2])); - assertTrue("detail message2".equals(splitLine[3])); - - line = reader.readLine(); - splitLine = line.split("\\|"); - assertTrue(splitLine.length==4); - assertTrue("test3".equals(splitLine[1])); - assertTrue("2".equals(splitLine[2])); - assertTrue("detail message3".equals(splitLine[3])); - - line = reader.readLine(); - assertNull(line); - reader.close(); - inputStream.close(); - - // Reset the file for others tests - PrintWriter writer = new PrintWriter(new File("./target/alarm-test.log")); - writer.print(""); - writer.close(); - - } -} diff --git a/common/src/test/java/org/onap/so/client/HttpClientTest.java b/common/src/test/java/org/onap/so/client/HttpClientTest.java new file mode 100644 index 0000000000..75ce5f322f --- /dev/null +++ b/common/src/test/java/org/onap/so/client/HttpClientTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 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.onap.so.client; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.exactly; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.verify; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import java.net.MalformedURLException; +import java.net.URL; +import org.junit.Rule; +import org.junit.Test; +import org.onap.so.utils.TargetEntity; + +public class HttpClientTest{ + + + private final HttpClientFactory httpClientFactory = new HttpClientFactory(); + @Rule + public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicHttpsPort()); + + @Test + public void testPost_success() throws MalformedURLException{ + + stubFor(post(urlEqualTo("/services/sdnc/post")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(""))); + + URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post"); + HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN); + + client.addBasicAuthHeader("97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF", "123"); + client.addAdditionalHeader("Accept", "application/json"); + + client.post("{}"); + + verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post"))); + } + + @Test + public void testPost_nullHeader() throws MalformedURLException{ + + stubFor(post(urlEqualTo("/services/sdnc/post")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(""))); + + URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post"); + HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN); + + client.addAdditionalHeader("Accept", "application/json"); + client.addAdditionalHeader("id", null); + + client.post("{}"); + + verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post")) + .withHeader("Accept", equalTo("application/json"))); + } + + @Test + public void testPost_nullBasicAuth() throws MalformedURLException{ + + stubFor(post(urlEqualTo("/services/sdnc/post")) + .willReturn(aResponse().withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody(""))); + + URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post"); + HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN); + + client.addBasicAuthHeader("", "12345"); + client.addAdditionalHeader("Accept", "application/json"); + + client.post("{}"); + + verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post")) + .withHeader("Accept", equalTo("application/json"))); + } + +} diff --git a/common/src/test/java/org/onap/so/client/RestClientTest.java b/common/src/test/java/org/onap/so/client/RestClientTest.java index 1443f04f3a..06196fd73e 100644 --- a/common/src/test/java/org/onap/so/client/RestClientTest.java +++ b/common/src/test/java/org/onap/so/client/RestClientTest.java @@ -20,7 +20,8 @@ package org.onap.so.client; -import static org.mockito.Matchers.any; + +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -39,23 +40,25 @@ import javax.ws.rs.core.UriBuilderException; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.ArgumentMatchers; import org.onap.so.utils.TargetEntity; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class RestClientTest { - + + private final HttpClientFactory httpClientFactory = new HttpClientFactory(); @Mock private RestProperties props; - - + + @Test public void retries() throws Exception { RestClient spy = buildSpy(); RestRequest mockCallable = mock(RestRequest.class); when(mockCallable.call()).thenThrow(new WebApplicationException(new SocketTimeoutException())); - doReturn(mockCallable).when(spy).buildRequest(any(String.class), any(Object.class)); + doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull()); try { spy.get(); } catch (Exception e) { @@ -70,7 +73,7 @@ public class RestClientTest { RestClient spy = buildSpy(); RestRequest mockCallable = mock(RestRequest.class); when(mockCallable.call()).thenThrow(new WebApplicationException(new NotFoundException())); - doReturn(mockCallable).when(spy).buildRequest(any(String.class), any(Object.class)); + doReturn(mockCallable).when(spy).buildRequest(any(String.class), ArgumentMatchers.isNull()); try { spy.get(); } catch (Exception e) { @@ -80,7 +83,8 @@ public class RestClientTest { } private RestClient buildSpy() throws MalformedURLException, IllegalArgumentException, UriBuilderException { - RestClient client = new HttpClient(UriBuilder.fromUri("http://localhost/test").build().toURL(), "application/json", TargetEntity.BPMN); + RestClient client = httpClientFactory + .newJsonClient(UriBuilder.fromUri("http://localhost/test").build().toURL(), TargetEntity.BPMN); return spy(client); } diff --git a/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java index 40410019f0..f30d2e17aa 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIConfigurationClientTest.java @@ -25,7 +25,7 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; @@ -34,13 +34,12 @@ import static org.mockito.Mockito.verify; import java.util.Optional; import java.util.UUID; -import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.aai.entities.Configuration; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUri; diff --git a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java index ea842719e8..d4eaf0873b 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java @@ -28,6 +28,20 @@ import org.onap.so.client.aai.entities.uri.AAIUriFactory; public class AAIObjectTypeTest { + + @Test + public void fromTypeNameTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException { + AAIObjectType type = AAIObjectType.fromTypeName("allotted-resource"); + assertEquals("allotted-resource", type.typeName()); + + } + + @Test + public void customTypeTest() throws IllegalArgumentException, IllegalAccessException, InstantiationException { + AAIObjectType type = AAIObjectType.fromTypeName("my-custom-name"); + assertEquals("my-custom-name", type.typeName()); + + } @Test public void verifyDefaultCase() { assertEquals("default removed for tenant", "tenant", AAIObjectType.DEFAULT_TENANT.typeName()); diff --git a/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java b/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java index 008b612cd8..0d4490f51d 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java @@ -33,7 +33,7 @@ import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; import com.fasterxml.jackson.core.JsonParseException; @@ -68,13 +68,23 @@ public class AAIPatchConverterTest { } @Test + public void convertStringToPatchFormatNull_Test() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { + AAIPatchConverter validator = new AAIPatchConverter(); + String payload = "{\"ipv4-loopback0-address\": null}"; + String result = validator.marshallObjectToPatchFormat(payload); + System.out.println(result); + assertEquals("expect no change", payload, result); + } + + @Test public void convertMapToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException { AAIPatchConverter validator = new AAIPatchConverter(); HashMap<String, String> map = new HashMap<>(); map.put("ipv4-loopback0-address", ""); + map.put("ipv4-loopback1-address", "192.168.1.1"); String result = validator.marshallObjectToPatchFormat(map); - assertEquals("expect string", "{\"ipv4-loopback0-address\":\"\"}", result); + assertEquals("expect string", "{\"ipv4-loopback1-address\":\"192.168.1.1\"}", result); } @Test diff --git a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java index 6e9c38517d..43616ba0c2 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIQueryClientTest.java @@ -21,8 +21,8 @@ package org.onap.so.client.aai; import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -39,7 +39,7 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.RestClient; import org.onap.so.client.aai.entities.CustomQuery; import org.onap.so.client.aai.entities.uri.AAIResourceUri; diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java index 22dc1cac30..32a9ca54a8 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientTest.java @@ -96,7 +96,7 @@ public class AAIResourcesClientTest { AAIResourceUri path = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, "test3"); wireMockRule.stubFor(get( urlPathEqualTo("/aai/" + AAIVersion.LATEST + path.build().toString())) - .withHeader("Authorization", equalTo("Basic TVNPOk1TTw==")) + .withHeader("Authorization", equalTo("Basic dGVzdDp0ZXN0")) .willReturn( aResponse() .withHeader("Content-Type", "application/json") diff --git a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java index 752c49eb5b..ad15417b71 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java @@ -21,8 +21,8 @@ package org.onap.so.client.aai; import static org.hamcrest.CoreMatchers.containsString; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -39,7 +39,7 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.so.client.RestClientSSL; import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException; diff --git a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java index 8c42686e5f..428fa276db 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java @@ -23,7 +23,7 @@ package org.onap.so.client.aai; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -35,6 +35,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.Optional; +import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.onap.aai.domain.yang.Pserver; @@ -66,7 +67,7 @@ public class AAISingleTransactionClientTest { } @Test - public void testRequest() throws IOException { + public void testRequest() throws JSONException,IOException { AAIResourcesClient client = createClient(); Pserver pserver = new Pserver(); pserver.setHostname("pserver-hostname"); diff --git a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java index cbf8d67a82..621375882b 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java @@ -21,7 +21,7 @@ package org.onap.so.client.aai; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; diff --git a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorImplTest.java b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorImplTest.java index 7ba92a1f06..fdfe41f12a 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorImplTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorImplTest.java @@ -41,13 +41,13 @@ public class AAIUpdatorImplTest { @Test(expected = NullPointerException.class) public void updateVnfToLockedTest() throws Exception { - test.updateVnfToLocked("vnfId","uuId"); + test.updateVnfToLocked("vnfId"); } @Test(expected = NullPointerException.class) public void updateVnfToUnLockedTest() throws Exception { - test.updateVnfToUnLocked("vnfId","uuId"); + test.updateVnfToUnLocked("vnfId"); } } diff --git a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java index fddd1e63ba..3fc97761a4 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIUpdatorTest.java @@ -20,7 +20,7 @@ package org.onap.so.client.aai; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -28,7 +28,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class AAIUpdatorTest { @@ -36,7 +36,6 @@ public class AAIUpdatorTest { @Mock protected AAIRestClientI client; String vnfName = "testVnf"; - String uuid = "UUID"; AAIUpdatorImpl updator; @Before @@ -47,15 +46,15 @@ public class AAIUpdatorTest { @Test public void testUpdateVnfToLocked() throws Exception{ - doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class), isA(String.class)); - updator.updateVnfToLocked(vnfName, uuid); - verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, true, uuid); + doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class)); + updator.updateVnfToLocked(vnfName); + verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, true); } @Test public void testUpdateVnfToUnLocked() throws Exception { - doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class), isA(String.class)); - updator.updateVnfToUnLocked(vnfName, uuid); - verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, false, uuid); + doNothing().when(client).updateMaintenceFlagVnfId(isA(String.class), isA(Boolean.class)); + updator.updateVnfToUnLocked(vnfName); + verify(client, times(1)).updateMaintenceFlagVnfId(vnfName, false); } }
\ No newline at end of file diff --git a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java index a2de528d9f..f32633122d 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java @@ -30,7 +30,7 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.Pserver; @@ -66,28 +66,28 @@ public class AAIValidatorTest { @Test public void test_IsPhysicalServerLocked_True() throws IOException{ when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPservers(true)); - boolean locked = validator.isPhysicalServerLocked(vnfName, uuid); + boolean locked = validator.isPhysicalServerLocked(vnfName); assertEquals(true, locked); } @Test public void test_IsPhysicalServerLocked_False() throws IOException { when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPservers(false)); - boolean locked = validator.isPhysicalServerLocked(vnfName, uuid); + boolean locked = validator.isPhysicalServerLocked(vnfName); assertEquals(false, locked); } @Test - public void test_IsVNFLocked_False() throws Exception{ - when(client.getVnfByName(vnfName,uuid)).thenReturn(createGenericVnfs(false)); - boolean locked = validator.isVNFLocked(vnfName, uuid); + public void test_IsVNFLocked_False() { + when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(false)); + boolean locked = validator.isVNFLocked(vnfName); assertEquals(false, locked); } @Test - public void test_IsVNFLocked_True() throws Exception{ - when(client.getVnfByName(vnfName,uuid)).thenReturn(createGenericVnfs(true)); - boolean locked = validator.isVNFLocked(vnfName, uuid); + public void test_IsVNFLocked_True() { + when(client.getVnfByName(vnfName)).thenReturn(createGenericVnfs(true)); + boolean locked = validator.isVNFLocked(vnfName); assertEquals(true,locked ); } } diff --git a/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java b/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java index d4bf1b0224..324be0114d 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java @@ -35,7 +35,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.GenericVnf; import org.onap.so.client.aai.AAICommonObjectMapperProvider; import org.springframework.util.SerializationUtils; diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java index 71ec49789e..0d2da3339a 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java @@ -21,7 +21,7 @@ package org.onap.so.client.aai.entities.uri; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java new file mode 100644 index 0000000000..729f0e50e9 --- /dev/null +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/IncorrectNumberOfUriKeysTest.java @@ -0,0 +1,50 @@ +package org.onap.so.client.aai.entities.uri; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.so.client.aai.AAIObjectPlurals; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.graphinventory.exceptions.IncorrectNumberOfUriKeys; + +public class IncorrectNumberOfUriKeysTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void verifyIncorrectNumberOfKeysSingle() { + + thrown.expect(IncorrectNumberOfUriKeys.class); + thrown.expectMessage(equalTo("Expected 3 variables: [cloud-owner, cloud-region-id, volume-group-id]")); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VOLUME_GROUP, "volume-group-id"); + + } + + @Test + public void verifyIncorrectNumberOfKeysPlural() { + + thrown.expect(IncorrectNumberOfUriKeys.class); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VOLUME_GROUP, "my-cloud-owner"); + + } + + @Test + public void verifyIncorrectNumberOfKeysFromParent() { + + thrown.expect(IncorrectNumberOfUriKeys.class); + AAIResourceUri parentUri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "my-cloud-owner", "my-cloud-region-id"); + AAIResourceUri uri = AAIUriFactory.createResourceFromParentURI(parentUri, AAIObjectType.VOLUME_GROUP); + } + + @Test + public void verifyIncorrectNumberOfKeysHttpAware() { + + thrown.expect(IncorrectNumberOfUriKeys.class); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "customer-id", "subscription-id"); + } +} diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java index 26f9d871fd..6059e7bd23 100644 --- a/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java +++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java @@ -29,7 +29,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -48,7 +48,7 @@ import javax.ws.rs.core.UriBuilder; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.onap.so.client.aai.AAIResourcesClient; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl; @@ -158,7 +158,7 @@ public class ServiceInstanceUriTest { ServiceInstanceUri spy = spy(instance); AAIResourcesClient mockResourcesClient = mock(AAIResourcesClient.class); AAIResultWrapper wrapper = mock(AAIResultWrapper.class); - when(mockResourcesClient.get(Matchers.<AAIResourceUri>any(AAIResourceUri.class), Matchers.<Class<NotFoundException>>any())).thenReturn(wrapper); + when(mockResourcesClient.get(ArgumentMatchers.<AAIResourceUri>any(AAIResourceUri.class), ArgumentMatchers.<Class<NotFoundException>>any())).thenReturn(wrapper); when(wrapper.getJson()).thenReturn(content); when(spy.getResourcesClient()).thenReturn(mockResourcesClient); exception.expect(GraphInventoryUriComputationException.class); @@ -181,10 +181,6 @@ public class ServiceInstanceUriTest { ServiceInstanceUri spy = spy(instance); AAIResourcesClient client = createClient(); doReturn(client).when(spy).getResourcesClient(); - /*AAIResultWrapper wrapper = mock(AAIResultWrapper.class); - when(client.get(Matchers.<AAIResourceUri>any(AAIResourceUri.class), Matchers.<Class<NotFoundException>>any())).thenReturn(wrapper); - when(wrapper.getJson()).thenReturn("{\"results\":[]}"); - doReturn(client).when(spy).getResourcesClient();*/ stubFor(get(urlPathMatching("/aai/v[0-9]+/nodes/service-instances/service-instance/key3")) .willReturn(aResponse() .withStatus(404) diff --git a/common/src/test/java/org/onap/so/client/aai/objects/AAIOperationalEnvironmentTest.java b/common/src/test/java/org/onap/so/client/aai/objects/AAIOperationalEnvironmentTest.java deleted file mode 100644 index e2a3cbd6bd..0000000000 --- a/common/src/test/java/org/onap/so/client/aai/objects/AAIOperationalEnvironmentTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -* ============LICENSE_START======================================================= - * ONAP : SO - * ================================================================================ - * Copyright (C) 2018 TechMahindra - * ================================================================================ - * 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.onap.so.client.aai.objects; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class AAIOperationalEnvironmentTest { - - AAIOperationalEnvironment aaiOE =new AAIOperationalEnvironment(); - - @Test - public void test() { - aaiOE.setOperationalEnvironmentId("operationalEnvironmentId"); - aaiOE.setOperationalEnvironmentName("operationalEnvironmentName"); - aaiOE.setOperationalEnvironmentStatus("operationalEnvironmentStatus"); - aaiOE.setOperationalEnvironmentType("operationalEnvironmentType"); - aaiOE.setResourceVersion("resourceVersion"); - aaiOE.setTenantContext("tenantContext"); - aaiOE.setWorkloadContext("workloadContext"); - assertEquals(aaiOE.getOperationalEnvironmentId(),"operationalEnvironmentId"); - assertEquals(aaiOE.getOperationalEnvironmentName(),"operationalEnvironmentName"); - assertEquals(aaiOE.getOperationalEnvironmentStatus(),"operationalEnvironmentStatus"); - assertEquals(aaiOE.getOperationalEnvironmentType(),"operationalEnvironmentType"); - assertEquals(aaiOE.getResourceVersion(),"resourceVersion"); - assertEquals(aaiOE.getTenantContext(),"tenantContext"); - assertEquals(aaiOE.getWorkloadContext(),"workloadContext"); - aaiOE.withOperationalEnvironmentId("operationalEnvironmentId"); - aaiOE.withOperationalEnvironmentName("operationalEnvironmentName"); - aaiOE.withOperationalEnvironmentStatus("operationalEnvironmentStatus"); - aaiOE.withOperationalEnvironmentType("operationalEnvironmentType"); - aaiOE.withResourceVersion("resourceVersion"); - aaiOE.withTenantContext("tenantContext"); - aaiOE.withWorkloadContext("workloadContext"); - } - -} diff --git a/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java new file mode 100644 index 0000000000..b964e905de --- /dev/null +++ b/common/src/test/java/org/onap/so/client/aai/objects/CustomAAIObjectType.java @@ -0,0 +1,20 @@ +package org.onap.so.client.aai.objects; + +import org.onap.so.client.aai.AAINamespaceConstants; +import org.onap.so.client.aai.AAIObjectType; + +public class CustomAAIObjectType extends AAIObjectType { + + private static final long serialVersionUID = 1919729212831978098L; + + public static final AAIObjectType CUSTOM = new CustomAAIObjectType(AAINamespaceConstants.NETWORK, "my-url", "my-custom-name"); + + /* Default constructor automatically called by AAIObjectType */ + public CustomAAIObjectType() { + super(); + } + protected CustomAAIObjectType(String parent, String uri, String name) { + super(parent, uri, name); + } + +} diff --git a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java index e1afa82e1e..c0633c1cca 100644 --- a/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java +++ b/common/src/test/java/org/onap/so/client/dmaap/DmaapPublisherTest.java @@ -45,7 +45,7 @@ public class DmaapPublisherTest { @Override public Optional<String> getHost() { - return Optional.of("http://localhost:8080"); + return Optional.of("http://test"); } }; diff --git a/common/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/common/src/test/java/org/onap/so/client/grm/GRMClientTest.java deleted file mode 100644 index 7b783762fa..0000000000 --- a/common/src/test/java/org/onap/so/client/grm/GRMClientTest.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ============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.onap.so.client.grm; - -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; -import static com.github.tomakehurst.wiremock.client.WireMock.*; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; -import java.io.File; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.ws.rs.core.MediaType; - -import ch.qos.logback.classic.spi.ILoggingEvent; - -import org.apache.log4j.MDC; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.client.grm.beans.OperationalInfo; -import org.onap.so.client.grm.beans.Property; -import org.onap.so.client.grm.beans.ServiceEndPoint; -import org.onap.so.client.grm.beans.ServiceEndPointList; -import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest; -import org.onap.so.client.grm.beans.ServiceEndPointRequest; -import org.onap.so.client.grm.beans.Version; -import org.onap.so.client.grm.exceptions.GRMClientCallFailed; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.tomakehurst.wiremock.junit.WireMockRule; - -import org.onap.so.utils.TestAppender; - -public class GRMClientTest { - - @Rule - public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().port(47389)); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static final String uuidRegex = "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$"; - - @BeforeClass - public static void setUp() throws Exception { - System.setProperty("mso.config.path", "src/test/resources"); - } - - private ObjectMapper mapper = new ObjectMapper(); - - @Test - public void testFind() throws Exception { - TestAppender.events.clear(); - String endpoints = getFileContentsAsString("__files/grm/endpoints.json"); - wireMockRule.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(endpoints))); - - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test"); - GRMClient client = new GRMClient(); - ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - List<ServiceEndPoint> list = sel.getServiceEndPointList(); - assertEquals(3, list.size()); - - boolean foundInvoke = false; - boolean foundInvokeReturn = false; - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker().getName().equals("INVOKE") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("GRM",mdc.get("TargetEntity")); - assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvoke=true; - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("INVOKE_RETURN")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); - assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvokeReturn=true; - } - - if(!foundInvoke) - fail("INVOKE Marker not found"); - - if(!foundInvokeReturn) - fail("INVOKE RETURN Marker not found"); - - verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); - TestAppender.events.clear(); - } - - @Test - public void testFindFail() throws Exception { - - wireMockRule.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(400) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(""))); - - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - } - - @Test - public void testAddFail() throws Exception { - wireMockRule.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody("test"))); - ServiceEndPointRequest request = new ServiceEndPointRequest(); - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.addServiceEndPoint(request); - } - - @Test - public void testBuildServiceEndPointLookupRequest() { - GRMClient client = new GRMClient(); - ServiceEndPointLookupRequest request = client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV"); - assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName()); - assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor())); - assertEquals("DEV", request.getEnv()); - - } - - protected String getFileContentsAsString(String fileName) { - String content = ""; - try { - ClassLoader classLoader = this.getClass().getClassLoader(); - File file = new File(classLoader.getResource(fileName).getFile()); - content = new String(Files.readAllBytes(file.toPath())); - } - catch(Exception e) { - e.printStackTrace(); - System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); - } - return content; - } -} diff --git a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java index a1fb43ea5e..d0d0e6701b 100644 --- a/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java +++ b/common/src/test/java/org/onap/so/client/grm/ServiceEndPointListTest.java @@ -58,6 +58,30 @@ public class ServiceEndPointListTest { assertEquals("DEV", se.getProperties().get(0).getValue()); } + @Test + public void testUnmarshallServiceEndpointListStartsWithUppercase() throws Exception { + String endpointsJson = getFileContentsAsString("__files/grm/endpoints2.json"); + ServiceEndPointList sel = mapper.readValue(endpointsJson, ServiceEndPointList.class); + + List<ServiceEndPoint> list = sel.getServiceEndPointList(); + ServiceEndPoint se = list.get(0); + + assertEquals(3, list.size()); + assertEquals("dummy.pod.ns.dummy-pod3", se.getName()); + assertEquals(Integer.valueOf(1), Integer.valueOf(se.getVersion().getMajor())); + assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getMinor())); + assertEquals(Integer.valueOf(0), Integer.valueOf(se.getVersion().getPatch())); + assertEquals("192.168.120.218", se.getHostAddress()); + assertEquals("32004", se.getListenPort()); + assertEquals("37.7022", se.getLatitude()); + assertEquals("121.9358", se.getLongitude()); + assertEquals("/", se.getContextPath()); + assertEquals("edge", se.getOperationalInfo().getCreatedBy()); + assertEquals("edge", se.getOperationalInfo().getUpdatedBy()); + assertEquals("Environment", se.getProperties().get(0).getName()); + assertEquals("DEV", se.getProperties().get(0).getValue()); + } + protected String getFileContentsAsString(String fileName) { String content = ""; diff --git a/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java b/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java index 4cb9bd0e16..46f9de2268 100644 --- a/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java +++ b/common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java @@ -23,9 +23,9 @@ package org.onap.so.client.policy; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.isA; +import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import java.io.File; import java.io.IOException; diff --git a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java new file mode 100644 index 0000000000..79ce196bd3 --- /dev/null +++ b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorImplTest.java @@ -0,0 +1,57 @@ +/*- + * ============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.onap.so.client.sdno; + +import static org.junit.Assert.assertEquals; +import java.util.UUID; + +import org.junit.Test; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.so.client.sdno.beans.RequestHealthDiagnostic; +import org.onap.so.client.sdno.beans.SDNO; + +public class SDNOValidatorImplTest { + + @Test + public void buildRequestDiagnosticTest() throws Exception { + SDNOValidatorImpl validator = new SDNOValidatorImpl(); + UUID uuid = UUID.randomUUID(); + GenericVnf vnf = new GenericVnf(); + vnf.setVnfName("VNFNAME"); + vnf.setVnfId("test"); + vnf.setIpv4OamAddress("1.2.3.4"); + vnf.setNfRole("VPE"); + SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid"); + assertEquals(request.getNodeType(), "VPE"); + assertEquals(request.getOperation(), "health-diagnostic"); + + RequestHealthDiagnostic innerRequest = request.getBody().getInput().getRequestHealthDiagnostic(); + assertEquals(innerRequest.getRequestClientName(), "MSO"); + assertEquals(innerRequest.getRequestNodeName(), "VNFNAME"); + assertEquals(innerRequest.getRequestNodeUuid(), "test"); + assertEquals(innerRequest.getRequestNodeType(), "VPE"); + assertEquals(innerRequest.getRequestNodeIp(), "1.2.3.4"); + assertEquals(innerRequest.getRequestUserId(), "mechid"); + assertEquals(innerRequest.getRequestId(), uuid.toString()); + assertEquals(innerRequest.getHealthDiagnosticCode(), "default"); + + } +} diff --git a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java index 89dd2f554f..9794c9b622 100644 --- a/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java +++ b/common/src/test/java/org/onap/so/client/sdno/SDNOValidatorTest.java @@ -21,7 +21,7 @@ package org.onap.so.client.sdno; import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; @@ -100,7 +100,7 @@ public class SDNOValidatorTest { GenericVnf vnf = new GenericVnf(); vnf.setVnfId("test"); vnf.setIpv4OamAddress("1.2.3.4"); - vnf.setVnfType("VPE"); + vnf.setNfRole("VPE"); SDNO request = validator.buildRequestDiagnostic(vnf, uuid, "mechid"); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(request); diff --git a/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java b/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java index b3ae7ba9f5..27fb584b3b 100644 --- a/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java +++ b/common/src/test/java/org/onap/so/exceptions/ValidationExceptionTest.java @@ -47,7 +47,7 @@ public class ValidationExceptionTest { @Test public void validationExceptionVersion(){ - ValidationException e = new ValidationException("testMessage", "1.0"); - Assert.assertEquals("testMessage is not valid in the 1.0 version", e.getMessage()); + ValidationException e = new ValidationException("testMessage", "secondTestMessage"); + Assert.assertEquals("testMessage does not match secondTestMessage", e.getMessage()); } } diff --git a/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java b/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java index 8bcc73515b..b49c5312e5 100644 --- a/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java +++ b/common/src/test/java/org/onap/so/web/exceptions/RuntimeExceptionMapperTest.java @@ -33,16 +33,11 @@ import javax.ws.rs.core.Response.Status; import org.junit.AfterClass; import org.junit.Test; -import org.onap.so.logger.MsoAlarmLogger; + public class RuntimeExceptionMapperTest { - - @AfterClass - public static void tearDown() { - MsoAlarmLogger logger = new MsoAlarmLogger(); - logger.resetAppender(); - } + @Test public void testResponse() { diff --git a/common/src/test/resources/__files/grm/endpoints2.json b/common/src/test/resources/__files/grm/endpoints2.json new file mode 100644 index 0000000000..7c9816ff55 --- /dev/null +++ b/common/src/test/resources/__files/grm/endpoints2.json @@ -0,0 +1,145 @@ +{ + "ServiceEndPointList": [ + { + "name": "dummy.pod.ns.dummy-pod3", + "version": { + "major": 1, + "minor": 0, + "patch": "0" + }, + "hostAddress": "192.168.120.218", + "listenPort": "32004", + "latitude": "37.7022", + "longitude": "121.9358", + "registrationTime": "2017-07-18T15:39:17.367+0000", + "expirationTime": "9999-10-09T15:39:17.368+0000", + "contextPath": "/", + "routeOffer": "DEFAULT", + "statusInfo": { + "status": "RUNNING" + }, + "eventStatusInfo": { + "status": "RUNNING" + }, + "validatorStatusInfo": { + "status": "RUNNING" + }, + "operationalInfo": { + "createdBy": "edge", + "updatedBy": "edge", + "createdTimestamp": "2017-07-18T15:39:17.367+0000", + "updatedTimestamp": "2017-07-18T15:39:17.367+0000" + }, + "protocol": "dummypod-port", + "properties": [ + { + "name": "Environment", + "value": "DEV" + }, + { + "name": "Kubernetes Namespace", + "value": "dummy-pod-ns" + }, + { + "name": "cpfrun_cluster_name", + "value": "CI-PDK1-TFINIT-CJ9125401" + } + ], + "disableType": [] + }, + { + "name": "dummy.pod.ns.dummy-pod3", + "version": { + "major": 1, + "minor": 0, + "patch": "0" + }, + "hostAddress": "192.168.120.22", + "listenPort": "32004", + "latitude": "1.0", + "longitude": "1.0", + "registrationTime": "2017-07-18T15:39:17.816+0000", + "expirationTime": "9999-10-09T15:39:17.817+0000", + "contextPath": "/", + "routeOffer": "DEFAULT", + "statusInfo": { + "status": "RUNNING" + }, + "eventStatusInfo": { + "status": "RUNNING" + }, + "validatorStatusInfo": { + "status": "RUNNING" + }, + "operationalInfo": { + "createdBy": "edge", + "updatedBy": "edge", + "createdTimestamp": "2017-07-18T15:39:17.816+0000", + "updatedTimestamp": "2017-07-18T15:39:17.816+0000" + }, + "protocol": "dummypod-port", + "properties": [ + { + "name": "Environment", + "value": "DEV" + }, + { + "name": "Kubernetes Namespace", + "value": "dummy-pod-ns" + }, + { + "name": "cpfrun_cluster_name", + "value": "CI-PDK1-TFINIT-CJ9125401" + } + ], + "disableType": [] + }, + { + "name": "dummy.pod.ns.dummy-pod1", + "version": { + "major": 1, + "minor": 0, + "patch": "0" + }, + "hostAddress": "192.168.120.218", + "listenPort": "32002", + "latitude": "1.0", + "longitude": "1.0", + "registrationTime": "2017-07-18T15:39:14.443+0000", + "expirationTime": "9999-10-09T15:39:14.453+0000", + "contextPath": "/", + "routeOffer": "DEFAULT", + "statusInfo": { + "status": "RUNNING" + }, + "eventStatusInfo": { + "status": "RUNNING" + }, + "validatorStatusInfo": { + "status": "RUNNING" + }, + "operationalInfo": { + "createdBy": "edge", + "updatedBy": "edge", + "createdTimestamp": "2017-07-18T15:39:14.443+0000", + "updatedTimestamp": "2017-07-18T15:39:14.443+0000" + }, + "protocol": "dummypod-port", + "properties": [ + { + "name": "Environment", + "value": "DEV" + }, + { + "name": "Kubernetes Namespace", + "value": "dummy-pod-ns" + }, + { + "name": "cpfrun_cluster_name", + "value": "CI-PDK1-TFINIT-CJ9125401" + } + ], + "disableType": [] + } + ] +}
\ No newline at end of file diff --git a/common/src/test/resources/aai.properties b/common/src/test/resources/aai.properties index 897659b332..2936e841bb 100644 --- a/common/src/test/resources/aai.properties +++ b/common/src/test/resources/aai.properties @@ -1,3 +1,3 @@ aai.endpoint=http://localhost:8443 -aai.auth=2630606608347B7124C244AB0FE34F6F +aai.auth=5E12ACACBD552A415E081E29F2C4772F9835792A51C766CCFDD7433DB5220B59969CB2798C mso.msoKey=07a7159d3bf51a0e53be7a8f89699be7
\ No newline at end of file diff --git a/common/src/test/resources/logback-test.xml b/common/src/test/resources/logback-test.xml index 772eeabeb6..b52e6be022 100644 --- a/common/src/test/resources/logback-test.xml +++ b/common/src/test/resources/logback-test.xml @@ -65,6 +65,10 @@ <appender-ref ref="STDOUT" /> </logger> + <logger name="org.reflections" level="ERROR" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + <root level="WARN"> <appender-ref ref="STDOUT" /> |