aboutsummaryrefslogtreecommitdiffstats
path: root/common/src
diff options
context:
space:
mode:
Diffstat (limited to 'common/src')
-rw-r--r--common/src/main/java/org/onap/so/client/RestClient.java65
-rw-r--r--common/src/main/java/org/onap/so/client/RestClientSSL.java10
-rw-r--r--common/src/main/java/org/onap/so/client/RestRequest.java2
-rw-r--r--common/src/main/java/org/onap/so/client/RestTemplateConfig.java35
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java3
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIObjectPlurals.java3
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIObjectType.java124
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java81
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java9
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIRestClient.java53
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java267
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java39
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIVersion.java3
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java20
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/AAIResultWrapper.java41
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java3
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java54
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java88
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java54
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java71
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java45
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java47
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java5
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java29
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java52
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java126
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java11
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java80
-rw-r--r--common/src/main/java/org/onap/so/client/aai/objects/AAIServiceInstance.java141
-rw-r--r--common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java2
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java20
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java20
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java6
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyClient.java3
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java48
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Config.java217
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java127
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/Content.java47
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java59
-rw-r--r--common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java166
-rw-r--r--common/src/main/java/org/onap/so/exceptions/MSOException.java56
-rw-r--r--common/src/main/java/org/onap/so/logger/LoggerStartupListener.java5
-rw-r--r--common/src/main/java/org/onap/so/logger/MsoLogger.java41
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java158
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java (renamed from common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java)164
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java110
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java (renamed from common/src/main/java/org/onap/so/client/policy/LoggingFilter.java)14
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java (renamed from common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java)2
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java135
-rw-r--r--common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java119
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Request.java19
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java62
-rw-r--r--common/src/main/java/org/onap/so/utils/TargetEntity.java15
-rw-r--r--common/src/test/java/org/onap/so/adapter_utils/tests/MsoLoggerTest.java331
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIObjectTypeTest.java14
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java1
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java102
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java20
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIRestClientTest.java72
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java133
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAITransactionalClientTest.java13
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/AAIResultWrapperTest.java27
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java41
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java8
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java52
-rw-r--r--common/src/test/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUriTest.java10
-rw-r--r--common/src/test/java/org/onap/so/client/aai/objects/AAIServiceInstanceTest.java53
-rw-r--r--common/src/test/java/org/onap/so/client/grm/GRMClientTest.java118
-rw-r--r--common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java71
-rw-r--r--common/src/test/resources/__files/Policy/configJson.json23
-rw-r--r--common/src/test/resources/__files/Policy/policyConfig.json20
-rw-r--r--common/src/test/resources/__files/aai/singletransaction/sample-request.json26
-rw-r--r--common/src/test/resources/__files/aai/singletransaction/sample-response-failure.json30
-rw-r--r--common/src/test/resources/__files/aai/singletransaction/sample-response.json22
-rw-r--r--common/src/test/resources/logback-test.xml189
-rw-r--r--common/src/test/resources/mso-bad.json20
-rw-r--r--common/src/test/resources/mso.json21
-rw-r--r--common/src/test/resources/mso.properties28
-rw-r--r--common/src/test/resources/mso2.json20
-rw-r--r--common/src/test/resources/mso2.properties22
80 files changed, 3243 insertions, 1420 deletions
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 79fd7df7ce..1a453c6b2f 100644
--- a/common/src/main/java/org/onap/so/client/RestClient.java
+++ b/common/src/main/java/org/onap/so/client/RestClient.java
@@ -36,7 +36,6 @@ import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
-
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation.Builder;
@@ -46,44 +45,38 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriBuilder;
-
import org.onap.so.client.policy.CommonObjectMapperProvider;
-import org.onap.so.client.policy.LoggingFilter;
-import org.onap.so.logger.MsoLogger;
-import org.onap.so.logging.jaxrs.filter.jersey.JaxRsClientLogging;
+import org.onap.so.logging.jaxrs.filter.JaxRsClientLogging;
+import org.onap.so.logging.jaxrs.filter.PayloadLoggingFilter;
import org.onap.so.utils.CryptoUtils;
import org.onap.so.utils.TargetEntity;
-import org.slf4j.MDC;
-
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
-
import net.jodah.failsafe.Failsafe;
import net.jodah.failsafe.RetryPolicy;
public abstract class RestClient {
- public static final String ECOMP_COMPONENT_NAME = "MSO";
+ 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;
protected final Map<String, String> headerMap;
- protected final MsoLogger msoLogger;
+ protected final Logger logger = LoggerFactory.getLogger(RestClient.class);
protected URL host;
protected Optional<URI> path;
protected String accept;
protected String contentType;
- protected String requestId;
+ protected String requestId = "";
protected JaxRsClientLogging jaxRsClientLogging;
protected RestProperties props;
protected RestClient(RestProperties props, Optional<URI> path) {
- msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, RestClient.class);
- this.requestId = MDC.get(MsoLogger.REQUEST_ID);
- if (requestId == null) {
- requestId = "";
- }
headerMap = new HashMap<>();
try {
host = props.getEndpoint();
@@ -99,24 +92,14 @@ public abstract class RestClient {
this(props, path);
this.accept = accept;
this.contentType = contentType;
- this.requestId = MDC.get(MsoLogger.REQUEST_ID);
- if (requestId == null) {
- requestId = "";
- }
this.props = props;
}
protected RestClient(URL host, String contentType) {
headerMap = new HashMap<>();
-
- msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, RestClient.class);
this.path = Optional.empty();
this.host = host;
this.contentType = contentType;
- this.requestId = MDC.get(MsoLogger.REQUEST_ID);
- if (requestId == null) {
- requestId = "";
- }
this.props = new DefaultProperties(host);
}
@@ -143,15 +126,17 @@ public abstract class RestClient {
if (webTarget == null) {
initializeClient(getClient());
- }
- Builder builder = webTarget.request();
- initializeHeaderMap(headerMap);
-
- headerMap.put("X-ECOMP-RequestID", requestId);
- for (Entry<String, String> entry : headerMap.entrySet()) {
- builder.header(entry.getKey(), entry.getValue());
- }
- return builder;
+ }
+ Builder builder = webTarget.request();
+ initializeHeaderMap(headerMap);
+ for (Entry<String, String> entry : headerMap.entrySet()) {
+ builder.header(entry.getKey(), entry.getValue());
+ }
+ return builder;
+ }
+
+ protected WebTarget getWebTarget() {
+ return this.webTarget;
}
protected abstract void initializeHeaderMap(Map<String, String> headerMap);
@@ -175,7 +160,7 @@ public abstract class RestClient {
String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(decryptedAuth);
headerMap.put("Authorization", authHeaderValue);
} catch (GeneralSecurityException e) {
- msoLogger.error(e.getMessage(), e);
+ logger.error(e.getMessage(), e);
}
}
@@ -188,7 +173,7 @@ public abstract class RestClient {
}
protected String getMergeContentType() {
- return "application/merge-patch+json";
+ return APPLICATION_MERGE_PATCH_JSON;
}
protected Client getClient() {
@@ -199,11 +184,11 @@ public abstract class RestClient {
protected void initializeClient(Client client) {
if (this.enableLogging()) {
- client.register(new LoggingFilter(this.getMaxPayloadSize()));
+ client.register(new PayloadLoggingFilter(this.getMaxPayloadSize()));
}
CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider();
client.register(new JacksonJsonProvider(provider.getMapper()));
-
+
jaxRsClientLogging = new JaxRsClientLogging();
jaxRsClientLogging.setTargetService(getTargetEntity());
client.register(jaxRsClientLogging);
@@ -286,7 +271,7 @@ public abstract class RestClient {
return format(method("DELETE", obj), resultClass).orElse(null);
}
- private Response method(String method, Object entity) {
+ public Response method(String method, Object entity) {
RetryPolicy policy = new RetryPolicy();
List<Predicate<Throwable>> items = retryOn();
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 8eaeee97ee..cb2839ae1f 100644
--- a/common/src/main/java/org/onap/so/client/RestClientSSL.java
+++ b/common/src/main/java/org/onap/so/client/RestClientSSL.java
@@ -32,7 +32,8 @@ import javax.ws.rs.client.ClientBuilder;
public abstract class RestClientSSL extends RestClient {
- public static final String SSL_KEY_STORE_KEY = "javax.net.ssl.keyStore";
+ private static final String TRUE = "true";
+ public static final String SSL_KEY_STORE_KEY = "javax.net.ssl.keyStore";
public static final String SSL_KEY_STORE_PASSWORD_KEY = "javax.net.ssl.keyStorePassword";
public static final String MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY = "mso.load.ssl.client.keystore";
@@ -51,19 +52,18 @@ public abstract class RestClientSSL extends RestClient {
Client client = null;
try {
String loadSSLKeyStore = System.getProperty(RestClientSSL.MSO_LOAD_SSL_CLIENT_KEYSTORE_KEY);
- if(loadSSLKeyStore != null && loadSSLKeyStore.equalsIgnoreCase("true")) {
+ if(loadSSLKeyStore != null && loadSSLKeyStore.equalsIgnoreCase(TRUE)) {
KeyStore ks = getKeyStore();
if(ks != null) {
client = ClientBuilder.newBuilder().keyStore(ks, System.getProperty(RestClientSSL.SSL_KEY_STORE_PASSWORD_KEY)).build();
- this.msoLogger.debug("RestClientSSL not using default SSL context - setting keystore here.");
+ logger.debug("RestClientSSL not using default SSL context - setting keystore here.");
return client;
}
}
//Use default SSL context
client = ClientBuilder.newBuilder().sslContext(SSLContext.getDefault()).build();
- this.msoLogger.debug("RestClientSSL using default SSL context!");
+ logger.info("RestClientSSL using default SSL context!");
} catch (NoSuchAlgorithmException e) {
- //this.logger.error(MessageEnum.APIH_GENERAL_EXCEPTION, "AAI", "Client init", MsoLogger.ErrorCode.UnknownError, "could not create SSL client", e);
throw new RuntimeException(e);
}
return client;
diff --git a/common/src/main/java/org/onap/so/client/RestRequest.java b/common/src/main/java/org/onap/so/client/RestRequest.java
index 985d7cc885..4788acfa7c 100644
--- a/common/src/main/java/org/onap/so/client/RestRequest.java
+++ b/common/src/main/java/org/onap/so/client/RestRequest.java
@@ -73,7 +73,7 @@ public class RestRequest implements Callable<Response> {
mapper.get().map(response);
} catch (NotFoundException e) {
if (this.client.props.mapNotFoundToEmpty() && "GET".equals(method)) {
- msoLogger.error(e);
+ msoLogger.debug("RestClient recieved not found on URL: " + this.client.getWebTarget().getUri());
return response;
} else {
throw e;
diff --git a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java
new file mode 100644
index 0000000000..ad833208dc
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java
@@ -0,0 +1,35 @@
+/*-
+ * ============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 org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
+import org.springframework.web.client.RestTemplate;
+
+@Configuration
+public class RestTemplateConfig {
+
+ @Bean
+ public RestTemplate restTemplate() {
+ return new RestTemplate( new HttpComponentsClientHttpRequestFactory());
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
index 514eab6fc4..ffc474a55a 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java
@@ -29,6 +29,7 @@ import javax.ws.rs.ext.Provider;
import javax.annotation.Priority;
import javax.ws.rs.ext.Provider;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.aai.entities.AAIError;
import org.onap.so.logger.MsoLogger;
@@ -42,7 +43,7 @@ public class AAIClientResponseExceptionMapper extends ResponseExceptionMapper {
private final String requestId;
public AAIClientResponseExceptionMapper() {
- this.requestId = MDC.get(MsoLogger.REQUEST_ID);
+ this.requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
}
@Override
public Optional<String> extractMessage(String entity) {
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 c50653a203..553c1e0db0 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
@@ -33,7 +33,8 @@ public enum AAIObjectPlurals implements GraphInventoryObjectPlurals {
SERVICE_SUBSCRIPTION(AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions"),
SERVICE_INSTANCE(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances"),
OWNING_ENTITIES(AAINamespaceConstants.BUSINESS, "/owning-entities"),
- VOLUME_GROUP(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups/");
+ VOLUME_GROUP(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups/"),
+ AVAILIBILITY_ZONE(AAIObjectType.CLOUD_REGION.uriTemplate(), "/availability-zones/");
private final String uriTemplate;
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 ce75b1716a..4b646f9ed7 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,6 +20,41 @@
package org.onap.so.client.aai;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.onap.aai.annotations.Metadata;
+import org.onap.aai.domain.yang.AllottedResource;
+import org.onap.aai.domain.yang.CloudRegion;
+import org.onap.aai.domain.yang.Collection;
+import org.onap.aai.domain.yang.Complex;
+import org.onap.aai.domain.yang.Configuration;
+import org.onap.aai.domain.yang.Customer;
+import org.onap.aai.domain.yang.GenericVnf;
+import org.onap.aai.domain.yang.InstanceGroup;
+import org.onap.aai.domain.yang.L3Network;
+import org.onap.aai.domain.yang.LineOfBusiness;
+import org.onap.aai.domain.yang.ModelVer;
+import org.onap.aai.domain.yang.NetworkPolicy;
+import org.onap.aai.domain.yang.OperationalEnvironment;
+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.Project;
+import org.onap.aai.domain.yang.Pserver;
+import org.onap.aai.domain.yang.RouteTableReferences;
+import org.onap.aai.domain.yang.ServiceInstance;
+import org.onap.aai.domain.yang.ServiceSubscription;
+import org.onap.aai.domain.yang.Tenant;
+import org.onap.aai.domain.yang.TunnelXconnect;
+import org.onap.aai.domain.yang.Vce;
+import org.onap.aai.domain.yang.VfModule;
+import org.onap.aai.domain.yang.VlanTag;
+import org.onap.aai.domain.yang.Vnfc;
+import org.onap.aai.domain.yang.VolumeGroup;
+import org.onap.aai.domain.yang.VpnBinding;
+import org.onap.aai.domain.yang.Vserver;
import org.onap.so.client.graphinventory.GraphInventoryObjectType;
import com.google.common.base.CaseFormat;
@@ -27,57 +62,84 @@ import com.google.common.base.CaseFormat;
public enum AAIObjectType implements GraphInventoryObjectType {
DEFAULT_CLOUD_REGION(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/cloud-regions/cloud-region/att-aic/{cloud-region-id}"),
- CUSTOMER(AAINamespaceConstants.BUSINESS, "/customers/customer/{global-customer-id}"),
+ CUSTOMER(AAINamespaceConstants.BUSINESS, Customer.class),
GENERIC_QUERY("/search", "/generic-query"),
BULK_PROCESS("/bulkprocess", ""),
- GENERIC_VNF(AAINamespaceConstants.NETWORK, "/generic-vnfs/generic-vnf/{vnf-id}"),
- VF_MODULE(AAIObjectType.GENERIC_VNF.uriTemplate(), "/vf-modules/vf-module/{vf-module-id}"),
- L3_NETWORK(AAINamespaceConstants.NETWORK, "/l3-networks/l3-network/{network-id}"),
- NETWORK_POLICY(AAINamespaceConstants.NETWORK, "/network-policies/network-policy/{network-policy-id}"),
+ 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, "/route-table-references/route-table-reference/{route-table-reference-id}"),
+ ROUTE_TABLE_REFERENCE(AAINamespaceConstants.NETWORK, RouteTableReferences.class),
DEFAULT_TENANT(AAINamespaceConstants.CLOUD_INFRASTRUCTURE + "/cloud-regions/cloud-region/att-aic/AAIAIC25", "/tenants/tenant/{tenant-id}"),
- VCE(AAINamespaceConstants.NETWORK, "/vces/vce/{vnf-id}"),
- VPN_BINDING(AAINamespaceConstants.NETWORK, "/vpn-bindings/vpn-binding/{vpn-id}"),
+ VCE(AAINamespaceConstants.NETWORK, Vce.class),
+ VPN_BINDING(AAINamespaceConstants.NETWORK, VpnBinding.class),
VPN_BINDINGS(AAINamespaceConstants.NETWORK, "/vpn-bindings"),
- CONFIGURATION(AAINamespaceConstants.NETWORK, "/configurations/configuration/{configuration-id}"),
- PSERVER(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/pservers/pserver/{hostname}"),
- SERVICE_SUBSCRIPTION(AAIObjectType.CUSTOMER.uriTemplate(), "/service-subscriptions/service-subscription/{service-type}"),
- SERVICE_INSTANCE(AAIObjectType.SERVICE_SUBSCRIPTION.uriTemplate(), "/service-instances/service-instance/{service-instance-id}"),
- PROJECT(AAINamespaceConstants.BUSINESS, "/projects/project/{id}"),
- LINE_OF_BUSINESS(AAINamespaceConstants.BUSINESS, "/lines-of-business/line-of-business/{id}"),
- PLATFORM(AAINamespaceConstants.BUSINESS, "/platforms/platform/{id}"),
- OWNING_ENTITY(AAINamespaceConstants.BUSINESS, "/owning-entities/owning-entity/{id}"),
- ALLOTTED_RESOURCE(AAIObjectType.SERVICE_INSTANCE.uriTemplate(), "/allotted-resources/allotted-resource/{id}"),
+ 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, "/operational-environments/operational-environment/{operational-environment-id}"),
- CLOUD_REGION(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, "/cloud-regions/cloud-region/{cloud-owner-id}/{cloud-region-id}"),
- TENANT(AAIObjectType.CLOUD_REGION.uriTemplate(), "/tenants/tenant/{tenant-id}"),
- VOLUME_GROUP(AAIObjectType.CLOUD_REGION.uriTemplate(), "/volume-groups/volume-group/{volume-group-id}"),
- VSERVER(AAIObjectType.TENANT.uriTemplate(), "/vservers/vserver/{vserver-id}"),
- MODEL_VER(AAINamespaceConstants.SERVICE_DESIGN_AND_CREATION + "/models/model/{model-invariant-id}", "/model-vers/model-ver/{model-version-id}"),
- TUNNEL_XCONNECT(AAIObjectType.ALLOTTED_RESOURCE.uriTemplate(), "/tunnel-xconnects/tunnel-xconnect/{tunnel-id}"),
- P_INTERFACE(AAIObjectType.PSERVER.uriTemplate(), "/p-interfaces/p-interface/{interface-name}"),
- PHYSICAL_LINK(AAINamespaceConstants.NETWORK, "/physical-links/physical-link/{link-name}"),
- INSTANCE_GROUP(AAINamespaceConstants.NETWORK, "/instance-groups/instance-group/{id}"),
- COLLECTION(AAINamespaceConstants.NETWORK, "/collections/collection/{collection-id}"),
+ 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),
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) {
this.parentUri = parentUri;
this.partialUri = partialUri;
this.uriTemplate = parentUri + partialUri;
+ this.aaiObjectClass = null;
+ }
+
+ private AAIObjectType(String parentUri, Class<?> aaiObjectClass) {
+ this.parentUri = parentUri;
+ this.partialUri = removeParentUri(aaiObjectClass, parentUri);
+ this.uriTemplate = parentUri + partialUri;
+ this.aaiObjectClass = aaiObjectClass;
}
@Override
public String toString() {
return this.uriTemplate();
}
-
+
+ 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 {
+ return AAIObjectType.UNKNOWN;
+ }
+ }
@Override
public String typeName() {
return this.typeName(CaseFormat.LOWER_HYPHEN);
@@ -101,4 +163,8 @@ public enum AAIObjectType implements GraphInventoryObjectType {
public String partialUri() {
return this.partialUri;
}
+
+ protected String removeParentUri(Class<?> aaiObjectClass, String parentUri) {
+ return aaiObjectClass.getAnnotation(Metadata.class).uriTemplate().replace(parentUri, "");
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java b/common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java
new file mode 100644
index 0000000000..6ccb592409
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/AAIPatchConverter.java
@@ -0,0 +1,81 @@
+/*-
+ * ============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.aai;
+
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException;
+import org.onap.so.jsonpath.JsonPathUtil;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+public class AAIPatchConverter {
+
+ private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider();
+ private static final AAICommonObjectMapperPatchProvider patchProvider = new AAICommonObjectMapperPatchProvider();
+ private static final Pattern LOCATE_COMPLEX_OBJECT = Pattern.compile("^((?!relationship-list).)+?\\['[^\\[\\]]+?'\\]$");
+
+
+ protected String convertPatchFormat(Object obj) {
+ return validatePatchObject(marshallObjectToPatchFormat(obj));
+ }
+
+ protected String validatePatchObject(String payload) {
+ if (hasComplexObject(payload)) {
+ throw new GraphInventoryPatchDepthExceededException(payload);
+ }
+
+ return payload;
+ }
+
+ /** validates client side that json does not include any complex objects
+ * relationship-list is omitted from this validation
+ */
+ protected boolean hasComplexObject(String json) {
+ if (json.isEmpty()) {
+ return false;
+ }
+ String complex = "$.*.*";
+ String array = "$.*.*.*";
+ List<String> result = JsonPathUtil.getInstance().getPathList(json, complex);
+ List<String> result2 = JsonPathUtil.getInstance().getPathList(json, array);
+
+ result.addAll(result2);
+ return result.stream().anyMatch(item -> LOCATE_COMPLEX_OBJECT.matcher(item).find());
+ }
+
+ protected String marshallObjectToPatchFormat(Object obj) {
+ Object value = obj;
+ try {
+ if (!(obj instanceof Map || obj instanceof String)) {
+ value = patchProvider.getMapper().writeValueAsString(obj);
+ } else if (obj instanceof Map) {
+ value = standardProvider.getMapper().writeValueAsString(obj);
+ }
+ } catch (JsonProcessingException e) {
+ value = "{}";
+ }
+
+ return (String)value;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
index 072534d6f6..7e4397ec29 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIResourcesClient.java
@@ -309,6 +309,15 @@ public class AAIResourcesClient extends AAIClient {
return new AAITransactionalClient(this.getVersion());
}
+ /**
+ * Starts a transaction groups multiple A&AI mutations
+ *
+ * @return
+ */
+ public AAISingleTransactionClient beginSingleTransaction() {
+ return new AAISingleTransactionClient(this.getVersion());
+ }
+
private AAIUri addParams(Optional<Depth> depth, boolean nodesOnly, AAIUri uri) {
AAIUri clone = uri.clone();
if (depth.isPresent()) {
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 2bd5f118c0..ac6e939e9e 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,6 +20,8 @@
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;
@@ -41,9 +43,9 @@ public class AAIRestClient extends RestClientSSL {
private final AAIProperties aaiProperties;
private static final AAICommonObjectMapperProvider standardProvider = new AAICommonObjectMapperProvider();
- private static final AAICommonObjectMapperPatchProvider patchProvider = new AAICommonObjectMapperPatchProvider();
- private static final Pattern LOCATE_COMPLEX_OBJECT = Pattern.compile("^((?!relationship-list).)+?\\['[^\\[\\]]+?'\\]$");
+ private final AAIPatchConverter patchConverter = new AAIPatchConverter();
+
protected AAIRestClient(AAIProperties props, URI uri) {
super(props, Optional.of(uri));
this.aaiProperties = props;
@@ -79,53 +81,20 @@ public class AAIRestClient extends RestClientSSL {
@Override
public Response patch(Object obj) {
- String value = convertObjectToPatchFormat(obj);
- validatePatchObject(value);
- return super.patch(value);
+ return super.patch(convertToPatchFormat(obj));
}
@Override
public <T> T patch(Object obj, Class<T> resultClass) {
- String value = convertObjectToPatchFormat(obj);
- validatePatchObject(value);
- return super.patch(value, resultClass);
+ return super.patch(convertToPatchFormat(obj), resultClass);
}
- protected String convertObjectToPatchFormat(Object obj) {
- Object value = obj;
- try {
- if (!(obj instanceof Map || obj instanceof String)) {
- value = patchProvider.getMapper().writeValueAsString(obj);
- } else if (obj instanceof Map) {
- value = standardProvider.getMapper().writeValueAsString(obj);
- }
- } catch (JsonProcessingException e) {
- value = "{}";
- }
-
- return (String)value;
+ protected AAIPatchConverter getPatchConverter() {
+ return this.patchConverter;
}
-
- protected void validatePatchObject(String payload) {
- if (hasComplexObject(payload)) {
- throw new GraphInventoryPatchDepthExceededException(payload);
- }
- }
-
- /** validates client side that json does not include any complex objects
- * relationship-list is omitted from this validation
- */
- protected boolean hasComplexObject(String json) {
- if (json.isEmpty()) {
- return false;
- }
- String complex = "$.*.*";
- String array = "$.*.*.*";
- List<String> result = JsonPathUtil.getInstance().getPathList(json, complex);
- List<String> result2 = JsonPathUtil.getInstance().getPathList(json, array);
-
- result.addAll(result2);
- return result.stream().anyMatch(item -> LOCATE_COMPLEX_OBJECT.matcher(item).find());
+ protected String convertToPatchFormat(Object obj) {
+ return getPatchConverter().convertPatchFormat(obj);
}
+
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java
new file mode 100644
index 0000000000..2ecdb7c480
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/AAISingleTransactionClient.java
@@ -0,0 +1,267 @@
+/*-
+ * ============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.aai;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
+
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.core.GenericType;
+
+import org.onap.aai.domain.yang.Relationship;
+import org.onap.so.client.RestClient;
+import org.onap.so.client.aai.entities.AAIEdgeLabel;
+import org.onap.so.client.aai.entities.AAIError;
+import org.onap.so.client.aai.entities.bulkprocess.Transactions;
+import org.onap.so.client.aai.entities.singletransaction.OperationBodyRequest;
+import org.onap.so.client.aai.entities.singletransaction.OperationBodyResponse;
+import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest;
+import org.onap.so.client.aai.entities.singletransaction.SingleTransactionResponse;
+import org.onap.so.client.aai.entities.uri.AAIResourceUri;
+import org.onap.so.client.aai.entities.uri.AAIUri;
+import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.onap.so.client.graphinventory.exceptions.BulkProcessFailed;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Joiner;
+
+public class AAISingleTransactionClient extends AAIClient {
+
+ private final SingleTransactionRequest request;
+ private final AAIVersion version;
+ private int actionCount = 0;
+
+ private final AAIPatchConverter patchConverter = new AAIPatchConverter();
+
+ protected AAISingleTransactionClient(AAIVersion version) {
+ super();
+ this.version = version;
+ this.request = new SingleTransactionRequest();
+ }
+
+ /**
+ * creates a new object in A&AI
+ *
+ * @param obj - can be any object which will marshal into a valid A&AI payload
+ * @param uri
+ * @return
+ */
+ public AAISingleTransactionClient create(AAIResourceUri uri, Object obj) {
+ request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri.build().toString()).withBody(obj));
+ incrementActionAmount();
+ return this;
+ }
+
+ /**
+ * creates a new object in A&AI with no payload body
+ *
+ * @param uri
+ * @return
+ */
+ public AAISingleTransactionClient createEmpty(AAIResourceUri uri) {
+ request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uri.build().toString()).withBody(new HashMap<String, String>()));
+ incrementActionAmount();
+ return this;
+ }
+
+ /**
+ * Adds a relationship between two objects in A&AI
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public AAISingleTransactionClient connect(AAIResourceUri uriA, AAIResourceUri uriB) {
+ AAIResourceUri uriAClone = uriA.clone();
+ request.getOperations().add(new OperationBodyRequest().withAction("put").withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB)));
+ incrementActionAmount();
+ return this;
+ }
+
+ /**
+ * relationship between multiple objects in A&AI - connects A to all objects specified in list
+ *
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public AAISingleTransactionClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris) {
+ for (AAIResourceUri uri : uris) {
+ this.connect(uriA, uri);
+ }
+ return this;
+ }
+
+ public AAISingleTransactionClient connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) {
+ AAIResourceUri uriAClone = uriA.clone();
+ RestClient aaiRC = this.createClient(uriAClone.relationshipAPI());
+ aaiRC.put(this.buildRelationship(uriB, label));
+ return this;
+ }
+
+ public AAISingleTransactionClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris, AAIEdgeLabel label) {
+ for (AAIResourceUri uri : uris) {
+ this.connect(uriA, uri, label);
+ }
+ return this;
+ }
+
+ /**
+ * Removes relationship from two objects in A&AI
+ *
+ * @param uriA
+ * @param uriB
+ * @return
+ */
+ public AAISingleTransactionClient disconnect(AAIResourceUri uriA, AAIResourceUri uriB) {
+ AAIResourceUri uriAClone = uriA.clone();
+ request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(uriAClone.relationshipAPI().build().toString()).withBody(this.buildRelationship(uriB)));
+ incrementActionAmount();
+ return this;
+ }
+
+ /**
+ * Removes relationship from multiple objects - disconnects A from all objects specified in list
+ * @param uriA
+ * @param uris
+ * @return
+ */
+ public AAISingleTransactionClient disconnect(AAIResourceUri uriA, List<AAIResourceUri> uris) {
+ for (AAIResourceUri uri : uris) {
+ this.disconnect(uriA, uri);
+ }
+ return this;
+ }
+ /**
+ * Deletes object from A&AI. Automatically handles resource-version.
+ *
+ * @param uri
+ * @return
+ */
+ public AAISingleTransactionClient delete(AAIResourceUri uri) {
+ AAIResourcesClient client = new AAIResourcesClient();
+ AAIResourceUri clone = uri.clone();
+ Map<String, Object> result = client.get(new GenericType<Map<String, Object>>(){}, clone)
+ .orElseThrow(() -> new NotFoundException(clone.build() + " does not exist in A&AI"));
+ String resourceVersion = (String) result.get("resource-version");
+ request.getOperations().add(new OperationBodyRequest().withAction("delete").withUri(clone.resourceVersion(resourceVersion).build().toString()).withBody(""));
+ incrementActionAmount();
+ return this;
+ }
+
+ /**
+ * @param obj - can be any object which will marshal into a valid A&AI payload
+ * @param uri
+ * @return
+ */
+ public AAISingleTransactionClient update(AAIResourceUri uri, Object obj) {
+
+ final String payload = getPatchConverter().convertPatchFormat(obj);
+ request.getOperations().add(new OperationBodyRequest().withAction("patch").withUri(uri.build().toString()).withBody(payload));
+ incrementActionAmount();
+ return this;
+ }
+
+ private void incrementActionAmount() {
+ actionCount++;
+ }
+ /**
+ * Executes all created transactions in A&AI
+ * @throws BulkProcessFailed
+ */
+ public void execute() throws BulkProcessFailed {
+ RestClient client = this.createClient(AAIUriFactory.createResourceUri(AAIObjectType.SINGLE_TRANSACTION));
+ try {
+ SingleTransactionResponse response = client.post(this.request, SingleTransactionResponse.class);
+ if (response != null) {
+ final Optional<String> errorMessage = this.locateErrorMessages(response);
+ if (errorMessage.isPresent()) {
+ throw new BulkProcessFailed("One or more transactions failed in A&AI. Check logs for payloads.\nMessages:\n" + errorMessage.get());
+ }
+ } else {
+ throw new BulkProcessFailed("Transactions acccepted by A&AI, but there was no response. Unsure of result.");
+ }
+ } finally {
+ this.request.getOperations().clear();
+ this.actionCount = 0;
+ }
+ }
+
+ protected Optional<String> locateErrorMessages(SingleTransactionResponse response) {
+ final List<String> errorMessages = new ArrayList<>();
+ final ObjectMapper mapper = new ObjectMapper();
+
+ for (OperationBodyResponse body : response.getOperationResponses()) {
+ if (Optional.ofNullable(body.getResponseStatusCode()).orElse(400) > 300) {
+ AAIError error;
+ try {
+ error = mapper.readValue(mapper.writeValueAsString(body.getResponseBody()), AAIError.class);
+ } catch (IOException e) {
+ logger.error("could not parse error object from A&AI", e);
+ error = new AAIError();
+ }
+ AAIErrorFormatter formatter = new AAIErrorFormatter(error);
+ String outputMessage = formatter.getMessage();
+ errorMessages.add(outputMessage);
+ }
+ }
+
+ if (!errorMessages.isEmpty()) {
+ return Optional.of(Joiner.on("\n").join(errorMessages));
+ } else {
+ return Optional.empty();
+ }
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri) {
+ return buildRelationship(uri, Optional.empty());
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) {
+ return buildRelationship(uri, Optional.of(label));
+ }
+ private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) {
+ final Relationship result = new Relationship();
+ result.setRelatedLink(uri.build().toString());
+ if (label.isPresent()) {
+ result.setRelationshipLabel(label.toString());
+ }
+ return result;
+ }
+
+ @Override
+ protected AAIVersion getVersion() {
+ return this.version;
+ }
+
+ protected SingleTransactionRequest getRequest() {
+ return this.request;
+ }
+
+ protected AAIPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
index 884d2aaec6..118a3edf1c 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAITransactionalClient.java
@@ -20,6 +20,8 @@
package org.onap.so.client.aai;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -34,6 +36,7 @@ import javax.ws.rs.core.Response;
import org.onap.aai.domain.yang.Relationship;
import org.onap.so.client.RestClient;
+import org.onap.so.client.aai.entities.AAIEdgeLabel;
import org.onap.so.client.aai.entities.AAIError;
import org.onap.so.client.aai.entities.bulkprocess.OperationBody;
import org.onap.so.client.aai.entities.bulkprocess.Transaction;
@@ -54,6 +57,9 @@ public class AAITransactionalClient extends AAIClient {
private Transaction currentTransaction;
private final AAIVersion version;
private int actionCount = 0;
+
+ private final AAIPatchConverter patchConverter = new AAIPatchConverter();
+
protected AAITransactionalClient(AAIVersion version) {
super();
this.version = version;
@@ -129,6 +135,20 @@ public class AAITransactionalClient extends AAIClient {
return this;
}
+ public AAITransactionalClient connect(AAIResourceUri uriA, AAIResourceUri uriB, AAIEdgeLabel label) {
+ AAIResourceUri uriAClone = uriA.clone();
+ RestClient aaiRC = this.createClient(uriAClone.relationshipAPI());
+ aaiRC.put(this.buildRelationship(uriB, label));
+ return this;
+ }
+
+ public AAITransactionalClient connect(AAIResourceUri uriA, List<AAIResourceUri> uris, AAIEdgeLabel label) {
+ for (AAIResourceUri uri : uris) {
+ this.connect(uriA, uri, label);
+ }
+ return this;
+ }
+
/**
* Removes relationship from two objects in A&AI
*
@@ -178,7 +198,8 @@ public class AAITransactionalClient extends AAIClient {
* @return
*/
public AAITransactionalClient update(AAIResourceUri uri, Object obj) {
- currentTransaction.getPatch().add(new OperationBody().withUri(uri.build().toString()).withBody(obj));
+ final String payload = getPatchConverter().convertPatchFormat(obj);
+ currentTransaction.getPatch().add(new OperationBody().withUri(uri.build().toString()).withBody(payload));
incrementActionAmount();
return this;
}
@@ -247,9 +268,19 @@ public class AAITransactionalClient extends AAIClient {
return Optional.empty();
}
}
- private Relationship buildRelationship(AAIUri uri) {
+ private Relationship buildRelationship(AAIResourceUri uri) {
+ return buildRelationship(uri, Optional.empty());
+ }
+
+ private Relationship buildRelationship(AAIResourceUri uri, AAIEdgeLabel label) {
+ return buildRelationship(uri, Optional.of(label));
+ }
+ private Relationship buildRelationship(AAIResourceUri uri, Optional<AAIEdgeLabel> label) {
final Relationship result = new Relationship();
result.setRelatedLink(uri.build().toString());
+ if (label.isPresent()) {
+ result.setRelationshipLabel(label.toString());
+ }
return result;
}
@@ -261,4 +292,8 @@ public class AAITransactionalClient extends AAIClient {
protected Transactions getTransactions() {
return this.transactions;
}
+
+ protected AAIPatchConverter getPatchConverter() {
+ return this.patchConverter;
+ }
}
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 20ee5becca..de418f32c0 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
@@ -28,7 +28,8 @@ public enum AAIVersion implements GraphInventoryVersion {
V10("v10"),
V11("v11"),
V12("v12"),
- V13("v13");
+ V13("v13"),
+ V14("v14");
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/AAIEdgeLabel.java b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
index 0356e86861..434dbf946b 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/AAIEdgeLabel.java
@@ -1,3 +1,23 @@
+/*-
+ * ============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.aai.entities;
import org.onap.so.client.graphinventory.entities.GraphInventoryEdgeLabel;
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 9087995f97..45621f09a6 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,28 +26,45 @@ 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 com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
public class AAIResultWrapper implements Serializable {
private static final long serialVersionUID = 5895841925807816737L;
- private final Optional<String> jsonBody;
+ private final String jsonBody;
private final ObjectMapper mapper;
+ private final transient Logger logger = Logger.getLogger(AAIResultWrapper.class);
+
public AAIResultWrapper(String json) {
- this.jsonBody = Optional.ofNullable(json);
+ this.jsonBody = json;
this.mapper = new AAICommonObjectMapperProvider().getMapper();
}
+ public AAIResultWrapper(Object aaiObject) {
+ this.mapper = new AAICommonObjectMapperProvider().getMapper();
+ this.jsonBody = mapObjectToString(aaiObject);
+ }
+
+ protected String mapObjectToString(Object aaiObject) {
+ try {
+ return mapper.writeValueAsString(aaiObject);
+ } catch (JsonProcessingException e) {
+ logger.warn("could not parse object into json - defaulting to {}");
+ return "{}";
+ }
+ }
public Optional<Relationships> getRelationships() {
final String path = "$.relationship-list";
- if (!jsonBody.isPresent()) {
+ if (isEmpty()) {
return Optional.empty();
}
- Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody.get(), path);
+ Optional<String> result = JsonPathUtil.getInstance().locateResult(jsonBody, path);
if (result.isPresent()) {
return Optional.of(new Relationships(result.get()));
} else {
@@ -56,33 +73,37 @@ public class AAIResultWrapper implements Serializable {
}
public String getJson() {
- return jsonBody.orElse("{}");
+ if(jsonBody == null) {
+ return "{}";
+ } else {
+ return jsonBody;
+ }
}
public Map<String, Object> asMap() {
- if (!this.jsonBody.isPresent()) {
+ if (isEmpty()) {
return new HashMap<>();
}
try {
- return mapper.readValue(this.jsonBody.get(), new TypeReference<Map<String, Object>>(){});
+ return mapper.readValue(this.jsonBody, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
return new HashMap<>();
}
}
public <T> Optional<T> asBean(Class<T> clazz) {
- if (!this.jsonBody.isPresent()) {
+ if (isEmpty()) {
return Optional.empty();
}
try {
- return Optional.of(mapper.readValue(this.jsonBody.get(), clazz));
+ return Optional.of(mapper.readValue(this.jsonBody, clazz));
} catch (IOException e) {
return Optional.empty();
}
}
public boolean isEmpty() {
- return !this.jsonBody.isPresent();
+ return jsonBody == null;
}
@Override
public String toString() {
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
index 1803440edd..4b2aac1364 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBody.java
@@ -23,6 +23,8 @@ package org.onap.so.client.aai.entities.bulkprocess;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.annotation.JsonRawValue;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
@@ -34,6 +36,7 @@ public class OperationBody {
@JsonProperty("uri")
private String uri;
@JsonProperty("body")
+@JsonSerialize(using = OperationBodySerializer.class)
private Object body;
@JsonProperty("uri")
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java
new file mode 100644
index 0000000000..2981e0deef
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/bulkprocess/OperationBodySerializer.java
@@ -0,0 +1,54 @@
+/*-
+ * ============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.aai.entities.bulkprocess;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+public class OperationBodySerializer extends StdSerializer<Object> {
+
+ private static final long serialVersionUID = 5367385969270400106L;
+
+ public OperationBodySerializer() {
+ this(null);
+ }
+ public OperationBodySerializer(Class<Object> t) {
+ super(t);
+ }
+
+ @Override
+ public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
+ throws IOException, JsonProcessingException {
+
+ if (value instanceof String) {
+ gen.writeRawValue((String)value);
+ } else {
+ gen.writeObject(value);
+ }
+
+ }
+
+}
+
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java
new file mode 100644
index 0000000000..f2626e9e43
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequest.java
@@ -0,0 +1,88 @@
+/*-
+ * ============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.entities.singletransaction;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.annotation.JsonRawValue;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+"action",
+"uri",
+"body"
+})
+public class OperationBodyRequest {
+
+@JsonProperty("action")
+private String action;
+@JsonProperty("uri")
+private String uri;
+@JsonProperty("body")
+@JsonSerialize(using = OperationBodyRequestSerializer.class)
+private Object body;
+
+
+public String getAction() {
+ return action;
+}
+
+public void setAction(String action) {
+ this.action = action;
+}
+
+public OperationBodyRequest withAction(String action) {
+ this.action = action;
+ return this;
+}
+@JsonProperty("uri")
+public String getUri() {
+return uri;
+}
+
+@JsonProperty("uri")
+public void setUri(String uri) {
+this.uri = uri;
+}
+
+public OperationBodyRequest withUri(String uri) {
+this.uri = uri;
+return this;
+}
+
+@JsonProperty("body")
+public Object getBody() {
+return body;
+}
+
+@JsonProperty("body")
+public void setBody(Object body) {
+this.body = body;
+}
+
+public OperationBodyRequest withBody(Object body) {
+this.body = body;
+return this;
+}
+
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java
new file mode 100644
index 0000000000..170719962e
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyRequestSerializer.java
@@ -0,0 +1,54 @@
+/*-
+ * ============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.aai.entities.singletransaction;
+
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.SerializerProvider;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+public class OperationBodyRequestSerializer extends StdSerializer<Object> {
+
+ private static final long serialVersionUID = 5367385969270400106L;
+
+ public OperationBodyRequestSerializer() {
+ this(null);
+ }
+ public OperationBodyRequestSerializer(Class<Object> t) {
+ super(t);
+ }
+
+ @Override
+ public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
+ throws IOException, JsonProcessingException {
+
+ if (value instanceof String) {
+ gen.writeRawValue((String)value);
+ } else {
+ gen.writeObject(value);
+ }
+
+ }
+
+}
+
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java
new file mode 100644
index 0000000000..71f65b50db
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/OperationBodyResponse.java
@@ -0,0 +1,71 @@
+/*-
+ * ============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.aai.entities.singletransaction;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonPropertyOrder({
+"action",
+"uri",
+"response-status-code",
+"response-body"
+})
+public class OperationBodyResponse {
+
+ @JsonProperty("action")
+ public String action;
+ @JsonProperty("uri")
+ public String uri;
+ @JsonProperty("response-status-code")
+ public Integer responseStatusCode;
+ @JsonProperty("response-body")
+ public Object responseBody;
+
+ public String getAction() {
+ return action;
+ }
+ public void setAction(String action) {
+ this.action = action;
+ }
+ public String getUri() {
+ return uri;
+ }
+ public void setUri(String uri) {
+ this.uri = uri;
+ }
+ @JsonProperty("response-status-code")
+ public Integer getResponseStatusCode() {
+ return responseStatusCode;
+ }
+ @JsonProperty("response-status-code")
+ public void setResponseStatusCode(Integer responseStatusCode) {
+ this.responseStatusCode = responseStatusCode;
+ }
+ @JsonProperty("response-body")
+ public Object getResponseBody() {
+ return responseBody;
+ }
+ @JsonProperty("response-body")
+ public void getResponseBody(Object responseBody) {
+ this.responseBody = responseBody;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java
new file mode 100644
index 0000000000..0d392c453f
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionRequest.java
@@ -0,0 +1,45 @@
+/*-
+ * ============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.aai.entities.singletransaction;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class SingleTransactionRequest {
+
+ @JsonProperty("operations")
+ public List<OperationBodyRequest> operations;
+
+ public List<OperationBodyRequest> getOperations() {
+
+ if (operations == null) {
+ operations = new ArrayList<>();
+ }
+
+ return operations;
+ }
+
+ public void setOperations(List<OperationBodyRequest> operations) {
+ this.operations = operations;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java
new file mode 100644
index 0000000000..db251b5b3b
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/singletransaction/SingleTransactionResponse.java
@@ -0,0 +1,47 @@
+/*-
+ * ============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.aai.entities.singletransaction;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+public class SingleTransactionResponse {
+
+ @JsonProperty("operation-responses")
+ public List<OperationBodyResponse> operationResponses;
+
+ @JsonProperty("operation-responses")
+ public List<OperationBodyResponse> getOperationResponses() {
+ if (operationResponses == null) {
+ operationResponses = new ArrayList<>();
+ }
+ return operationResponses;
+ }
+
+ @JsonProperty("operation-responses")
+ public void setOperationResponses(List<OperationBodyResponse> operationResponses) {
+ this.operationResponses = operationResponses;
+ }
+
+
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
index 8731ae719a..9b5acc5bee 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
@@ -27,7 +27,9 @@ import javax.ws.rs.core.UriBuilder;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.Format;
+import org.onap.so.client.graphinventory.GraphInventoryObjectType;
import org.onap.so.client.graphinventory.entities.uri.Depth;
+import org.onap.so.client.graphinventory.entities.uri.GraphInventoryResourceUri;
import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAISimpleUri extends SimpleUri implements AAIResourceUri {
@@ -51,6 +53,9 @@ public class AAISimpleUri extends SimpleUri implements AAIResourceUri {
protected AAISimpleUri(AAIObjectPlurals type, Object... values) {
super(type, values);
}
+ protected AAISimpleUri(AAIResourceUri parentUri, AAIObjectType childType, Object... childValues) {
+ super(parentUri, childType, childValues);
+ }
@Override
public AAISimpleUri relationshipAPI() {
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
index 2a7c8ee78c..1f819ca5de 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAIUriFactory.java
@@ -24,14 +24,18 @@ import java.net.URI;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
-import org.onap.so.client.graphinventory.entities.uri.SimpleUri;
public class AAIUriFactory {
/**
* values are filled into the URI template specified in {@link AAIObjectType} in order
- *
+ * <br>
+ * There are two special lookups performed on certain types when a single value is specified:
+ * <br>
+ * Service Instance and AllottedResources
+ * <br>
+ * These can be retrieved without all their required keys but an HTTP call is required to do so
* @param type
* @param values
* @return
@@ -39,6 +43,8 @@ public class AAIUriFactory {
public static AAIResourceUri createResourceUri(AAIObjectType type, Object... values) {
if (AAIObjectType.SERVICE_INSTANCE.equals(type)) {
return new ServiceInstanceUri(values);
+ } else if (AAIObjectType.ALLOTTED_RESOURCE.equals(type)) {
+ return new AllottedResourceLookupUri(values);
} else {
return new AAISimpleUri(type, values);
}
@@ -49,6 +55,11 @@ public class AAIUriFactory {
}
+ public static AAIResourceUri createNodesUri(AAIObjectPlurals type) {
+ return new NodesUri(type);
+
+ }
+
/**
* This method should only be used to wrap a URI retrieved from A&AI contained within an object response
*
@@ -60,6 +71,20 @@ public class AAIUriFactory {
return new AAISimpleUri(type, uri);
}
+
+ /**
+ * creates an AAIResourceUri from a parentUri
+ *
+ * @param parentUri
+ * @param childType
+ * @param childValues
+ * @return
+ */
+ public static AAIResourceUri createResourceFromParentURI(AAIResourceUri parentUri, AAIObjectType childType, Object... childValues) {
+
+ return new AAISimpleUri(parentUri, childType, childValues);
+ }
+
/**
* Creates a uri for a plural type e.g. /cloud-infrastructure/pservers
*
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java
new file mode 100644
index 0000000000..091d0c9e97
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUri.java
@@ -0,0 +1,52 @@
+/*-
+ * ============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.entities.uri;
+
+import java.net.URI;
+import java.util.Optional;
+
+import javax.ws.rs.core.UriBuilder;
+
+import org.onap.so.client.aai.AAIObjectType;
+import org.onap.so.client.aai.AAIResourcesClient;
+
+public class AllottedResourceLookupUri extends HttpLookupUri {
+
+ protected AllottedResourceLookupUri(Object... values) {
+ super(AAIObjectType.ALLOTTED_RESOURCE, values);
+ }
+ protected AllottedResourceLookupUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
+ super(AAIObjectType.ALLOTTED_RESOURCE, builder, cachedValue, values);
+ }
+
+ @Override
+ public AllottedResourceLookupUri clone() {
+ return new AllottedResourceLookupUri(this.internalURI.clone(), this.getCachedValue(), values);
+ }
+
+ public AAIResourcesClient getResourcesClient() {
+ return new AAIResourcesClient();
+ }
+ @Override
+ public URI buildNoNetwork() {
+ return super.build(new String[]{"NONE", "NONE", "NONE", (String)this.values[0]});
+ }
+}
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
new file mode 100644
index 0000000000..884f8c6ac4
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/HttpLookupUri.java
@@ -0,0 +1,126 @@
+/*-
+ * ============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.entities.uri;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Optional;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.core.UriBuilder;
+
+import org.onap.so.client.aai.AAIObjectType;
+import org.onap.so.client.aai.AAIResourcesClient;
+import org.onap.so.client.aai.entities.Results;
+import org.onap.so.client.graphinventory.Format;
+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 com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public abstract class HttpLookupUri extends AAISimpleUri implements HttpAwareUri {
+
+ private Optional<String> cachedValue = Optional.empty();
+ private final AAIObjectType aaiType;
+ protected HttpLookupUri(AAIObjectType type, Object... values) {
+ super(type, values);
+ this.aaiType = type;
+ }
+ protected HttpLookupUri(AAIObjectType type, UriBuilder builder, Optional<String> cachedValue, Object... values) {
+ super(type, builder, values);
+ this.cachedValue = cachedValue;
+ this.aaiType = type;
+ }
+ protected String getObjectById(Object id) throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+ if (!this.getCachedValue().isPresent()) {
+ AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(aaiType, id).format(Format.PATHED);
+ String resultJson;
+ try {
+ resultJson = this.getResourcesClient().get(serviceInstanceUri, NotFoundException.class).getJson();
+ } catch (BadRequestException e) {
+ throw new GraphInventoryUriNotFoundException(aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
+
+ }
+ try {
+ cachedValue = extractRelatedLink(resultJson);
+ if (!cachedValue.isPresent()) {
+ throw new GraphInventoryUriNotFoundException(aaiType.typeName() + " " + id + " not found at: " + serviceInstanceUri.build());
+ }
+ } catch (IOException e) {
+ throw new GraphInventoryPayloadException("could not map payload: " + resultJson, e);
+ }
+ }
+ Optional<String> cachedValueOpt = this.getCachedValue();
+ return cachedValueOpt.isPresent() ? cachedValueOpt.get() : "";
+ }
+
+ protected Optional<String> extractRelatedLink(String jsonString) throws IOException {
+ Optional<String> result;
+ ObjectMapper mapper = new ObjectMapper();
+
+ Results<Map<String, String>> results = mapper.readValue(jsonString, new TypeReference<Results<Map<String, String>>>(){});
+ if (results.getResult().size() == 1) {
+ String uriString = results.getResult().get(0).get("resource-link");
+ URI uri = UriBuilder.fromUri(uriString).build();
+ String rawPath = uri.getRawPath();
+ result = Optional.of(rawPath.replaceAll("/aai/v\\d+", ""));
+ } else if (results.getResult().isEmpty()) {
+ result = Optional.empty();
+ } else {
+ throw new IllegalStateException("more than one result returned");
+ }
+
+ return result;
+ }
+
+ protected Optional<String> getCachedValue() {
+ return this.cachedValue;
+ }
+
+ @Override
+ public URI build() {
+ try {
+ if (this.values.length == 1) {
+ String uri = getObjectById(this.values[0]);
+ Map<String, String> map = getURIKeys(uri);
+ return super.build(map.values().toArray(values));
+ }
+ } catch (GraphInventoryUriNotFoundException | GraphInventoryPayloadException e) {
+ throw new GraphInventoryUriComputationException(e);
+ }
+ return super.build();
+ }
+
+ @Override
+ public abstract HttpLookupUri clone();
+
+ public AAIResourcesClient getResourcesClient() {
+ return new AAIResourcesClient();
+ }
+ @Override
+ public abstract URI buildNoNetwork();
+}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
index ccae0b44b7..3c9ca0ed7f 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/NodesUri.java
@@ -20,6 +20,9 @@
package org.onap.so.client.aai.entities.uri;
+import javax.ws.rs.core.UriBuilder;
+
+import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.graphinventory.GraphInventoryObjectPlurals;
import org.onap.so.client.graphinventory.GraphInventoryObjectType;
@@ -30,14 +33,18 @@ public class NodesUri extends AAISimpleUri {
super(type, values);
}
+ protected NodesUri(AAIObjectPlurals type) {
+ super(type);
+ }
+
@Override
protected String getTemplate(GraphInventoryObjectType type) {
- return "/nodes" + type.partialUri();
+ return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
}
@Override
protected String getTemplate(GraphInventoryObjectPlurals type) {
- return "/nodes" + type.partialUri();
+ return UriBuilder.fromUri("/nodes").path(type.partialUri()).toTemplate();
}
}
diff --git a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
index a132e15d1f..00a213b264 100644
--- a/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
+++ b/common/src/main/java/org/onap/so/client/aai/entities/uri/ServiceInstanceUri.java
@@ -20,97 +20,21 @@
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;
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.UriBuilder;
import org.onap.so.client.aai.AAIObjectType;
import org.onap.so.client.aai.AAIResourcesClient;
-import org.onap.so.client.aai.entities.Results;
-import org.onap.so.client.graphinventory.Format;
-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 com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-public class ServiceInstanceUri extends AAISimpleUri implements HttpAwareUri {
-
- private Optional<String> cachedValue = Optional.empty();
+public class ServiceInstanceUri extends HttpLookupUri {
protected ServiceInstanceUri(Object... values) {
super(AAIObjectType.SERVICE_INSTANCE, values);
}
protected ServiceInstanceUri(UriBuilder builder, Optional<String> cachedValue, Object... values) {
- super(AAIObjectType.SERVICE_INSTANCE, builder, values);
- this.cachedValue = cachedValue;
- }
- protected String getSerivceInstance(Object id) throws GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
- if (!this.getCachedValue().isPresent()) {
- AAIResourceUri serviceInstanceUri = AAIUriFactory.createNodesUri(AAIObjectType.SERVICE_INSTANCE, id).format(Format.PATHED);
- String resultJson;
- try {
- resultJson = this.getResourcesClient().get(serviceInstanceUri, NotFoundException.class).getJson();
- } catch (BadRequestException e) {
- throw new GraphInventoryUriNotFoundException("Service instance " + id + " not found at: " + serviceInstanceUri.build());
-
- }
- try {
- cachedValue = extractRelatedLink(resultJson);
- if (!cachedValue.isPresent()) {
- throw new GraphInventoryUriNotFoundException("Service instance " + id + " not found at: " + serviceInstanceUri.build());
- }
- } catch (IOException e) {
- throw new GraphInventoryPayloadException("could not map payload: " + resultJson, e);
- }
- }
- Optional<String> cachedValueOpt = this.getCachedValue();
- return cachedValueOpt.isPresent() ? cachedValueOpt.get() : "";
- }
-
- protected Optional<String> extractRelatedLink(String jsonString) throws IOException {
- Optional<String> result;
- ObjectMapper mapper = new ObjectMapper();
-
- Results<Map<String, String>> results = mapper.readValue(jsonString, new TypeReference<Results<Map<String, String>>>(){});
- if (results.getResult().size() == 1) {
- String uriString = results.getResult().get(0).get("resource-link");
- URI uri = UriBuilder.fromUri(uriString).build();
- String rawPath = uri.getRawPath();
- result = Optional.of(rawPath.replaceAll("/aai/v\\d+", ""));
- } else if (results.getResult().isEmpty()) {
- result = Optional.empty();
- } else {
- throw new IllegalStateException("more than one result returned");
- }
-
- return result;
- }
-
- protected Optional<String> getCachedValue() {
- return this.cachedValue;
- }
-
- @Override
- public URI build() {
- try {
- if (this.values.length == 1) {
- String uri = getSerivceInstance(this.values[0]);
- Map<String, String> map = getURIKeys(uri);
- return super.build(map.values().toArray(values));
- }
- } catch (GraphInventoryUriNotFoundException | GraphInventoryPayloadException e) {
- throw new GraphInventoryUriComputationException(e);
- }
- return super.build();
+ super(AAIObjectType.SERVICE_INSTANCE, builder, cachedValue, values);
}
@Override
diff --git a/common/src/main/java/org/onap/so/client/aai/objects/AAIServiceInstance.java b/common/src/main/java/org/onap/so/client/aai/objects/AAIServiceInstance.java
deleted file mode 100644
index af21949277..0000000000
--- a/common/src/main/java/org/onap/so/client/aai/objects/AAIServiceInstance.java
+++ /dev/null
@@ -1,141 +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 org.onap.so.client.aai.AAIObjectType;
-import org.onap.so.client.aai.entities.AAIEntityObject;
-import org.onap.so.client.aai.entities.uri.AAIResourceUri;
-import org.onap.so.client.aai.entities.uri.AAIUriFactory;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-public class AAIServiceInstance implements AAIEntityObject {
-
- @JsonProperty("service-instance-id")
- private String serviceInstanceId;
- @JsonProperty("service-instance-name")
- private String serviceInstanceName;
- @JsonProperty("service-type")
- private String serviceType;
- @JsonProperty("service-role")
- private String serviceRole;
- @JsonProperty("orchestration-status")
- private String oStatus;
- @JsonProperty("model-invariant-id")
- private String modelInvariantUuid;
- @JsonProperty("model-version-id")
- private String modelUuid;
- @JsonProperty("environment-context")
- private String environmentContext;
- @JsonProperty("workload-context")
- private String workloadContext;
-
- public String getServiceInstanceName() {
- return serviceInstanceName;
- }
-
- public void setServiceInstanceName(String serviceInstanceName) {
- this.serviceInstanceName = serviceInstanceName;
- }
-
- public String getServiceType() {
- return serviceType;
- }
-
- public void setServiceType(String serviceType) {
- this.serviceType = serviceType;
- }
-
- public String getServiceRole() {
- return serviceRole;
- }
-
- public void setServiceRole(String serviceRole) {
- this.serviceRole = serviceRole;
- }
-
- public String getoStatus() {
- return oStatus;
- }
-
- public void setoStatus(String oStatus) {
- this.oStatus = oStatus;
- }
-
- public String getModelInvariantUuid() {
- return modelInvariantUuid;
- }
-
- public void setModelInvariantUuid(String modelInvariantUuid) {
- this.modelInvariantUuid = modelInvariantUuid;
- }
-
- public String getModelUuid() {
- return modelUuid;
- }
-
- public void setModelUuid(String modelUuid) {
- this.modelUuid = modelUuid;
- }
-
- public String getEnvironmentContext() {
- return environmentContext;
- }
-
- public void setEnvironmentContext(String environmentContext) {
- this.environmentContext = environmentContext;
- }
-
- public String getWorkloadContext() {
- return workloadContext;
- }
-
- public void setWorkloadContext(String workloadContext) {
- this.workloadContext = workloadContext;
- }
-
- public String getServiceInstanceId() {
- return serviceInstanceId;
- }
-
- public void setServiceInstanceId(String serviceInstanceId) {
- this.serviceInstanceId = serviceInstanceId;
- }
-
- public AAIServiceInstance withServiceInstance(String serviceInstanceId) {
- this.setServiceInstanceId(serviceInstanceId);
- return this;
- }
-
- @Override
- public AAIResourceUri getUri() {
- AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, this.serviceInstanceId);
- return uri;
- }
- @Override
- public String toString() {
- return "AAIServiceInstance [serviceInstanceId=" + serviceInstanceId + ", serviceInstanceName="
- + serviceInstanceName + ", serviceType=" + serviceType + ", serviceRole=" + serviceRole + ", oStatus="
- + oStatus + ", modelInvariantUuid=" + modelInvariantUuid + ", modelUuid=" + modelUuid
- + ", environmentContext=" + environmentContext + ", workloadContext=" + workloadContext + "]";
- }
-
-}
diff --git a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
index 2329a5acb9..9d72fdf85b 100644
--- a/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
+++ b/common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java
@@ -72,7 +72,7 @@ public class AdapterRestClient extends RestClient {
encodedString = "Basic " + encodedString;
return encodedString;
} catch (GeneralSecurityException e) {
- this.msoLogger.debug(e.getMessage());
+ logger.error(e.getMessage(),e);
return null;
}
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
index 1ede2f9e1b..461920fe7f 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/GraphInventoryEdgeLabel.java
@@ -1,3 +1,23 @@
+/*-
+ * ============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.graphinventory.entities;
public interface GraphInventoryEdgeLabel {
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
index 145959dc73..3d08c8d40c 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/uri/HttpAwareUri.java
@@ -1,3 +1,23 @@
+/*-
+ * ============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.graphinventory.entities.uri;
import java.net.URI;
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 975fa318e8..026f1c3929 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
@@ -82,6 +82,12 @@ public class SimpleUri implements GraphInventoryResourceUri {
this.internalURI = UriBuilder.fromPath(this.getTemplate(type));
this.values = 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;
+ }
@Override
public SimpleUri relationshipAPI() {
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyClient.java b/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
index 74c1e398db..6743bc2c34 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyClient.java
@@ -20,6 +20,7 @@
package org.onap.so.client.policy;
+import org.onap.so.client.policy.entities.Config;
import org.onap.so.client.policy.entities.DictionaryData;
import org.onap.so.client.policy.entities.PolicyDecision;
@@ -29,4 +30,6 @@ public interface PolicyClient {
String errorCode);
public DictionaryData getAllowedTreatments(String bbID, String workStep);
+
+ public Config getConfigWithPolicyName(String policyName);
}
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java b/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
index 1fd01e65ed..71a3227c56 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyClientImpl.java
@@ -20,6 +20,7 @@
package org.onap.so.client.policy;
+import java.io.IOException;
import java.util.List;
import org.onap.so.client.RestClient;
@@ -27,10 +28,13 @@ import org.onap.so.client.RestPropertiesLoader;
import org.onap.so.client.defaultproperties.PolicyRestPropertiesImpl;
import org.onap.so.client.policy.entities.AllowedTreatments;
import org.onap.so.client.policy.entities.Bbid;
+import org.onap.so.client.policy.entities.Config;
+import org.onap.so.client.policy.entities.ConfigRequestParameters;
import org.onap.so.client.policy.entities.DecisionAttributes;
import org.onap.so.client.policy.entities.DictionaryData;
import org.onap.so.client.policy.entities.DictionaryItemsRequest;
import org.onap.so.client.policy.entities.DictionaryJson;
+import org.onap.so.client.policy.entities.PolicyConfig;
import org.onap.so.client.policy.entities.PolicyDecision;
import org.onap.so.client.policy.entities.PolicyDecisionRequest;
import org.onap.so.client.policy.entities.PolicyServiceType;
@@ -38,11 +42,19 @@ import org.onap.so.client.policy.entities.Workstep;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
public class PolicyClientImpl implements PolicyClient {
private static Logger logger = LoggerFactory.getLogger(PolicyClientImpl.class);
private PolicyRestProperties props;
+ private ObjectMapper mapper = new ObjectMapper();
+
public PolicyClientImpl() {
props = RestPropertiesLoader.getInstance().getNewImpl(PolicyRestProperties.class);
if (props == null) {
@@ -63,7 +75,7 @@ public class PolicyClientImpl implements PolicyClient {
}
protected PolicyDecision getDecision(DecisionAttributes decisionAttributes) {
- PolicyRestClient client = new PolicyRestClient(this.props, PolicyServiceType.GET_DECISION);
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DECISION);
PolicyDecisionRequest decisionRequest = new PolicyDecisionRequest();
decisionRequest.setDecisionAttributes(decisionAttributes);
decisionRequest.setEcompcomponentName(RestClient.ECOMP_COMPONENT_NAME);
@@ -73,7 +85,7 @@ public class PolicyClientImpl implements PolicyClient {
public DictionaryData getAllowedTreatments(String bbID, String workStep)
{
- PolicyRestClient client = new PolicyRestClient(this.props, PolicyServiceType.GET_DICTIONARY_ITEMS);
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_DICTIONARY_ITEMS);
DictionaryItemsRequest dictionaryItemsRequest = new DictionaryItemsRequest();
dictionaryItemsRequest.setDictionaryType("Decision");
dictionaryItemsRequest.setDictionary("RainyDayTreatments");
@@ -92,5 +104,35 @@ public class PolicyClientImpl implements PolicyClient {
logger.error("There is no AllowedTreatments with that specified parameter set");
return null;
}
-
+
+ @Override
+ public Config getConfigWithPolicyName(String policyName) {
+ PolicyRestClient client = this.getPolicyRestClient(PolicyServiceType.GET_CONFIG);
+ ConfigRequestParameters configReqParameters = new ConfigRequestParameters();
+ configReqParameters.setPolicyName(policyName);
+ PolicyConfig[] policyConfigList = client.post(configReqParameters, PolicyConfig[].class);
+ PolicyConfig policyConfig = null;
+ if(policyConfigList.length > 1) {
+ logger.debug("Too many configs for policyName: " + policyName);
+ return null;
+ }
+ try {
+ policyConfig = policyConfigList[0];
+ return this.getConfigFromStringJson(policyConfig.getConfig());
+ } catch (IOException e) {
+ logger.error(e.getMessage());
+ return null;
+ }
+ }
+
+ protected Config getConfigFromStringJson(String configJson) throws JsonParseException, JsonMappingException, IOException {
+ String unescapedJson = configJson.replaceAll("\\\\", "");
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ return mapper.readValue(unescapedJson, Config.class);
+ }
+
+ protected PolicyRestClient getPolicyRestClient(PolicyServiceType policyServiceType) {
+ return new PolicyRestClient(this.props, policyServiceType);
+ }
}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Config.java b/common/src/main/java/org/onap/so/client/policy/entities/Config.java
new file mode 100644
index 0000000000..6c9c0759d6
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Config.java
@@ -0,0 +1,217 @@
+/*-
+ * ============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.policy.entities;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+import com.fasterxml.jackson.annotation.JsonRootName;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+ "configName",
+ "riskLevel",
+ "policyName",
+ "policyScope",
+ "guard",
+ "description",
+ "priority",
+ "uuid",
+ "version",
+ "content",
+ "riskType",
+ "service",
+ "location",
+ "templateVersion"
+})
+@JsonRootName(value = "config")
+public class Config {
+
+ @JsonProperty("configName")
+ private String configName;
+ @JsonProperty("riskLevel")
+ private String riskLevel;
+ @JsonProperty("policyName")
+ private String policyName;
+ @JsonProperty("policyScope")
+ private String policyScope;
+ @JsonProperty("guard")
+ private String guard;
+ @JsonProperty("description")
+ private String description;
+ @JsonProperty("priority")
+ private String priority;
+ @JsonProperty("uuid")
+ private String uuid;
+ @JsonProperty("version")
+ private String version;
+ @JsonProperty("content")
+ private Content content;
+ @JsonProperty("riskType")
+ private String riskType;
+ @JsonProperty("service")
+ private String service;
+ @JsonProperty("location")
+ private String location;
+ @JsonProperty("templateVersion")
+ private String templateVersion;
+
+ @JsonProperty("configName")
+ public String getConfigName() {
+ return configName;
+ }
+
+ @JsonProperty("configName")
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+
+ @JsonProperty("riskLevel")
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+
+ @JsonProperty("riskLevel")
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+
+ @JsonProperty("policyName")
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ @JsonProperty("policyName")
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ @JsonProperty("policyScope")
+ public String getPolicyScope() {
+ return policyScope;
+ }
+
+ @JsonProperty("policyScope")
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+
+ @JsonProperty("guard")
+ public String getGuard() {
+ return guard;
+ }
+
+ @JsonProperty("guard")
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+
+ @JsonProperty("description")
+ public String getDescription() {
+ return description;
+ }
+
+ @JsonProperty("description")
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @JsonProperty("priority")
+ public String getPriority() {
+ return priority;
+ }
+
+ @JsonProperty("priority")
+ public void setPriority(String priority) {
+ this.priority = priority;
+ }
+
+ @JsonProperty("uuid")
+ public String getUuid() {
+ return uuid;
+ }
+
+ @JsonProperty("uuid")
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ @JsonProperty("version")
+ public String getVersion() {
+ return version;
+ }
+
+ @JsonProperty("version")
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ @JsonProperty("content")
+ public Content getContent() {
+ return content;
+ }
+
+ @JsonProperty("content")
+ public void setContent(Content content) {
+ this.content = content;
+ }
+
+ @JsonProperty("riskType")
+ public String getRiskType() {
+ return riskType;
+ }
+
+ @JsonProperty("riskType")
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+
+ @JsonProperty("service")
+ public String getService() {
+ return service;
+ }
+
+ @JsonProperty("service")
+ public void setService(String service) {
+ this.service = service;
+ }
+
+ @JsonProperty("location")
+ public String getLocation() {
+ return location;
+ }
+
+ @JsonProperty("location")
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ @JsonProperty("templateVersion")
+ public String getTemplateVersion() {
+ return templateVersion;
+ }
+
+ @JsonProperty("templateVersion")
+ public void setTemplateVersion(String templateVersion) {
+ this.templateVersion = templateVersion;
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java b/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java
new file mode 100644
index 0000000000..8cd5b93a36
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/policy/entities/ConfigRequestParameters.java
@@ -0,0 +1,127 @@
+/*-
+ * ============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.policy.entities;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+ "configAttributes",
+ "configName",
+ "ecompName",
+ "onapName",
+ "policyName",
+ "requestID",
+ "unique"
+})
+public class ConfigRequestParameters {
+
+ @JsonProperty("configAttributes")
+ private Map<String, String> configAttributes = new HashMap<>();
+ @JsonProperty("configName")
+ private String configName;
+ @JsonProperty("ecompName")
+ private String ecompName;
+ @JsonProperty("onapName")
+ private String onapName;
+ @JsonProperty("policyName")
+ private String policyName;
+ @JsonProperty("requestID")
+ private String requestID;
+ @JsonProperty("unique")
+ private Boolean unique;
+
+ @JsonProperty("configAttributes")
+ public Map<String, String> getConfigAttributes() {
+ return configAttributes;
+ }
+
+ @JsonProperty("configAttributes")
+ public void setConfigAttributes(Map<String, String> configAttributes) {
+ this.configAttributes = configAttributes;
+ }
+
+ @JsonProperty("configName")
+ public String getConfigName() {
+ return configName;
+ }
+
+ @JsonProperty("configName")
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+
+ @JsonProperty("ecompName")
+ public String getEcompName() {
+ return ecompName;
+ }
+
+ @JsonProperty("ecompName")
+ public void setEcompName(String ecompName) {
+ this.ecompName = ecompName;
+ }
+
+ @JsonProperty("onapName")
+ public String getOnapName() {
+ return onapName;
+ }
+
+ @JsonProperty("onapName")
+ public void setOnapName(String onapName) {
+ this.onapName = onapName;
+ }
+
+ @JsonProperty("policyName")
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ @JsonProperty("policyName")
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ @JsonProperty("requestID")
+ public String getRequestID() {
+ return requestID;
+ }
+
+ @JsonProperty("requestID")
+ public void setRequestID(String requestID) {
+ this.requestID = requestID;
+ }
+
+ @JsonProperty("unique")
+ public Boolean getUnique() {
+ return unique;
+ }
+
+ @JsonProperty("unique")
+ public void setUnique(Boolean unique) {
+ this.unique = unique;
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/Content.java b/common/src/main/java/org/onap/so/client/policy/entities/Content.java
new file mode 100644
index 0000000000..a473f6c566
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/policy/entities/Content.java
@@ -0,0 +1,47 @@
+/*-
+ * ============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.policy.entities;
+
+import java.util.List;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+ "fabric-config-models"
+})
+public class Content {
+
+ @JsonProperty("fabric-config-models")
+ private List<FabricConfigModel> fabricConfigModels = null;
+
+ @JsonProperty("fabric-config-models")
+ public List<FabricConfigModel> getFabricConfigModels() {
+ return fabricConfigModels;
+ }
+
+ @JsonProperty("fabric-config-models")
+ public void setFabricConfigModels(List<FabricConfigModel> fabricConfigModels) {
+ this.fabricConfigModels = fabricConfigModels;
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java b/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java
new file mode 100644
index 0000000000..d1a924cb7d
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/policy/entities/FabricConfigModel.java
@@ -0,0 +1,59 @@
+/*-
+ * ============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.policy.entities;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+ "vnfProfile",
+ "lagProfile"
+})
+public class FabricConfigModel {
+
+ @JsonProperty("vnfProfile")
+ private String vnfProfile;
+ @JsonProperty("lagProfile")
+ private String lagProfile;
+
+ @JsonProperty("vnfProfile")
+ public String getVnfProfile() {
+ return vnfProfile;
+ }
+
+ @JsonProperty("vnfProfile")
+ public void setVnfProfile(String vnfProfile) {
+ this.vnfProfile = vnfProfile;
+ }
+
+ @JsonProperty("lagProfile")
+ public String getLagProfile() {
+ return lagProfile;
+ }
+
+ @JsonProperty("lagProfile")
+ public void setLagProfile(String lagProfile) {
+ this.lagProfile = lagProfile;
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java b/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java
new file mode 100644
index 0000000000..807829e323
--- /dev/null
+++ b/common/src/main/java/org/onap/so/client/policy/entities/PolicyConfig.java
@@ -0,0 +1,166 @@
+/*-
+ * ============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.policy.entities;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonPropertyOrder;
+
+@JsonInclude(JsonInclude.Include.NON_NULL)
+@JsonPropertyOrder({
+ "policyConfigMessage",
+ "policyConfigStatus",
+ "type",
+ "config",
+ "policyName",
+ "policyType",
+ "policyVersion",
+ "matchingConditions",
+ "responseAttributes",
+ "property"
+})
+public class PolicyConfig {
+
+ @JsonProperty("policyConfigMessage")
+ private String policyConfigMessage;
+ @JsonProperty("policyConfigStatus")
+ private String policyConfigStatus;
+ @JsonProperty("type")
+ private String type;
+ @JsonProperty("config")
+ private String config;
+ @JsonProperty("policyName")
+ private String policyName;
+ @JsonProperty("policyType")
+ private String policyType;
+ @JsonProperty("policyVersion")
+ private String policyVersion;
+ @JsonProperty("matchingConditions")
+ private Map<String, String> matchingConditions = new HashMap<>();
+ @JsonProperty("responseAttributes")
+ private Map<String, String> responseAttributes = new HashMap<>();
+ @JsonProperty("property")
+ private Object property;
+
+ @JsonProperty("policyConfigMessage")
+ public String getPolicyConfigMessage() {
+ return policyConfigMessage;
+ }
+
+ @JsonProperty("policyConfigMessage")
+ public void setPolicyConfigMessage(String policyConfigMessage) {
+ this.policyConfigMessage = policyConfigMessage;
+ }
+
+ @JsonProperty("policyConfigStatus")
+ public String getPolicyConfigStatus() {
+ return policyConfigStatus;
+ }
+
+ @JsonProperty("policyConfigStatus")
+ public void setPolicyConfigStatus(String policyConfigStatus) {
+ this.policyConfigStatus = policyConfigStatus;
+ }
+
+ @JsonProperty("type")
+ public String getType() {
+ return type;
+ }
+
+ @JsonProperty("type")
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ @JsonProperty("config")
+ public String getConfig() {
+ return config;
+ }
+
+ @JsonProperty("config")
+ public void setConfig(String config) {
+ this.config = config;
+ }
+
+ @JsonProperty("policyName")
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ @JsonProperty("policyName")
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ @JsonProperty("policyType")
+ public String getPolicyType() {
+ return policyType;
+ }
+
+ @JsonProperty("policyType")
+ public void setPolicyType(String policyType) {
+ this.policyType = policyType;
+ }
+
+ @JsonProperty("policyVersion")
+ public String getPolicyVersion() {
+ return policyVersion;
+ }
+
+ @JsonProperty("policyVersion")
+ public void setPolicyVersion(String policyVersion) {
+ this.policyVersion = policyVersion;
+ }
+
+ @JsonProperty("matchingConditions")
+ public Map<String, String> getMatchingConditions() {
+ return matchingConditions;
+ }
+
+ @JsonProperty("matchingConditions")
+ public void setMatchingConditions(Map<String, String> matchingConditions) {
+ this.matchingConditions = matchingConditions;
+ }
+
+ @JsonProperty("responseAttributes")
+ public Map<String, String> getResponseAttributes() {
+ return responseAttributes;
+ }
+
+ @JsonProperty("responseAttributes")
+ public void setResponseAttributes(Map<String, String> responseAttributes) {
+ this.responseAttributes = responseAttributes;
+ }
+
+ @JsonProperty("property")
+ public Object getProperty() {
+ return property;
+ }
+
+ @JsonProperty("property")
+ public void setProperty(Object property) {
+ this.property = property;
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/exceptions/MSOException.java b/common/src/main/java/org/onap/so/exceptions/MSOException.java
new file mode 100644
index 0000000000..f49cd8d8f8
--- /dev/null
+++ b/common/src/main/java/org/onap/so/exceptions/MSOException.java
@@ -0,0 +1,56 @@
+/*-
+ * ============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.exceptions;
+
+
+public class MSOException extends Exception{
+ /**
+ *
+ */
+ private static final long serialVersionUID = 4563920496855255206L;
+ private Integer errorCode;
+
+ public MSOException(String msg){
+ super(msg);
+ }
+
+ public MSOException (Throwable e) {
+ super(e);
+ }
+
+ public MSOException (String msg, Throwable e) {
+ super (msg, e);
+ }
+
+ public MSOException(String msg, int errorCode){
+ super(msg);
+ this.errorCode=errorCode;
+ }
+
+ public MSOException(String msg, int errorCode, Throwable t){
+ super(msg,t);
+ this.errorCode=errorCode;
+ }
+
+ public Integer getErrorCode(){
+ return errorCode;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java b/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
index 0d20dd8bf9..794d02a240 100644
--- a/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
+++ b/common/src/main/java/org/onap/so/logger/LoggerStartupListener.java
@@ -23,6 +23,7 @@ package org.onap.so.logger;
import java.net.InetAddress;
import java.net.UnknownHostException;
+import org.onap.so.utils.UUIDChecker;
import org.springframework.stereotype.Component;
import ch.qos.logback.classic.Level;
@@ -37,6 +38,7 @@ import ch.qos.logback.core.spi.LifeCycle;
public class LoggerStartupListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
private boolean started = false;
+ private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.GENERAL, LoggerStartupListener.class);
@Override
public void start() {
@@ -46,7 +48,8 @@ public class LoggerStartupListener extends ContextAwareBase implements LoggerCon
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
- e.printStackTrace();
+ LOGGER.error("UnknownHostException",e);
+
}
Context context = getContext();
if (addr != null) {
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 e4cac067ba..94ffa71169 100644
--- a/common/src/main/java/org/onap/so/logger/MsoLogger.java
+++ b/common/src/main/java/org/onap/so/logger/MsoLogger.java
@@ -31,6 +31,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
+import org.apache.commons.lang3.StringUtils;
import org.onap.so.entity.MsoRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,13 +61,26 @@ public class MsoLogger {
public static final String RESPONSECODE = "ResponseCode";
public static final String RESPONSEDESC = "ResponseDesc";
public static final String FQDN = "ServerFQDN";
+ public static final String ENTRY_TIMESTAMP = "EntryTimestamp";
+ public static final String CLIENT_IPADDRESS = "EntryTimestamp";
- public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId";
+ //HTTP Headers
+ public static final String HEADER_FROM_APP_ID = "X-FromAppId";
+ public static final String ONAP_PARTNER_NAME = "X-ONAP-PartnerName";
+ public static final String HEADER_REQUEST_ID = "X-RequestId";
+ public static final String TRANSACTION_ID = "X-TransactionID";
+ public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID";
+ 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";
+ //Default values for not found
+ public static final String UNKNOWN_PARTNER = "UnknownPartner";
+
+ public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId";
public static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName";
- public static final String SERVER_IP = "ServerIPAddress";
-
+ public static final String SERVER_IP = "ServerIPAddress";
public static final String REMOTE_HOST = "RemoteHost";
public static final String ALERT_SEVERITY = "AlertSeverity";
@@ -77,16 +91,15 @@ public class MsoLogger {
public static final String CAT_LOG_LEVEL = "CategoryLogLevel";
public static final String AUDI_CAT_LOG_LEVEL = "AuditCategoryLogLevel";
- //For getting an identity of calling application
- public static final String HEADER_FROM_APP_ID = "X-FromAppId";
- public static final String FROM_APP_ID = "FromAppId";
- public static final String HEADER_REQUEST_ID = "X-RequestId";
- public static final String TRANSACTION_ID = "X-TransactionID";
- public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID";
- public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID";
+
+
+ public static final String PARTNER_NAME = "PartnerName";
+
- public static final String CLIENT_ID = "X-ClientID";
- public static final String INVOCATION_ID_HEADER = "X-InvocationID";
+
+
+
+
// Audit/Metric log specific
public static final String BEGINTIME = "BeginTimestamp";
@@ -279,7 +292,9 @@ public class MsoLogger {
public void recordAuditEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode,
String responseDesc) {
- MDC.put(MsoLogger.PARTNERNAME, "UNKNOWN");
+ if (StringUtils.isEmpty(MDC.get(MsoLogger.PARTNERNAME))) {
+ MDC.put(MsoLogger.PARTNERNAME, "UNKNOWN");
+ }
prepareAuditMsg(startTime, statusCode, responseCode.getValue(), responseDesc);
auditLogger.info("");
MDC.remove(TIMER);
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
new file mode 100644
index 0000000000..49dc71e773
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
@@ -0,0 +1,158 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.logging.jaxrs.filter;
+
+
+import org.apache.commons.io.IOUtils;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.utils.TargetEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.slf4j.MarkerFactory;
+import org.springframework.stereotype.Component;
+import javax.annotation.Priority;
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.client.ClientResponseContext;
+import javax.ws.rs.client.ClientResponseFilter;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Providers;
+import java.io.*;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Map;
+import java.util.UUID;
+
+@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
+@Component
+@Priority(0)
+public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter {
+
+ @Context
+ private Providers providers;
+
+ private static final String TRACE = "trace-#";
+ private static final String SO = "SO";
+ private static Logger logger = LoggerFactory.getLogger(JaxRsClientLogging.class);
+
+ public void setTargetService(TargetEntity targetEntity){
+ MDC.put("TargetEntity", targetEntity.toString());
+ }
+
+ @Override
+ public void filter(ClientRequestContext clientRequest) {
+ try{
+ setupMDC(clientRequest);
+ setupHeaders(clientRequest);
+ logger.info(ONAPLogConstants.Markers.INVOKE, "Invoke");
+ } catch (Exception e) {
+ logger.warn("Error in incoming JAX-RS Inteceptor", e);
+ }
+ }
+
+ private void setupHeaders(ClientRequestContext clientRequest) {
+ MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
+ headers.add(ONAPLogConstants.Headers.REQUEST_ID, extractRequestID(clientRequest));
+ headers.add(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
+ headers.add(ONAPLogConstants.Headers.PARTNER_NAME, SO);
+ }
+
+ private void setupMDC(ClientRequestContext clientRequest) {
+ MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, clientRequest.getUri().toString());
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+ setInvocationId();
+ MDC.put("TargetEntity",MDC.get("TargetEntity"));
+ }
+
+ private String extractRequestID(ClientRequestContext clientRequest) {
+ String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
+ if(requestId == null || requestId.isEmpty() || requestId.equals(TRACE)){
+ requestId = UUID.randomUUID().toString();
+ logger.warn("Could not Find Request ID Generating New One: {}",clientRequest.getUri().getPath());
+ }
+ return requestId;
+ }
+
+ private void setInvocationId() {
+ String invocationId = MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID);
+ if(invocationId == null || invocationId.isEmpty())
+ invocationId =UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
+ }
+
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
+
+ try {
+ String statusCode;
+ if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
+ statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ }else{
+ statusCode=ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus()));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,getStringFromInputStream(responseContext));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
+ logger.info(MarkerFactory.getMarker("INVOKE_RETURN"), "InvokeReturn");
+ clearClientMDCs();
+ } catch ( Exception e) {
+ logger.warn("Error in outgoing JAX-RS Inteceptor", e);
+ }
+ }
+
+ private void clearClientMDCs() {
+ MDC.remove(ONAPLogConstants.MDCs.INVOCATION_ID);
+ MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
+ MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
+ MDC.remove(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION);
+ MDC.remove(ONAPLogConstants.MDCs.RESPONSE_CODE);
+ }
+
+ private static String getStringFromInputStream(ClientResponseContext clientResponseContext) {
+
+ InputStream is = clientResponseContext.getEntityStream();
+ ByteArrayOutputStream boas = new ByteArrayOutputStream();
+
+ try {
+ IOUtils.copy(is,boas);
+ InputStream copiedStream = new ByteArrayInputStream(boas.toByteArray());
+ clientResponseContext.setEntityStream(copiedStream);
+ return boas.toString();
+
+ } catch (IOException e) {
+ logger.warn("Failed to read response body", e);
+ }
+ return "Unable to read input stream";
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
index d278a5f761..7d02136860 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsFilterLogging.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
@@ -18,19 +18,14 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.so.logging.jaxrs.filter.jersey;
+package org.onap.so.logging.jaxrs.filter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
-import java.time.Instant;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
-import java.util.Locale;
import java.util.UUID;
-
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
@@ -44,7 +39,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.Providers;
-import org.onap.so.logger.MsoLogger;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
@@ -56,120 +51,65 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Provider
@Component
public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerResponseFilter {
-
- protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class);
+
+ protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class);
@Context
private HttpServletRequest httpServletRequest;
@Context
private Providers providers;
-
+
@Autowired
- ObjectMapper objectMapper;
+ private MDCSetup mdcSetup;
@Override
- public void filter(ContainerRequestContext containerRequest) {
-
+ public void filter(ContainerRequestContext containerRequest) {
try {
- String clientID = null;
- //check headers for request id
MultivaluedMap<String, String> headers = containerRequest.getHeaders();
- String requestId = findRequestId(headers);
- containerRequest.setProperty("requestId", requestId);
- if(headers.containsKey(MsoLogger.CLIENT_ID)){
- clientID = headers.getFirst(MsoLogger.CLIENT_ID);
- }else{
- clientID = "UNKNOWN";
- headers.add(MsoLogger.CLIENT_ID, clientID);
- }
-
- String remoteIpAddress = "";
- if (httpServletRequest != null) {
- remoteIpAddress = httpServletRequest.getRemoteAddr();
- }
- Instant instant = Instant.now();
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
- .withLocale( Locale.US )
- .withZone( ZoneId.systemDefault() );
-
- String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID );
- if(partnerName == null || partnerName.isEmpty())
- partnerName="UNKNOWN";
-
- MDC.put(MsoLogger.REQUEST_ID,requestId);
- MDC.put(MsoLogger.INVOCATION_ID,requestId);
- MDC.put(MsoLogger.FROM_APP_ID,partnerName);
- MDC.put(MsoLogger.SERVICE_NAME, containerRequest.getUriInfo().getPath());
- MDC.put(MsoLogger.INVOCATION_ID, findInvocationId(headers));
- MDC.put(MsoLogger.STATUSCODE, MsoLogger.INPROGRESS);
- MDC.put(MsoLogger.BEGINTIME, formatter.format(instant));
- MDC.put(MsoLogger.PARTNERNAME,partnerName);
- MDC.put(MsoLogger.REMOTE_HOST, String.valueOf(remoteIpAddress));
- MDC.put(MsoLogger.STARTTIME, String.valueOf(System.currentTimeMillis()));
- logger.debug(MsoLogger.ENTRY, "Entering.");
+ setRequestId(headers);
+ containerRequest.setProperty("requestId", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ setInvocationId(headers);
+ setServiceName(containerRequest);
+ setMDCPartnerName(headers);
+ mdcSetup.setServerFQDN();
+ mdcSetup.setClientIPAddress(httpServletRequest);
+ mdcSetup.setInstanceUUID();
+ mdcSetup.setEntryTimeStamp();
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "INPROGRESS");
+ logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
} catch (Exception e) {
logger.warn("Error in incoming JAX-RS Inteceptor", e);
}
}
-
- private String findRequestId(MultivaluedMap<String, String> headers) {
- String requestId = (String) headers.getFirst(MsoLogger.HEADER_REQUEST_ID );
- if(requestId == null || requestId.isEmpty()){
- if(headers.containsKey(MsoLogger.ONAP_REQUEST_ID)){
- requestId = headers.getFirst(MsoLogger.ONAP_REQUEST_ID);
- }else if(headers.containsKey(MsoLogger.ECOMP_REQUEST_ID)){
- requestId = headers.getFirst(MsoLogger.ECOMP_REQUEST_ID);
- }else{
- requestId = UUID.randomUUID().toString();
- }
- }
- return requestId;
- }
-
- private String findInvocationId(MultivaluedMap<String, String> headers) {
- String invocationId = (String) headers.getFirst(MsoLogger.INVOCATION_ID_HEADER );
- if(invocationId == null || invocationId.isEmpty())
- invocationId =UUID.randomUUID().toString();
- return invocationId;
- }
-
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
try {
- Instant instant = Instant.now();
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
- .withLocale( Locale.US )
- .withZone( ZoneId.systemDefault() );
- String startTime= MDC.get(MsoLogger.STARTTIME);
- long elapsedTime;
- try {
- elapsedTime = System.currentTimeMillis() - Long.parseLong(startTime);
- }catch(NumberFormatException e){
- elapsedTime = 0;
- }
- String statusCode;
- if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=MsoLogger.COMPLETE;
- }else{
- statusCode= MsoLogger.StatusCode.ERROR.toString();
- }
-
- MDC.put(MsoLogger.RESPONSEDESC,payloadMessage(responseContext));
- MDC.put(MsoLogger.STATUSCODE, statusCode);
- MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus()));
- MDC.put(MsoLogger.TIMER, String.valueOf(elapsedTime));
- MDC.put(MsoLogger.ENDTIME,formatter.format(instant));
- logger.debug(MsoLogger.EXIT, "Exiting.");
+ setResponseStatusCode(responseContext);
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,payloadMessage(responseContext));
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE,String.valueOf(responseContext.getStatus()));
+ logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
+ MDC.clear();
} catch ( Exception e) {
+ MDC.clear();
logger.warn("Error in outgoing JAX-RS Inteceptor", e);
}
+ }
+
+ private void setResponseStatusCode(ContainerResponseContext responseContext) {
+ String statusCode;
+ if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
+ statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ }else{
+ statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
}
private String payloadMessage(ContainerResponseContext responseContext) throws IOException {
- String message = new String();
+ String message = "";
if (responseContext.hasEntity()) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Class<?> entityClass = responseContext.getEntityClass();
@@ -192,4 +132,38 @@ public class JaxRsFilterLogging implements ContainerRequestFilter,ContainerRespo
}
return message;
}
+
+
+ private void setRequestId(MultivaluedMap<String, String> headers){
+ String requestId=headers.getFirst(ONAPLogConstants.Headers.REQUEST_ID);
+ if(requestId == null || requestId.isEmpty())
+ requestId = UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ }
+
+ private void setInvocationId(MultivaluedMap<String, String> headers){
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, findInvocationId(headers));
+ }
+
+ private void setMDCPartnerName(MultivaluedMap<String, String> headers){
+ String partnerName=headers.getFirst(ONAPLogConstants.Headers.PARTNER_NAME);
+ if(partnerName == null || partnerName.isEmpty())
+ partnerName = "";
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ }
+
+ private String findInvocationId(MultivaluedMap<String, String> headers) {
+ String invocationId = headers.getFirst(ONAPLogConstants.Headers.INVOCATION_ID);
+ if(invocationId == null || invocationId.isEmpty())
+ invocationId =UUID.randomUUID().toString();
+ return invocationId;
+ }
+
+ private void setServiceName(ContainerRequestContext containerRequest){
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, containerRequest.getUriInfo().getPath());
+ }
+
+
+
+
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
new file mode 100644
index 0000000000..f0a16561aa
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
@@ -0,0 +1,110 @@
+/*-
+ * ============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.logging.jaxrs.filter;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Map;
+import java.util.UUID;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.Response;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+
+@Component
+public class MDCSetup {
+
+ protected static Logger logger = LoggerFactory.getLogger(MDCSetup.class);
+
+ private static final String INSTANCE_UUID = UUID.randomUUID().toString();
+
+ public void setInstanceUUID(){
+ MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, INSTANCE_UUID);
+ }
+
+ public void setServerFQDN(){
+ String serverFQDN = "";
+ InetAddress addr= null;
+ try {
+ addr = InetAddress.getLocalHost();
+ serverFQDN = addr.toString();
+ } catch (UnknownHostException e) {
+ logger.warn("Cannot Resolve Host Name");
+ serverFQDN = "";
+ }
+ MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, serverFQDN);
+ }
+
+ public void setClientIPAddress(HttpServletRequest httpServletRequest){
+ String remoteIpAddress = "";
+ if (httpServletRequest != null) {
+ remoteIpAddress = httpServletRequest.getRemoteAddr();
+ }
+ MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, remoteIpAddress);
+ }
+
+ public void setEntryTimeStamp() {
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ }
+
+ public void setServiceName(HttpServletRequest request) {
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
+ }
+
+ public void setRequestId(Map<String, String> headers) {
+ String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID);
+ if(requestId == null || requestId.isEmpty())
+ requestId = UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ }
+
+ public void setInvocationId(Map<String, String> headers) {
+ String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
+ if(invocationId == null || invocationId.isEmpty())
+ invocationId =UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
+ }
+
+ public void setMDCPartnerName(Map<String, String> headers) {
+ String partnerName=headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
+ if(partnerName == null || partnerName.isEmpty())
+ partnerName = "";
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ }
+
+
+ public void setResponseStatusCode(HttpServletResponse response) {
+ String statusCode;
+ if(Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
+ statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ }else{
+ statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
+ }
+}
diff --git a/common/src/main/java/org/onap/so/client/policy/LoggingFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
index 83cf08f77f..29264f4e42 100644
--- a/common/src/main/java/org/onap/so/client/policy/LoggingFilter.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
@@ -18,7 +18,7 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.so.client.policy;
+package org.onap.so.logging.jaxrs.filter;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
@@ -40,22 +40,24 @@ import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import org.onap.so.logger.MsoLogger;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
@Provider
-@Priority(0)
-public class LoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor {
+@Priority(1)
+public class PayloadLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor {
- private static final MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, LoggingFilter.class);
+ private static final Logger logger = LoggerFactory.getLogger(PayloadLoggingFilter.class);
private static final String ENTITY_STREAM_PROPERTY = "LoggingFilter.entityStream";
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final int maxEntitySize;
- public LoggingFilter() {
+ public PayloadLoggingFilter() {
maxEntitySize = 1024 * 1024;
}
- public LoggingFilter(int maxPayloadSize) {
+ public PayloadLoggingFilter(int maxPayloadSize) {
this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024);
}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
index 0477c9a429..6af7a916d0 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/SpringClientFilter.java
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
@@ -18,7 +18,7 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.so.logging.jaxrs.filter.jersey;
+package org.onap.so.logging.jaxrs.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java
deleted file mode 100644
index 2888cbf3a1..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/jersey/JaxRsClientLogging.java
+++ /dev/null
@@ -1,135 +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.logging.jaxrs.filter.jersey;
-
-
-import org.apache.commons.io.IOUtils;
-import org.onap.so.logger.MsoLogger;
-import org.onap.so.utils.TargetEntity;
-import org.slf4j.MDC;
-import org.springframework.stereotype.Component;
-
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
-import javax.ws.rs.client.ClientResponseContext;
-import javax.ws.rs.client.ClientResponseFilter;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-
-import java.io.*;
-
-import java.time.Instant;
-import java.time.ZoneId;
-import java.time.format.DateTimeFormatter;
-import java.util.Locale;
-import java.util.UUID;
-
-@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
-@Component
-public class JaxRsClientLogging implements ClientRequestFilter,ClientResponseFilter {
-
- private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA,JaxRsClientLogging.class);
-
- private TargetEntity targetEntity;
-
- public void setTargetService(TargetEntity targetEntity){
- this.targetEntity = targetEntity;
- }
-
- @Override
- public void filter(ClientRequestContext clientRequest) {
- try{
- MultivaluedMap<String, Object> headers = clientRequest.getHeaders();
-
-
- Instant instant = Instant.now();
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
- .withLocale( Locale.US )
- .withZone( ZoneId.systemDefault() );
-
- String requestId = MDC.get(MsoLogger.REQUEST_ID);
- if(requestId == null || requestId.isEmpty()){
- requestId = UUID.randomUUID().toString();
- logger.warnSimple(clientRequest.getUri().getPath(),"Could not Find Request ID Generating New One");
- }
-
- MDC.put(MsoLogger.METRIC_BEGIN_TIME, formatter.format(instant));
- MDC.put(MsoLogger.METRIC_START_TIME, String.valueOf(System.currentTimeMillis()));
- MDC.put(MsoLogger.REQUEST_ID,requestId);
- MDC.put(MsoLogger.TARGETSERVICENAME, clientRequest.getUri().toString());
- } catch (Exception e) {
- logger.warnSimple("Error in incoming JAX-RS Inteceptor", e);
- }
- }
-
-
- @Override
- public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
-
- try {
- Instant instant = Instant.now();
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" )
- .withLocale( Locale.US )
- .withZone( ZoneId.systemDefault() );
- String startTime= MDC.get(MsoLogger.METRIC_START_TIME);
-
- long elapsedTime = System.currentTimeMillis()-Long.parseLong(startTime);
- String statusCode;
- if(Response.Status.Family.familyOf(responseContext.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
- statusCode=MsoLogger.COMPLETE;
- }else{
- statusCode=MsoLogger.StatusCode.ERROR.toString();
- }
- MultivaluedMap<String, String> headers = responseContext.getHeaders();
-
- String partnerName = headers.getFirst(MsoLogger.HEADER_FROM_APP_ID );
- if(partnerName == null || partnerName.isEmpty())
- partnerName="UNKNOWN";
- MDC.put(MsoLogger.RESPONSEDESC,getStringFromInputStream(responseContext));
- MDC.put(MsoLogger.STATUSCODE, statusCode);
- MDC.put(MsoLogger.RESPONSECODE,String.valueOf(responseContext.getStatus()));
- MDC.put(MsoLogger.METRIC_TIMER, String.valueOf(elapsedTime));
- MDC.put(MsoLogger.METRIC_END_TIME,formatter.format(instant));
- MDC.put(MsoLogger.PARTNERNAME,partnerName);
- MDC.put(MsoLogger.TARGETENTITY, targetEntity.toString());
- logger.recordMetricEvent();
- } catch ( Exception e) {
- logger.warnSimple("Error in outgoing JAX-RS Inteceptor", e);
- }
- }
-
- private static String getStringFromInputStream(ClientResponseContext clientResponseContext) {
-
- InputStream is = clientResponseContext.getEntityStream();
- ByteArrayOutputStream boas = new ByteArrayOutputStream();
-
- try {
- IOUtils.copy(is,boas);
- InputStream copiedStream = new ByteArrayInputStream(boas.toByteArray());
- clientResponseContext.setEntityStream(copiedStream);
- return boas.toString();
-
- } catch (IOException e) {
- logger.warnSimple("Failed to read response body", e);
- }
- return "Unable to read input stream";
- }
-}
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
new file mode 100644
index 0000000000..194a445ce2
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
@@ -0,0 +1,119 @@
+/*-
+ * ============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.logging.spring.interceptor;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+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.logging.jaxrs.filter.MDCSetup;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.ModelAndView;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+@Component
+public class LoggingInterceptor extends HandlerInterceptorAdapter {
+
+ Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
+
+ @Autowired
+ MDCSetup mdcSetup;
+
+ @Context
+ private Providers providers;
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+ Map<String, String> headers = Collections.list(((HttpServletRequest) request).getHeaderNames())
+ .stream()
+ .collect(Collectors.toMap(h -> h, request::getHeader));
+ setRequestId(headers);
+ setInvocationId(headers);
+ setServiceName(request);
+ setMDCPartnerName(headers);
+ mdcSetup.setClientIPAddress(request);
+ mdcSetup.setEntryTimeStamp();
+ mdcSetup.setInstanceUUID();
+ mdcSetup.setServerFQDN();
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, "INPROGRESS");
+ logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
+ return true;
+ }
+
+ @Override
+ public void postHandle(
+ HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
+ throws Exception {
+ setResponseStatusCode(response);
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION,"");
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE,String.valueOf(response.getStatus()));
+ logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
+ MDC.clear();
+ }
+
+ private void setResponseStatusCode(HttpServletResponse response) {
+ String statusCode;
+ if(Response.Status.Family.familyOf(response.getStatus()).equals(Response.Status.Family.SUCCESSFUL)){
+ statusCode=ONAPLogConstants.ResponseStatus.COMPLETED.toString();
+ }else{
+ statusCode= ONAPLogConstants.ResponseStatus.ERROR.toString();
+ }
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
+ }
+
+ private void setServiceName(HttpServletRequest request) {
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
+ }
+
+ private void setRequestId(Map<String, String> headers) {
+ String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID);
+ if(requestId == null || requestId.isEmpty())
+ requestId = UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID,requestId);
+ }
+
+ private void setInvocationId(Map<String, String> headers) {
+ String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID);
+ if(invocationId == null || invocationId.isEmpty())
+ invocationId =UUID.randomUUID().toString();
+ MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
+ }
+
+ private void setMDCPartnerName(Map<String, String> headers) {
+ String partnerName=headers.get(ONAPLogConstants.Headers.PARTNER_NAME);
+ if(partnerName == null || partnerName.isEmpty())
+ partnerName = "";
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME,partnerName);
+ }
+
+
+}
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 bda3096f05..8e7e5e945e 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Request.java
@@ -20,9 +20,10 @@
package org.onap.so.serviceinstancebeans;
+import java.util.List;
+
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
-import org.apache.commons.lang3.builder.ToStringBuilder;
@JsonInclude(Include.NON_DEFAULT)
@@ -35,6 +36,7 @@ public class Request {
protected RequestDetails requestDetails;
protected InstanceReferences instanceReferences;
protected RequestStatus requestStatus;
+ protected List<RequestProcessingData> requestProcessingData;
public String getRequestId() {
@@ -79,12 +81,19 @@ public class Request {
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
+ public List<RequestProcessingData> getRequestProcessingData() {
+ return requestProcessingData;
+ }
+ public void setRequestProcessingData(List<RequestProcessingData> requestProcessingData) {
+ this.requestProcessingData = requestProcessingData;
+ }
@Override
public String toString() {
- return new ToStringBuilder(this).append("requestId", requestId).append("startTime", startTime)
- .append("requestScope", requestScope).append("requestType", requestType)
- .append("requestDetails", requestDetails).append("instanceReferences", instanceReferences)
- .append("requestStatus", requestStatus).toString();
+ return "Request [requestId=" + requestId + ", startTime=" + startTime
+ + ", requestScope=" + requestScope + ", requestType=" + requestType
+ + ", requestDetails=" + requestDetails + ", instanceReferences=" + instanceReferences
+ + ", requestStatus=" + requestStatus + ", requestProcessingData=" + requestProcessingData + "]";
}
+
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java
new file mode 100644
index 0000000000..3373f78335
--- /dev/null
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestProcessingData.java
@@ -0,0 +1,62 @@
+/* ============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.serviceinstancebeans;
+
+import java.util.HashMap;
+import java.util.List;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+
+
+@JsonInclude(Include.NON_DEFAULT)
+public class RequestProcessingData {
+
+ protected String groupingId;
+ protected String tag;
+ protected List<HashMap<String, String>> dataPairs;
+
+ public String getGroupingId() {
+ return groupingId;
+ }
+ public void setGroupingId(String groupingId) {
+ this.groupingId = groupingId;
+ }
+ public String getTag() {
+ return tag;
+ }
+ public void setTag(String tag) {
+ this.tag = tag;
+ }
+ public List<HashMap<String, String>> getDataPairs() {
+ return dataPairs;
+ }
+ public void setDataPairs(List<HashMap<String, String>> dataPairs) {
+ this.dataPairs = dataPairs;
+ }
+ @Override
+ public String toString() {
+ return new ToStringBuilder(this).append("groupingId", groupingId).append("tag", tag)
+ .append("dataPairs", dataPairs).toString();
+ }
+
+
+}
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 ad76e56a56..84dae957ba 100644
--- a/common/src/main/java/org/onap/so/utils/TargetEntity.java
+++ b/common/src/main/java/org/onap/so/utils/TargetEntity.java
@@ -20,13 +20,22 @@
package org.onap.so.utils;
+import java.util.EnumSet;
public enum TargetEntity {
OPENSTACK_ADAPTER, BPMN, GRM ,AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER, NARAD;
- private static final String PREFIX = "MSO";
+ 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(){
- return TargetEntity.PREFIX + "." + this.name();
+ if(getSOInternalComponents().contains(this))
+ return TargetEntity.PREFIX + "." + this.name();
+ else
+ return this.name();
}
-}
+} \ No newline at end of file
diff --git a/common/src/test/java/org/onap/so/adapter_utils/tests/MsoLoggerTest.java b/common/src/test/java/org/onap/so/adapter_utils/tests/MsoLoggerTest.java
deleted file mode 100644
index 29ac91c864..0000000000
--- a/common/src/test/java/org/onap/so/adapter_utils/tests/MsoLoggerTest.java
+++ /dev/null
@@ -1,331 +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 org.onap.so.entity.MsoRequest;
-import org.onap.so.logger.MessageEnum;
-import org.onap.so.logger.MsoLogger;
-import org.onap.so.logger.MsoLogger.ErrorCode;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.slf4j.MDC;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.URL;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.List;
-
-/**
- * This class implements all test methods of the MsoLogger features.
- *
- *
- */
-public class MsoLoggerTest {
-
- static MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, MsoLoggerTest.class);
-
- /**
- * This method is called before any test occurs. It creates a fake tree from
- * scratch
- */
- @BeforeClass
- public static final void prepare() {
-
- }
-
- @Before
- public final void cleanErrorLogFile() throws FileNotFoundException {
- URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
- String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
- + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log";
- PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
- asdcConfigFileWriter.print("");
- asdcConfigFileWriter.flush();
- asdcConfigFileWriter.close();
- }
-
- @Before
- public final void cleanMetricLogFile() throws FileNotFoundException {
- URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
- String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
- + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log";
- PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
- asdcConfigFileWriter.print("");
- asdcConfigFileWriter.flush();
- asdcConfigFileWriter.close();
- }
-
- @Before
- public final void cleanAuditLogFile() throws FileNotFoundException {
- URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
- String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
- + "/MSO/Test/auditjbo.server.name_IS_UNDEFINED.log";
- PrintWriter asdcConfigFileWriter = new PrintWriter(logFile);
- asdcConfigFileWriter.print("");
- asdcConfigFileWriter.flush();
- asdcConfigFileWriter.close();
- }
-
- /**
- * This method implements a test of getSeverifyLevel method.
- */
- @Test
- public final void testGetSeverityLevel() {
-
- try {
- String levelInfo = (String) invokePriveMethod("getSeverityLevel", "INFO");
- Assert.assertEquals(levelInfo, "0");
-
- String levelWarn = (String) invokePriveMethod("getSeverityLevel", "WARN");
- Assert.assertEquals(levelWarn, "1");
-
- String levelERROR = (String) invokePriveMethod("getSeverityLevel", "ERROR");
- Assert.assertEquals(levelERROR, "2");
-
- String levelDEBUG = (String) invokePriveMethod("getSeverityLevel", "DEBUG");
- Assert.assertEquals(levelDEBUG, "0");
-
- String levelFATAL = (String) invokePriveMethod("getSeverityLevel", "FATAL");
- Assert.assertEquals(levelFATAL, "3");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- /**
- * This method implements a test of getFinalServiceName method.
- */
- @Test
- public final void testGetFinalServiceName() {
- try {
- String serviceName1 = (String) invokePriveMethod("getFinalServiceName", "testServiceName1");
- Assert.assertEquals(serviceName1, "testServiceName1");
-
- MsoLogger.setServiceName("testServiceName2");
- String serviceName2 = (String) invokePriveMethod("getFinalServiceName", "testServiceName1");
- Assert.assertEquals(serviceName2, "testServiceName1");
-
- String msgNull = null;
- String serviceName3 = (String) invokePriveMethod("getFinalServiceName", msgNull);
- Assert.assertEquals(serviceName3, "testServiceName2");
-
- MsoLogger.resetServiceName();
- String serviceName4 = (String) invokePriveMethod("getFinalServiceName", msgNull);
- Assert.assertEquals(serviceName4, "invoke0");
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- @Test
- public final void testPrepareMsg() {
- try {
- String msgNull = null;
- MDC.clear();
- invokePrepareMsg("INFO", null, null);
-
- Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("trace-#")
- && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("trace-#")
- && MDC.get(MsoLogger.SERVICE_NAME).equals("invoke0") && MDC.get(MsoLogger.TIMER) == null
- && MDC.get(MsoLogger.ALERT_SEVERITY).equals("0"));
-
- MsoLogger.setLoggerParameters("testRemoteIp", "testUser");
- MsoLogger.setLogContext("testReqId", "testSvcId");
- invokePrepareMsg("ERROR", "testServiceName3", null);
- Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("testReqId")
- && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId")
- && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName3") && MDC.get(MsoLogger.TIMER) == null
- && MDC.get(MsoLogger.ALERT_SEVERITY).equals("2"));
-
- MsoLogger.setServiceName("testServiceName2");
- invokePrepareMsg("WARN", msgNull, msgNull);
- Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("testReqId")
- && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("testSvcId")
- && MDC.get(MsoLogger.SERVICE_NAME).equals("testServiceName2") && MDC.get(MsoLogger.TIMER) == null
- && MDC.get(MsoLogger.ALERT_SEVERITY).equals("1"));
-
- MDC.clear();
- MsoRequest msoRequest = new MsoRequest();
- msoRequest.setRequestId("reqId2");
- msoRequest.setServiceInstanceId("servId2");
- MsoLogger.setLogContext(msoRequest);
- invokePrepareMsg("FATAL", null, "123");
- Assert.assertTrue(MDC.get(MsoLogger.REQUEST_ID).equals("reqId2")
- && MDC.get(MsoLogger.SERVICE_INSTANCE_ID).equals("servId2")
- && MDC.get(MsoLogger.TIMER).equals("123") && MDC.get(MsoLogger.ALERT_SEVERITY).equals("3"));
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- /**
- * This method implements a test of log methods
- */
- @Test
- @Ignore
- public final void testLogMethods() {
- try {
- MDC.clear();
- MsoLogger.setLogContext("reqId2", "servId2");
- MsoLogger.setServiceName("MSO.testServiceName");
- msoLogger.info(MessageEnum.LOGGER_UPDATE_SUC, "testLogger", "INFO", "DEBUG", "target entity",
- "target service");
- msoLogger.warn(MessageEnum.GENERAL_WARNING, "warning test", "", "", MsoLogger.ErrorCode.UnknownError,
- "warning test");
- msoLogger.error(MessageEnum.GENERAL_EXCEPTION, "target entity", "target service",
- MsoLogger.ErrorCode.UnknownError, "error test");
-
- // Fetch from the error log
- URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
- String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
- + "/MSO/Test/errorjboss.server.name_IS_UNDEFINED.log";
-
- Path filePath = new File(logFile).toPath();
- Charset charset = Charset.defaultCharset();
- List<String> stringList = Files.readAllLines(filePath, charset);
- String[] stringArray = stringList.toArray(new String[] {});
- int size = stringArray.length;
-
- Assert.assertTrue(stringArray[size - 3]
- .contains("|reqId2|main|MSO.testServiceName||target entity|target service|INFO|null||")
- && stringArray[size - 3].contains(
- "||MSO-GENERAL-5408I Successfully update Logger: testLogger from level INFO to level DEBUG"));
- Assert.assertTrue(stringArray[size - 2]
- .contains("|reqId2|main|MSO.testServiceName||||WARN|UnknownError|warning test|")
- && stringArray[size - 2].contains("|MSO-GENERAL-5401W WARNING: warning test"));
- Assert.assertTrue(stringArray[size - 1].contains(
- "|reqId2|main|MSO.testServiceName||target entity|target service|ERROR|UnknownError|error test|")
- && stringArray[size - 1].contains("|MSO-GENERAL-9401E Exception encountered"));
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- /**
- * This method implements a test of recordMetricEvent method.
- *
- * @throws IOException
- */
- @Test
- @Ignore
- public final void testRecordMetricEvent() throws IOException {
- MDC.clear();
- MsoLogger.setLogContext("reqId", "servId");
- msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successful",
- "VNF", "createVNF", null);
- MDC.put(MsoLogger.REMOTE_HOST, "127.0.0.1");
- MDC.put(MsoLogger.PARTNERNAME, "testUser");
- msoLogger.recordMetricEvent(123456789L, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.ServiceNotAvailable,
- "Exception", "SDNC", "removeSDNC", "testVNF");
-
- // Fetch from the metric log
- URL url = this.getClass().getClassLoader().getResource("logback-test.xml");
- String logFile = url.getFile().substring(0, url.getFile().indexOf("test-classes"))
- + "/MSO/Test/metricsjboss.server.name_IS_UNDEFINED.log";
-
- Path filePath = new File(logFile).toPath();
- Charset charset = Charset.defaultCharset();
- List<String> stringList = Files.readAllLines(filePath, charset);
- String[] stringArray = stringList.toArray(new String[] {});
- msoLogger.error(MessageEnum.GENERAL_EXCEPTION, "", "", MsoLogger.ErrorCode.UnknownError, "test error msg");
-
- Assert.assertTrue(stringArray[0]
- .contains("|reqId|servId|main||testRecordMetricEvent||VNF|createVNF|COMPLETE|0|Successful|"));
- // count the occurance of symbol "|"
- Assert.assertTrue((stringArray[0].length() - stringArray[0].replace("|", "").length()) == 28);
- Assert.assertTrue(stringArray[1]
- .contains("|reqId|servId|main||testRecordMetricEvent|testUser|SDNC|removeSDNC|ERROR|501|Exception|")
- && stringArray[1].contains("|127.0.0.1||||testVNF|||||"));
- Assert.assertTrue((stringArray[1].length() - stringArray[1].replace("|", "").length()) == 28);
- }
-
- /**
- * This method implements a test of testRecordAuditEvent method.
- */
-
- // User reflection to invoke to avoid change the publicity of the method
- private static String invokePrepareMsg(String arg1, String arg2, String arg3) {
- Method method;
- try {
- method = MsoLogger.class.getDeclaredMethod("prepareMsg", String.class, String.class, String.class);
- method.setAccessible(true);
- return (String) method.invoke(msoLogger, arg1, arg2, arg3);
- } catch (NoSuchMethodException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-
- // User reflection to invoke to avoid change the publicity of the method
- private static Object invokePriveMethod(String methodName, String arg) {
- Method method;
- try {
- method = MsoLogger.class.getDeclaredMethod(methodName, String.class);
- method.setAccessible(true);
- return method.invoke(msoLogger, arg);
- } catch (NoSuchMethodException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
-}
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 ce90ccdc0e..ea842719e8 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
@@ -52,4 +52,18 @@ public class AAIObjectTypeTest {
AAIUri aaiUri = AAIUriFactory.createResourceUri(AAIObjectType.COLLECTION, id);
assertEquals("/network/collections/collection/test1", aaiUri.build().toString());
}
+
+ @Test
+ public void genericVnfTest() {
+ AAIObjectType type = AAIObjectType.GENERIC_VNF;
+ assertEquals("/network/generic-vnfs/generic-vnf/{vnf-id}", type.uriTemplate());
+ assertEquals("/generic-vnfs/generic-vnf/{vnf-id}", type.partialUri());
+ }
+
+ @Test
+ public void pInterfaceTest() {
+ AAIObjectType type = AAIObjectType.P_INTERFACE;
+ assertEquals("/cloud-infrastructure/pservers/pserver/{hostname}/p-interfaces/p-interface/{interface-name}", type.uriTemplate());
+ assertEquals("/p-interfaces/p-interface/{interface-name}", type.partialUri());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java b/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
index 1e2e7471f1..37188bc4bc 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIPServerTest.java
@@ -44,6 +44,7 @@ public class AAIPServerTest {
List<Pserver> list = client.getListOfPservers(json);
assertEquals("", list.get(0).getHostname(), "test");
+ assertEquals("", list.size(), 2);
}
@Test
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
new file mode 100644
index 0000000000..008b612cd8
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/aai/AAIPatchConverterTest.java
@@ -0,0 +1,102 @@
+/*-
+ * ============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.aai;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.aai.domain.yang.GenericVnf;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+
+@RunWith(MockitoJUnitRunner.class)
+public class AAIPatchConverterTest {
+
+ private ObjectMapper mapper = new AAICommonObjectMapperProvider().getMapper();
+
+ @Test
+ public void convertObjectToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ AAIPatchConverter validator = new AAIPatchConverter();
+ GenericVnf vnf = new GenericVnf();
+ vnf.setIpv4Loopback0Address("");
+ String result = validator.marshallObjectToPatchFormat(vnf);
+ GenericVnf resultObj = mapper.readValue(result.toString(), GenericVnf.class);
+ assertTrue("expect object to become a String to prevent double marshalling", result instanceof String);
+ assertNull("expect null because of custom mapper", resultObj.getIpv4Loopback0Address());
+
+ }
+
+ @Test
+ public void convertStringToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
+ AAIPatchConverter validator = new AAIPatchConverter();
+ String payload = "{\"ipv4-loopback0-address\":\"\"}";
+ String result = validator.marshallObjectToPatchFormat(payload);
+
+ 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", "");
+ String result = validator.marshallObjectToPatchFormat(map);
+
+ assertEquals("expect string", "{\"ipv4-loopback0-address\":\"\"}", result);
+ }
+
+ @Test
+ public void hasComplexObjectTest() {
+ AAIPatchConverter validator = new AAIPatchConverter();
+ String hasNesting = "{ \"hello\" : \"world\", \"nested\" : { \"key\" : \"value\" } }";
+ String noNesting = "{ \"hello\" : \"world\" }";
+ String arrayCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"nestedComplex\" : [{\"key\" : \"value\"}]}";
+ String empty = "{}";
+ String arrayCaseSimpleOnly = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"]}";
+ String relationshipListCaseNesting = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}";
+ String relationshipListCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}]}";
+ String nothing = "";
+
+ assertTrue("expect has nesting", validator.hasComplexObject(hasNesting));
+ assertFalse("expect no nesting", validator.hasComplexObject(noNesting));
+ assertTrue("expect has nesting", validator.hasComplexObject(arrayCase));
+ assertFalse("expect no nesting", validator.hasComplexObject(empty));
+ assertFalse("expect no nesting", validator.hasComplexObject(arrayCaseSimpleOnly));
+ assertFalse("expect no nesting", validator.hasComplexObject(relationshipListCase));
+ assertTrue("expect has nesting", validator.hasComplexObject(relationshipListCaseNesting));
+ assertFalse("expect no nesting", validator.hasComplexObject(nothing));
+ }
+
+}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
index efd60a36a8..3d23213ff0 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIResourcesClientWithServiceInstanceUriTest.java
@@ -1,3 +1,23 @@
+/*-
+ * ============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.aai;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
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 f2e371c999..752c49eb5b 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,18 +21,16 @@
package org.onap.so.client.aai;
import static org.hamcrest.CoreMatchers.containsString;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
-import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.HashMap;
import javax.ws.rs.core.Response;
@@ -42,11 +40,9 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
-import org.onap.aai.domain.yang.GenericVnf;
+import org.onap.so.client.RestClientSSL;
import org.onap.so.client.graphinventory.exceptions.GraphInventoryPatchDepthExceededException;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
@@ -61,64 +57,22 @@ public class AAIRestClientTest {
public ExpectedException thrown = ExpectedException.none();
@Test
- public void convertObjectToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- AAIRestClient client = new AAIRestClient(props, new URI(""));
- GenericVnf vnf = new GenericVnf();
- vnf.setIpv4Loopback0Address("");
- String result = client.convertObjectToPatchFormat(vnf);
- GenericVnf resultObj = mapper.readValue(result.toString(), GenericVnf.class);
- assertTrue("expect object to become a String to prevent double marshalling", result instanceof String);
- assertNull("expect null because of custom mapper", resultObj.getIpv4Loopback0Address());
-
- }
-
- @Test
- public void convertStringToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- AAIRestClient client = new AAIRestClient(props, new URI(""));
- String payload = "{\"ipv4-loopback0-address\":\"\"}";
- String result = client.convertObjectToPatchFormat(payload);
-
- assertEquals("expect no change", payload, result);
- }
-
- @Test
- public void convertMapToPatchFormatTest() throws URISyntaxException, JsonParseException, JsonMappingException, IOException {
- AAIRestClient client = new AAIRestClient(props, new URI(""));
- HashMap<String, String> map = new HashMap<>();
- map.put("ipv4-loopback0-address", "");
- String result = client.convertObjectToPatchFormat(map);
-
- assertEquals("expect string", "{\"ipv4-loopback0-address\":\"\"}", result);
- }
-
- @Test
public void failPatchOnComplexObject() throws URISyntaxException {
AAIRestClient client = new AAIRestClient(props, new URI(""));
this.thrown.expect(GraphInventoryPatchDepthExceededException.class);
this.thrown.expectMessage(containsString("Object exceeds allowed depth for update action"));
client.patch("{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}");
-
}
@Test
- public void hasComplexObjectTest() throws URISyntaxException {
+ public void verifyPatchValidation() throws URISyntaxException {
AAIRestClient client = new AAIRestClient(props, new URI(""));
- String hasNesting = "{ \"hello\" : \"world\", \"nested\" : { \"key\" : \"value\" } }";
- String noNesting = "{ \"hello\" : \"world\" }";
- String arrayCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"nestedComplex\" : [{\"key\" : \"value\"}]}";
- String empty = "{}";
- String arrayCaseSimpleOnly = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"]}";
- String relationshipListCaseNesting = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}], \"nested\" : { \"key\" : \"value\" }}";
- String relationshipListCase = "{ \"hello\" : \"world\", \"nestedSimple\" : [\"value1\" , \"value2\"], \"relationship-list\" : [{\"key\" : \"value\"}]}";
- String nothing = "";
-
- assertTrue("expect has nesting", client.hasComplexObject(hasNesting));
- assertFalse("expect no nesting", client.hasComplexObject(noNesting));
- assertTrue("expect has nesting", client.hasComplexObject(arrayCase));
- assertFalse("expect no nesting", client.hasComplexObject(empty));
- assertFalse("expect no nesting", client.hasComplexObject(arrayCaseSimpleOnly));
- assertFalse("expect no nesting", client.hasComplexObject(relationshipListCase));
- assertTrue("expect has nesting", client.hasComplexObject(relationshipListCaseNesting));
- assertFalse("expect no nesting", client.hasComplexObject(nothing));
+ AAIRestClient spy = spy(client);
+ AAIPatchConverter patchValidatorMock = mock(AAIPatchConverter.class);
+ doReturn(patchValidatorMock).when(spy).getPatchConverter();
+ String payload = "{}";
+ doReturn(Response.ok().build()).when(spy).method(eq("PATCH"), any());
+ spy.patch(payload);
+ verify(patchValidatorMock, times(1)).convertPatchFormat(eq((Object)payload));
}
}
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
new file mode 100644
index 0000000000..8c42686e5f
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/aai/AAISingleTransactionClientTest.java
@@ -0,0 +1,133 @@
+/*-
+ * ============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.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.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Optional;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.domain.yang.Pserver;
+import org.onap.aai.domain.yang.v9.Complex;
+import org.onap.so.client.aai.entities.singletransaction.SingleTransactionRequest;
+import org.onap.so.client.aai.entities.singletransaction.SingleTransactionResponse;
+import org.onap.so.client.aai.entities.uri.AAIResourceUri;
+import org.onap.so.client.aai.entities.uri.AAIUriFactory;
+import org.onap.so.client.defaultproperties.DefaultAAIPropertiesImpl;
+import org.skyscreamer.jsonassert.JSONAssert;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
+public class AAISingleTransactionClientTest {
+
+ private final static String AAI_JSON_FILE_LOCATION = "src/test/resources/__files/aai/singletransaction/";
+ AAIResourceUri uriA = AAIUriFactory.createResourceUri(AAIObjectType.PSERVER, "pserver-hostname");
+ AAIResourceUri uriB = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, "my-complex");
+
+ ObjectMapper mapper;
+
+ @Before
+ public void before() throws JsonParseException, JsonMappingException, IOException {
+ mapper = new AAICommonObjectMapperProvider().getMapper();
+ mapper.enable(SerializationFeature.INDENT_OUTPUT);
+ }
+
+ @Test
+ public void testRequest() throws IOException {
+ AAIResourcesClient client = createClient();
+ Pserver pserver = new Pserver();
+ pserver.setHostname("pserver-hostname");
+ pserver.setFqdn("pserver-bulk-process-single-transactions-multiple-actions-1-fqdn");
+ Pserver pserver2 = new Pserver();
+ pserver2.setFqdn("patched-fqdn");
+ Complex complex = new Complex();
+ complex.setCity("my-city");
+ AAISingleTransactionClient singleTransaction =
+ client.beginSingleTransaction()
+ .create(uriA, pserver)
+ .update(uriA, pserver2)
+ .create(uriB, complex);
+
+
+ SingleTransactionRequest actual = singleTransaction.getRequest();
+
+ SingleTransactionRequest expected = mapper.readValue(this.getJson("sample-request.json"), SingleTransactionRequest.class);
+
+ JSONAssert.assertEquals(mapper.writeValueAsString(expected),mapper.writeValueAsString(actual), false);
+ }
+
+ @Test
+ public void testFailure() throws IOException {
+ AAIResourcesClient client = createClient();
+ AAISingleTransactionClient singleTransaction = client.beginSingleTransaction();
+ SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response-failure.json"), SingleTransactionResponse.class);
+ Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
+
+ assertThat(expected.getOperationResponses().size(), greaterThan(0));
+ assertThat(errorMessage.isPresent(), equalTo(true));
+
+ }
+
+ @Test
+ public void testSuccessResponse() throws IOException {
+ AAIResourcesClient client = createClient();
+ AAISingleTransactionClient singleTransaction = client.beginSingleTransaction();
+ SingleTransactionResponse expected = mapper.readValue(this.getJson("sample-response.json"), SingleTransactionResponse.class);
+ Optional<String> errorMessage = singleTransaction.locateErrorMessages(expected);
+
+ assertThat(expected.getOperationResponses().size(), greaterThan(0));
+ assertThat(errorMessage.isPresent(), equalTo(false));
+
+ }
+
+ @Test
+ public void confirmPatchFormat() {
+ AAISingleTransactionClient singleTransaction = spy(new AAISingleTransactionClient(AAIVersion.LATEST));
+ AAIPatchConverter mock = mock(AAIPatchConverter.class);
+ doReturn(mock).when(singleTransaction).getPatchConverter();
+ singleTransaction.update(uriA, "{}");
+ verify(mock, times(1)).convertPatchFormat(any());
+ }
+ private String getJson(String filename) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
+ }
+
+ private AAIResourcesClient createClient() {
+ AAIResourcesClient client = spy(new AAIResourcesClient());
+ doReturn(new DefaultAAIPropertiesImpl()).when(client).getRestProperties();
+ return client;
+ }
+}
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 f6ee826a78..cbf8d67a82 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,8 +21,12 @@
package org.onap.so.client.aai;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.nio.file.Files;
@@ -136,6 +140,15 @@ public class AAITransactionalClientTest {
assertEquals(transactions.locateErrorMessages(getJson("response-failure.json")).get(), "another error message\nmy great error");
}
+ @Test
+ public void confirmPatchFormat() {
+ AAITransactionalClient client = spy(new AAITransactionalClient(AAIVersion.LATEST));
+ AAIPatchConverter mock = mock(AAIPatchConverter.class);
+ doReturn(mock).when(client).getPatchConverter();
+ client.update(uriA, "{}");
+ verify(mock, times(1)).convertPatchFormat(any());
+ }
+
private String getJson(String filename) throws IOException {
return new String(Files.readAllBytes(Paths.get(AAI_JSON_FILE_LOCATION + filename)));
}
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 ff940a0dea..d4bf1b0224 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
@@ -20,9 +20,10 @@
package org.onap.so.client.aai.entities;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
import java.io.IOException;
+import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
@@ -30,11 +31,15 @@ import java.util.Map;
import java.util.Optional;
import org.junit.Before;
+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.onap.aai.domain.yang.GenericVnf;
import org.onap.so.client.aai.AAICommonObjectMapperProvider;
+import org.springframework.util.SerializationUtils;
+
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
@@ -43,7 +48,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(MockitoJUnitRunner.class)
public class AAIResultWrapperTest {
String json;
-
+ @Rule
+ public ExpectedException thrown= ExpectedException.none();
+
AAIResultWrapper aaiResultWrapper;
AAIResultWrapper aaiResultWrapperEmpty;
@@ -57,6 +64,14 @@ public class AAIResultWrapperTest {
}
@Test
+ public void testAAIResultWrapperIsSerializable() throws IOException {
+ AAIResultWrapper original = new AAIResultWrapper("");
+ byte[] serialized = SerializationUtils.serialize(original);
+ AAIResultWrapper deserialized = (AAIResultWrapper) SerializationUtils.deserialize(serialized);
+ assertEquals(deserialized.getJson(), original.getJson());
+ }
+
+ @Test
public void testGetRelationshipsEmpty() {
Optional<Relationships> relationships = aaiResultWrapperEmpty.getRelationships();
assertEquals("Compare relationships", Optional.empty(), relationships);
@@ -87,8 +102,12 @@ public class AAIResultWrapperTest {
assertEquals(Optional.empty(), wrapper.asBean(GenericVnf.class));
assertEquals(true, wrapper.asMap().isEmpty());
assertEquals("{}", wrapper.toString());
-
-
}
+
+ @Test
+ public void objectConstructor() {
+ AAIResultWrapper wrapper = new AAIResultWrapper(new GenericVnf());
+ assertEquals("{}", wrapper.getJson());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java
new file mode 100644
index 0000000000..beb18a389c
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriFromParentUriTest.java
@@ -0,0 +1,41 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 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.aai.entities.uri;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.onap.so.client.aai.AAIObjectType;
+
+public class AAISimpleUriFromParentUriTest {
+
+
+ @Test
+ public void appendChildren() {
+
+ AAIResourceUri parentUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "key1", "key2", "key3");
+
+ AAIUri uri = new AAISimpleUri(parentUri, AAIObjectType.ALLOTTED_RESOURCE, "key4");
+
+ assertEquals("path appended", "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4", uri.build().toString());
+
+ }
+}
diff --git a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
index 1b6cc7bf66..fcf054f489 100644
--- a/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AAISimpleUriTest.java
@@ -75,4 +75,12 @@ public class AAISimpleUriTest {
System.out.println(uri.build());
assertEquals("vserver1", keys.get("vserver-id"));
}
+
+ @Test
+ public void getEncodedKeyTest() {
+ AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, "test1", "my value", "test3");
+ Map<String,String> keys = uri.getURIKeys();
+
+ assertEquals("my value", keys.get("service-type"));
+ }
}
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
new file mode 100644
index 0000000000..71ec49789e
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/aai/entities/uri/AllottedResourceLookupUriTest.java
@@ -0,0 +1,52 @@
+/*-
+ * ============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.entities.uri;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.ws.rs.core.UriBuilder;
+
+import org.junit.Test;
+import org.onap.so.client.graphinventory.exceptions.GraphInventoryPayloadException;
+import org.onap.so.client.graphinventory.exceptions.GraphInventoryUriNotFoundException;
+
+public class AllottedResourceLookupUriTest {
+
+ @Test
+ public void oneKey() throws IOException, URISyntaxException, GraphInventoryUriNotFoundException, GraphInventoryPayloadException {
+
+ AllottedResourceLookupUri instance = new AllottedResourceLookupUri("key1");
+ AllottedResourceLookupUri spy = spy(instance);
+ doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4").when(spy).getObjectById(any(Object.class));
+
+ final URI result = spy.build();
+ final URI expected = UriBuilder.fromPath("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3/allotted-resources/allotted-resource/key4").build();
+ assertEquals("result is equal", expected, result);
+
+ }
+}
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 2cd7848cfa..26f9d871fd 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
@@ -84,7 +84,7 @@ public class ServiceInstanceUriTest {
ServiceInstanceUri instance = new ServiceInstanceUri("key1");
ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getSerivceInstance(any(Object.class));
+ doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getObjectById(any(Object.class));
final URI result = spy.build();
final URI expected = UriBuilder.fromPath("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").build();
@@ -97,7 +97,7 @@ public class ServiceInstanceUriTest {
ServiceInstanceUri instance = new ServiceInstanceUri("key1");
ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getSerivceInstance(any(Object.class));
+ doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3").when(spy).getObjectById(any(Object.class));
final URI result = spy.resourceVersion("1234").build();
final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234").build();
@@ -110,7 +110,7 @@ public class ServiceInstanceUriTest {
ServiceInstanceUri instance = new ServiceInstanceUri("key1");
ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space").when(spy).getSerivceInstance(any(Object.class));
+ doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space").when(spy).getObjectById(any(Object.class));
final URI result = spy.build();
final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%20space").build();
@@ -123,7 +123,7 @@ public class ServiceInstanceUriTest {
ServiceInstanceUri instance = new ServiceInstanceUri("key1");
ServiceInstanceUri spy = spy(instance);
- doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%28space").when(spy).getSerivceInstance(any(Object.class));
+ doReturn("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3%28space").when(spy).getObjectById(any(Object.class));
assertThat(spy.getURIKeys().values(), contains("key1", "key2", "key3(space"));
@@ -133,7 +133,7 @@ public class ServiceInstanceUriTest {
ServiceInstanceUri instance = new ServiceInstanceUri("key1");
ServiceInstanceUri spy = spy(instance);
String uri = "/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3";
- doReturn(uri).when(spy).getSerivceInstance(any(Object.class));
+ doReturn(uri).when(spy).getObjectById(any(Object.class));
doReturn(Optional.of(uri)).when(spy).getCachedValue();
final URI result = spy.resourceVersion("1234").clone().build();
final URI expected = UriBuilder.fromUri("/business/customers/customer/key1/service-subscriptions/service-subscription/key2/service-instances/service-instance/key3?resource-version=1234").build();
diff --git a/common/src/test/java/org/onap/so/client/aai/objects/AAIServiceInstanceTest.java b/common/src/test/java/org/onap/so/client/aai/objects/AAIServiceInstanceTest.java
deleted file mode 100644
index 4b080252b2..0000000000
--- a/common/src/test/java/org/onap/so/client/aai/objects/AAIServiceInstanceTest.java
+++ /dev/null
@@ -1,53 +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 AAIServiceInstanceTest {
-
- @Test
- public void test() {
- AAIServiceInstance aaiSI= new AAIServiceInstance();
- aaiSI.setEnvironmentContext("environmentContext");
- aaiSI.setModelInvariantUuid("modelInvariantUuid");
- aaiSI.setModelUuid("modelUuid");
- aaiSI.setoStatus("oStatus");
- aaiSI.setServiceInstanceId("serviceInstanceId");
- aaiSI.setServiceInstanceName("serviceInstanceName");
- aaiSI.setServiceRole("serviceRole");
- aaiSI.setServiceType("serviceType");
- aaiSI.setWorkloadContext("workloadContext");
- assertEquals(aaiSI.getEnvironmentContext(), "environmentContext");
- assertEquals(aaiSI.getModelInvariantUuid(), "modelInvariantUuid");
- assertEquals(aaiSI.getModelUuid(), "modelUuid");
- assertEquals(aaiSI.getoStatus(), "oStatus");
- assertEquals(aaiSI.getServiceInstanceId(), "serviceInstanceId");
- assertEquals(aaiSI.getServiceInstanceName(), "serviceInstanceName");
- assertEquals(aaiSI.getServiceRole(), "serviceRole");
- assertEquals(aaiSI.getServiceType(), "serviceType");
- assertEquals(aaiSI.getWorkloadContext(), "workloadContext");
- aaiSI.withServiceInstance("serviceInstanceId");
- assert(aaiSI.getUri()!=null);
- }
-
-}
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
index 3cce6a626b..7b783762fa 100644
--- a/common/src/test/java/org/onap/so/client/grm/GRMClientTest.java
+++ b/common/src/test/java/org/onap/so/client/grm/GRMClientTest.java
@@ -24,9 +24,11 @@ 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;
@@ -43,6 +45,7 @@ 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;
@@ -54,8 +57,7 @@ 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.logger.MsoLogger;
-import org.onap.so.logger.MsoLogger.Catalog;
+
import org.onap.so.utils.TestAppender;
public class GRMClientTest {
@@ -66,6 +68,8 @@ public class GRMClientTest {
@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");
@@ -81,25 +85,45 @@ public class GRMClientTest {
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", MediaType.APPLICATION_JSON)
- .withHeader("X-FromAppId", "GRM")
.withBody(endpoints)));
- MDC.put(MsoLogger.SERVICE_NAME, "my-value");
+ 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());
- ILoggingEvent logEvent = TestAppender.events.get(0);
- Map<String,String> mdc = logEvent.getMDCPropertyMap();
- assertNotNull(mdc.get(MsoLogger.METRIC_BEGIN_TIME));
- assertNotNull(mdc.get(MsoLogger.METRIC_END_TIME));
- assertNotNull(mdc.get(MsoLogger.REQUEST_ID));
- assertNotNull(mdc.get(MsoLogger.METRIC_TIMER));
- assertEquals("200",mdc.get(MsoLogger.RESPONSECODE));
- assertEquals("GRM",mdc.get(MsoLogger.PARTNERNAME));
- assertEquals("expect value to not be overwritten by jax rs client interceptor", "my-value",mdc.get(MsoLogger.SERVICE_NAME));
- assertEquals("COMPLETE",mdc.get(MsoLogger.STATUSCODE));
- assertNotNull(mdc.get(MsoLogger.RESPONSEDESC));
+
+ 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
@@ -116,68 +140,6 @@ public class GRMClientTest {
client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST");
}
- @Ignore
- @Test
- public void testAdd() throws Exception {
-
- wireMockRule.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add"))
- .willReturn(aResponse()
- .withStatus(202)
- .withHeader("Content-Type", MediaType.APPLICATION_JSON)
- .withBody("test")));
- wireMockRule.addMockServiceRequestListener((request, response) -> {
- System.out.println("URL Requested => " + request.getAbsoluteUrl());
- System.out.println("Request Body => " + request.getBodyAsString());
- System.out.println("Request Headers => " + request.getHeaders().toString());
- System.out.println("Response Status => " + response.getStatus());
- System.out.println("Response Body => " + response.getBodyAsString());
- });
-
- Version ver = new Version();
- ver.setMajor(1);
- ver.setMinor(0);
- ver.setPatch("0");
-
- ServiceEndPoint sep = new ServiceEndPoint();
- sep.setName("TEST.ECOMP_PSL.Inventory");
- sep.setVersion(ver);
- sep.setHostAddress("127.0.0.1");
- sep.setListenPort("8080");
- sep.setLatitude("37.7022");
- sep.setLongitude("121.9358");
- sep.setContextPath("/");
- sep.setRouteOffer("TEST");
-
- OperationalInfo operInfo = new OperationalInfo();
- operInfo.setCreatedBy("edge");
- operInfo.setUpdatedBy("edge");
-
- sep.setOperationalInfo(operInfo);
-
- Property prop1 = new Property();
- prop1.setName("Environment");
- prop1.setValue("TEST");
-
- Property prop2 = new Property();
- prop2.setName("cpfrun_cluster_name");
- prop2.setValue("testcase_cluster_no_cluster");
-
- List<Property> props = new ArrayList<Property>();
- props.add(prop1);
- props.add(prop2);
-
- sep.setProperties(props);
-
- ServiceEndPointRequest request = new ServiceEndPointRequest();
- request.setEnv("DEV");
- request.setServiceEndPoint(sep);
-
- System.out.println("Request in JSON: " + mapper.writeValueAsString(request));
-
- GRMClient client = new GRMClient();
- client.addServiceEndPoint(request);
- }
-
@Test
public void testAddFail() throws Exception {
wireMockRule.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add"))
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 104d40f76e..4cb9bd0e16 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,8 +23,12 @@ 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.Mockito.doReturn;
+import static org.mockito.Matchers.any;
+import java.io.File;
+import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@@ -33,16 +37,28 @@ import org.junit.Ignore;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.so.client.defaultproperties.PolicyRestPropertiesImpl;
+import org.onap.so.client.policy.entities.Config;
+import org.onap.so.client.policy.entities.ConfigRequestParameters;
import org.onap.so.client.policy.entities.DictionaryData;
+import org.onap.so.client.policy.entities.PolicyConfig;
import org.onap.so.client.policy.entities.PolicyDecision;
import org.onap.so.client.policy.entities.PolicyServiceType;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+
public class PolicyClientImplTest {
-
+
@BeforeClass
public static void setUp() {
System.setProperty("mso.config.path", "src/test/resources");
}
+
+ private static String RESOURCE_PATH = "src/test/resources/__files/Policy/";
+
@Test
public void successReadProperties() {
PolicyRestClient client = new PolicyRestClient(new PolicyRestPropertiesImpl(), PolicyServiceType.GET_DECISION);
@@ -52,7 +68,7 @@ public class PolicyClientImplTest {
assertEquals("Found expected Authorization", "Basic dGVzdHBkcDphbHBoYTEyMw==", map.get("Authorization"));
assertEquals("Found expected Environment", "TEST", map.get("Environment"));
}
-
+
@Test
@Ignore
public void getDecisionTest() {
@@ -61,10 +77,10 @@ public class PolicyClientImplTest {
assertEquals("Decision is correct", decision.getDecision(), "PERMIT");
assertEquals("Decision details is correct", decision.getDetails(), "Retry");
}
-
+
@Test
@Ignore
- public void getAllowedTreatmentsTest(){
+ public void getAllowedTreatmentsTest() {
PolicyClient client = new PolicyClientImpl();
DictionaryData dictClient = client.getAllowedTreatments("BB1", "1");
final String dictBbidString = dictClient.getBbid().getString();
@@ -72,7 +88,7 @@ public class PolicyClientImplTest {
assertEquals("DictionaryData matches a response Bbid", dictBbidString, "BB1");
assertEquals("DicitonaryData matches a response WorkStep", dictWorkStepString, "1");
}
-
+
@Test
public void getDecisionMockTest() {
String serviceType = "S";
@@ -80,11 +96,11 @@ public class PolicyClientImplTest {
String bbID = "BB1";
String workStep = "1";
String errorCode = "123";
-
+
PolicyDecision expected = new PolicyDecision();
expected.setDecision("PERMIT");
expected.setDetails("Retry");
-
+
DecisionAttributes decisionAttributes = new DecisionAttributes();
decisionAttributes.setServiceType(serviceType);
decisionAttributes.setVNFType(vnfType);
@@ -92,20 +108,43 @@ public class PolicyClientImplTest {
decisionAttributes.setWorkStep(workStep);
decisionAttributes.setErrorCode(errorCode);
PolicyClient client = Mockito.spy(PolicyClientImpl.class);
-
+
doReturn(expected).when(client).getDecision(serviceType, vnfType, bbID, workStep, errorCode);
PolicyDecision actual = client.getDecision(serviceType, vnfType, bbID, workStep, errorCode);
assertThat(actual, sameBeanAs(expected));
}
+
+ @Test
+ public void getConfigFromStringJsonTest() throws JsonParseException, JsonMappingException, IOException {
+ PolicyClientImpl client = new PolicyClientImpl();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
+ PolicyConfig[] returnedPolicyConfigList = mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
+ String configJson = returnedPolicyConfigList[0].getConfig();
+ Config actual = client.getConfigFromStringJson(configJson);
+
+ assertThat(actual, sameBeanAs(expected));
+ }
- /*
@Test
- public void getAllowedTreatmentsTest() {
- PolicyClient client = new PolicyClientImpl();
- AllowedTreatments allowedTreatments = client.getAllowedTreatments("BB1", "1");
- int expectedSizeOfList = 4;
- int sizeOfList = allowedTreatments.getAllowedTreatments().size();
- assertEquals("Decision is correct", sizeOfList, expectedSizeOfList);
- }*/
+ public void getConfigWithPolicyNameTest() throws JsonParseException, JsonMappingException, IOException {
+ PolicyClientImpl client = Mockito.spy(PolicyClientImpl.class);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
+ mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
+ PolicyConfig[] returnedPolicyConfigList = mapper.readValue(new File(RESOURCE_PATH + "policyConfig.json"), PolicyConfig[].class);
+ Config expected = mapper.readValue(new File(RESOURCE_PATH + "configJson.json"), Config.class);
+
+ PolicyRestClient mockedClient = Mockito.mock(PolicyRestClient.class);
+ doReturn(mockedClient).when(client).getPolicyRestClient(PolicyServiceType.GET_CONFIG);
+ doReturn(returnedPolicyConfigList).when(mockedClient).post(isA(ConfigRequestParameters.class), any());
+
+ Config actual = client.getConfigWithPolicyName("policyName");
+
+ assertThat(actual, sameBeanAs(expected));
+
+ }
}
diff --git a/common/src/test/resources/__files/Policy/configJson.json b/common/src/test/resources/__files/Policy/configJson.json
new file mode 100644
index 0000000000..b206998b41
--- /dev/null
+++ b/common/src/test/resources/__files/Policy/configJson.json
@@ -0,0 +1,23 @@
+{
+ "configName": "Testing",
+ "riskLevel": "1",
+ "policyName": "fabric_configuration",
+ "policyScope": "resource=Test1,service=vSCP,type=configuration,closedLoopControlName=Firewall",
+ "guard": "False",
+ "description": "null",
+ "priority": "9",
+ "uuid": "1234",
+ "version": "1.0",
+ "content": {
+ "fabric-config-models": [
+ {
+ "vnfProfile": "v5",
+ "lagProfile": "N1"
+ }
+ ]
+ },
+ "riskType": "test",
+ "service": "mso-fabric-configuration-model",
+ "location": " Edge",
+ "templateVersion": "1607"
+} \ No newline at end of file
diff --git a/common/src/test/resources/__files/Policy/policyConfig.json b/common/src/test/resources/__files/Policy/policyConfig.json
new file mode 100644
index 0000000000..b67c9c0e48
--- /dev/null
+++ b/common/src/test/resources/__files/Policy/policyConfig.json
@@ -0,0 +1,20 @@
+[
+ {
+ "policyConfigMessage": "Config Retrieved! ",
+ "policyConfigStatus": "CONFIG_RETRIEVED",
+ "type": "JSON",
+ "config": "{\"configName\":\"Testing\",\"riskLevel\":\"1\",\"policyName\":\"fabric_configuration\",\"policyScope\":\"resource=Test1,service=vSCP,type=configuration,closedLoopControlName=Firewall\",\"guard\":\"False\",\"description\":\"null\",\"priority\":\"9\",\"uuid\":\"1234\",\"version\":\"1.0\",\"content\":{\"fabric-config-models\":[{\"vnfProfile\":\"v5\",\"lagProfile\":\"N1\"}]},\"riskType\":\"test\",\"service\":\"mso-fabric-configuration-model\",\"location\":\" Edge\",\"templateVersion\":\"1607\"}",
+ "policyName": "MSO_Policy.Config_MS_fabric_configuration_vPE.2.xml",
+ "policyType": "MicroService",
+ "policyVersion": "2",
+ "matchingConditions": {
+ "ECOMPName": "MSO",
+ "ONAPName": "MSO",
+ "service": "mso-fabric-configuration-model"
+ },
+ "responseAttributes": {
+
+ },
+ "property": null
+ }
+] \ No newline at end of file
diff --git a/common/src/test/resources/__files/aai/singletransaction/sample-request.json b/common/src/test/resources/__files/aai/singletransaction/sample-request.json
new file mode 100644
index 0000000000..f0761a07b6
--- /dev/null
+++ b/common/src/test/resources/__files/aai/singletransaction/sample-request.json
@@ -0,0 +1,26 @@
+{
+ "operations": [
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "body": {
+ "hostname": "pserver-hostname",
+ "fqdn": "pserver-bulk-process-single-transactions-multiple-actions-1-fqdn"
+ }
+ },
+ {
+ "action": "patch",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "body": {
+ "fqdn": "patched-fqdn"
+ }
+ },
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/complexes/complex/my-complex",
+ "body": {
+ "city": "my-city"
+ }
+ }
+ ]
+} \ No newline at end of file
diff --git a/common/src/test/resources/__files/aai/singletransaction/sample-response-failure.json b/common/src/test/resources/__files/aai/singletransaction/sample-response-failure.json
new file mode 100644
index 0000000000..d0b0e39924
--- /dev/null
+++ b/common/src/test/resources/__files/aai/singletransaction/sample-response-failure.json
@@ -0,0 +1,30 @@
+{
+ "operation-responses": [
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "response-status-code": 201,
+ "response-body": null
+ },
+ {
+ "action": "patch",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "response-status-code": 200,
+ "response-body": null
+ },
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/complexes/complex/my-complex",
+ "response-status-code": 400,
+ "response-body": {
+ "requestError": {
+ "serviceException": {
+ "messageId": "SVC3003",
+ "text": "another error message",
+ "variables": []
+ }
+ }
+ }
+ }
+ ]
+} \ No newline at end of file
diff --git a/common/src/test/resources/__files/aai/singletransaction/sample-response.json b/common/src/test/resources/__files/aai/singletransaction/sample-response.json
new file mode 100644
index 0000000000..a5b322ee2e
--- /dev/null
+++ b/common/src/test/resources/__files/aai/singletransaction/sample-response.json
@@ -0,0 +1,22 @@
+{
+ "operation-responses": [
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "response-status-code": 201,
+ "response-body": null
+ },
+ {
+ "action": "patch",
+ "uri": "/cloud-infrastructure/pservers/pserver/pserver-hostname",
+ "response-status-code": 200,
+ "response-body": null
+ },
+ {
+ "action": "put",
+ "uri": "/cloud-infrastructure/complexes/complex/my-complex",
+ "response-status-code": 201,
+ "response-body": null
+ }
+ ]
+} \ 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 c4248bf985..772eeabeb6 100644
--- a/common/src/test/resources/logback-test.xml
+++ b/common/src/test/resources/logback-test.xml
@@ -1,8 +1,8 @@
<!--
============LICENSE_START=======================================================
- ECOMP MSO
+ ONAP SO
================================================================================
- Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ Copyright (C) 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.
@@ -18,159 +18,58 @@
============LICENSE_END=========================================================
-->
-<configuration scan="false" debug="true">
- <!--<jmxConfigurator /> -->
- <!-- directory path for all other type logs -->
+<configuration>
+ <property name="p_tim" value="%d{&quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXX&quot;, UTC}"/>
+ <property name="p_lvl" value="%level"/>
+ <property name="p_log" value="%logger"/>
+ <property name="p_mdc" value="%replace(%replace(%mdc){'\t','\\\\t'}){'\n', '\\\\n'}"/>
+ <property name="p_msg" value="%replace(%replace(%msg){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_exc" value="%replace(%replace(%rootException){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_mak" value="%replace(%replace(%marker){'\t', '\\\\t'}){'\n','\\\\n'}"/>
+ <property name="p_thr" value="%thread"/>
+ <property name="pattern" value="%nopexception${p_tim}\t${p_thr}\t${p_lvl}\t${p_log}\t${p_mdc}\t${p_msg}\t${p_exc}\t${p_mak}\t%n"/>
- <property name="logDir" value="./target" />
-
- <!-- directory path for debugging type logs -->
- <property name="debugDir" value="./target" />
-
- <!-- specify the component name
- <ECOMP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
- <property name="componentName" value="MSO"></property>
- <property name="subComponentName" value="Test"></property>
- <!-- log file names -->
- <property name="errorLogName" value="error" />
- <property name="metricsLogName" value="metrics" />
- <property name="auditLogName" value="audit" />
- <property name="debugLogName" value="debug" />
- <property name="errorPattern" value="%d{&quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXX&quot;, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%.-5level|%X{ErrorCode}|%X{ErrorDesc}|%msg%n" />
- <property name="debugPattern" value="%d{&quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXX&quot;, UTC}|%X{RequestId}|%msg%n" />
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${pattern}</pattern>
+ </encoder>
+ </appender>
- <property name="auditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread||%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{RemoteHost}||||||||%msg%n" />
- <property name="metricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread||%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDesc}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{Timer}|%X{ServerFQDN}|%X{RemoteHost}||||%X{TargetVirtualEntity}|||||%msg%n" />
+ <appender name="test"
+ class="org.onap.so.utils.TestAppender" />
- <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
- <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
+ <logger name="com.att.ecomp.audit" level="info" additivity="false">
+ <appender-ref ref="STDOUT" />
+ </logger>
- <appender name="test" class="org.onap.so.utils.TestAppender"/>
- <!-- ============================================================================ -->
- <!-- EELF Appenders -->
- <!-- ============================================================================ -->
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="STDOUT" />
+ </logger>
- <!-- The EELFAppender is used to record events to the general application
- log -->
-
- <!-- EELF Audit Appender. This appender is used to record audit engine
- related logging events. The audit logger and appender are specializations
- of the EELF application root logger and appender. This can be used to segregate
- Policy engine events from other components, or it can be eliminated to record
- these events as part of the application root log. -->
-
- <appender name="EELFAudit"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${auditLogName}${jboss.server.name}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${logDirectory}/${auditLogName}${jboss.server.name}.log.%d</fileNamePattern>
- <!--<maxHistory>30</maxHistory>-->
- </rollingPolicy>
- <encoder>
- <pattern>${auditPattern}</pattern>
- </encoder>
- </appender>
- <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>500</queueSize>
- <discardingThreshold>0</discardingThreshold>
- <appender-ref ref="EELFAudit" />
- </appender>
+ <logger name="com.att.eelf.error" level="WARN" additivity="false">
+ <appender-ref ref="STDOUT" />
+ </logger>
-<appender name="EELFMetrics"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${metricsLogName}${jboss.server.name}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${logDirectory}/${metricsLogName}${jboss.server.name}.log.%d</fileNamePattern>
- <!--<maxHistory>30</maxHistory>-->
- </rollingPolicy>
- <encoder>
- <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
- %msg%n"</pattern> -->
- <pattern>${metricPattern}</pattern>
- </encoder>
- </appender>
-
-
- <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>500</queueSize>
- <discardingThreshold>0</discardingThreshold>
- <appender-ref ref="EELFMetrics"/>
- </appender>
-
- <appender name="EELFError"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${logDirectory}/${errorLogName}${jboss.server.name}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${logDirectory}/${errorLogName}${jboss.server.name}.log.%d</fileNamePattern>
- <!--<maxHistory>30</maxHistory>-->
- </rollingPolicy>
- <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
- <level>INFO</level>
- </filter>
- <encoder>
- <pattern>${errorPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>500</queueSize>
- <discardingThreshold>0</discardingThreshold>
- <appender-ref ref="EELFError"/>
- </appender>
-
- <appender name="EELFDebug"
- class="ch.qos.logback.core.rolling.RollingFileAppender">
- <file>${debugLogDirectory}/${debugLogName}${jboss.server.name}.log</file>
- <rollingPolicy
- class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${debugLogDirectory}/${debugLogName}${jboss.server.name}.log.%d</fileNamePattern>
- <!--<maxHistory>30</maxHistory>-->
- </rollingPolicy>
- <encoder>
- <pattern>${debugPattern}</pattern>
- </encoder>
- </appender>
-
- <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
- <queueSize>500</queueSize>
- <discardingThreshold>0</discardingThreshold>
- <appender-ref ref="EELFDebug" />
- <includeCallerData>true</includeCallerData>
- </appender>
-
- <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%d{HH:mm:ss.SSS} [%thread] |%X{RequestId}| %-5level
- %logger{1024} - %msg%n
- </pattern>
- </encoder>
- </appender>
+ <logger name="org.onap" level="${so.log.level:-DEBUG}" additivity="false">
+ <appender-ref ref="STDOUT" />
+ <appender-ref ref="test" />
+ </logger>
+
+ <logger name="org.flywaydb" level="DEBUG" additivity="false">
+ <appender-ref ref="STDOUT" />
+ </logger>
- <!-- ============================================================================ -->
- <!-- EELF loggers -->
- <!-- ============================================================================ -->
- <logger name="com.att.eelf.audit" level="${so.log.level:-DEBUG}" additivity="false">
- <appender-ref ref="asyncEELFAudit" />
- </logger>
-
- <logger name="METRIC" level="${so.log.level:-DEBUG}" additivity="true">
- <appender-ref ref="asyncEELFMetrics" />
- <appender-ref ref="test" />
- </logger>
+ <logger name="ch.vorburger" level="WARN" additivity="false">
+ <appender-ref ref="STDOUT" />
+ </logger>
+
- <logger name="com.att.eelf.error" level="${so.log.level:-DEBUG}" additivity="false">
- <appender-ref ref="asyncEELFError" />
- </logger>
-
- <root level="${so.log.level:-DEBUG}">
- <appender-ref ref="asyncEELFDebug" />
- <appender-ref ref="STDOUT" />
- </root>
+ <root level="WARN">
+ <appender-ref ref="STDOUT" />
+ <appender-ref ref="test" />
+ </root>
</configuration> \ No newline at end of file
diff --git a/common/src/test/resources/mso-bad.json b/common/src/test/resources/mso-bad.json
deleted file mode 100644
index 1aaea50042..0000000000
--- a/common/src/test/resources/mso-bad.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "asdc-connections": {
- "asdc-controller1": {
- "asdcUser": "user1",
- "asdcConsumerGroup": "consumer1",
- "asdcConsumerId": "consumer1",
- "asdcEnvironmentName": "PROD",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- },
- "asdc-controller2": {
- "asdcUser": "user2",
- "asdcConsumerGroup": "consumer2",
- "asdcConsumerId": "consumer2",
- "asdcEnvironmentName": "E2E",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- }
- }
-} \ No newline at end of file
diff --git a/common/src/test/resources/mso.json b/common/src/test/resources/mso.json
deleted file mode 100644
index e8ee4a9185..0000000000
--- a/common/src/test/resources/mso.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "asdc-connections":{
- "asdc-controller1":{
- "asdcUser": "user1",
- "asdcConsumerGroup": "consumer1",
- "asdcConsumerId": "consumer1",
- "asdcEnvironmentName": "PROD",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- },
- "asdc-controller2":{
- "asdcUser": "user2",
- "asdcConsumerGroup": "consumer2",
- "asdcConsumerId": "consumer2",
- "asdcEnvironmentName": "E2E",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- }
- },
- "mso.properties.reload.time.minutes":2
-}
diff --git a/common/src/test/resources/mso.properties b/common/src/test/resources/mso.properties
deleted file mode 100644
index bb0e4ebf0d..0000000000
--- a/common/src/test/resources/mso.properties
+++ /dev/null
@@ -1,28 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# ECOMP MSO
-# ================================================================================
-# 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=========================================================
-###
-
-mso.properties.reload.time.minutes=2
-ecomp.mso.cloud.1.cloudId=MT
-ecomp.mso.cloud.1.keystoneUrl=http://localhost:5000/v2.0
-ecomp.mso.cloud.1.msoId=John
-ecomp.mso.cloud.1.publicNetId=FD205490A48D48475607C36B9AD902BF
-ecomp.mso.cloud.1.test=1234
-ecomp.mso.cloud.1.boolean=true
-ecomp.mso.cloud.1.enum=enum1
diff --git a/common/src/test/resources/mso2.json b/common/src/test/resources/mso2.json
deleted file mode 100644
index bac30c495c..0000000000
--- a/common/src/test/resources/mso2.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "asdc-connections": {
- "asdc-controller1": {
- "asdcUser": "user1B",
- "asdcConsumerGroup": "consumer1",
- "asdcConsumerId": "consumer1",
- "asdcEnvironmentName": "PROD",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- },
- "asdc-controller2": {
- "asdcUser": "user2B",
- "asdcConsumerGroup": "consumer2",
- "asdcConsumerId": "consumer2",
- "asdcEnvironmentName": "E2E",
- "asdcAddress": "localhost:8443",
- "asdcPassword": "1c551b8b5ab91fcd5a0907b11c304199"
- }
- }
-} \ No newline at end of file
diff --git a/common/src/test/resources/mso2.properties b/common/src/test/resources/mso2.properties
deleted file mode 100644
index 423346e953..0000000000
--- a/common/src/test/resources/mso2.properties
+++ /dev/null
@@ -1,22 +0,0 @@
-###
-# ============LICENSE_START=======================================================
-# ECOMP MSO
-# ================================================================================
-# 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=========================================================
-###
-
-mso.properties.reload.time.minutes=1
-ecomp.mso.cloud.1.cloudId=MT2