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/appc/orchestrator/service/beans/ApplicationControllerTaskRequest.java104
-rw-r--r--common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVm.java30
-rw-r--r--common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVnf.java49
-rw-r--r--common/src/main/java/org/onap/so/client/BaseClient.java6
-rw-r--r--common/src/main/java/org/onap/so/client/HttpClient.java8
-rw-r--r--common/src/main/java/org/onap/so/client/HttpClientFactory.java8
-rw-r--r--common/src/main/java/org/onap/so/client/RestClient.java20
-rw-r--r--common/src/main/java/org/onap/so/client/RestTemplateConfig.java9
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java4
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIRestClient.java6
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIVersion.java2
-rw-r--r--common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java6
-rw-r--r--common/src/main/java/org/onap/so/client/adapter/rest/AdapterRestClient.java6
-rw-r--r--common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java9
-rw-r--r--common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java16
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java5
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java14
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java23
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/__.java2
-rw-r--r--common/src/main/java/org/onap/so/client/graphinventory/entities/uri/SimpleUri.java7
-rw-r--r--common/src/main/java/org/onap/so/client/grm/GRMRestClient.java6
-rw-r--r--common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java6
-rw-r--r--common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java2
-rw-r--r--common/src/main/java/org/onap/so/db/connections/ScheduledDnsLookup.java16
-rw-r--r--common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java56
-rw-r--r--common/src/main/java/org/onap/so/listener/ListenerRunner.java56
-rw-r--r--common/src/main/java/org/onap/so/listener/Skip.java (renamed from common/src/main/java/org/onap/so/utils/TargetEntities.java)14
-rw-r--r--common/src/main/java/org/onap/so/logger/ErrorCode.java2
-rw-r--r--common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java8
-rw-r--r--common/src/main/java/org/onap/so/logger/LogConstants.java2
-rw-r--r--common/src/main/java/org/onap/so/logger/MdcConstants.java10
-rw-r--r--common/src/main/java/org/onap/so/logger/ScheduledTasksMDCSetup.java75
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java136
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java173
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java111
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java158
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java34
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java61
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java67
-rw-r--r--common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java156
-rw-r--r--common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java132
-rw-r--r--common/src/main/java/org/onap/so/rest/exceptions/HttpResouceNotFoundException.java31
-rw-r--r--common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java16
-rw-r--r--common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java18
-rw-r--r--common/src/main/java/org/onap/so/security/SecurityFilters.java (renamed from common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java)36
-rw-r--r--common/src/main/java/org/onap/so/security/SoBasicWebSecurityConfigurerAdapter.java68
-rw-r--r--common/src/main/java/org/onap/so/security/SoCadiFilter.java118
-rw-r--r--common/src/main/java/org/onap/so/security/SoNoAuthWebSecurityConfigurerAdapter.java45
-rw-r--r--common/src/main/java/org/onap/so/security/SoUserCredentialConfiguration.java (renamed from common/src/main/java/org/onap/so/security/WebSecurityConfig.java)34
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java114
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java11
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java13
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java13
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java12
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java3
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java11
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java13
-rw-r--r--common/src/main/java/org/onap/so/utils/Components.java23
-rw-r--r--common/src/main/java/org/onap/so/utils/CryptoUtils.java6
-rw-r--r--common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java46
-rw-r--r--common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java36
-rw-r--r--common/src/main/java/org/onap/so/utils/TargetEntity.java59
-rw-r--r--common/src/test/java/org/onap/so/BeansTest.java1
-rw-r--r--common/src/test/java/org/onap/so/client/HttpClientTest.java8
-rw-r--r--common/src/test/java/org/onap/so/client/RestClientTest.java4
-rw-r--r--common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java16
-rw-r--r--common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java37
-rw-r--r--common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java6
-rw-r--r--common/src/test/java/org/onap/so/client/dmaap/rest/DMaaPRestClientTest.java97
-rw-r--r--common/src/test/java/org/onap/so/client/policy/PolicyClientImplTest.java118
-rw-r--r--common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java93
-rw-r--r--common/src/test/java/org/onap/so/logger/ScheduledTasksMDCSetupTest.java83
-rw-r--r--common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java5
-rw-r--r--common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java65
74 files changed, 1761 insertions, 1113 deletions
diff --git a/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerTaskRequest.java b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerTaskRequest.java
new file mode 100644
index 0000000000..3811b52551
--- /dev/null
+++ b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerTaskRequest.java
@@ -0,0 +1,104 @@
+package org.onap.so.appc.orchestrator.service.beans;
+
+import java.io.Serializable;
+import org.onap.appc.client.lcm.model.Action;
+import org.onap.so.appc.orchestrator.service.beans.ApplicationControllerVnf;
+
+public class ApplicationControllerTaskRequest implements Serializable {
+
+ private static final long serialVersionUID = -3150320542857627682L;
+
+ private Action action;
+ private String controllerType;
+ private String identityUrl;
+ private String operationsTimeout;
+ private String bookName;
+ private String nodeList;
+ private String fileParameters;
+ private String existingSoftwareVersion;
+ private String newSoftwareVersion;
+ private ApplicationControllerVnf applicationControllerVnf;
+
+ public Action getAction() {
+ return action;
+ }
+
+ public void setAction(Action action) {
+ this.action = action;
+ }
+
+ public String getControllerType() {
+ return controllerType;
+ }
+
+ public void setControllerType(String controllerType) {
+ this.controllerType = controllerType;
+ }
+
+ public ApplicationControllerVnf getApplicationControllerVnf() {
+ return applicationControllerVnf;
+ }
+
+ public void setApplicationControllerVnf(ApplicationControllerVnf applicationControllerVnf) {
+ this.applicationControllerVnf = applicationControllerVnf;
+ }
+
+ public String getIdentityUrl() {
+ return identityUrl;
+ }
+
+ public void setIdentityUrl(String identityUrl) {
+ this.identityUrl = identityUrl;
+ }
+
+ public String getOperationsTimeout() {
+ return operationsTimeout;
+ }
+
+ public void setOperationsTimeout(String operationsTimeout) {
+ this.operationsTimeout = operationsTimeout;
+ }
+
+ public String getBookName() {
+ return bookName;
+ }
+
+ public void setBookName(String bookName) {
+ this.bookName = bookName;
+ }
+
+ public String getNodeList() {
+ return nodeList;
+ }
+
+ public void setNodeList(String nodeList) {
+ this.nodeList = nodeList;
+ }
+
+ public String getFileParameters() {
+ return fileParameters;
+ }
+
+ public void setFileParameters(String fileParameters) {
+ this.fileParameters = fileParameters;
+ }
+
+ public String getExistingSoftwareVersion() {
+ return existingSoftwareVersion;
+ }
+
+ public void setExistingSoftwareVersion(String existingSoftwareVersion) {
+ this.existingSoftwareVersion = existingSoftwareVersion;
+ }
+
+ public String getNewSoftwareVersion() {
+ return newSoftwareVersion;
+ }
+
+ public void setNewSoftwareVersion(String newSoftwareVersion) {
+ this.newSoftwareVersion = newSoftwareVersion;
+ }
+
+
+
+}
diff --git a/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVm.java b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVm.java
new file mode 100644
index 0000000000..75e2053077
--- /dev/null
+++ b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVm.java
@@ -0,0 +1,30 @@
+package org.onap.so.appc.orchestrator.service.beans;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class ApplicationControllerVm implements Serializable {
+
+ private static final long serialVersionUID = 2786675508024214638L;
+
+ private String vserverId;
+ private String vmId;
+
+ public String getVserverId() {
+ return vserverId;
+ }
+
+ public void setVserverId(String vserverId) {
+ this.vserverId = vserverId;
+ }
+
+ public String getVmId() {
+ return vmId;
+ }
+
+ public void setVmId(String vmId) {
+ this.vmId = vmId;
+ }
+
+
+}
diff --git a/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVnf.java b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVnf.java
new file mode 100644
index 0000000000..526941dc39
--- /dev/null
+++ b/common/src/main/java/org/onap/so/appc/orchestrator/service/beans/ApplicationControllerVnf.java
@@ -0,0 +1,49 @@
+package org.onap.so.appc.orchestrator.service.beans;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class ApplicationControllerVnf implements Serializable {
+
+ private static final long serialVersionUID = 2786675508024214637L;
+
+ private String vnfId;
+ private String vnfName;
+ private String vnfHostIpAddress;
+ private ApplicationControllerVm applicationControllerVm;
+
+ public String getVnfId() {
+ return vnfId;
+ }
+
+ public void setVnfId(String vnfId) {
+ this.vnfId = vnfId;
+ }
+
+ public String getVnfName() {
+ return vnfName;
+ }
+
+ public void setVnfName(String vnfName) {
+ this.vnfName = vnfName;
+ }
+
+ public String getVnfHostIpAddress() {
+ return vnfHostIpAddress;
+ }
+
+ public void setVnfHostIpAddress(String vnfHostIpAddress) {
+ this.vnfHostIpAddress = vnfHostIpAddress;
+ }
+
+ public ApplicationControllerVm getApplicationControllerVm() {
+ return applicationControllerVm;
+ }
+
+ public void setApplicationControllerVm(ApplicationControllerVm applicationControllerVm) {
+ this.applicationControllerVm = applicationControllerVm;
+ }
+
+
+
+}
diff --git a/common/src/main/java/org/onap/so/client/BaseClient.java b/common/src/main/java/org/onap/so/client/BaseClient.java
index d939a33358..24c83cbcab 100644
--- a/common/src/main/java/org/onap/so/client/BaseClient.java
+++ b/common/src/main/java/org/onap/so/client/BaseClient.java
@@ -22,7 +22,8 @@ package org.onap.so.client;
import java.util.ArrayList;
import java.util.List;
-import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
+import org.onap.logging.filter.spring.SpringClientPayloadFilter;
+import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -80,7 +81,8 @@ public class BaseClient<I, O> {
RestTemplate restTemplate = new RestTemplate();
restTemplate
.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
- restTemplate.getInterceptors().add(new SpringClientFilter());
+ restTemplate.getInterceptors().add(new SOSpringClientFilter());
+ restTemplate.getInterceptors().add((new SpringClientPayloadFilter()));
ResponseEntity<O> responseEntity =
restTemplate.exchange(getTargetUrl(), method, requestEntity, typeRef, uriVariables);
return responseEntity.getBody();
diff --git a/common/src/main/java/org/onap/so/client/HttpClient.java b/common/src/main/java/org/onap/so/client/HttpClient.java
index 715ba32831..63a4b1cd65 100644
--- a/common/src/main/java/org/onap/so/client/HttpClient.java
+++ b/common/src/main/java/org/onap/so/client/HttpClient.java
@@ -24,22 +24,22 @@ import java.net.URL;
import java.util.Map;
import java.util.Optional;
import static org.apache.commons.lang3.StringUtils.*;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClient extends RestClient {
protected final Logger log = LoggerFactory.getLogger(HttpClient.class);
- private TargetEntity targetEntity;
+ private ONAPComponents targetEntity;
- HttpClient(URL host, String contentType, TargetEntity targetEntity) {
+ HttpClient(URL host, String contentType, ONAPComponents targetEntity) {
super(host, contentType);
this.targetEntity = targetEntity;
}
@Override
- public TargetEntity getTargetEntity() {
+ public ONAPComponents getTargetEntity() {
return targetEntity;
}
diff --git a/common/src/main/java/org/onap/so/client/HttpClientFactory.java b/common/src/main/java/org/onap/so/client/HttpClientFactory.java
index d02c18ff56..3a8a9ee1bd 100644
--- a/common/src/main/java/org/onap/so/client/HttpClientFactory.java
+++ b/common/src/main/java/org/onap/so/client/HttpClientFactory.java
@@ -21,19 +21,19 @@ package org.onap.so.client;
import java.net.URL;
import javax.ws.rs.core.MediaType;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class HttpClientFactory {
- public HttpClient newJsonClient(URL host, TargetEntity targetEntity) {
+ public HttpClient newJsonClient(URL host, ONAPComponents targetEntity) {
return new HttpClient(host, MediaType.APPLICATION_JSON, targetEntity);
}
- public HttpClient newXmlClient(URL host, TargetEntity targetEntity) {
+ public HttpClient newXmlClient(URL host, ONAPComponents targetEntity) {
return new HttpClient(host, MediaType.APPLICATION_XML, targetEntity);
}
- public HttpClient newTextXmlClient(URL host, TargetEntity targetEntity) {
+ public HttpClient newTextXmlClient(URL host, ONAPComponents targetEntity) {
return new HttpClient(host, MediaType.TEXT_XML, targetEntity);
}
}
diff --git a/common/src/main/java/org/onap/so/client/RestClient.java b/common/src/main/java/org/onap/so/client/RestClient.java
index d3a4d444f7..077ba24c2b 100644
--- a/common/src/main/java/org/onap/so/client/RestClient.java
+++ b/common/src/main/java/org/onap/so/client/RestClient.java
@@ -44,11 +44,12 @@ 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.logging.filter.base.MDCSetup;
+import org.onap.logging.filter.base.ONAPComponentsList;
+import org.onap.logging.filter.base.PayloadLoggingClientFilter;
import org.onap.so.client.policy.CommonObjectMapperProvider;
-import org.onap.so.logging.jaxrs.filter.JaxRsClientLogging;
-import org.onap.so.logging.jaxrs.filter.PayloadLoggingFilter;
+import org.onap.so.logging.jaxrs.filter.SOMetricLogClientFilter;
import org.onap.so.utils.CryptoUtils;
-import org.onap.so.utils.TargetEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
@@ -71,7 +72,8 @@ public abstract class RestClient {
protected String accept;
protected String contentType;
protected String requestId = "";
- protected JaxRsClientLogging jaxRsClientLogging;
+ protected SOMetricLogClientFilter metricLogClientFilter;
+ protected MDCSetup mdcSetup = new MDCSetup();
protected RestProperties props;
protected RestClient(RestProperties props, Optional<URI> path) {
@@ -179,18 +181,18 @@ public abstract class RestClient {
return ClientBuilder.newBuilder().build();
}
- protected abstract TargetEntity getTargetEntity();
+ protected abstract ONAPComponentsList getTargetEntity();
protected void initializeClient(Client client) {
if (this.enableLogging()) {
- client.register(new PayloadLoggingFilter(this.getMaxPayloadSize()));
+ client.register(new PayloadLoggingClientFilter(this.getMaxPayloadSize()));
}
CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider();
client.register(new JacksonJsonProvider(provider.getMapper()));
- jaxRsClientLogging = new JaxRsClientLogging();
- jaxRsClientLogging.setTargetService(getTargetEntity());
- client.register(jaxRsClientLogging);
+ metricLogClientFilter = new SOMetricLogClientFilter();
+ mdcSetup.setTargetEntity(getTargetEntity());
+ client.register(metricLogClientFilter);
if (!path.isPresent()) {
webTarget = client.target(host.toString());
diff --git a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java
index 0633ae74c9..f8587ff776 100644
--- a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java
+++ b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java
@@ -20,8 +20,9 @@
package org.onap.so.client;
+import org.onap.logging.filter.spring.SpringClientPayloadFilter;
import org.onap.so.configuration.rest.HttpComponentsClientConfiguration;
-import org.onap.so.logging.jaxrs.filter.SpringClientFilter;
+import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
@@ -45,7 +46,8 @@ public class RestTemplateConfig {
final RestTemplate restTemplate = new RestTemplate();
restTemplate
.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
- restTemplate.getInterceptors().add(new SpringClientFilter());
+ restTemplate.getInterceptors().add(new SOSpringClientFilter());
+ restTemplate.getInterceptors().add((new SpringClientPayloadFilter()));
return restTemplate;
}
@@ -56,7 +58,8 @@ public class RestTemplateConfig {
httpComponentsClientConfiguration.httpComponentsClientHttpRequestFactory();
final RestTemplate restTemplate =
new RestTemplate(new BufferingClientHttpRequestFactory(clientHttpRequestFactory));
- restTemplate.getInterceptors().add(new SpringClientFilter());
+ restTemplate.getInterceptors().add(new SOSpringClientFilter());
+ restTemplate.getInterceptors().add((new SpringClientPayloadFilter()));
return restTemplate;
}
}
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java b/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
index 2fe3910486..e255b297ed 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIErrorFormatter.java
@@ -50,6 +50,8 @@ public class AAIErrorFormatter {
}
protected String format(String s, List<String> variables) {
- return String.format(s.replaceAll("%(\\d+)", "%$1\\$s"), variables.toArray());
+ s = s.replaceAll("%(\\d(?!\\d))", "%$1\\$s");
+ s = s.replaceAll("%(\\d{2})", "%%$1");
+ return String.format(s, variables.toArray());
}
}
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 b546aaa23e..610ff728e9 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
@@ -26,7 +26,7 @@ import java.util.Optional;
import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.graphinventory.GraphInventoryPatchConverter;
import org.onap.so.client.graphinventory.GraphInventoryRestClient;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class AAIRestClient extends GraphInventoryRestClient {
@@ -38,8 +38,8 @@ public class AAIRestClient extends GraphInventoryRestClient {
}
@Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.AAI;
+ public ONAPComponents getTargetEntity() {
+ return ONAPComponents.AAI;
}
@Override
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 91030d831a..4f06b787f7 100644
--- a/common/src/main/java/org/onap/so/client/aai/AAIVersion.java
+++ b/common/src/main/java/org/onap/so/client/aai/AAIVersion.java
@@ -23,7 +23,7 @@ package org.onap.so.client.aai;
import org.onap.so.client.graphinventory.GraphInventoryVersion;
public enum AAIVersion implements GraphInventoryVersion {
- V13("v13"), V14("v14"), V15("v15");
+ V13("v13"), V14("v14"), V15("v15"), V16("v16"), V17("v17"), V18("v18"), V19("v19");
public static final 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/uri/AAISimpleUri.java b/common/src/main/java/org/onap/so/client/aai/entities/uri/AAISimpleUri.java
index f2f99050db..1fe9da984f 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
@@ -21,6 +21,7 @@
package org.onap.so.client.aai.entities.uri;
import java.net.URI;
+import java.util.regex.Pattern;
import javax.ws.rs.core.UriBuilder;
import org.onap.so.client.aai.AAIObjectPlurals;
import org.onap.so.client.aai.AAIObjectType;
@@ -138,4 +139,9 @@ public class AAISimpleUri extends SimpleUri implements AAIResourceUri {
public AAISimpleUri format(Format format) {
return (AAISimpleUri) super.format(format);
}
+
+ @Override
+ protected Pattern getPrefixPattern() {
+ return Pattern.compile("/aai/v\\d+");
+ }
}
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 d6c7072c14..88899a7097 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
@@ -29,7 +29,7 @@ import org.onap.so.client.RestClient;
import org.onap.so.client.policy.CommonObjectMapperProvider;
import org.onap.so.client.policy.JettisonStyleMapperProvider;
import org.onap.so.utils.CryptoUtils;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class AdapterRestClient extends RestClient {
@@ -46,8 +46,8 @@ public class AdapterRestClient extends RestClient {
}
@Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.OPENSTACK_ADAPTER;
+ public ONAPComponents getTargetEntity() {
+ return ONAPComponents.OPENSTACK_ADAPTER;
}
@Override
diff --git a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
index 4ca5690188..8ef08057e6 100644
--- a/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
+++ b/common/src/main/java/org/onap/so/client/defaultproperties/DefaultDmaapPropertiesImpl.java
@@ -35,11 +35,12 @@ public class DefaultDmaapPropertiesImpl implements DmaapProperties {
public DefaultDmaapPropertiesImpl() throws IOException {
File initialFile = new File("src/test/resources/dmaap.properties");
- InputStream targetStream = new FileInputStream(initialFile);
Properties properties = new Properties();
- properties.load(targetStream);
- this.properties = new HashMap<>();
- properties.forEach((key, value) -> this.properties.put((String) key, (String) value));
+ try (InputStream targetStream = new FileInputStream(initialFile)) {
+ properties.load(targetStream);
+ this.properties = new HashMap<>();
+ properties.forEach((key, value) -> this.properties.put((String) key, (String) value));
+ }
}
@Override
diff --git a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
index 68b4e84448..e0c8d4ba80 100644
--- a/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
+++ b/common/src/main/java/org/onap/so/client/dmaap/rest/DMaaPRestClient.java
@@ -22,11 +22,15 @@ package org.onap.so.client.dmaap.rest;
import java.net.URL;
import java.util.Map;
+import java.util.UUID;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.onap.so.client.RestClient;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.slf4j.MDC;
public class DMaaPRestClient extends RestClient {
+ private static final String SO = "SO";
private final String auth;
private final String key;
@@ -37,8 +41,8 @@ public class DMaaPRestClient extends RestClient {
}
@Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.DMAAP;
+ public ONAPComponents getTargetEntity() {
+ return ONAPComponents.DMAAP;
}
@Override
@@ -46,6 +50,10 @@ public class DMaaPRestClient extends RestClient {
if (auth != null && !auth.isEmpty() && key != null && !key.isEmpty()) {
addBasicAuthHeader(auth, key);
}
+ String onapRequestId = UUID.randomUUID().toString();
+ headerMap.put(ONAPLogConstants.Headers.REQUEST_ID, onapRequestId);
+ if (MDC.get(ONAPLogConstants.MDCs.REQUEST_ID) != null) {
+ headerMap.put(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ }
}
-
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
index 434c65da46..babfa14d71 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/GraphInventoryRestClient.java
@@ -28,7 +28,8 @@ import org.onap.so.client.ResponseExceptionMapper;
import org.onap.so.client.RestClientSSL;
import org.onap.so.client.RestProperties;
import org.onap.so.client.policy.CommonObjectMapperProvider;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.onap.logging.filter.base.ONAPComponentsList;
public abstract class GraphInventoryRestClient extends RestClientSSL {
@@ -42,7 +43,7 @@ public abstract class GraphInventoryRestClient extends RestClientSSL {
}
@Override
- public abstract TargetEntity getTargetEntity();
+ public abstract ONAPComponentsList getTargetEntity();
@Override
protected abstract void initializeHeaderMap(Map<String, String> headerMap);
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
index f7f5d78604..e301edb0fd 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLNodeKey.java
@@ -32,9 +32,9 @@ public class DSLNodeKey implements QueryStep {
private boolean not = false;
private final StringBuilder query = new StringBuilder();
private final String keyName;
- private final List<String> values;
+ private final List<Object> values;
- public DSLNodeKey(String keyName, String... value) {
+ public DSLNodeKey(String keyName, Object... value) {
this.keyName = keyName;
this.values = Arrays.asList(value);
@@ -54,14 +54,18 @@ public class DSLNodeKey implements QueryStep {
result.append(" !");
}
result.append("('").append(keyName).append("', ");
- List<String> temp = new ArrayList<>();
- for (String item : values) {
+ List<Object> temp = new ArrayList<>();
+ for (Object item : values) {
if ("null".equals(item)) {
temp.add(String.format("' %s '", item));
} else if ("".equals(item)) {
temp.add("' '");
} else {
- temp.add(String.format("'%s'", item));
+ if (item instanceof String) {
+ temp.add(String.format("'%s'", item));
+ } else {
+ temp.add(item);
+ }
}
}
result.append(Joiner.on(", ").join(temp)).append(")");
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
index ffbb86f023..540472a88d 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/DSLQueryBuilder.java
@@ -20,12 +20,15 @@
package org.onap.so.client.graphinventory.entities;
+import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.onap.so.client.aai.entities.QueryStep;
import org.onap.so.client.graphinventory.GraphInventoryObjectName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
@@ -33,6 +36,7 @@ public class DSLQueryBuilder<S, E> implements QueryStep {
private List<QueryStep> steps = new ArrayList<>();
private String suffix = "";
+ private static final Logger logger = LoggerFactory.getLogger(DSLQueryBuilder.class);
public DSLQueryBuilder() {
@@ -49,8 +53,25 @@ public class DSLQueryBuilder<S, E> implements QueryStep {
}
public DSLQueryBuilder<S, E> output() {
- if (steps.get(steps.size() - 1) instanceof DSLNode) {
+ Object obj = steps.get(steps.size() - 1);
+ if (obj instanceof DSLNode) {
((DSLNode) steps.get(steps.size() - 1)).output();
+ } else if (obj.getClass().getName().contains("$$Lambda$")) {
+ // process lambda expressions
+ for (Field f : obj.getClass().getDeclaredFields()) {
+ f.setAccessible(true);
+ Object o;
+ try {
+ o = f.get(obj);
+ if (o instanceof DSLQueryBuilder && ((DSLQueryBuilder) o).steps.get(0) instanceof DSLNode) {
+ ((DSLNode) ((DSLQueryBuilder) o).steps.get(0)).output();
+ }
+ } catch (IllegalArgumentException | IllegalAccessException e) {
+ logger.error("Exception occured", e);
+ }
+ f.setAccessible(false);
+ break;
+ }
}
return this;
}
diff --git a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
index 2fdd6574e5..87d4d84cac 100644
--- a/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
+++ b/common/src/main/java/org/onap/so/client/graphinventory/entities/__.java
@@ -45,7 +45,7 @@ public class __ {
return __.<DSLNode>start(new DSLNode(name, key));
}
- public static DSLNodeKey key(String keyName, String... value) {
+ public static DSLNodeKey key(String keyName, Object... value) {
return new DSLNodeKey(keyName, value);
}
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 41ba07ad6c..ffe47c5c51 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
@@ -29,6 +29,7 @@ import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import java.util.regex.Pattern;
import javax.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.onap.so.client.graphinventory.Format;
@@ -61,7 +62,7 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable {
protected SimpleUri(GraphInventoryObjectType type, URI uri) {
this.type = type;
this.pluralType = null;
- this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll("/aai/v\\d+", ""));
+ this.internalURI = UriBuilder.fromPath(uri.getRawPath().replaceAll(getPrefixPattern().toString(), ""));
this.values = new Object[0];
}
@@ -174,6 +175,10 @@ public class SimpleUri implements GraphInventoryResourceUri, Serializable {
return build(this.values);
}
+ protected Pattern getPrefixPattern() {
+ return Pattern.compile("/.*?/v\\d+");
+ }
+
protected URI build(Object... values) {
// This is a workaround because resteasy does not encode URIs correctly
final String[] encoded = new String[values.length];
diff --git a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
index 507f1130b5..147f688ea8 100644
--- a/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
+++ b/common/src/main/java/org/onap/so/client/grm/GRMRestClient.java
@@ -25,7 +25,7 @@ import java.net.URI;
import java.util.Map;
import java.util.Optional;
import org.onap.so.client.RestClient;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class GRMRestClient extends RestClient {
@@ -37,8 +37,8 @@ public class GRMRestClient extends RestClient {
}
@Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.GRM;
+ public ONAPComponents getTargetEntity() {
+ return ONAPComponents.GRM;
}
@Override
diff --git a/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java b/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
index 95bc4282ae..33ece07e3d 100644
--- a/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
+++ b/common/src/main/java/org/onap/so/client/policy/PolicyRestClient.java
@@ -26,7 +26,7 @@ import java.util.Optional;
import javax.ws.rs.core.UriBuilder;
import org.onap.so.client.RestClient;
import org.onap.so.client.policy.entities.PolicyServiceType;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class PolicyRestClient extends RestClient {
@@ -38,8 +38,8 @@ public class PolicyRestClient extends RestClient {
}
@Override
- public TargetEntity getTargetEntity() {
- return TargetEntity.POLICY;
+ public ONAPComponents getTargetEntity() {
+ return ONAPComponents.POLICY;
}
@Override
diff --git a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java
index ccfd2f4de6..641bbb28c7 100644
--- a/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java
+++ b/common/src/main/java/org/onap/so/constants/OrchestrationRequestFormat.java
@@ -21,5 +21,5 @@
package org.onap.so.constants;
public enum OrchestrationRequestFormat {
- DETAIL, STATUSDETAIL
+ DETAIL, STATUSDETAIL, SIMPLE
}
diff --git a/common/src/main/java/org/onap/so/db/connections/ScheduledDnsLookup.java b/common/src/main/java/org/onap/so/db/connections/ScheduledDnsLookup.java
index 14f2f5e9b7..40acac57aa 100644
--- a/common/src/main/java/org/onap/so/db/connections/ScheduledDnsLookup.java
+++ b/common/src/main/java/org/onap/so/db/connections/ScheduledDnsLookup.java
@@ -8,6 +8,11 @@ import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
+import org.jboss.logging.MDC;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.ErrorCode;
+import org.onap.so.logger.ScheduledTasksMDCSetup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -27,16 +32,22 @@ public class ScheduledDnsLookup {
@Autowired
private DbDnsIpAddress dnsIpAddress;
+ @Autowired
+ private ScheduledTasksMDCSetup scheduledMDCSetup;
+
private static Logger logger = LoggerFactory.getLogger(ScheduledDnsLookup.class);
@Scheduled(fixedRate = 15000)
public void performDnsLookup() {
-
+ scheduledMDCSetup.mdcSetup(ONAPComponents.SO, "performDnsLookup");
String dnsUrl = System.getenv(DB_HOST);
try {
if (dnsUrl == null) {
+ scheduledMDCSetup.errorMDCSetup(ErrorCode.DataError, "Database DNS is not provided.");
logger.error("Database DNS is not provided. Please verify the configuration");
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.ERROR.toString());
+ scheduledMDCSetup.exitAndClearMDC();
return;
}
@@ -46,6 +57,7 @@ public class ScheduledDnsLookup {
/* This is in initial state */
if (currentIpAddress == null) {
dnsIpAddress.setIpAddress(ipAddress);
+ scheduledMDCSetup.exitAndClearMDC();
return;
}
@@ -57,7 +69,7 @@ public class ScheduledDnsLookup {
} catch (UnknownHostException e) {
logger.warn("Database DNS %s is not resolvable to an IP Address", dnsUrl);
}
-
+ scheduledMDCSetup.exitAndClearMDC();
}
private void softEvictConnectionPool() {
diff --git a/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java b/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java
new file mode 100644
index 0000000000..9f71e61e1f
--- /dev/null
+++ b/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java
@@ -0,0 +1,56 @@
+package org.onap.so.externaltasks.logging;
+
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import org.camunda.bpm.client.task.ExternalTask;
+import org.onap.logging.filter.base.MDCSetup;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.MdcConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+
+@Component
+public class AuditMDCSetup {
+
+ private static final Logger logger = LoggerFactory.getLogger(AuditMDCSetup.class);
+
+ private MDCSetup mdcSetup = new MDCSetup();
+
+ public void setupMDC(ExternalTask externalTask) {
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ String msoRequestId = externalTask.getVariable("mso-request-id");
+ if (msoRequestId != null && !msoRequestId.isEmpty()) {
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId);
+ }
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, externalTask.getTopicName());
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, ONAPComponents.OPENSTACK_ADAPTER.toString());
+ setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+ setElapsedTime();
+ mdcSetup.setServerFQDN();
+ logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
+ }
+
+ public void setElapsedTime() {
+ DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME;
+ MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, Long.toString(System.currentTimeMillis() - ZonedDateTime
+ .parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter).toInstant().toEpochMilli()));
+ }
+
+ public void setResponseCode(String code) {
+ MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, code);
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, code);
+ }
+
+ public void clearClientMDCs() {
+ MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
+ MDC.remove(MdcConstants.OPENSTACK_STATUS_CODE);
+ MDC.remove(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP);
+ MDC.remove(ONAPLogConstants.MDCs.ELAPSED_TIME);
+ MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME);
+ }
+}
diff --git a/common/src/main/java/org/onap/so/listener/ListenerRunner.java b/common/src/main/java/org/onap/so/listener/ListenerRunner.java
new file mode 100644
index 0000000000..a489be6070
--- /dev/null
+++ b/common/src/main/java/org/onap/so/listener/ListenerRunner.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 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.listener;
+
+import java.lang.annotation.Annotation;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+import javax.annotation.Priority;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+
+public abstract class ListenerRunner {
+
+ @Autowired
+ protected ApplicationContext context;
+
+ public <T> List<T> filterListeners(List<T> validators, Predicate<T> predicate) {
+ return validators.stream().filter(item -> {
+ return !item.getClass().isAnnotationPresent(Skip.class) && predicate.test(item);
+ }).sorted(Comparator.comparing(item -> {
+ Priority p = Optional.ofNullable(item.getClass().getAnnotation(Priority.class)).orElse(new Priority() {
+ public int value() {
+ return 1000;
+ }
+
+ @Override
+ public Class<? extends Annotation> annotationType() {
+ return Priority.class;
+ }
+ });
+ return p.value();
+ })).collect(Collectors.toList());
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/utils/TargetEntities.java b/common/src/main/java/org/onap/so/listener/Skip.java
index 94385ec8ea..aa3ec2a204 100644
--- a/common/src/main/java/org/onap/so/utils/TargetEntities.java
+++ b/common/src/main/java/org/onap/so/listener/Skip.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017 - 2019 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.
@@ -18,8 +18,12 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.so.utils;
+package org.onap.so.listener;
-public interface TargetEntities {
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Skip {
}
diff --git a/common/src/main/java/org/onap/so/logger/ErrorCode.java b/common/src/main/java/org/onap/so/logger/ErrorCode.java
index 7fb9522b7c..a57ed99f2b 100644
--- a/common/src/main/java/org/onap/so/logger/ErrorCode.java
+++ b/common/src/main/java/org/onap/so/logger/ErrorCode.java
@@ -25,7 +25,7 @@ public enum ErrorCode {
AvailabilityError(200),
DataError(300),
SchemaError(400),
- BusinessProcesssError(500),
+ BusinessProcessError(500),
UnknownError(900);
private int value;
diff --git a/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java b/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java
index 83b860ff01..2010bc1988 100644
--- a/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java
+++ b/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java
@@ -21,13 +21,5 @@
package org.onap.so.logger;
public class HttpHeadersConstants {
- 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";
public static final String REQUESTOR_ID = "X-RequestorID";
}
diff --git a/common/src/main/java/org/onap/so/logger/LogConstants.java b/common/src/main/java/org/onap/so/logger/LogConstants.java
index 30915c6171..3dc0c062c6 100644
--- a/common/src/main/java/org/onap/so/logger/LogConstants.java
+++ b/common/src/main/java/org/onap/so/logger/LogConstants.java
@@ -21,8 +21,6 @@
package org.onap.so.logger;
public class LogConstants {
- public static final String TARGET_ENTITY_HEADER = "X-Target-Entity";
- public static final String UNKNOWN_TARGET_ENTITY = "Unknown-Target-Entity";
public static final String HTTP_URL = "Http-Url";
public static final String URI_BASE = "Uri-Base";
}
diff --git a/common/src/main/java/org/onap/so/logger/MdcConstants.java b/common/src/main/java/org/onap/so/logger/MdcConstants.java
index 33fceb2f0f..4c6672e59f 100644
--- a/common/src/main/java/org/onap/so/logger/MdcConstants.java
+++ b/common/src/main/java/org/onap/so/logger/MdcConstants.java
@@ -21,14 +21,6 @@
package org.onap.so.logger;
public class MdcConstants {
- public static final String INVOCATION_ID = "InvocationID";
- public static final String RESPONSECODE = "ResponseCode";
- public static final String RESPONSEDESC = "ResponseDesc";
- public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID";
- public static final String CLIENT_ID = "X-ClientID";
- public static final String PARTNERNAME = "PartnerName";
- public static final String SERVICE_NAME = "ServiceName";
- public static final String STATUSCODE = "StatusCode";
- public static final String ENDTIME = "EndTimestamp";
public static final String ORIGINAL_PARTNER_NAME = "OriginalPartnerName";
+ public static final String OPENSTACK_STATUS_CODE = "OpenstackStatusCode";
}
diff --git a/common/src/main/java/org/onap/so/logger/ScheduledTasksMDCSetup.java b/common/src/main/java/org/onap/so/logger/ScheduledTasksMDCSetup.java
new file mode 100644
index 0000000000..41c4b4bfae
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logger/ScheduledTasksMDCSetup.java
@@ -0,0 +1,75 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.logger;
+
+import java.util.UUID;
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.filter.base.MDCSetup;
+import org.onap.logging.filter.base.ONAPComponentsList;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ScheduledTasksMDCSetup extends MDCSetup {
+
+ public void mdcSetup(ONAPComponentsList targetEntity, String serviceName) {
+ try {
+ setEntryTimeStamp();
+ setServerFQDN();
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, UUID.randomUUID().toString());
+ MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, targetEntity.toString());
+ MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, Constants.DefaultValues.UNKNOWN);
+ MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName);
+ setLogTimestamp();
+ setElapsedTime();
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, getProperty(Constants.Property.PARTNER_NAME));
+ logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
+ } catch (Exception e) {
+ logger.warn("Error in ScheduledTasksMDCSetup mdcSetup: {}", e.getMessage());
+ }
+ }
+
+ public void errorMDCSetup(ErrorCode errorCode, String errorDescription) {
+ MDC.put(ONAPLogConstants.MDCs.ERROR_CODE, String.valueOf(errorCode.getValue()));
+ MDC.put(ONAPLogConstants.MDCs.ERROR_DESC, errorDescription);
+ }
+
+ public void exitAndClearMDC() {
+ try {
+ setStatusCode();
+ setLogTimestamp();
+ setElapsedTime();
+ logger.info(ONAPLogConstants.Markers.EXIT, "Exiting.");
+ } catch (Exception e) {
+ logger.warn("Error in ScheduledTasksMDCSetup clear MDC: {}", e.getMessage());
+ }
+ MDC.clear();
+ }
+
+ public void setStatusCode() {
+ String currentStatusCode = MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE);
+ if (currentStatusCode == null || !currentStatusCode.equals(ONAPLogConstants.ResponseStatus.ERROR.toString())) {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.COMPLETE.toString());
+ }
+ }
+}
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
deleted file mode 100644
index 5dbf88d346..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsClientLogging.java
+++ /dev/null
@@ -1,136 +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;
-
-
-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.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.core.Context;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.Providers;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-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(ONAPLogConstants.MDCs.TARGET_ENTITY, 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(ONAPLogConstants.MDCs.TARGET_ENTITY, MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY));
- }
-
- 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_STATUS_CODE, statusCode);
- logger.info(ONAPLogConstants.Markers.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);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
- MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
- MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);
- }
-
-}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
deleted file mode 100644
index 7e2b603ba6..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/JaxRsFilterLogging.java
+++ /dev/null
@@ -1,173 +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;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Type;
-import java.util.UUID;
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ContainerResponseFilter;
-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.Provider;
-import javax.ws.rs.ext.Providers;
-import org.onap.logging.ref.slf4j.ONAPLogConstants;
-import org.onap.so.logger.HttpHeadersConstants;
-import org.onap.so.logger.LogConstants;
-import org.onap.so.logger.MdcConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Priority(1)
-@Provider
-@Component
-public class JaxRsFilterLogging implements ContainerRequestFilter, ContainerResponseFilter {
-
- protected static Logger logger = LoggerFactory.getLogger(JaxRsFilterLogging.class);
-
- @Context
- private HttpServletRequest httpServletRequest;
-
- @Context
- private Providers providers;
-
- @Autowired
- private MDCSetup mdcSetup;
-
- @Override
- public void filter(ContainerRequestContext containerRequest) {
- try {
- MultivaluedMap<String, String> headers = containerRequest.getHeaders();
- 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(HttpHeadersConstants.REQUESTOR_ID, headers.getFirst("X-RequestorID"));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
- MDC.put(LogConstants.URI_BASE, containerRequest.getUriInfo().getBaseUri().toString());
- MDC.put(MdcConstants.ORIGINAL_PARTNER_NAME, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
- logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
- } catch (Exception e) {
- logger.warn("Error in incoming JAX-RS Inteceptor", e);
- }
- }
-
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
- throws IOException {
- try {
- 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 = "";
- if (responseContext.hasEntity()) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- Class<?> entityClass = responseContext.getEntityClass();
- Type entityType = responseContext.getEntityType();
- Annotation[] entityAnnotations = responseContext.getEntityAnnotations();
- MediaType mediaType = responseContext.getMediaType();
- @SuppressWarnings("unchecked")
- MessageBodyWriter<Object> bodyWriter = (MessageBodyWriter<Object>) providers
- .getMessageBodyWriter(entityClass, entityType, entityAnnotations, mediaType);
- bodyWriter.writeTo(responseContext.getEntity(), entityClass, entityType, entityAnnotations, mediaType,
- responseContext.getHeaders(), baos);
- message = message.concat(new String(baos.toByteArray()));
- }
- 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());
- }
-
- 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);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
- MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
- }
-
-}
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
deleted file mode 100644
index 607f067ec4..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCSetup.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*-
- * ============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/logging/jaxrs/filter/PayloadLoggingFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
deleted file mode 100644
index 21c0b52a91..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/PayloadLoggingFilter.java
+++ /dev/null
@@ -1,158 +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;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import javax.annotation.Priority;
-import javax.ws.rs.WebApplicationException;
-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.ext.Provider;
-import javax.ws.rs.ext.WriterInterceptor;
-import javax.ws.rs.ext.WriterInterceptorContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-@Provider
-@Priority(1)
-public class PayloadLoggingFilter implements ClientRequestFilter, ClientResponseFilter, WriterInterceptor {
-
- 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 PayloadLoggingFilter() {
- maxEntitySize = 1024 * 1024;
- }
-
- public PayloadLoggingFilter(int maxPayloadSize) {
- this.maxEntitySize = Integer.min(maxPayloadSize, 1024 * 1024);
- }
-
- private void log(StringBuilder sb) {
- logger.debug(sb.toString());
- }
-
- protected InputStream logInboundEntity(final StringBuilder b, InputStream stream, final Charset charset)
- throws IOException {
- if (!stream.markSupported()) {
- stream = new BufferedInputStream(stream);
- }
- stream.mark(maxEntitySize + 1);
- final byte[] entity = new byte[maxEntitySize + 1];
- final int entitySize = stream.read(entity);
- if (entitySize != -1) {
- b.append(new String(entity, 0, Math.min(entitySize, maxEntitySize), charset));
- }
- if (entitySize > maxEntitySize) {
- b.append("...more...");
- }
- b.append('\n');
- stream.reset();
- return stream;
- }
-
- @Override
- public void filter(ClientRequestContext requestContext) throws IOException {
- if (requestContext.hasEntity()) {
- final OutputStream stream = new LoggingStream(requestContext.getEntityStream());
- requestContext.setEntityStream(stream);
- requestContext.setProperty(ENTITY_STREAM_PROPERTY, stream);
- }
- String method = formatMethod(requestContext);
- log(new StringBuilder("Making " + method + " request to: " + requestContext.getUri() + "\nRequest Headers: "
- + requestContext.getHeaders().toString()));
-
- }
-
- @Override
- public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
- final StringBuilder sb = new StringBuilder();
- if (responseContext.hasEntity()) {
- responseContext.setEntityStream(logInboundEntity(sb, responseContext.getEntityStream(), DEFAULT_CHARSET));
- String method = formatMethod(requestContext);
- log(sb.insert(0, "Response from " + method + ": " + requestContext.getUri() + "\nResponse Headers: "
- + responseContext.getHeaders().toString()));
- }
- }
-
- @Override
- public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
- final LoggingStream stream = (LoggingStream) context.getProperty(ENTITY_STREAM_PROPERTY);
- context.proceed();
- if (stream != null) {
- log(stream.getStringBuilder(DEFAULT_CHARSET));
- }
- }
-
- private class LoggingStream extends FilterOutputStream {
-
- private final StringBuilder sb = new StringBuilder();
- private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- LoggingStream(OutputStream out) {
- super(out);
- }
-
- StringBuilder getStringBuilder(Charset charset) {
- // write entity to the builder
- final byte[] entity = baos.toByteArray();
-
- sb.append(new String(entity, 0, entity.length, charset));
- if (entity.length > maxEntitySize) {
- sb.append("...more...");
- }
- sb.append('\n');
-
- return sb;
- }
-
- @Override
- public void write(final int i) throws IOException {
- if (baos.size() <= maxEntitySize) {
- baos.write(i);
- }
- out.write(i);
- }
- }
-
- private String formatMethod(ClientRequestContext requestContext) {
- String method = requestContext.getHeaderString("X-HTTP-Method-Override");
- if (method == null) {
- method = requestContext.getMethod();
- } else {
- method = requestContext.getMethod() + " (overridden to " + method + ")";
- }
-
- return method;
- }
-}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java
new file mode 100644
index 0000000000..5ae1082464
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOAuditLogContainerFilter.java
@@ -0,0 +1,34 @@
+package org.onap.so.logging.jaxrs.filter;
+
+import javax.annotation.Priority;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.HttpHeadersConstants;
+import org.onap.so.logger.LogConstants;
+import org.slf4j.MDC;
+import org.springframework.stereotype.Component;
+import org.onap.logging.filter.base.AuditLogContainerFilter;
+
+@Priority(1)
+@Component
+public class SOAuditLogContainerFilter extends AuditLogContainerFilter {
+
+ private static final String ORIGINAL_PARTNER_NAME = "OriginalPartnerName";
+
+ @Override
+ protected void additionalPreHandling(ContainerRequestContext request) {
+ request.setProperty("requestId", MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ MDC.put(ORIGINAL_PARTNER_NAME, MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ String requestorId = request.getHeaders().getFirst("X-RequestorID");
+ if (requestorId != null) {
+ MDC.put(HttpHeadersConstants.REQUESTOR_ID, requestorId);
+ }
+ MDC.put(LogConstants.URI_BASE, request.getUriInfo().getBaseUri().toString());
+ }
+
+ @Override
+ protected void additionalPostHandling(ContainerResponseContext response) {
+ // override to add additional post handling
+ }
+}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java
new file mode 100644
index 0000000000..3b6b5216e0
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOMetricLogClientFilter.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 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 javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientResponseContext;
+import org.onap.logging.filter.base.MetricLogClientFilter;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.MdcConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.slf4j.Marker;
+import org.slf4j.MarkerFactory;
+
+
+public class SOMetricLogClientFilter extends MetricLogClientFilter {
+
+ protected static Logger logger = LoggerFactory.getLogger(SOMetricLogClientFilter.class);
+ private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
+ try {
+ setLogTimestamp();
+ setElapsedTimeInvokeTimestamp();
+ setResponseStatusCode(responseContext.getStatus());
+ setResponseDescription(responseContext.getStatus());
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(responseContext.getStatus()));
+ logger.info(INVOKE_RETURN, "InvokeReturn");
+ clearClientMDCs();
+ setOpenStackResponseCode();
+ } catch (Exception e) {
+ logger.warn("Error in JAX-RS request,response client filter", e);
+ }
+ }
+
+ protected void setOpenStackResponseCode() {
+ if (MDC.get(MdcConstants.OPENSTACK_STATUS_CODE) != null) {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, MDC.get(MdcConstants.OPENSTACK_STATUS_CODE));
+ }
+ }
+}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java
new file mode 100644
index 0000000000..cf826d6350
--- /dev/null
+++ b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SOSpringClientFilter.java
@@ -0,0 +1,67 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 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.io.IOException;
+import org.onap.logging.filter.spring.SpringClientFilter;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.MdcConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.slf4j.Marker;
+import org.slf4j.MarkerFactory;
+import org.springframework.http.HttpRequest;
+import org.springframework.http.client.ClientHttpRequestInterceptor;
+import org.springframework.http.client.ClientHttpResponse;
+import org.springframework.stereotype.Component;
+
+@Component
+public class SOSpringClientFilter extends SpringClientFilter implements ClientHttpRequestInterceptor {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass());
+ private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
+
+ @Override
+ protected void post(HttpRequest request, ClientHttpResponse response) {
+ setLogTimestamp();
+ setElapsedTimeInvokeTimestamp();
+ try {
+ setResponseStatusCode(response.getRawStatusCode());
+ int statusCode = response.getRawStatusCode();
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(statusCode));
+ setResponseDescription(statusCode);
+ } catch (IOException e) {
+ logger.error("Unable to get statusCode from response", e);
+ }
+
+
+ logger.info(INVOKE_RETURN, "InvokeReturn");
+ clearClientMDCs();
+ setOpenStackResponseCode();
+ }
+
+ protected void setOpenStackResponseCode() {
+ if (MDC.get(MdcConstants.OPENSTACK_STATUS_CODE) != null) {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, MDC.get(MdcConstants.OPENSTACK_STATUS_CODE));
+ }
+ }
+}
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java b/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
deleted file mode 100644
index c763dd4374..0000000000
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/SpringClientFilter.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*-
- * ============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 org.onap.logging.ref.slf4j.ONAPLogConstants;
-import org.onap.so.logger.LogConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.slf4j.MDC;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpRequest;
-import org.springframework.http.client.ClientHttpRequestExecution;
-import org.springframework.http.client.ClientHttpRequestInterceptor;
-import org.springframework.http.client.ClientHttpResponse;
-import org.springframework.util.StreamUtils;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.List;
-import java.util.UUID;
-import javax.ws.rs.core.Response;
-
-public class SpringClientFilter implements ClientHttpRequestInterceptor {
-
- private final Logger log = LoggerFactory.getLogger(this.getClass());
-
- private static final String TRACE = "trace-#";
- private static final String SO = "SO";
-
- @Override
- public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
- throws IOException {
- processRequest(request, body);
- ClientHttpResponse response = execution.execute(request, body);
- processResponse(response);
- return response;
- }
-
- private void processRequest(HttpRequest request, byte[] body) throws IOException {
- setInvocationId();
- setupHeaders(request);
- setupMDC(request);
- if (log.isDebugEnabled()) {
- log.debug("===========================request begin================================================");
- log.debug("URI : {}", request.getURI());
- log.debug("Method : {}", request.getMethod());
- log.debug("Headers : {}", request.getHeaders());
- log.debug("Request body: {}", new String(body, "UTF-8"));
- log.debug("==========================request end================================================");
- }
- }
-
- private void setupHeaders(HttpRequest clientRequest) {
- HttpHeaders 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 String extractRequestID(HttpRequest clientRequest) {
- String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- if (requestId == null || requestId.isEmpty() || requestId.equals(TRACE)) {
- requestId = UUID.randomUUID().toString();
- log.warn("Could not Find Request ID Generating New One: {}", clientRequest.getURI());
- }
- return requestId;
- }
-
- private void setupMDC(HttpRequest 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());
- MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, extractTargetEntity(clientRequest));
- }
-
- private String extractTargetEntity(HttpRequest clientRequest) {
- HttpHeaders headers = clientRequest.getHeaders();
- String headerTargetEntity = null;
- List<String> headerTargetEntityList = headers.get(LogConstants.TARGET_ENTITY_HEADER);
- if (headerTargetEntityList != null && !headerTargetEntityList.isEmpty())
- headerTargetEntity = headerTargetEntityList.get(0);
- String targetEntity = MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY);
- if (targetEntity != null && !targetEntity.isEmpty()) {
- return targetEntity;
- } else if (headerTargetEntity != null && !headerTargetEntity.isEmpty()) {
- targetEntity = headerTargetEntity;
- } else {
- targetEntity = LogConstants.UNKNOWN_TARGET_ENTITY;
- log.warn("Could not Target Entity: {}", clientRequest.getURI());
- }
- return targetEntity;
- }
-
- 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);
- }
-
-
- private void processResponse(ClientHttpResponse response) throws IOException {
- if (log.isDebugEnabled()) {
- log.debug("============================response begin==========================================");
- log.debug("Status code : {}", response.getStatusCode());
- log.debug("Status text : {}", response.getStatusText());
- log.debug("Headers : {}", response.getHeaders());
- log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
- log.debug("=======================response end=================================================");
- }
- String statusCode;
- if (Response.Status.Family.familyOf(response.getRawStatusCode()).equals(Response.Status.Family.SUCCESSFUL)) {
- statusCode = ONAPLogConstants.ResponseStatus.COMPLETED.toString();
- } else {
- statusCode = ONAPLogConstants.ResponseStatus.ERROR.toString();
- }
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, String.valueOf(response.getRawStatusCode()));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, "");
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, statusCode);
- log.info(ONAPLogConstants.Markers.INVOKE_RETURN, "InvokeReturn");
- clearClientMDCs();
- }
-
- 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);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
- MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
- MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP);
- }
-}
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
deleted file mode 100644
index fa5a5d5da4..0000000000
--- a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*-
- * ============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
- private MDCSetup mdcSetup;
-
- @Context
- private Providers providers;
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
-
- Map<String, String> headers = Collections.list((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, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
- logger.info(ONAPLogConstants.Markers.ENTRY, "Entering");
- if (logger.isDebugEnabled())
- logRequestInformation(request);
- return true;
- }
-
- protected void logRequestInformation(HttpServletRequest request) {
- Map<String, String> headers = Collections.list((request).getHeaderNames()).stream()
- .collect(Collectors.toMap(h -> h, request::getHeader));
-
- logger.debug("===========================request begin================================================");
- logger.debug("URI : {}", request.getRequestURI());
- logger.debug("Method : {}", request.getMethod());
- logger.debug("Headers : {}", headers);
- logger.debug("==========================request end================================================");
-
- }
-
- @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();
- }
-
- protected 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);
- }
-
- protected void setServiceName(HttpServletRequest request) {
- MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
- }
-
- protected void setRequestId(Map<String, String> headers) {
- String requestId = headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase());
- if (requestId == null || requestId.isEmpty())
- requestId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
- }
-
- protected void setInvocationId(Map<String, String> headers) {
- String invocationId = headers.get(ONAPLogConstants.Headers.INVOCATION_ID.toLowerCase());
- if (invocationId == null || invocationId.isEmpty())
- invocationId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
- }
-
- protected void setMDCPartnerName(Map<String, String> headers) {
- String partnerName = headers.get(ONAPLogConstants.Headers.PARTNER_NAME.toLowerCase());
- if (partnerName == null || partnerName.isEmpty())
- partnerName = "";
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, partnerName);
- }
-
-
-}
diff --git a/common/src/main/java/org/onap/so/rest/exceptions/HttpResouceNotFoundException.java b/common/src/main/java/org/onap/so/rest/exceptions/HttpResouceNotFoundException.java
new file mode 100644
index 0000000000..e7b7b72957
--- /dev/null
+++ b/common/src/main/java/org/onap/so/rest/exceptions/HttpResouceNotFoundException.java
@@ -0,0 +1,31 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2019 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.rest.exceptions;
+
+
+public class HttpResouceNotFoundException extends RuntimeException {
+
+ private static final long serialVersionUID = 9007892558312387355L;
+
+ public HttpResouceNotFoundException(final String message) {
+ super(message);
+ }
+}
diff --git a/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java b/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java
index e8ce00c7e5..5d62d8488a 100644
--- a/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java
+++ b/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java
@@ -26,12 +26,28 @@ package org.onap.so.rest.exceptions;
public class RestProcessingException extends RuntimeException {
private static final long serialVersionUID = 16862313537198441L;
+ private final int statusCode;
public RestProcessingException(final String message) {
super(message);
+ statusCode = 0;
}
public RestProcessingException(final String message, final Throwable cause) {
+ this(message, cause, 0);
+ }
+
+ public RestProcessingException(final String message, final Throwable cause, final int statusCode) {
super(message, cause);
+ this.statusCode = statusCode;
+ }
+
+ /**
+ * Get the status code from the response to the rest request, if available
+ *
+ * @return the status code, or 0 if not available
+ */
+ public int getStatusCode() {
+ return statusCode;
}
}
diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
index a627e82802..b82d73bbbf 100644
--- a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
+++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java
@@ -23,6 +23,7 @@ package org.onap.so.rest.service;
import com.google.common.base.Optional;
import org.onap.so.configuration.rest.BasicHttpHeadersProvider;
import org.onap.so.configuration.rest.HttpHeadersProvider;
+import org.onap.so.rest.exceptions.HttpResouceNotFoundException;
import org.onap.so.rest.exceptions.InvalidRestRequestException;
import org.onap.so.rest.exceptions.RestProcessingException;
import org.slf4j.Logger;
@@ -32,7 +33,7 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
@@ -116,15 +117,18 @@ public class HttpRestServiceProviderImpl implements HttpRestServiceProvider {
try {
return restTemplate.exchange(url, httpMethod, request, clazz);
- } catch (final HttpClientErrorException httpClientErrorException) {
+ } catch (final HttpStatusCodeException httpStatusCodeException) {
final String message = "Unable to invoke HTTP " + httpMethod + " using url: " + url + ", Response: "
- + httpClientErrorException.getRawStatusCode();
- LOGGER.error(message, httpClientErrorException);
- final int rawStatusCode = httpClientErrorException.getRawStatusCode();
- if (rawStatusCode == HttpStatus.BAD_REQUEST.value() || rawStatusCode == HttpStatus.NOT_FOUND.value()) {
+ + httpStatusCodeException.getRawStatusCode();
+ LOGGER.error(message, httpStatusCodeException);
+ final int rawStatusCode = httpStatusCodeException.getRawStatusCode();
+ if (rawStatusCode == HttpStatus.BAD_REQUEST.value()) {
throw new InvalidRestRequestException("No result found for given url: " + url);
+ } else if (rawStatusCode == HttpStatus.NOT_FOUND.value()) {
+ throw new HttpResouceNotFoundException("No result found for given url: " + url);
}
- throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url);
+ throw new RestProcessingException("Unable to invoke HTTP " + httpMethod + " using URL: " + url,
+ httpStatusCodeException, rawStatusCode);
} catch (final RestClientException restClientException) {
LOGGER.error("Unable to invoke HTTP POST using url: {}", url, restClientException);
diff --git a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java b/common/src/main/java/org/onap/so/security/SecurityFilters.java
index e644f9e030..7ad0fd05df 100644
--- a/common/src/main/java/org/onap/so/logging/jaxrs/filter/MDCTaskDecorator.java
+++ b/common/src/main/java/org/onap/so/security/SecurityFilters.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
- * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017 - 2019 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,26 +18,24 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.so.logging.jaxrs.filter;
+package org.onap.so.security;
-import java.util.Map;
-import org.slf4j.MDC;
-import org.springframework.core.task.TaskDecorator;
+import org.springframework.boot.web.servlet.FilterRegistrationBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.Ordered;
-public class MDCTaskDecorator implements TaskDecorator {
+@Configuration
+@Profile("!test & aaf")
+public class SecurityFilters {
- @Override
- public Runnable decorate(Runnable runnable) {
- Map<String, String> contextMap = MDC.getCopyOfContextMap();
- return () -> {
- try {
- if (contextMap != null) {
- MDC.setContextMap(contextMap);
- runnable.run();
- }
- } finally {
- MDC.clear();
- }
- };
+ @Bean
+ public FilterRegistrationBean<SoCadiFilter> loginRegistrationBean() {
+ FilterRegistrationBean<SoCadiFilter> filterRegistrationBean = new FilterRegistrationBean<>();
+ filterRegistrationBean.setFilter(new SoCadiFilter());
+ filterRegistrationBean.setName("cadiFilter");
+ filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
+ return filterRegistrationBean;
}
}
diff --git a/common/src/main/java/org/onap/so/security/SoBasicWebSecurityConfigurerAdapter.java b/common/src/main/java/org/onap/so/security/SoBasicWebSecurityConfigurerAdapter.java
new file mode 100644
index 0000000000..c778dde9af
--- /dev/null
+++ b/common/src/main/java/org/onap/so/security/SoBasicWebSecurityConfigurerAdapter.java
@@ -0,0 +1,68 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.security;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.web.firewall.StrictHttpFirewall;
+import org.springframework.util.StringUtils;
+
+/**
+ * @author Waqas Ikram (waqas.ikram@est.tech)
+ *
+ */
+@EnableWebSecurity
+@Configuration
+@Order(1)
+@Profile({"basic"})
+public class SoBasicWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
+
+ @Autowired
+ private SoUserCredentialConfiguration soUserCredentialConfiguration;
+
+ @Override
+ protected void configure(final HttpSecurity http) throws Exception {
+ http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll()
+ .antMatchers("/**")
+ .hasAnyRole(StringUtils.collectionToDelimitedString(soUserCredentialConfiguration.getRoles(), ","))
+ .and().httpBasic();
+ }
+
+ @Override
+ public void configure(final WebSecurity web) throws Exception {
+ super.configure(web);
+ final StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
+
+ @Override
+ protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
+ auth.userDetailsService(soUserCredentialConfiguration.userDetailsService())
+ .passwordEncoder(soUserCredentialConfiguration.passwordEncoder());
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/security/SoCadiFilter.java b/common/src/main/java/org/onap/so/security/SoCadiFilter.java
new file mode 100644
index 0000000000..2763d6ee15
--- /dev/null
+++ b/common/src/main/java/org/onap/so/security/SoCadiFilter.java
@@ -0,0 +1,118 @@
+/*-
+ * ============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.security;
+
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import org.onap.aaf.cadi.config.Config;
+import org.onap.aaf.cadi.filter.CadiFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Component;
+
+@Component
+@Profile("!test & aaf")
+public class SoCadiFilter extends CadiFilter {
+
+ protected final Logger logger = LoggerFactory.getLogger(SoCadiFilter.class);
+
+ @Value("${mso.config.cadi.cadiLoglevel:#{null}}")
+ private String cadiLoglevel;
+
+ @Value("${mso.config.cadi.cadiKeyFile:#{null}}")
+ private String cadiKeyFile;
+
+ @Value("${mso.config.cadi.cadiTruststorePassword:#{null}}")
+ private String cadiTrustStorePassword;
+
+ @Value("${mso.config.cadi.cadiTrustStore:#{null}}")
+ private String cadiTrustStore;
+
+ @Value("${mso.config.cadi.cadiLatitude:#{null}}")
+ private String cadiLatitude;
+
+ @Value("${mso.config.cadi.cadiLongitude:#{null}}")
+ private String cadiLongitude;
+
+ @Value("${mso.config.cadi.aafEnv:#{null}}")
+ private String aafEnv;
+
+ @Value("${mso.config.cadi.aafApiVersion:#{null}}")
+ private String aafApiVersion;
+
+ @Value("${mso.config.cadi.aafRootNs:#{null}}")
+ private String aafRootNs;
+
+ @Value("${mso.config.cadi.aafId:#{null}}")
+ private String aafMechId;
+
+ @Value("${mso.config.cadi.aafPassword:#{null}}")
+ private String aafMechIdPassword;
+
+ @Value("${mso.config.cadi.aafLocateUrl:#{null}}")
+ private String aafLocateUrl;
+
+ @Value("${mso.config.cadi.aafUrl:#{null}}")
+ private String aafUrl;
+
+ @Value("${mso.config.cadi.apiEnforcement:#{null}}")
+ private String apiEnforcement;
+
+ @Value("${mso.config.cadi.userExpires:#{null}}")
+ private String userExpires;
+
+ private void checkIfNullProperty(String key, String value) {
+ /*
+ * When value is null, it is not defined in application.yaml set nothing in System properties
+ */
+ if (value != null) {
+ System.setProperty(key, value);
+ }
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ checkIfNullProperty(Config.CADI_LOGLEVEL, cadiLoglevel);
+ checkIfNullProperty(Config.CADI_KEYFILE, cadiKeyFile);
+ checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiTrustStore);
+ checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiTrustStorePassword);
+ checkIfNullProperty(Config.CADI_LATITUDE, cadiLatitude);
+ checkIfNullProperty(Config.CADI_LONGITUDE, cadiLongitude);
+ checkIfNullProperty(Config.AAF_ENV, aafEnv);
+ checkIfNullProperty(Config.AAF_API_VERSION, aafApiVersion);
+ checkIfNullProperty(Config.AAF_ROOT_NS, aafRootNs);
+ checkIfNullProperty(Config.AAF_APPID, aafMechId);
+ checkIfNullProperty(Config.AAF_APPPASS, aafMechIdPassword);
+ checkIfNullProperty(Config.AAF_LOCATE_URL, aafLocateUrl);
+ checkIfNullProperty(Config.AAF_URL, aafUrl);
+ checkIfNullProperty(Config.CADI_API_ENFORCEMENT, apiEnforcement);
+ checkIfNullProperty(Config.AAF_USER_EXPIRES, userExpires);
+ // checkIfNullProperty(AFT_ENVIRONMENT_VAR, aftEnv);
+ logger.debug(" *** init Filter Config *** ");
+ super.init(filterConfig);
+ }
+
+
+}
diff --git a/common/src/main/java/org/onap/so/security/SoNoAuthWebSecurityConfigurerAdapter.java b/common/src/main/java/org/onap/so/security/SoNoAuthWebSecurityConfigurerAdapter.java
new file mode 100644
index 0000000000..b3e4842bbd
--- /dev/null
+++ b/common/src/main/java/org/onap/so/security/SoNoAuthWebSecurityConfigurerAdapter.java
@@ -0,0 +1,45 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2020 Nordix Foundation.
+ * ================================================================================
+ * 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.security;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.core.annotation.Order;
+import org.springframework.security.config.annotation.web.builders.WebSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+import org.springframework.security.web.firewall.StrictHttpFirewall;
+
+/**
+ * @author Waqas Ikram (waqas.ikram@est.tech)
+ *
+ */
+@EnableWebSecurity
+@Configuration
+@Order(2)
+@Profile({"aaf", "test"})
+public class SoNoAuthWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
+ @Override
+ public void configure(final WebSecurity web) throws Exception {
+ web.ignoring().antMatchers("/**");
+ final StrictHttpFirewall firewall = new MSOSpringFirewall();
+ web.httpFirewall(firewall);
+ }
+}
diff --git a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java b/common/src/main/java/org/onap/so/security/SoUserCredentialConfiguration.java
index 635784c642..ee680511b9 100644
--- a/common/src/main/java/org/onap/so/security/WebSecurityConfig.java
+++ b/common/src/main/java/org/onap/so/security/SoUserCredentialConfiguration.java
@@ -1,8 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * ONAP - SO
- * ================================================================================
- * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,9 +13,10 @@
* 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
* ============LICENSE_END=========================================================
*/
-
package org.onap.so.security;
import java.util.ArrayList;
@@ -25,17 +24,20 @@ import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.stereotype.Component;
-
+/**
+ * @author Waqas Ikram (waqas.ikram@est.tech)
+ *
+ */
+@Component
@ConfigurationProperties(prefix = "spring.security")
-public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
+public class SoUserCredentialConfiguration {
- private List<UserCredentials> credentials;
- private List<String> roles = new ArrayList<>();
+ private List<UserCredentials> credentials = new ArrayList<>();
+ private final List<String> roles = new ArrayList<>();
public List<String> getRoles() {
return roles;
@@ -52,8 +54,10 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
return credentials;
}
- public void setUsercredentials(List<UserCredentials> usercredentials) {
- this.credentials = usercredentials;
+ public void setUsercredentials(final List<UserCredentials> usercredentials) {
+ if (usercredentials != null) {
+ this.credentials = usercredentials;
+ }
}
@Bean
@@ -65,10 +69,4 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
-
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
- }
-
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java
new file mode 100644
index 0000000000..f601ebc3bd
--- /dev/null
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Pnfs.java
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 Nokia
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.onap.so.serviceinstancebeans;
+
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonRootName;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+@JsonRootName(value = "pnfs")
+@JsonInclude(JsonInclude.Include.NON_DEFAULT)
+public class Pnfs implements Serializable {
+
+ private static final long serialVersionUID = 8081495240474276501L;
+ @JsonProperty("modelInfo")
+ protected ModelInfo modelInfo;
+ @JsonProperty("cloudConfiguration")
+ protected CloudConfiguration cloudConfiguration;
+ @JsonProperty("instanceName")
+ protected String instanceName;
+ @JsonProperty("platform")
+ protected Platform platform;
+ @JsonProperty("lineOfBusiness")
+ protected LineOfBusiness lineOfBusiness;
+ @JsonProperty("productFamilyId")
+ protected String productFamilyId;
+ @JsonProperty("instanceParams")
+ private List<Map<String, String>> instanceParams = new ArrayList<>();
+
+
+ public ModelInfo getModelInfo() {
+ return modelInfo;
+ }
+
+ public void setModelInfo(ModelInfo modelInfo) {
+ this.modelInfo = modelInfo;
+ }
+
+ public CloudConfiguration getCloudConfiguration() {
+ return cloudConfiguration;
+ }
+
+ public void setCloudConfiguration(CloudConfiguration cloudConfiguration) {
+ this.cloudConfiguration = cloudConfiguration;
+ }
+
+ public String getInstanceName() {
+ return instanceName;
+ }
+
+ public void setInstanceName(String instanceName) {
+ this.instanceName = instanceName;
+ }
+
+ public Platform getPlatform() {
+ return platform;
+ }
+
+ public void setPlatform(Platform platform) {
+ this.platform = platform;
+ }
+
+ public LineOfBusiness getLineOfBusiness() {
+ return lineOfBusiness;
+ }
+
+ public void setLineOfBusiness(LineOfBusiness lineOfBusiness) {
+ this.lineOfBusiness = lineOfBusiness;
+ }
+
+ public String getProductFamilyId() {
+ return productFamilyId;
+ }
+
+ public void setProductFamilyId(String productFamilyId) {
+ this.productFamilyId = productFamilyId;
+ }
+
+ public List<Map<String, String>> getInstanceParams() {
+ return instanceParams;
+ }
+
+ public void setInstanceParams(List<Map<String, String>> instanceParams) {
+ this.instanceParams = instanceParams;
+ }
+
+ @Override
+ public String toString() {
+ return "Pnfs [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ + instanceName + ", platform=" + platform + ", " + "lineOfBusiness=" + lineOfBusiness
+ + ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams + "]";
+ }
+
+}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
index 121fd4a1a5..33678b336f 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestError.java
@@ -33,7 +33,12 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.ToStringBuilder;
-import com.fasterxml.jackson.annotation.JsonRootName;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
+import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
+import com.fasterxml.jackson.annotation.JsonTypeName;
/**
@@ -63,7 +68,9 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"policyException", "serviceException"})
@XmlRootElement(name = "requestError")
-@JsonRootName(value = "requestError")
+@JsonTypeName("requestError")
+@JsonTypeInfo(include = As.WRAPPER_OBJECT, use = Id.NAME)
+@JsonInclude(Include.NON_NULL)
public class RequestError {
protected PolicyException policyException;
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
index 61192c3147..250c5df5ce 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestInfo.java
@@ -55,6 +55,8 @@ public class RequestInfo implements Serializable {
protected boolean suppressRollback;
@JsonProperty("requestorId")
protected String requestorId;
+ @JsonProperty("applicationId")
+ protected String applicationId;
/**
* Gets the value of the callbackUrl property.
@@ -201,12 +203,21 @@ public class RequestInfo implements Serializable {
this.requestorId = requestorId;
}
+ public String getApplicationId() {
+ return applicationId;
+ }
+
+ public void setApplicationId(String applicationId) {
+ this.applicationId = applicationId;
+ }
+
@Override
public String toString() {
return "RequestInfo [billingAccountNumber=" + billingAccountNumber + ", callbackUrl=" + callbackUrl
+ ", correlator=" + correlator + ", orderNumber=" + orderNumber + ", productFamilyId=" + productFamilyId
+ ", orderVersion=" + orderVersion + ", source=" + source + ", instanceName=" + instanceName
- + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + "]";
+ + ", suppressRollback=" + suppressRollback + ", requestorId=" + requestorId + ", applicationId="
+ + applicationId + "]";
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
index 9fceed1641..a72229a25c 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestParameters.java
@@ -57,6 +57,9 @@ public class RequestParameters implements Serializable {
@JsonProperty("rebuildVolumeGroups")
private Boolean rebuildVolumeGroups;
+ @JsonProperty("enforceValidNfValues")
+ private Boolean enforceValidNfValues = false;
+
@Override
public String toString() {
return new ToStringBuilder(this).append("subscriptionServiceType", subscriptionServiceType)
@@ -64,7 +67,15 @@ public class RequestParameters implements Serializable {
.append("usePreload", usePreload).append("autoBuildVfModules", autoBuildVfModules)
.append("cascadeDelete", cascadeDelete).append("testApi", testApi)
.append("retainAssignments", retainAssignments).append("rebuildVolumeGroups", rebuildVolumeGroups)
- .toString();
+ .append("enforceValidNfValues", enforceValidNfValues).toString();
+ }
+
+ public Boolean getEnforceValidNfValues() {
+ return enforceValidNfValues;
+ }
+
+ public void setEnforceValidNfValues(Boolean enforceValidNfValues) {
+ this.enforceValidNfValues = enforceValidNfValues;
}
public String getSubscriptionServiceType() {
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
index 2123b2f6fc..acac8c4033 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Resources.java
@@ -5,6 +5,8 @@
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
* ================================================================================
+ * Modifications Copyright (c) 2019 Nokia
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -36,6 +38,8 @@ public class Resources implements Serializable {
private static final long serialVersionUID = 2194797231782624520L;
@JsonProperty("vnfs")
private List<Vnfs> vnfs = new ArrayList<>();
+ @JsonProperty("pnfs")
+ private List<Pnfs> pnfs = new ArrayList<>();
@JsonProperty("networks")
private List<Networks> networks = new ArrayList<>();
@@ -47,6 +51,14 @@ public class Resources implements Serializable {
this.vnfs = vnfs;
}
+ public List<Pnfs> getPnfs() {
+ return pnfs;
+ }
+
+ public void setPnfs(List<Pnfs> pnfs) {
+ this.pnfs = pnfs;
+ }
+
public List<Networks> getNetworks() {
return networks;
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
index f2976136e9..cbbc7f61c1 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceException.java
@@ -31,6 +31,8 @@ package org.onap.so.serviceinstancebeans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonRootName;
@@ -55,6 +57,7 @@ import com.fasterxml.jackson.annotation.JsonRootName;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "serviceException")
@JsonRootName(value = "serviceException")
+@JsonInclude(Include.NON_EMPTY)
public class ServiceException extends ExceptionType {
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
index 1a0e13587e..5bcdcb181b 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/ServiceInstancesRequest.java
@@ -32,6 +32,8 @@ public class ServiceInstancesRequest implements Serializable {
private String serviceInstanceId;
@JsonProperty("vnfInstanceId")
private String vnfInstanceId;
+ @JsonProperty("pnfId")
+ private String pnfId;
@JsonProperty("networkInstanceId")
private String networkInstanceId;
@JsonProperty("volumeGroupInstanceId")
@@ -67,6 +69,14 @@ public class ServiceInstancesRequest implements Serializable {
this.vnfInstanceId = vnfInstanceId;
}
+ public String getPnfId() {
+ return pnfId;
+ }
+
+ public void setPnfId(String pnfId) {
+ this.pnfId = pnfId;
+ }
+
public String getNetworkInstanceId() {
return networkInstanceId;
}
@@ -113,6 +123,7 @@ public class ServiceInstancesRequest implements Serializable {
sb.append("requestDetails=").append(requestDetails);
sb.append(", serviceInstanceId='").append(serviceInstanceId).append('\'');
sb.append(", vnfInstanceId='").append(vnfInstanceId).append('\'');
+ sb.append(", pnfId='").append(pnfId).append('\'');
sb.append(", networkInstanceId='").append(networkInstanceId).append('\'');
sb.append(", volumeGroupInstanceId='").append(volumeGroupInstanceId).append('\'');
sb.append(", vfModuleInstanceId='").append(vfModuleInstanceId).append('\'');
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java b/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
index a2eb35464b..ca67f566b1 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/Vnfs.java
@@ -51,7 +51,8 @@ public class Vnfs implements Serializable {
private List<Map<String, String>> instanceParams = new ArrayList<>();
@JsonProperty("vfModules")
private List<VfModules> vfModules = new ArrayList<>();
-
+ @JsonProperty("applicationId")
+ protected String applicationId;
public ModelInfo getModelInfo() {
return modelInfo;
@@ -117,12 +118,20 @@ public class Vnfs implements Serializable {
this.vfModules = vfModules;
}
+ public String getApplicationId() {
+ return applicationId;
+ }
+
+ public void setApplicationId(String applicationId) {
+ this.applicationId = applicationId;
+ }
+
@Override
public String toString() {
return "Vnfs [modelInfo=" + modelInfo + ", cloudConfiguration=" + cloudConfiguration + ", instanceName="
+ instanceName + ", platform=" + platform + ", " + "lineOfBusiness=" + lineOfBusiness
+ ", productFamilyId=" + productFamilyId + ", instanceParams=" + instanceParams + ", vfModules="
- + vfModules + "]";
+ + vfModules + ", applicaionId=" + applicationId + " ]";
}
}
diff --git a/common/src/main/java/org/onap/so/utils/Components.java b/common/src/main/java/org/onap/so/utils/Components.java
new file mode 100644
index 0000000000..5af8c5aa56
--- /dev/null
+++ b/common/src/main/java/org/onap/so/utils/Components.java
@@ -0,0 +1,23 @@
+package org.onap.so.utils;
+
+import java.util.EnumSet;
+import java.util.Set;
+import org.onap.logging.filter.base.ONAPComponents;
+import org.onap.logging.filter.base.ONAPComponentsList;
+
+public enum Components implements ONAPComponentsList {
+ OPENSTACK, UNKNOWN, ASDC_CONTROLLER, APIH, SDNC_ADAPTER;
+
+
+ public static Set<Components> getSOInternalComponents() {
+ return EnumSet.of(ASDC_CONTROLLER, APIH, SDNC_ADAPTER);
+ }
+
+ @Override
+ public String toString() {
+ if (getSOInternalComponents().contains(this))
+ return ONAPComponents.SO + "." + this.name();
+ else
+ return this.name();
+ }
+}
diff --git a/common/src/main/java/org/onap/so/utils/CryptoUtils.java b/common/src/main/java/org/onap/so/utils/CryptoUtils.java
index 640660e97c..1c38dfb774 100644
--- a/common/src/main/java/org/onap/so/utils/CryptoUtils.java
+++ b/common/src/main/java/org/onap/so/utils/CryptoUtils.java
@@ -76,6 +76,8 @@ public final class CryptoUtils {
* @throws GeneralSecurityException
*/
public static String decrypt(String message, String keyString) throws GeneralSecurityException {
+ if (message.equals(System.getenv("PLAINTEXTPASSWORD")))
+ return message;
SecretKeySpec sks = getSecretKeySpec(keyString);
byte[] cipherText = hexStringToByteArray(message);
Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
@@ -91,7 +93,7 @@ public final class CryptoUtils {
return CryptoUtils.encrypt(message, CLOUD_KEY);
} catch (GeneralSecurityException e) {
logger.error(LoggingAnchor.THREE, MessageEnum.RA_GENERAL_EXCEPTION.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
+ ErrorCode.BusinessProcessError.getValue(), "Exception in encryptPassword ", e);
return null;
}
}
@@ -101,7 +103,7 @@ public final class CryptoUtils {
return CryptoUtils.decrypt(message, CLOUD_KEY);
} catch (GeneralSecurityException e) {
logger.error(LoggingAnchor.THREE, MessageEnum.RA_GENERAL_EXCEPTION.toString(),
- ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e);
+ ErrorCode.BusinessProcessError.getValue(), "Exception in encryptPassword ", e);
return null;
}
}
diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java
new file mode 100644
index 0000000000..e43b431821
--- /dev/null
+++ b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java
@@ -0,0 +1,46 @@
+package org.onap.so.utils;
+
+import java.security.GeneralSecurityException;
+import org.camunda.bpm.client.ExternalTaskClient;
+import org.camunda.bpm.client.interceptor.ClientRequestInterceptor;
+import org.camunda.bpm.client.interceptor.auth.BasicAuthProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ExternalTaskServiceUtils {
+
+ @Autowired
+ public Environment env;
+
+ private static final Logger logger = LoggerFactory.getLogger(ExternalTaskServiceUtils.class);
+
+ public ExternalTaskClient createExternalTaskClient() throws Exception {
+ String auth = getAuth();
+ ClientRequestInterceptor interceptor = createClientInterceptor(auth);
+ return ExternalTaskClient.create().baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1)
+ .addInterceptor(interceptor).asyncResponseTimeout(120000).build();
+ }
+
+ protected ClientRequestInterceptor createClientInterceptor(String auth) {
+ return new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth);
+ }
+
+ protected String getAuth() throws Exception {
+ try {
+ return CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey"));
+ } catch (IllegalStateException | GeneralSecurityException e) {
+ logger.error("Error Decrypting Password", e);
+ throw new Exception("Cannot load password");
+ }
+ }
+
+ public int getMaxClients() {
+ return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "3"));
+ }
+
+
+}
diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java
new file mode 100644
index 0000000000..a2aed638fe
--- /dev/null
+++ b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java
@@ -0,0 +1,36 @@
+package org.onap.so.utils;
+
+import org.camunda.bpm.client.task.ExternalTask;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+import org.springframework.stereotype.Component;
+
+@Component
+public abstract class ExternalTaskUtils {
+
+ @Autowired
+ Environment env;
+
+ private static final Logger logger = LoggerFactory.getLogger(ExternalTaskUtils.class);
+
+ public long calculateRetryDelay(int currentRetries) {
+ int retrySequence = getRetrySequence().length - currentRetries;
+ return Integer.parseInt(getRetrySequence()[retrySequence]) * getRetryMutiplier();
+ }
+
+ protected Long getRetryMutiplier() {
+ return Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000"));
+ }
+
+ protected String[] getRetrySequence() {
+ String[] seq = {"1", "1", "2", "3", "5", "8", "13", "20"};
+ if (env.getProperty("mso.workflow.topics.retrySequence") != null) {
+ seq = env.getProperty("mso.workflow.topics.retrySequence", String[].class);
+ }
+ return seq;
+ }
+}
diff --git a/common/src/main/java/org/onap/so/utils/TargetEntity.java b/common/src/main/java/org/onap/so/utils/TargetEntity.java
deleted file mode 100644
index 3a3ec91d2f..0000000000
--- a/common/src/main/java/org/onap/so/utils/TargetEntity.java
+++ /dev/null
@@ -1,59 +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.utils;
-
-import java.util.EnumSet;
-
-public enum TargetEntity implements TargetEntities {
- OPENSTACK_ADAPTER,
- BPMN,
- GRM,
- AAI,
- DMAAP,
- POLICY,
- CATALOG_DB,
- REQUEST_DB,
- VNF_ADAPTER,
- SDNC_ADAPTER,
- SNIRO,
- SDC,
- EXTERNAL,
- MULTICLOUD,
- OOF,
- SDNC,
- SO,
- UNKNOWN,
- OPENSTACK;
-
- private static final String PREFIX = "SO";
-
- public static EnumSet<TargetEntity> getSOInternalComponents() {
- return EnumSet.of(OPENSTACK_ADAPTER, BPMN, CATALOG_DB, REQUEST_DB, VNF_ADAPTER, SDNC_ADAPTER);
- }
-
- @Override
- public String toString() {
- if (getSOInternalComponents().contains(this))
- return TargetEntity.PREFIX + "." + this.name();
- else
- return this.name();
- }
-}
diff --git a/common/src/test/java/org/onap/so/BeansTest.java b/common/src/test/java/org/onap/so/BeansTest.java
index 8bde3c4eb7..9e8a0184ab 100644
--- a/common/src/test/java/org/onap/so/BeansTest.java
+++ b/common/src/test/java/org/onap/so/BeansTest.java
@@ -60,6 +60,7 @@ public class BeansTest {
@Test
public void pojoStructure() {
+ test("org.onap.so.appc.orchestrator.service.beans");
test("org.onap.so.client.policy.entities");
test("org.onap.so.client.grm.beans");
test("org.onap.so.client.ruby.beans");
diff --git a/common/src/test/java/org/onap/so/client/HttpClientTest.java b/common/src/test/java/org/onap/so/client/HttpClientTest.java
index b12ed5956a..a01e2bb812 100644
--- a/common/src/test/java/org/onap/so/client/HttpClientTest.java
+++ b/common/src/test/java/org/onap/so/client/HttpClientTest.java
@@ -32,7 +32,7 @@ import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Rule;
import org.junit.Test;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
public class HttpClientTest {
@@ -49,7 +49,7 @@ public class HttpClientTest {
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ HttpClient client = httpClientFactory.newJsonClient(url, ONAPComponents.BPMN);
client.addBasicAuthHeader(
"97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF",
@@ -68,7 +68,7 @@ public class HttpClientTest {
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ HttpClient client = httpClientFactory.newJsonClient(url, ONAPComponents.BPMN);
client.addAdditionalHeader("Accept", "application/json");
client.addAdditionalHeader("id", null);
@@ -86,7 +86,7 @@ public class HttpClientTest {
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody("")));
URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
- HttpClient client = httpClientFactory.newJsonClient(url, TargetEntity.BPMN);
+ HttpClient client = httpClientFactory.newJsonClient(url, ONAPComponents.BPMN);
client.addBasicAuthHeader("", "12345");
client.addAdditionalHeader("Accept", "application/json");
diff --git a/common/src/test/java/org/onap/so/client/RestClientTest.java b/common/src/test/java/org/onap/so/client/RestClientTest.java
index 745dee23e8..cd00a9e4de 100644
--- a/common/src/test/java/org/onap/so/client/RestClientTest.java
+++ b/common/src/test/java/org/onap/so/client/RestClientTest.java
@@ -39,7 +39,7 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
@RunWith(MockitoJUnitRunner.class)
public class RestClientTest {
@@ -82,7 +82,7 @@ public class RestClientTest {
private RestClient buildSpy() throws MalformedURLException, IllegalArgumentException, UriBuilderException {
RestClient client = httpClientFactory.newJsonClient(UriBuilder.fromUri("http://localhost/test").build().toURL(),
- TargetEntity.BPMN);
+ ONAPComponents.BPMN);
return spy(client);
}
diff --git a/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java b/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
index 2ef50dd77b..3587c71de0 100644
--- a/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/AAIErrorFormatterTest.java
@@ -79,6 +79,22 @@ public class AAIErrorFormatterTest {
}
@Test
+ public void errorMessageOnPercentEncodedTest() {
+ ServiceException svcException = new ServiceException();
+ svcException.setText("test my%20Test %1 message - %2");
+ svcException.setVariables(Arrays.asList("error", "service exception %1 test"));
+
+ RequestError requestError = new RequestError();
+ requestError.setServiceException(svcException);
+
+ doReturn(requestError).when(errorObj).getRequestError();
+
+ AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
+ String result = formatter.getMessage();
+ assertEquals("equal", "test my%20Test error message - service exception error test", result);
+ }
+
+ @Test
public void testGetMessageNoParsable() {
errorObj.setRequestError(null);
AAIErrorFormatter formatter = new AAIErrorFormatter(errorObj);
diff --git a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
index 6e55fe17fa..fb45652d53 100644
--- a/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
+++ b/common/src/test/java/org/onap/so/client/aai/DSLQueryBuilderTest.java
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.onap.so.client.graphinventory.entities.DSLNode;
+import org.onap.so.client.graphinventory.entities.DSLNodeKey;
import org.onap.so.client.graphinventory.entities.DSLQueryBuilder;
import org.onap.so.client.graphinventory.entities.__;
@@ -108,4 +109,40 @@ public class DSLQueryBuilderTest {
builder.equals("pserver*('hostname', 'my-hostname') > p-interface > sriov-pf('pf-pci-id', 'my-id')"));
assertTrue(builder.equals(builder));
}
+
+
+ @Test
+ public void mixedTypeTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder = new DSLQueryBuilder<>(new DSLNode(AAIObjectType.CLOUD_REGION,
+ __.key("cloud-owner", "owner"), __.key("cloud-region-id", "id")));
+ builder.to(__.node(AAIObjectType.VLAN_TAG, __.key("vlan-id-outer", 167), __.key("my-boolean", true)).output());
+ assertTrue(builder.equals(
+ "cloud-region('cloud-owner', 'owner')('cloud-region-id', 'id') > vlan-tag*('vlan-id-outer', 167)('my-boolean', true)"));
+ }
+
+ @Test
+ public void outputOnNodeLambdasTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.L_INTERFACE, new DSLNodeKey("interface-id", "myId")));
+
+ builder.to(AAIObjectType.VSERVER, __.key("vserver-name", "myName")).output().to(AAIObjectType.P_INTERFACE)
+ .output();
+ assertEquals("l-interface('interface-id', 'myId') > vserver*('vserver-name', 'myName') > p-interface*",
+ builder.build());
+ }
+
+ @Test
+ public void skipOutputOnUnionTest() {
+ DSLQueryBuilder<DSLNode, DSLNode> builder =
+ new DSLQueryBuilder<>(new DSLNode(AAIObjectType.GENERIC_VNF, __.key("vnf-id", "vnfId")).output());
+
+ builder.union(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output()),
+ __.node(AAIObjectType.VSERVER)
+ .to(__.node(AAIObjectType.PSERVER).output().to(__.node(AAIObjectType.COMPLEX).output())))
+ .output();
+
+ assertEquals(
+ "generic-vnf*('vnf-id', 'vnfId') > " + "[ pserver* > complex*, " + "vserver > pserver* > complex* ]",
+ builder.build());
+ }
}
diff --git a/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
index bc600310b3..5075da3b7a 100644
--- a/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
+++ b/common/src/test/java/org/onap/so/client/adapter/rest/AdapterRestClientTest.java
@@ -34,7 +34,7 @@ import org.junit.Before;
import org.junit.Test;
import org.onap.so.client.policy.JettisonStyleMapperProvider;
import org.onap.so.utils.CryptoUtils;
-import org.onap.so.utils.TargetEntity;
+import org.onap.logging.filter.base.ONAPComponents;
public class AdapterRestClientTest {
@@ -88,9 +88,9 @@ public class AdapterRestClientTest {
}
@Test
- public void getTargetEntity_success() throws URISyntaxException {
+ public void getONAPComponents_success() throws URISyntaxException {
AdapterRestClient testedObject = new AdapterRestClient(adapterRestPropertiesMock, new URI(""));
- assertThat(testedObject.getTargetEntity()).isEqualTo(TargetEntity.OPENSTACK_ADAPTER);
+ assertThat(testedObject.getTargetEntity()).isEqualTo(ONAPComponents.OPENSTACK_ADAPTER);
}
@Test
diff --git a/common/src/test/java/org/onap/so/client/dmaap/rest/DMaaPRestClientTest.java b/common/src/test/java/org/onap/so/client/dmaap/rest/DMaaPRestClientTest.java
new file mode 100644
index 0000000000..ca5b5da2da
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/dmaap/rest/DMaaPRestClientTest.java
@@ -0,0 +1,97 @@
+/*-
+ * ============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.dmaap.rest;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import org.junit.Test;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.slf4j.MDC;
+
+public class DMaaPRestClientTest {
+
+ URL url;
+ private final String contentType = "application/json";
+ private final String auth = "";
+ private final String key = "";
+
+
+ @Test
+ public void headerMapTest() {
+
+ try {
+ url = new URL("http://testhost.com");
+ } catch (MalformedURLException e) {
+
+ throw new RuntimeException(e);
+ }
+ DMaaPRestClient client = new DMaaPRestClient(url, contentType, auth, key);
+ Map<String, String> map = new HashMap<>();
+ client.initializeHeaderMap(map);
+ map.put(ONAPLogConstants.MDCs.REQUEST_ID, "1234");
+ assertNotNull(map);
+ assertEquals("Found expected RequesttId", "1234", map.get(ONAPLogConstants.MDCs.REQUEST_ID));
+
+ }
+
+ @Test
+ public void headerMapInvocationIdNotNullTest() {
+
+ try {
+ url = new URL("http://testhost.com");
+ } catch (MalformedURLException e) {
+
+ throw new RuntimeException(e);
+ }
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, "1234");
+ DMaaPRestClient client = new DMaaPRestClient(url, contentType, auth, key);
+ Map<String, String> map = new HashMap<>();
+ client.initializeHeaderMap(map);
+
+ assertNotNull(map);
+ assertEquals("Found expected RequestId", "1234", map.get(ONAPLogConstants.Headers.INVOCATION_ID));
+
+ }
+
+ @Test
+ public void headerMapInvocationIdNullTest() {
+
+ try {
+ url = new URL("http://testhost.com");
+ } catch (MalformedURLException e) {
+
+ throw new RuntimeException(e);
+ }
+
+ MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, null);
+ DMaaPRestClient client = new DMaaPRestClient(url, contentType, auth, key);
+ Map<String, String> map = new HashMap<>();
+ client.initializeHeaderMap(map);
+
+ assertNotNull(map);
+ assertEquals("header not found as expected", null, map.get(ONAPLogConstants.Headers.INVOCATION_ID));
+
+ }
+}
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 ad22c65248..3323fd8409 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
@@ -4,6 +4,8 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
+ * Copyright (C) 2019 Nokia.
+ * ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
@@ -23,32 +25,50 @@ 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.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doReturn;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
+import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
+import org.onap.so.client.RestClient;
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;
-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;
+import org.onap.so.client.policy.entities.Workstep;
public class PolicyClientImplTest {
+ private static final String SERVICE_TYPE = "serviceTest";
+ private static final String VNF_TYPE = "vTypeTest";
+ private static final String BB_ID = "bbTest";
+ private static final String WORK_STEP = "wStepTest";
+ private static final String ERROR_CODE = "errCodeTest";
+
@BeforeClass
public static void setUp() {
System.setProperty("mso.config.path", "src/test/resources");
@@ -67,53 +87,65 @@ public class PolicyClientImplTest {
}
@Test
- @Ignore
- public void getDecisionTest() {
- PolicyClient client = new PolicyClientImpl();
- PolicyDecision decision = client.getDecision("S", "V", "BB1", "1", "123");
- assertEquals("Decision is correct", decision.getDecision(), "PERMIT");
- assertEquals("Decision details is correct", decision.getDetails(), "Retry");
+ public void getDecision_success() {
+ // given
+ PolicyClientImpl testedObject = Mockito.spy(PolicyClientImpl.class);
+ PolicyRestClient policyRestClientMock = Mockito.mock(PolicyRestClient.class);
+ when(testedObject.getPolicyRestClient(PolicyServiceType.GET_DECISION)).thenReturn(policyRestClientMock);
+ // when
+ testedObject.getDecision(SERVICE_TYPE, VNF_TYPE, BB_ID, WORK_STEP, ERROR_CODE);
+ // then
+ ArgumentCaptor<PolicyDecisionRequest> captor1 = ArgumentCaptor.forClass(PolicyDecisionRequest.class);
+ verify(policyRestClientMock).post(captor1.capture(), eq(PolicyDecision.class));
+ verifyPolicyDecisionRequestArg(captor1.getValue());
}
- @Test
- @Ignore
- public void getAllowedTreatmentsTest() {
- PolicyClient client = new PolicyClientImpl();
- DictionaryData dictClient = client.getAllowedTreatments("BB1", "1");
- final String dictBbidString = dictClient.getBbid().getString();
- final String dictWorkStepString = dictClient.getWorkstep().getString();
- assertEquals("DictionaryData matches a response Bbid", dictBbidString, "BB1");
- assertEquals("DicitonaryData matches a response WorkStep", dictWorkStepString, "1");
+ private void verifyPolicyDecisionRequestArg(PolicyDecisionRequest actual) {
+ assertThat(actual.getEcompcomponentName()).isEqualTo(RestClient.ECOMP_COMPONENT_NAME);
+ DecisionAttributes decisionAttributes = actual.getDecisionAttributes();
+ assertThat(decisionAttributes.getServiceType()).isEqualTo(SERVICE_TYPE);
+ assertThat(decisionAttributes.getvNFType()).isEqualTo(VNF_TYPE);
+ assertThat(decisionAttributes.getBbID()).isEqualTo(BB_ID);
+ assertThat(decisionAttributes.getWorkStep()).isEqualTo(WORK_STEP);
+ assertThat(decisionAttributes.getErrorCode()).isEqualTo(ERROR_CODE);
}
@Test
- public void getDecisionMockTest() {
- String serviceType = "S";
- String vnfType = "V";
- 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);
- decisionAttributes.setBBID(bbID);
- 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));
+ public void getAllowedTreatments_success() {
+ // given
+ PolicyClientImpl testedObject = Mockito.spy(PolicyClientImpl.class);
+ PolicyRestClient policyRestClientMock = Mockito.mock(PolicyRestClient.class);
+ when(testedObject.getPolicyRestClient(PolicyServiceType.GET_DICTIONARY_ITEMS)).thenReturn(policyRestClientMock);
+ when(policyRestClientMock.post(any(DictionaryItemsRequest.class), eq(AllowedTreatments.class)))
+ .thenReturn(createAllowedTreatments());
+ // when
+ DictionaryData dictionaryDataResult = testedObject.getAllowedTreatments(BB_ID, WORK_STEP);
+ // then
+ assertThat(dictionaryDataResult.getBbid().getString()).isEqualTo(BB_ID);
+ assertThat(dictionaryDataResult.getWorkstep().getString()).isEqualTo(WORK_STEP);
+ }
+
+ private AllowedTreatments createAllowedTreatments() {
+ AllowedTreatments allowedTreatments = new AllowedTreatments();
+ DictionaryJson dictionaryJson = new DictionaryJson();
+ dictionaryJson.setDictionaryDatas(createDictionaryDataList());
+ allowedTreatments.setDictionaryJson(dictionaryJson);
+ return allowedTreatments;
+ }
+
+ private List<DictionaryData> createDictionaryDataList() {
+ DictionaryData dictionaryData = new DictionaryData();
+ Bbid bbid = new Bbid();
+ bbid.setString(BB_ID);
+ dictionaryData.setBbid(bbid);
+ Workstep workstep = new Workstep();
+ workstep.setString(WORK_STEP);
+ dictionaryData.setWorkstep(workstep);
+ return Arrays.asList(dictionaryData, new DictionaryData());
}
@Test
- public void getConfigFromStringJsonTest() throws JsonParseException, JsonMappingException, IOException {
+ public void getConfigFromStringJsonTest() throws IOException {
PolicyClientImpl client = new PolicyClientImpl();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
@@ -128,7 +160,7 @@ public class PolicyClientImplTest {
}
@Test
- public void getConfigWithPolicyNameTest() throws JsonParseException, JsonMappingException, IOException {
+ public void getConfigWithPolicyNameTest() throws IOException {
PolicyClientImpl client = Mockito.spy(PolicyClientImpl.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
diff --git a/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java b/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java
new file mode 100644
index 0000000000..c4609f0336
--- /dev/null
+++ b/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java
@@ -0,0 +1,93 @@
+package org.onap.so.externaltasks.logging;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.Mockito.doReturn;
+import org.camunda.bpm.client.task.ExternalTask;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Spy;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.logging.filter.base.MDCSetup;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.MdcConstants;
+import org.slf4j.MDC;
+
+@RunWith(MockitoJUnitRunner.class)
+public class AuditMDCSetupTest {
+
+ @Mock
+ private ExternalTask externalTask;
+
+ @Mock
+ private MDCSetup mdcSet;
+
+ @Spy
+ @InjectMocks
+ private AuditMDCSetup mdcSetup;
+
+ private String requestId = "9bb86b8d-a02f-4a0b-81a9-2eb963850009";
+ private String serviceName = "testServiceName";
+
+ @After
+ public void tearDown() {
+ MDC.clear();
+ }
+
+ @Test
+ public void setupMDCTest() {
+ doReturn(requestId).when(externalTask).getVariable("mso-request-id");
+ doReturn(serviceName).when(externalTask).getTopicName();
+
+ mdcSetup.setupMDC(externalTask);
+
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
+ assertEquals(requestId, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
+ assertEquals(serviceName, MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals("SO.OPENSTACK_ADAPTER", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(),
+ MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ }
+
+ @Test
+ public void setElapsedTimeTest() {
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z");
+
+ mdcSetup.setElapsedTime();
+
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME));
+ }
+
+ @Test
+ public void setResponseCodeTest() {
+ mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+
+ assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(),
+ MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(),
+ MDC.get(MdcConstants.OPENSTACK_STATUS_CODE));
+ }
+
+ @Test
+ public void clearClientMDCsTest() {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+ MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
+ MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z");
+ MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, "318");
+ MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, "SO.OPENSTACK_ADAPTER");
+
+ mdcSetup.clearClientMDCs();
+
+ assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ assertNull(MDC.get(MdcConstants.OPENSTACK_STATUS_CODE));
+ assertNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
+ assertNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME));
+ assertNull(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+
+ }
+
+}
diff --git a/common/src/test/java/org/onap/so/logger/ScheduledTasksMDCSetupTest.java b/common/src/test/java/org/onap/so/logger/ScheduledTasksMDCSetupTest.java
new file mode 100644
index 0000000000..f232781871
--- /dev/null
+++ b/common/src/test/java/org/onap/so/logger/ScheduledTasksMDCSetupTest.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.logger;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import org.junit.After;
+import org.junit.Test;
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.utils.Components;
+import org.onap.so.utils.UUIDChecker;
+import org.slf4j.MDC;
+
+public class ScheduledTasksMDCSetupTest {
+ private ScheduledTasksMDCSetup tasksMDCSetup = new ScheduledTasksMDCSetup();
+
+ @After
+ public void tearDown() {
+ MDC.clear();
+ System.clearProperty("partnerName");
+ }
+
+ @Test
+ public void mdcSetupTest() {
+ System.setProperty("partnerName", Components.APIH.toString());
+ tasksMDCSetup.mdcSetup(Components.APIH, "mdcSetupTest");
+
+ assertTrue(UUIDChecker.isValidUUID(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
+ assertEquals(Components.APIH.toString(), MDC.get(ONAPLogConstants.MDCs.TARGET_ENTITY));
+ assertEquals(Components.APIH.toString(), MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME));
+ assertEquals("mdcSetupTest", MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME));
+ assertEquals(Constants.DefaultValues.UNKNOWN, MDC.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME));
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP));
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME));
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.LOG_TIMESTAMP));
+ assertNotNull(MDC.get(ONAPLogConstants.MDCs.SERVER_FQDN));
+ }
+
+ @Test
+ public void errorMDCSetupTest() {
+ tasksMDCSetup.errorMDCSetup(ErrorCode.UnknownError, "Error");
+
+ assertEquals("900", MDC.get(ONAPLogConstants.MDCs.ERROR_CODE));
+ assertEquals("Error", MDC.get(ONAPLogConstants.MDCs.ERROR_DESC));
+ }
+
+ @Test
+ public void setStatusCodeTest() {
+ tasksMDCSetup.setStatusCode();
+
+ assertEquals(ONAPLogConstants.ResponseStatus.COMPLETE.toString(),
+ MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ }
+
+ @Test
+ public void setStatusCodeErrorTest() {
+ MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.ERROR.toString());
+ tasksMDCSetup.setStatusCode();
+
+ assertEquals(ONAPLogConstants.ResponseStatus.ERROR.toString(),
+ MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE));
+ }
+}
diff --git a/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java b/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java
index 978c016dec..72bacdf2db 100644
--- a/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java
+++ b/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java
@@ -33,6 +33,7 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.so.rest.exceptions.InvalidRestRequestException;
+import org.onap.so.rest.exceptions.HttpResouceNotFoundException;
import org.onap.so.rest.exceptions.RestProcessingException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
@@ -116,7 +117,7 @@ public class HttpRestServiceProviderImplTest {
}
- @Test(expected = InvalidRestRequestException.class)
+ @Test(expected = HttpResouceNotFoundException.class)
public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() {
assertGetErrorScenario(HttpStatus.NOT_FOUND);
}
@@ -239,7 +240,7 @@ public class HttpRestServiceProviderImplTest {
}
- @Test(expected = InvalidRestRequestException.class)
+ @Test(expected = HttpResouceNotFoundException.class)
public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() {
assertPostErrorScenario(HttpStatus.NOT_FOUND);
}
diff --git a/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java
new file mode 100644
index 0000000000..f918781b39
--- /dev/null
+++ b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java
@@ -0,0 +1,65 @@
+package org.onap.so.utils;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.springframework.core.env.Environment;
+
+@RunWith(MockitoJUnitRunner.class)
+public class ExternalTaskUtilsTest {
+
+ @Mock
+ private Environment mockenv;
+
+ @InjectMocks
+ private ExternalTaskUtils externalTaskUtilsAnony = new ExternalTaskUtils() {
+
+ };
+
+ @Test
+ public void retry_sequence_calculation_Test() {
+ Mockito.when(mockenv.getProperty("mso.workflow.topics.retryMultiplier", "6000")).thenReturn("6000");
+ long firstRetry = externalTaskUtilsAnony.calculateRetryDelay(8);
+ assertEquals(6000L, firstRetry);
+ long secondRetry = externalTaskUtilsAnony.calculateRetryDelay(7);
+ assertEquals(6000L, secondRetry);
+ long thirdRetry = externalTaskUtilsAnony.calculateRetryDelay(6);
+ assertEquals(12000L, thirdRetry);
+ long fourthRetry = externalTaskUtilsAnony.calculateRetryDelay(5);
+ assertEquals(18000L, fourthRetry);
+ long fifthRetry = externalTaskUtilsAnony.calculateRetryDelay(4);
+ assertEquals(30000L, fifthRetry);
+ long sixRetry = externalTaskUtilsAnony.calculateRetryDelay(3);
+ assertEquals(48000L, sixRetry);
+ long seventhRetry = externalTaskUtilsAnony.calculateRetryDelay(2);
+ assertEquals(78000L, seventhRetry);
+ long eigthRetry = externalTaskUtilsAnony.calculateRetryDelay(1);
+ assertEquals(120000L, eigthRetry);
+ }
+
+ @Test
+ public void retry_sequence_Test() {
+ Mockito.when(mockenv.getProperty("mso.workflow.topics.retryMultiplier", "6000")).thenReturn("6000");
+ long firstRetry = externalTaskUtilsAnony.calculateRetryDelay(8);
+ assertEquals(6000L, firstRetry);
+ long secondRetry = externalTaskUtilsAnony.calculateRetryDelay(7);
+ assertEquals(6000L, secondRetry);
+ long thirdRetry = externalTaskUtilsAnony.calculateRetryDelay(6);
+ assertEquals(12000L, thirdRetry);
+ long fourthRetry = externalTaskUtilsAnony.calculateRetryDelay(5);
+ assertEquals(18000L, fourthRetry);
+ long fifthRetry = externalTaskUtilsAnony.calculateRetryDelay(4);
+ assertEquals(30000L, fifthRetry);
+ long sixRetry = externalTaskUtilsAnony.calculateRetryDelay(3);
+ assertEquals(48000L, sixRetry);
+ long seventhRetry = externalTaskUtilsAnony.calculateRetryDelay(2);
+ assertEquals(78000L, seventhRetry);
+ long eigthRetry = externalTaskUtilsAnony.calculateRetryDelay(1);
+ assertEquals(120000L, eigthRetry);
+ }
+
+}