diff options
Diffstat (limited to 'common')
32 files changed, 1037 insertions, 1159 deletions
diff --git a/common/pom.xml b/common/pom.xml index 883d48c21c..2a9f88f6d2 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -15,7 +15,7 @@ <grpc.version>1.17.1</grpc.version> <protobuf.version>3.6.1</protobuf.version> <grpc.netty.version>4.1.30.Final</grpc.netty.version> - <ccsdk.version>0.4.1-SNAPSHOT</ccsdk.version> + <ccsdk.version>0.4.2-SNAPSHOT</ccsdk.version> </properties> <dependencies> @@ -143,7 +143,7 @@ <!-- CDS dependencies --> <dependency> - <groupId>org.onap.ccsdk.apps.components</groupId> + <groupId>org.onap.ccsdk.cds.components</groupId> <artifactId>proto-definition</artifactId> <version>${ccsdk.version}</version> </dependency> 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 14556f1211..0633ae74c9 100644 --- a/common/src/main/java/org/onap/so/client/RestTemplateConfig.java +++ b/common/src/main/java/org/onap/so/client/RestTemplateConfig.java @@ -20,9 +20,13 @@ package org.onap.so.client; +import org.onap.so.configuration.rest.HttpComponentsClientConfiguration; import org.onap.so.logging.jaxrs.filter.SpringClientFilter; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.http.client.BufferingClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @@ -30,11 +34,29 @@ import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { - @Bean - public RestTemplate restTemplate() { - RestTemplate restTemplate = new RestTemplate(); - restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); - restTemplate.getInterceptors().add(new SpringClientFilter()); - return restTemplate; - } + public static final String CONFIGURABLE_REST_TEMPLATE = "configurableRestTemplate"; + + @Autowired + private HttpComponentsClientConfiguration httpComponentsClientConfiguration; + + @Bean + @Primary + public RestTemplate restTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + restTemplate + .setRequestFactory(new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory())); + restTemplate.getInterceptors().add(new SpringClientFilter()); + return restTemplate; + } + + @Bean + @Qualifier(CONFIGURABLE_REST_TEMPLATE) + public RestTemplate configurableRestTemplate() { + final HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = + httpComponentsClientConfiguration.httpComponentsClientHttpRequestFactory(); + final RestTemplate restTemplate = + new RestTemplate(new BufferingClientHttpRequestFactory(clientHttpRequestFactory)); + restTemplate.getInterceptors().add(new SpringClientFilter()); + return restTemplate; + } } diff --git a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java index ffc474a55a..6c6cf9024d 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIClientResponseExceptionMapper.java @@ -32,7 +32,6 @@ import javax.ws.rs.ext.Provider; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.client.ResponseExceptionMapper; import org.onap.so.client.aai.entities.AAIError; -import org.onap.so.logger.MsoLogger; import org.slf4j.MDC; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java index 21e36cde6c..34d560210c 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java @@ -21,7 +21,6 @@ package org.onap.so.client.aai; import java.io.Serializable; -import java.lang.reflect.Field; import java.net.URL; import java.util.HashMap; import java.util.Map; @@ -39,7 +38,9 @@ import org.onap.aai.domain.yang.Connector; import org.onap.aai.domain.yang.Customer; import org.onap.aai.domain.yang.Device; import org.onap.aai.domain.yang.ExtAaiNetwork; +import org.onap.aai.domain.yang.Flavor; import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.Image; import org.onap.aai.domain.yang.InstanceGroup; import org.onap.aai.domain.yang.L3Network; import org.onap.aai.domain.yang.LInterface; @@ -134,6 +135,8 @@ public class AAIObjectType implements GraphInventoryObjectType, Serializable { public static final AAIObjectType EXT_AAI_NETWORK = new AAIObjectType(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class); public static final AAIObjectType AGGREGATE_ROUTE = new AAIObjectType(AAINamespaceConstants.NETWORK, AggregateRoute.class); public static final AAIObjectType L_INTERFACE = new AAIObjectType(AAIObjectType.VSERVER.uriTemplate(), LInterface.class); + public static final AAIObjectType IMAGE = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Image.class); + public static final AAIObjectType FLAVOR = new AAIObjectType(AAIObjectType.CLOUD_REGION.uriTemplate(), Flavor.class); public static final AAIObjectType UNKNOWN = new AAIObjectType("", "", "unknown"); public static final AAIObjectType DSL = new AAIObjectType("/dsl", "", "dsl"); diff --git a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java index 6ece8a2620..1bd7720e55 100644 --- a/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java +++ b/common/src/main/java/org/onap/so/client/aai/AAIValidatorImpl.java @@ -26,8 +26,7 @@ import java.util.List; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.Pserver; import org.springframework.beans.factory.annotation.Autowired; - - +import org.springframework.stereotype.Component; public class AAIValidatorImpl implements AAIValidator { @@ -50,10 +49,12 @@ public class AAIValidatorImpl implements AAIValidator { List<Pserver> pservers; boolean isLocked = false; pservers = client.getPhysicalServerByVnfId(vnfId); - for (Pserver pserver : pservers) - if (pserver.isInMaint()) + for (Pserver pserver : pservers) { + if (pserver.isInMaint()) { isLocked = true; - + return isLocked; + } + } return isLocked; } diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java b/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java index 756c26ddef..9b2fd3fdb0 100644 --- a/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java +++ b/common/src/main/java/org/onap/so/client/cds/CDSProcessingClient.java @@ -25,7 +25,7 @@ import io.grpc.internal.DnsNameResolverProvider; import io.grpc.internal.PickFirstLoadBalancerProvider; import io.grpc.netty.NettyChannelBuilder; import java.util.concurrent.CountDownLatch; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; import org.onap.so.client.PreconditionFailedException; import org.onap.so.client.RestPropertiesLoader; import org.slf4j.Logger; diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java b/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java index 1791be2991..4b86493f79 100644 --- a/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java +++ b/common/src/main/java/org/onap/so/client/cds/CDSProcessingHandler.java @@ -23,11 +23,11 @@ package org.onap.so.client.cds; import io.grpc.ManagedChannel; import io.grpc.stub.StreamObserver; import java.util.concurrent.CountDownLatch; -import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceStub; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceStub; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProcessingListener.java b/common/src/main/java/org/onap/so/client/cds/CDSProcessingListener.java index 8c92a5810c..ed7b4e51ba 100644 --- a/common/src/main/java/org/onap/so/client/cds/CDSProcessingListener.java +++ b/common/src/main/java/org/onap/so/client/cds/CDSProcessingListener.java @@ -20,7 +20,7 @@ package org.onap.so.client.cds; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; public interface CDSProcessingListener { diff --git a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java index 42a4b47aa2..59c64e0459 100644 --- a/common/src/main/java/org/onap/so/client/cds/CDSProperties.java +++ b/common/src/main/java/org/onap/so/client/cds/CDSProperties.java @@ -1,23 +1,18 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 Bell Canada. - * ================================================================================ +/* + * Copyright (C) 2019 Bell Canada. + * * 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.cds; import org.onap.so.client.RestProperties; @@ -30,4 +25,6 @@ public interface CDSProperties extends RestProperties { int getPort(); String getBasicAuth(); + + int getTimeout(); } diff --git a/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java b/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java new file mode 100644 index 0000000000..7606f3a8d3 --- /dev/null +++ b/common/src/main/java/org/onap/so/configuration/rest/BasicHttpHeadersProvider.java @@ -0,0 +1,54 @@ +/*- + * ============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.configuration.rest; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +/** + * @author waqas.ikram@est.tech + */ +public class BasicHttpHeadersProvider implements HttpHeadersProvider { + + public static final String AUTHORIZATION_HEADER = "Authorization"; + + private final HttpHeaders headers = new HttpHeaders(); + + public BasicHttpHeadersProvider(final String authorization) { + headers.add(AUTHORIZATION_HEADER, authorization); + headers.setContentType(MediaType.APPLICATION_JSON); + } + + public BasicHttpHeadersProvider() { + headers.setContentType(MediaType.APPLICATION_JSON); + } + + @Override + public HttpHeaders getHttpHeaders() { + return headers; + } + + @Override + public String toString() { + return "BasicHttpHeadersProvider [headers=" + headers + "]"; + } + +} diff --git a/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java new file mode 100644 index 0000000000..a5a4cb7d53 --- /dev/null +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpClientConnectionConfiguration.java @@ -0,0 +1,87 @@ +/*- + * ============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.configuration.rest; + +import java.util.concurrent.TimeUnit; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +/** + * This class is used configure the parameters needed for + * {@link org.apache.http.impl.client.CloseableHttpClient} + * + * @author waqas.ikram@est.tech + */ +@Service +public class HttpClientConnectionConfiguration { + + @Value(value = "${rest.http.client.configuration.connTimeOutInSec:10}") + private int connectionTimeOutInSeconds; + + @Value(value = "${rest.http.client.configuration.socketTimeOutInSec:180}") + private int socketTimeOutInSeconds; + + @Value(value = "${rest.http.client.configuration.socketTimeOutInSec:600}") + private int timeToLiveInSeconds; + + @Value(value = "${rest.http.client.configuration.maxConnections:10}") + private int maxConnections; + + @Value(value = "${rest.http.client.configuration.maxConnectionsPerRoute:2}") + private int maxConnectionsPerRoute; + + /** + * @return the socket connection time out in milliseconds + */ + public int getSocketTimeOutInMiliSeconds() { + return (int) TimeUnit.SECONDS.toMillis(socketTimeOutInSeconds); + } + + /** + * @return the maximum total connection value. + */ + public int getMaxConnections() { + return maxConnections; + } + + /** + * @return the maximum connection per route value. + */ + public int getMaxConnectionsPerRoute() { + return maxConnectionsPerRoute; + } + + /** + * @return the connect time out value in milliseconds. + */ + public int getConnectionTimeOutInMilliSeconds() { + return (int) TimeUnit.SECONDS.toMillis(connectionTimeOutInSeconds); + } + + /** + * @return the connection time to live value in mintues. + */ + public int getTimeToLiveInMins() { + return (int) TimeUnit.SECONDS.toMinutes(timeToLiveInSeconds); + } + +} diff --git a/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java new file mode 100644 index 0000000000..e943aef159 --- /dev/null +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpComponentsClientConfiguration.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.configuration.rest; + +import java.util.concurrent.TimeUnit; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +/** + * Allow user to configure {@link org.apache.http.client.HttpClient} + * + * @author waqas.ikram@est.tech + */ +@Configuration +public class HttpComponentsClientConfiguration { + + private final HttpClientConnectionConfiguration clientConnectionConfiguration; + + @Autowired + public HttpComponentsClientConfiguration(final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; + } + + @Bean + public HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory() { + return new HttpComponentsClientHttpRequestFactory(httpClient()); + } + + @Bean + public CloseableHttpClient httpClient() { + return HttpClientBuilder.create().setConnectionManager(poolingHttpClientConnectionManager()) + .setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) + .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) + .setDefaultRequestConfig(requestConfig()).build(); + } + + @Bean + public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() { + return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), + TimeUnit.MINUTES); + } + + @Bean + public RequestConfig requestConfig() { + return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) + .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); + } +} diff --git a/common/src/main/java/org/onap/so/configuration/rest/HttpHeadersProvider.java b/common/src/main/java/org/onap/so/configuration/rest/HttpHeadersProvider.java new file mode 100644 index 0000000000..0cff7b4ba0 --- /dev/null +++ b/common/src/main/java/org/onap/so/configuration/rest/HttpHeadersProvider.java @@ -0,0 +1,35 @@ +/*- + * ============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.configuration.rest; + +import org.springframework.http.HttpHeaders; + +/** + * Providers {@link org.springframework.http.HttpHeaders} for HTTP requests + * + * @author waqas.ikram@est.tech + * + */ +public interface HttpHeadersProvider { + + HttpHeaders getHttpHeaders(); + +} diff --git a/common/src/main/java/org/onap/so/logger/ErrorCode.java b/common/src/main/java/org/onap/so/logger/ErrorCode.java new file mode 100644 index 0000000000..b58189efda --- /dev/null +++ b/common/src/main/java/org/onap/so/logger/ErrorCode.java @@ -0,0 +1,16 @@ +package org.onap.so.logger; + +public enum ErrorCode { + PermissionError(100), AvailabilityError(200), DataError(300), SchemaError(400), BusinessProcesssError( + 500), UnknownError(900); + + private int value; + + ErrorCode(int value) { + this.value = value; + } + + public int getValue() { + return this.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 new file mode 100644 index 0000000000..f34b4b5a9a --- /dev/null +++ b/common/src/main/java/org/onap/so/logger/HttpHeadersConstants.java @@ -0,0 +1,13 @@ +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/MdcConstants.java b/common/src/main/java/org/onap/so/logger/MdcConstants.java new file mode 100644 index 0000000000..9f8417e047 --- /dev/null +++ b/common/src/main/java/org/onap/so/logger/MdcConstants.java @@ -0,0 +1,13 @@ +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"; +} diff --git a/common/src/main/java/org/onap/so/logger/MsoLogger.java b/common/src/main/java/org/onap/so/logger/MsoLogger.java deleted file mode 100644 index 9715695d7c..0000000000 --- a/common/src/main/java/org/onap/so/logger/MsoLogger.java +++ /dev/null @@ -1,1092 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.logger; - - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.invoke.MethodHandles; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.apache.commons.lang3.StringUtils; -import org.onap.so.entity.MsoRequest; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.slf4j.Marker; -import org.slf4j.MarkerFactory; - - -/** - * This class supports all of the normal logging functions (debug, info, etc.), prepending - * a string of format "[<requestId>|<serviceId]" to each message. - * - * SO code should initialize with these IDs when available, so that individual - * requests and/or services can be tracked throughout the various MSO component - * logs (API Handler, BPEL, and Adapters). - * - * - */ - -public class MsoLogger { - // Required MDC parameters - public static final String REQUEST_ID = "RequestID"; - public static final String INVOCATION_ID = "InvocationID"; - public static final String INSTANCE_UUID = "InstanceUUID"; - public static final String SERVICE_NAME = "ServiceName"; - public static final String STATUSCODE = "StatusCode"; - public static final String RESPONSECODE = "ResponseCode"; - public static final String RESPONSEDESC = "ResponseDesc"; - public static final String FQDN = "ServerFQDN"; - public static final String ENTRY_TIMESTAMP = "EntryTimestamp"; - public static final String CLIENT_IPADDRESS = "EntryTimestamp"; - - - //HTTP Headers - public static final String HEADER_FROM_APP_ID = "X-FromAppId"; - public static final String ONAP_PARTNER_NAME = "X-ONAP-PartnerName"; - public static final String HEADER_REQUEST_ID = "X-RequestId"; - public static final String TRANSACTION_ID = "X-TransactionID"; - public static final String ECOMP_REQUEST_ID = "X-ECOMP-RequestID"; - public static final String ONAP_REQUEST_ID = "X-ONAP-RequestID"; - public static final String CLIENT_ID = "X-ClientID"; - public static final String INVOCATION_ID_HEADER = "X-InvocationID"; - public static final String REQUESTOR_ID = "X-RequestorID"; - - //Default values for not found - public static final String UNKNOWN_PARTNER = "UnknownPartner"; - - public static final String SERVICE_INSTANCE_ID = "ServiceInstanceId"; - public static final String SERVICE_NAME_IS_METHOD_NAME = "ServiceNameIsMethodName"; - public static final String SERVER_IP = "ServerIPAddress"; - - public static final String REMOTE_HOST = "RemoteHost"; - public static final String ALERT_SEVERITY = "AlertSeverity"; - public static final String TIMER = "Timer"; - public static final String USER = "User"; - public static final String DUMMY_VALUE = "trace-#"; - public static final String UNKNOWN = "UNKNOWN"; - public static final String CAT_LOG_LEVEL = "CategoryLogLevel"; - public static final String AUDI_CAT_LOG_LEVEL = "AuditCategoryLogLevel"; - - - - public static final String PARTNER_NAME = "PartnerName"; - - // Audit/Metric log specific - public static final String BEGINTIME = "BeginTimestamp"; - public static final String STARTTIME = "StartTimeMilis"; - public static final String ENDTIME = "EndTimestamp"; - public static final String PARTNERNAME = "PartnerName"; - - - - // Metric log specific - public static final String METRIC_BEGIN_TIME = "MetricBeginTime"; - public static final String METRIC_START_TIME = "MetricStartTime"; - public static final String METRIC_END_TIME = "MetricEndTime"; - public static final String METRIC_TIMER = "MetricEndTime"; - public static final String TARGETENTITY = "TargetEntity"; - public static final String TARGETSERVICENAME = "TargetServiceName"; - public static final String TARGETVIRTUALENTITY = "TargetVirtualEntity"; - - public static final String FATAL_LEVEL = "FATAL"; - public static final String ERROR_LEVEL = "ERROR"; - public static final String WARN_LEVEL = "WARN"; - public static final String INFO_LEVEL = "INFO"; - public static final String DEBUG_LEVEL = "DEBUG"; - - public static final String ERRORCODE = "ErrorCode"; - public static final String ERRORDESC = "ErrorDesc"; - - //Status Codes - public static final String COMPLETE = "COMPLETE"; - public static final String INPROGRESS = "INPROGRESS"; - - public enum Catalog { - APIH, BPEL, RA, ASDC, GENERAL - } - - public enum StatusCode { - COMPLETE, ERROR - } - - public enum TargetEntity { - CAMUNDA("Camunda"); - - private String name; - - TargetEntity(String name) { - this.name = name; - } - - public String getUrl() { - return name; - } - } - - public enum ResponseCode { - Suc(0), PermissionError(100), DataError(300), DataNotFound(301), BadRequest(302), SchemaError( - 400), BusinessProcesssError(500), ServiceNotAvailable(501), InternalError( - 502), Conflict(503), DBAccessError(504), CommunicationError(505), UnknownError(900); - - private int value; - - public int getValue() { - return this.value; - } - - private ResponseCode(int value) { - this.value = value; - } - } - - public enum ErrorCode { - PermissionError(100), AvailabilityError(200), DataError(300), SchemaError(400), BusinessProcesssError( - 500), UnknownError(900); - - private int value; - - public int getValue() { - return this.value; - } - - private ErrorCode(int value) { - this.value = value; - } - } - - - private Logger logger; - private Logger metricsLogger; - private Logger auditLogger; - private static String instanceUUID, serverIP, serverName; - private MessageEnum exceptionArg, defaultException, defaultWarning, defaultAudit, defaultMetrics; - - private MsoLogger() { - this(MsoLogger.Catalog.GENERAL); - } - - private MsoLogger(MsoLogger.Catalog cat) { - this(cat, MethodHandles.lookup().lookupClass()); - } - - private MsoLogger(MsoLogger.Catalog cat, Class<?> clazz) { - this.logger = LoggerFactory.getLogger(clazz); - this.auditLogger = LoggerFactory.getLogger("AUDIT"); - this.metricsLogger = LoggerFactory.getLogger("METRIC"); - setDefaultLogCatalog(cat); - } - - public static MsoLogger getMsoLogger(MsoLogger.Catalog cat, Class<?> clazz) { - return new MsoLogger(cat,clazz); - } - - - - /** - * Record the Metrics event with no argument - * - * @param startTime - * Transaction starting time in millieseconds - * @param statusCode - * StatusCode of the transaction, either COMPLETE or ERROR - * @param responseCode - * The response code returned by the sub-components - * @param responseDesc - * Human redable description of the response code - * @param targetEntity - * The component which is invoked for this sub-operation - * @param targetServiceName - * API invoked on the TargetEntity - * @param targetVEntity - * Target VNF or VM acted opon by the component, if available - */ - - public void recordMetricEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode, String responseDesc, - String targetEntity, String targetServiceName, String targetVEntity) { - prepareMetricMsg(startTime, statusCode, responseCode.getValue(), responseDesc, targetEntity, targetServiceName, - targetVEntity); - metricsLogger.info(""); - MDC.remove(TIMER); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - - /** - * Record the Audit event - * - * @param startTime - * Transaction starting time in millieseconds - * @param statusCode - * StatusCode of the transaction, either COMPLETE or ERROR - * @param responseCode - * The application specific response code - * @param responseDesc - * Human redable description of the application response code - */ - - public void recordAuditEvent(Long startTime, StatusCode statusCode, ResponseCode responseCode, - String responseDesc) { - if (StringUtils.isEmpty(MDC.get(MsoLogger.PARTNERNAME))) { - MDC.put(MsoLogger.PARTNERNAME, "UNKNOWN"); - } - prepareAuditMsg(startTime, statusCode, responseCode.getValue(), responseDesc); - auditLogger.info(""); - MDC.remove(TIMER); - } - - // Debug methods - /** - * Record the Debug event - * - * @param msg - * The log message to put - */ - public void debug(String msg) { - prepareMsg(DEBUG_LEVEL); - logger.debug(msg); - } - - /** - * Record the Debug event - * - * @param msg - * The log message to put - * @param t - * The exception to put - */ - public void debug(String msg, Throwable t) { - prepareMsg(DEBUG_LEVEL); - logger.debug(msg, t); - } - - public void info(String msg) { - prepareMsg(DEBUG_LEVEL); - logger.info(msg); - } - - - /** - * Log error message with the details of the exception that caused the error. - * @param msg - * @param throwable - */ - public void error(String msg) { - prepareMsg(ERROR_LEVEL); - logger.error(msg); - } - - /** - * Log error message with the details of the exception that caused the error. - * @param msg - * @param throwable - */ - public void error(String msg, Throwable throwable) { - prepareMsg(ERROR_LEVEL); - logger.error(msg, throwable); - } - - // Info methods - /** - * Record the Info event - * - * @param msg - * The log message to put - */ - public void info(String msg, String targetEntity, String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 1 argument - * - * @param msg - * The log message to put - * @param arg0 - * The argument used in the log message - */ - public void info(MessageEnum msg, String arg0, String targetEntity, String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg.toString(), normalize(arg0)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 2 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1 - * The arguments used in the log message - */ - public void info(String msg, String arg0, String arg1, String targetEntity, - String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg, normalize(arg0), normalize(arg1)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 3 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2 - * The arguments used in the log message - */ - public void info(MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, - String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 4 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3 - * The arguments used in the log message - */ - public void info(String msg, String arg0, String arg1, String arg2, String arg3, - String targetEntity, String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 5 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4 - * The arguments used in the log message - */ - public void info(String msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String targetEntity, String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Info event with 6 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4,arg5 - * The arguments used in the log message - */ - public void info(String msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String arg5, String targetEntity, String targetServiceName) { - prepareErrorMsg(INFO_LEVEL, targetEntity, targetServiceName, null, ""); - - logger.info(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), - normalize(arg5)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - // Warning methods - - - /** - * Record the Warning event - * - * @param msg - * The log message to put - */ - public void warnSimple( String targetServiceName, String errorDesc) { - logger.warn("Service Name: {} Error: {}" , targetServiceName, errorDesc); - } - /** - * Record the Warning event - * - * @param msg - * The log message to put - */ - public void warn(MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, - String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - - logger.warn(msg.toString()); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warning event - * - * @param msg - * The log message to put - * @param t - * The exception info - */ - public void warn(MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, - String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn("Warning: "+msg, t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 1 argument - * - * @param msg - * The log message to put - * @param arg - * The argument used in the log message - */ - public void warn(MessageEnum msg, String arg, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg.toString(), arg); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 1 argument - * - * @param msg - * The log message to put - * @param arg - * The arguments used in the log message - * @param t - * The exception info - */ - public void warn(MessageEnum msg, String arg, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg.toString(), arg); - logger.debug("Exception raised", t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 2 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1 - * The arguments used in the log message - */ - public void warn(MessageEnum msg, String arg0, String arg1, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg.toString(), normalize(arg0), normalize(arg1)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 2 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1 - * The arguments used in the log message - * @param t - * The exception info - */ - public void warn(String msg, String arg0, String arg1, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1)); - logger.warn(msg, t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 3 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2 - * The arguments used in the log message - */ - public void warn(String msg, String arg0, String arg1, String arg2, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 3 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2 - * The arguments used in the log message - * @param t - * The exception info - */ - public void warn(String msg, String arg0, String arg1, String arg2, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2)); - logger.warn(msg, t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 4 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3 - * The arguments used in the log message - */ - public void warn(String msg, String arg0, String arg1, String arg2, String arg3, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 4 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2, - * arg3 The arguments used in the log message - * @param t - * The exception info - */ - public void warn(String msg, String arg0, String arg1, String arg2, String arg3, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - logger.warn(msg, t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 5 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4 - * The arguments used in the log message - */ - public void warn(String msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Warn event with 5 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4 - * The arguments used in the log message - * @param t - * The exception info - */ - public void warn(String msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(WARN_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.warn(msg, normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - logger.warn(msg, t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - - - // Error methods - /** - * Record the Error event - * - * @param generalException - * The log message to put - */ - public void error(MessageEnum generalException, String targetEntity, String targetServiceName, ErrorCode errorCode, - String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(generalException.toString() + ": " +errorDesc); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - - /** - * Record the Error event - * - * @param msg - * The log message to put - * @param t - * The exception info - */ - public void trace(String traceMessage) { - logger.trace(traceMessage); - } - - - /** - * Record the Error event - * - * @param msg - * The log message to put - * @param t - * The exception info - */ - public void error( Throwable t) { - logger.error(t.getMessage(), t); - } - - - /** - * Record the Error event - * - * @param msg - * The log message to put - * @param t - * The exception info - */ - public void error(MessageEnum msg, String targetEntity, String targetServiceName, ErrorCode errorCode, - String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 1 argument - * - * @param msg - * The log message to put - * @param arg0 - * The arguments used in the log message - */ - public void error(MessageEnum msg, String arg0, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 1 argument - * - * @param msg - * The log message to put - * @param arg0 - * The arguments used in the log message - * @param t - * The exception info - */ - public void error(MessageEnum msg, String arg0, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 2 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1 - * The arguments used in the log message - */ - public void error(MessageEnum msg, String arg0, String arg1, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 2 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1 - * The arguments used in the log message - * @param t - * The exception info - */ - public void error(MessageEnum msg, String arg0, String arg1, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), t); - logger.debug("Exception raised", t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 3 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2 - * The arguments used in the log message - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 3 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2 - * The arguments used in the log message - * @param t - * The exception info - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String targetEntity, - String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2), t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 4 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3 - * The arguments used in the log message - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String arg3, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 4 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3 - * The arguments used in the log message - * @param t - * The exception info - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String arg3, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), t); - - logger.debug("Exception raised", t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 5 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4 - * The arguments used in the log message - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4)); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - /** - * Record the Error event with 5 arguments - * - * @param msg - * The log message to put - * @param arg0,arg1,arg2,arg3,arg4 - * The arguments used in the log message - * @param t - * The exception info - */ - public void error(MessageEnum msg, String arg0, String arg1, String arg2, String arg3, String arg4, - String targetEntity, String targetServiceName, ErrorCode errorCode, String errorDesc, Throwable t) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorDesc); - logger.error(msg.toString(), normalize(arg0), normalize(arg1), normalize(arg2), normalize(arg3), normalize(arg4), t); - logger.debug("Exception raised", t); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - } - - public void error(String errorMessage, String errorSource, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorText) { - prepareErrorMsg(ERROR_LEVEL, targetEntity, targetServiceName, errorCode, errorText); - logger.error(errorMessage); - MDC.remove(TARGETENTITY); - MDC.remove(TARGETSERVICENAME); - - } - - private void prepareMsg(String loggingLevel) { - prepareMsg(loggingLevel, null, null); - } - - private void prepareMsg(String loggingLevel, String serviceNamep, String timer) { - String reqId = MDC.get(REQUEST_ID); - String svcId = MDC.get(SERVICE_INSTANCE_ID); - - // Based on the discussion with Adrian, - // if these 2 parameters is not available, using dummy value "trace-#" - if (reqId == null || reqId.isEmpty()) { - MDC.put(REQUEST_ID, DUMMY_VALUE); - } - - if (timer != null) { - MDC.put(TIMER, timer); - } - - writeIfNotNullorEmpty(SERVICE_NAME,getFinalServiceName(serviceNamep)); - writeIfNotNullorEmpty(ALERT_SEVERITY,getSeverityLevel(loggingLevel)); - writeIfNotNullorEmpty(INSTANCE_UUID,instanceUUID); - writeIfNotNullorEmpty(SERVER_IP,serverIP); - writeIfNotNullorEmpty(FQDN,serverName); - - } - - private void writeIfNotNullorEmpty(String Key, String value) { - if (MDC.get(Key) == null|| MDC.get(Key).isEmpty()) { - MDC.put(Key, value); - } - } - - private void prepareAuditMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc) { - long endTime = System.currentTimeMillis(); - prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime)); - prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc); - } - - private void prepareAuditMetricMsg(long startTime, long endTime, StatusCode statusCode, int responseCode, - String responseDesc) { - Date startDate = new Date(startTime); - Date endDate = new Date(endTime); - DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); - - MDC.put(BEGINTIME, String.valueOf(formatter.format(startDate))); - MDC.put(ENDTIME, String.valueOf(formatter.format(endDate))); - MDC.put(STATUSCODE, statusCode.name()); - MDC.put(RESPONSECODE, String.valueOf(responseCode)); - MDC.put(RESPONSEDESC, responseDesc); - } - - private void prepareErrorMsg(String loggingLevel, String targetEntity, String targetServiceName, - ErrorCode errorCode, String errorDesc) { - MDC.put(ALERT_SEVERITY, getSeverityLevel(loggingLevel)); - if(errorCode != null) { - MDC.put(ERRORCODE, Integer.toString(errorCode.getValue())); - } - MDC.put(ERRORDESC, errorDesc); - MDC.put(TARGETENTITY, targetEntity); - MDC.put(TARGETSERVICENAME, targetServiceName); - } - - private void prepareMetricMsg(long startTime, StatusCode statusCode, int responseCode, String responseDesc, - String targetEntity, String targetServiceName, String targetVEntity) { - long endTime = System.currentTimeMillis(); - prepareMsg(INFO_LEVEL, null, String.valueOf(endTime - startTime)); - prepareAuditMetricMsg(startTime, endTime, statusCode, responseCode, responseDesc); - - // Populate Metric log specific parameter - MDC.put(TARGETENTITY, targetEntity); - MDC.put(TARGETSERVICENAME, targetServiceName); - - if (null != targetVEntity) { - MDC.put(TARGETVIRTUALENTITY, targetVEntity); - } - } - - private String getSeverityLevel(String loggingLevel) { - String severity; - // According to the Nagios alerting: 0=OK; 1=WARNING; 2=UNKOWN; - // 3=CRITICAL - switch (loggingLevel) { - case ERROR_LEVEL: - severity = "2"; - break; - case FATAL_LEVEL: - severity = "3"; - break; - case WARN_LEVEL: - severity = "1"; - break; - default: - severity = "0"; - break; - } - return severity; - } - - private String getFinalServiceName(String serviceNamep) { - // This step to set the serviceName should be put after the className is - // get, - // since the default serviceName is obtained during the method to get - // the className. - // - // There's 3 ways to set the serviceName. The first method has the most - // priority to set the value. - // a) If the serviceName is set within the log method, this value will - // be used first - // b) If serviceName is not set within the log method, the value defined - // in the MDC will be used - // c) If nothing is set specifically, then MsoLogger will assign a - // default(MSO.<method_name>) value to it - String serName = MDC.get(MsoLogger.SERVICE_NAME); - - // Check if service name was already set as the method name by a - // previous call to this method. - String isMethodNameStr = MDC.get(MsoLogger.SERVICE_NAME_IS_METHOD_NAME); - boolean isMethodName = isMethodNameStr != null && isMethodNameStr.equals(Boolean.TRUE.toString()); - if (serviceNamep != null) { - return serviceNamep; - } else if (serName != null && !isMethodName) { - return serName; - } - - MDC.put(MsoLogger.SERVICE_NAME_IS_METHOD_NAME, Boolean.TRUE.toString()); - int limit; - StackTraceElement[] classArr = new Exception().getStackTrace(); - if (classArr.length >= 6) { - limit = 7; - } else { - limit = classArr.length; - } - for (int i = 1; i < limit; i++) { - if (!classArr[i].getClassName().equals(this.getClass().getName())) { - return classArr[i].getMethodName(); - } - } - return classArr[0].getMethodName(); - } - - /** - * Set the requestId and serviceInstanceId - * - * @param reqId - * The requestId - * @param svcId - * The serviceInstanceId - */ - public static void setLogContext(String reqId, String svcId) { - if (null != reqId) { - MDC.put(REQUEST_ID, reqId); - } - - if (null != svcId) { - MDC.put(SERVICE_INSTANCE_ID, svcId); - } - } - - private String normalize(String input) { - if (input == null) { - return null; - } - String result = input.replace('|', '!'); - result = result.replace("\n", " - "); - return result; - } - - private void setDefaultLogCatalog(MsoLogger.Catalog cat) { - if ("APIH".equals(cat.toString())) { - exceptionArg = MessageEnum.APIH_GENERAL_EXCEPTION_ARG; - defaultException = MessageEnum.APIH_GENERAL_EXCEPTION; - defaultWarning = MessageEnum.APIH_GENERAL_WARNING; - defaultAudit = MessageEnum.APIH_AUDIT_EXEC; - defaultMetrics = MessageEnum.APIH_GENERAL_METRICS; - } else if ("RA".equals(cat.toString())) { - exceptionArg = MessageEnum.RA_GENERAL_EXCEPTION_ARG; - defaultException = MessageEnum.RA_GENERAL_EXCEPTION; - defaultWarning = MessageEnum.RA_GENERAL_WARNING; - defaultAudit = MessageEnum.RA_AUDIT_EXEC; - defaultMetrics = MessageEnum.RA_GENERAL_METRICS; - } else if ("BPEL".equals(cat.toString())) { - exceptionArg = MessageEnum.BPMN_GENERAL_EXCEPTION_ARG; - defaultException = MessageEnum.BPMN_GENERAL_EXCEPTION; - defaultWarning = MessageEnum.BPMN_GENERAL_WARNING; - defaultAudit = MessageEnum.BPMN_AUDIT_EXEC; - defaultMetrics = MessageEnum.BPMN_GENERAL_METRICS; - } else if ("ASDC".equals(cat.toString())) { - exceptionArg = MessageEnum.ASDC_GENERAL_EXCEPTION_ARG; - defaultException = MessageEnum.ASDC_GENERAL_EXCEPTION; - defaultWarning = MessageEnum.ASDC_GENERAL_WARNING; - defaultAudit = MessageEnum.ASDC_AUDIT_EXEC; - defaultMetrics = MessageEnum.ASDC_GENERAL_METRICS; - } else { - exceptionArg = MessageEnum.GENERAL_EXCEPTION_ARG; - defaultException = MessageEnum.GENERAL_EXCEPTION; - defaultWarning = MessageEnum.GENERAL_WARNING; - defaultAudit = MessageEnum.AUDIT_EXEC; - defaultMetrics = MessageEnum.GENERAL_METRICS; - } - } -} 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 index 29264f4e42..7f88f22b79 100644 --- 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 @@ -39,7 +39,6 @@ import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; -import org.onap.so.logger.MsoLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -156,4 +155,4 @@ public class PayloadLoggingFilter implements ClientRequestFilter, ClientResponse return method; } -}
\ No newline at end of file +} 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 index cecef1945b..ed63a706a2 100644 --- 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 @@ -57,6 +57,7 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { } private void processRequest(HttpRequest request, byte[] body) throws IOException { + setInvocationId(); setupHeaders(request); setupMDC(request); if (log.isDebugEnabled()) { @@ -89,7 +90,6 @@ public class SpringClientFilter implements ClientHttpRequestInterceptor { 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,extractTargetEntity(clientRequest)); } diff --git a/common/src/main/java/org/onap/so/rest/exceptions/InvalidRestRequestException.java b/common/src/main/java/org/onap/so/rest/exceptions/InvalidRestRequestException.java new file mode 100644 index 0000000000..2a9799315e --- /dev/null +++ b/common/src/main/java/org/onap/so/rest/exceptions/InvalidRestRequestException.java @@ -0,0 +1,37 @@ +/*- + * ============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; + +/** + * @author waqas.ikram@est.tech + * + */ +public class InvalidRestRequestException extends RuntimeException { + private static final long serialVersionUID = -1158414939006977465L; + + public InvalidRestRequestException(final String message) { + super(message); + } + + public InvalidRestRequestException(final String message, final Throwable cause) { + super(message, cause); + } +} 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 new file mode 100644 index 0000000000..e8ce00c7e5 --- /dev/null +++ b/common/src/main/java/org/onap/so/rest/exceptions/RestProcessingException.java @@ -0,0 +1,37 @@ +/*- + * ============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; + +/** + * @author waqas.ikram@est.tech + * + */ +public class RestProcessingException extends RuntimeException { + + private static final long serialVersionUID = 16862313537198441L; + + public RestProcessingException(final String message) { + super(message); + } + + public RestProcessingException(final String message, final Throwable cause) { + super(message, cause); + } +} diff --git a/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java new file mode 100644 index 0000000000..43b2fb4292 --- /dev/null +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProvider.java @@ -0,0 +1,72 @@ +/*- + * ============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.service; + +import org.springframework.http.ResponseEntity; + +import com.google.common.base.Optional; + +/** + * @author waqas.ikram@est.tech + */ +public interface HttpRestServiceProvider { + + /** + * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param clazz the type of the return value + * @return Returns the body of this entity. + */ + public <T> Optional<T> get(final String url, final Class<T> clazz); + + /** + * Execute the HTTP GET to the given URI template + * + * @param url the URL + * @param clazz the type of the return value + * @return Returns the {@link ResponseEntity}. + */ + public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz); + + + /** + * Execute the HTTP POST to the given URI template + * + * @param object the entity (i.e. body) to write to the request + * @param url the URL + * @param clazz the type of the return value + * @return Returns the body of this entity. + */ + public <T> Optional<T> post(final Object object, final String url, final Class<T> clazz); + + /** + * Execute the HTTP POST to the given URI template + * + * @param object the entity (i.e. body) to write to the request + * @param url the URL + * @param clazz the type of the return value + * @return Returns the {@link ResponseEntity}. + */ + public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz); + + +} 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 new file mode 100644 index 0000000000..032df84a98 --- /dev/null +++ b/common/src/main/java/org/onap/so/rest/service/HttpRestServiceProviderImpl.java @@ -0,0 +1,144 @@ +/*- + * ============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.service; + +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.rest.exceptions.InvalidRestRequestException; +import org.onap.so.rest.exceptions.RestProcessingException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpEntity; +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.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.google.common.base.Optional; + +/** + * A Service to perform HTTP requests + * + * @author waqas.ikram@est.tech + */ +public class HttpRestServiceProviderImpl implements HttpRestServiceProvider { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpRestServiceProviderImpl.class); + private final RestTemplate restTemplate; + private final HttpHeadersProvider httpHeadersProvider; + + public HttpRestServiceProviderImpl(final RestTemplate restTemplate) { + this.restTemplate = restTemplate; + this.httpHeadersProvider = new BasicHttpHeadersProvider(); + } + + public HttpRestServiceProviderImpl(final RestTemplate restTemplate, final HttpHeadersProvider httpHeadersProvider) { + this.restTemplate = restTemplate; + this.httpHeadersProvider = httpHeadersProvider; + } + + @Override + public <T> Optional<T> get(final String url, final Class<T> clazz) { + final ResponseEntity<T> response = getHttpResponse(url, clazz); + if (!response.getStatusCode().equals(HttpStatus.OK)) { + final String message = + "Unable to invoke HTTP GET using URL: " + url + ", Response Code: " + response.getStatusCode(); + LOGGER.error(message); + return Optional.absent(); + } + + if (response.hasBody()) { + return Optional.of(response.getBody()); + } + return Optional.absent(); + } + + + @Override + public <T> ResponseEntity<T> getHttpResponse(final String url, final Class<T> clazz) { + LOGGER.trace("Will invoke HTTP GET using URL: {}", url); + try { + final HttpEntity<?> request = new HttpEntity<>(getHttpHeaders()); + return restTemplate.exchange(url, HttpMethod.GET, request, clazz); + + } catch (final HttpClientErrorException httpClientErrorException) { + final String message = "Unable to invoke HTTP GET 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()) { + throw new InvalidRestRequestException("No result found for given url: " + url); + } + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url); + + } catch (final RestClientException restClientException) { + LOGGER.error("Unable to invoke HTTP GET using url: {}", url, restClientException); + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url, restClientException); + } + } + + @Override + public <T> Optional<T> post(final Object object, final String url, final Class<T> clazz) { + final ResponseEntity<T> response = postHttpRequest(object, url, clazz); + if (!response.getStatusCode().equals(HttpStatus.OK)) { + final String message = + "Unable to invoke HTTP GET using URL: " + url + ", Response Code: " + response.getStatusCode(); + LOGGER.error(message); + return Optional.absent(); + } + + if (response.hasBody()) { + return Optional.of(response.getBody()); + } + + return Optional.absent(); + } + + + @Override + public <T> ResponseEntity<T> postHttpRequest(final Object object, final String url, final Class<T> clazz) { + try { + final HttpEntity<?> request = new HttpEntity<>(object, getHttpHeaders()); + return restTemplate.exchange(url, HttpMethod.POST, request, clazz); + + } catch (final HttpClientErrorException httpClientErrorException) { + final String message = "Unable to invoke HTTP POST 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()) { + throw new InvalidRestRequestException("No result found for given url: " + url); + } + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url); + + } catch (final RestClientException restClientException) { + LOGGER.error("Unable to invoke HTTP POST using url: {}", url, restClientException); + throw new RestProcessingException("Unable to invoke HTTP GET using URL: " + url, restClientException); + } + } + + private HttpHeaders getHttpHeaders() { + return httpHeadersProvider.getHttpHeaders(); + } +} 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 a1097780c0..7d272e39c7 100644 --- a/common/src/main/java/org/onap/so/utils/CryptoUtils.java +++ b/common/src/main/java/org/onap/so/utils/CryptoUtils.java @@ -23,8 +23,8 @@ package org.onap.so.utils; +import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -92,7 +92,7 @@ public final class CryptoUtils { return CryptoUtils.encrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), - MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); + ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); return null; } } @@ -101,7 +101,7 @@ public final class CryptoUtils { return CryptoUtils.decrypt(message, CLOUD_KEY); } catch (GeneralSecurityException e) { logger.error("{} {} {}", MessageEnum.RA_GENERAL_EXCEPTION.toString(), - MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); + ErrorCode.BusinessProcesssError.getValue(), "Exception in encryptPassword ", e); return null; } } diff --git a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java index 864266bf40..4aeecf88d8 100644 --- a/common/src/main/java/org/onap/so/utils/XmlMarshaller.java +++ b/common/src/main/java/org/onap/so/utils/XmlMarshaller.java @@ -35,8 +35,8 @@ import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.onap.so.exceptions.MarshallerException; +import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; -import org.onap.so.logger.MsoLogger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; @@ -55,8 +55,8 @@ public class XmlMarshaller { jaxbMarshaller.marshal(object, stringWriter); } catch (JAXBException e) { logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), - MsoLogger.ErrorCode.SchemaError.getValue(), e.getMessage(), e); - throw new MarshallerException(e.getMessage(), MsoLogger.ErrorCode.SchemaError.getValue(), e); + ErrorCode.SchemaError.getValue(), e.getMessage(), e); + throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e); } return stringWriter.toString(); @@ -80,8 +80,8 @@ public class XmlMarshaller { object = jaxbUnmarshaller.unmarshal(source, object.getClass()).getValue(); } catch (Exception e) { logger.error("{} {} {}", MessageEnum.GENERAL_EXCEPTION.toString(), - MsoLogger.ErrorCode.SchemaError.getValue(), e.getMessage(), e); - throw new MarshallerException(e.getMessage(), MsoLogger.ErrorCode.SchemaError.getValue(), e); + ErrorCode.SchemaError.getValue(), e.getMessage(), e); + throw new MarshallerException(e.getMessage(), ErrorCode.SchemaError.getValue(), e); } return object; diff --git a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java index f32633122d..85d690feaf 100644 --- a/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java +++ b/common/src/test/java/org/onap/so/client/aai/AAIValidatorTest.java @@ -49,11 +49,25 @@ public class AAIValidatorTest { validator.setClient(client); } - public List<Pserver> getPservers(boolean locked){ - Pserver pserver = new Pserver(); - pserver.setInMaint(locked); + public List<Pserver> getPserversLocked(){ + Pserver pserver1 = new Pserver(); + pserver1.setInMaint(true); + Pserver pserver2 = new Pserver(); + pserver2.setInMaint(false); List<Pserver> pservers = new ArrayList<Pserver>(); - pservers.add(pserver); + pservers.add(pserver1); + pservers.add(pserver2); + return pservers; + } + + public List<Pserver> getPserversNotLocked(){ + Pserver pserver1 = new Pserver(); + pserver1.setInMaint(false); + Pserver pserver2 = new Pserver(); + pserver2.setInMaint(false); + List<Pserver> pservers = new ArrayList<Pserver>(); + pservers.add(pserver1); + pservers.add(pserver2); return pservers; } @@ -64,15 +78,15 @@ public class AAIValidatorTest { } @Test - public void test_IsPhysicalServerLocked_True() throws IOException{ - when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPservers(true)); + public void test_IsPhysicalServerLocked_True() throws IOException{ + when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversLocked()); boolean locked = validator.isPhysicalServerLocked(vnfName); assertEquals(true, locked); } @Test public void test_IsPhysicalServerLocked_False() throws IOException { - when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPservers(false)); + when(client.getPhysicalServerByVnfId(vnfName)).thenReturn(getPserversNotLocked()); boolean locked = validator.isPhysicalServerLocked(vnfName); assertEquals(false, locked); } diff --git a/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java b/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java index 135277fa47..f6bf21458d 100644 --- a/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java +++ b/common/src/test/java/org/onap/so/client/cds/CDSProcessingClientTest.java @@ -42,10 +42,10 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; -import org.onap.ccsdk.apps.controllerblueprints.common.api.ActionIdentifiers; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceInput; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.BluePrintProcessingServiceGrpc.BluePrintProcessingServiceImplBase; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; @RunWith(JUnit4.class) public class CDSProcessingClientTest { diff --git a/common/src/test/java/org/onap/so/client/cds/TestCDSProcessingListener.java b/common/src/test/java/org/onap/so/client/cds/TestCDSProcessingListener.java index 977f1d41be..ce515e162e 100644 --- a/common/src/test/java/org/onap/so/client/cds/TestCDSProcessingListener.java +++ b/common/src/test/java/org/onap/so/client/cds/TestCDSProcessingListener.java @@ -21,7 +21,7 @@ package org.onap.so.client.cds; import io.grpc.Status; -import org.onap.ccsdk.apps.controllerblueprints.processing.api.ExecutionServiceOutput; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java index 514c595100..636f92835f 100644 --- a/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java +++ b/common/src/test/java/org/onap/so/client/cds/TestCDSPropertiesImpl.java @@ -1,26 +1,20 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 Bell Canada. - * ================================================================================ +/* + * Copyright (C) 2019 Bell Canada. + * * 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.cds; -import java.net.MalformedURLException; import java.net.URL; public class TestCDSPropertiesImpl implements CDSProperties { @@ -68,4 +62,9 @@ public class TestCDSPropertiesImpl implements CDSProperties { public boolean mapNotFoundToEmpty() { return false; } + + @Override + public int getTimeout() { + return 60; + } } diff --git a/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java new file mode 100644 index 0000000000..3e762cfbe7 --- /dev/null +++ b/common/src/test/java/org/onap/so/configuration/rest/BasicHttpHeadersProviderTest.java @@ -0,0 +1,58 @@ +/*- + * ============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.configuration.rest; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.so.configuration.rest.BasicHttpHeadersProvider.AUTHORIZATION_HEADER; + +import java.util.Arrays; + +import org.junit.Test; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + + +/** + * @author waqas.ikram@est.tech + * + */ +public class BasicHttpHeadersProviderTest { + + private static final String BASIC_AUTH_VALUE = "Basic AuthValue"; + + @Test + public void test_getHttpHeaders_ContentTypeIsJson() { + final HttpHeadersProvider objUnderTest = new BasicHttpHeadersProvider(); + final HttpHeaders actualHttpHeaders = objUnderTest.getHttpHeaders(); + assertNull(actualHttpHeaders.get(AUTHORIZATION_HEADER)); + assertEquals(MediaType.APPLICATION_JSON, actualHttpHeaders.getContentType()); + } + + @Test + public void test_getHttpHeaders_ContainAuthorizationHeader() { + final HttpHeadersProvider objUnderTest = new BasicHttpHeadersProvider(BASIC_AUTH_VALUE); + final HttpHeaders actualHttpHeaders = objUnderTest.getHttpHeaders(); + assertEquals(Arrays.asList(BASIC_AUTH_VALUE), actualHttpHeaders.get(AUTHORIZATION_HEADER)); + assertEquals(MediaType.APPLICATION_JSON, actualHttpHeaders.getContentType()); + } + +} diff --git a/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java new file mode 100644 index 0000000000..5084acc934 --- /dev/null +++ b/common/src/test/java/org/onap/so/configuration/rest/HttpComponentsClientConfigurationTest.java @@ -0,0 +1,45 @@ +/*- + * ============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.configuration.rest; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +/** + * @author waqas.ikram@est.tech + */ +public class HttpComponentsClientConfigurationTest { + + @Test + public void test_httpComponentsClientHttpRequestFactory_HttpComponentsClientHttpRequestFactoryNotNull() { + final HttpClientConnectionConfiguration clientConnectionConfiguration = new HttpClientConnectionConfiguration(); + final HttpComponentsClientConfiguration objUnderTest = + new HttpComponentsClientConfiguration(clientConnectionConfiguration); + + final HttpComponentsClientHttpRequestFactory factory = objUnderTest.httpComponentsClientHttpRequestFactory(); + assertNotNull(factory); + assertNotNull(factory.getHttpClient()); + + } + +} 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 new file mode 100644 index 0000000000..a738afe565 --- /dev/null +++ b/common/src/test/java/org/onap/so/rest/service/HttpRestServiceProviderImplTest.java @@ -0,0 +1,252 @@ +/*- + * ============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.service; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.Test; +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.RestProcessingException; +import org.springframework.http.HttpEntity; +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.RestClientException; +import org.springframework.web.client.RestTemplate; + +import com.google.common.base.Optional; + + +/** + * @author waqas.ikram@est.tech + */ +@RunWith(MockitoJUnitRunner.class) +public class HttpRestServiceProviderImplTest { + + private static final String BODY = "{}"; + private static final String DUMMY_URL = "http://localhost:9000/dummy/url"; + + @Mock + private RestTemplate mockRestTemplate; + + @Mock + private ResponseEntity<String> mockEntity; + + @Test + public void test_get_returnOptionalPresentIfResponseIsOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(true); + when(mockEntity.getBody()).thenReturn(BODY); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertTrue(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_get_returnOptionalPresentIfResponseIsNotOK() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_get_returnOptionalPresentIfResponseIsOKAndNoBody() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(false); + + final Optional<String> actual = objUnderTest.get(DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), + eq(String.class)); + } + + @Test(expected = InvalidRestRequestException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusBadRequest() { + assertGetErrorScenario(HttpStatus.BAD_REQUEST); + + } + + @Test(expected = InvalidRestRequestException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() { + assertGetErrorScenario(HttpStatus.NOT_FOUND); + } + + @Test(expected = RestProcessingException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(HttpClientErrorException.class); + + objUnderTest.get(DUMMY_URL, String.class); + } + + @Test(expected = RestProcessingException.class) + public void test_get_ThrowsInvalidRestRequestExceptionifRestProcessingExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(RestClientException.class); + + objUnderTest.get(DUMMY_URL, String.class); + } + + @Test + public void test_post_returnOptionalPresentIfResponseIsOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(true); + when(mockEntity.getBody()).thenReturn(BODY); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertTrue(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + @Test + public void test_post_returnOptionalPresentIfResponseIsOKAndHasNoBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.OK); + when(mockEntity.hasBody()).thenReturn(false); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + + @Test + public void test_post_returnOptionalPresentIfResponseIsNotOKAndHasBody() { + + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenReturn(mockEntity); + + when(mockEntity.getStatusCode()).thenReturn(HttpStatus.PARTIAL_CONTENT); + + final Optional<String> actual = objUnderTest.post(BODY, DUMMY_URL, String.class); + + assertFalse(actual.isPresent()); + verify(mockRestTemplate, atLeastOnce()).exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), + eq(String.class)); + } + + @Test(expected = InvalidRestRequestException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusBadRequest() { + assertPostErrorScenario(HttpStatus.BAD_REQUEST); + + } + + @Test(expected = InvalidRestRequestException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionWithHttpStatusNotFoundHttpStatus() { + assertPostErrorScenario(HttpStatus.NOT_FOUND); + } + + @Test(expected = RestProcessingException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifHttpClientErrorExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(HttpClientErrorException.class); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + @Test(expected = RestProcessingException.class) + public void test_post_ThrowsInvalidRestRequestExceptionifRestProcessingExceptionOccured() { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(RestClientException.class); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + private void assertPostErrorScenario(final HttpStatus status) { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + final HttpClientErrorException errorException = new HttpClientErrorException(status); + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) + .thenThrow(errorException); + + objUnderTest.post(BODY, DUMMY_URL, String.class); + } + + private void assertGetErrorScenario(final HttpStatus status) { + final HttpRestServiceProvider objUnderTest = new HttpRestServiceProviderImpl(mockRestTemplate); + + final HttpClientErrorException errorException = new HttpClientErrorException(status); + when(mockRestTemplate.exchange(eq(DUMMY_URL), eq(HttpMethod.GET), any(HttpEntity.class), eq(String.class))) + .thenThrow(errorException); + + objUnderTest.get(DUMMY_URL, String.class); + } + +} |