aboutsummaryrefslogtreecommitdiffstats
path: root/common/src
diff options
context:
space:
mode:
authorBenjamin, Max (mb388a) <mb388a@us.att.com>2018-11-05 11:00:36 -0500
committerBenjamin, Max (mb388a) <mb388a@us.att.com>2018-11-05 17:03:14 -0500
commit61affc6311906aee71b16ee8632c1e7468cd1990 (patch)
tree5dec424176ff959080cc7f801c6d4cb0c60ca949 /common/src
parent6fa3d2b80d2384b830e3231fe69a8daf7884a35e (diff)
Catchup commits for Dublin
added property for retry timer multiplier for testing Infra APIH table, fixed test assertNull condition. Infra APIH table, added tests for request-url = null. Infra APIH should write request_url to infra_active_requests. Return SelfLink URL on ServiceInstantiation SyncResponse. Added JUNITS. Added helper method to get AAI ResourceUri to faciliate unit test. Fixed code to correctly extract related generic vnf or vce id. updated unit test coverage for update network Handle REST NotFoundException for serviceInstance nodes query. Process should continue for new order request and throw exception only for SUPP request. Added disconnect functionality to the gw vnf test tool. Added conversion of vnf management option to dhv change speed sync subnet status with network update updated macroData vol assigned delete continue script Correct the name of DeleteVfModuleBB subprocess. fix the custom resolver to not convert int in string to int Write the returned value from Homing to gBBInput Use explicit conversion to JSON to read cloudConfiguration settings. added property for retry timer multiplier for testing avoid storing AAI yang models in execution added handlingCode to rollback test in workflowactionbb passed in alacarte flag to execute layer for rainy day added test cases for RollbackToAssigned rainy day hand added rollback to assign in catalog db rainy day hand Updated vnf adapter delete stubs to be a post for test. Added a javadoc to basic auth override method Added a check to not add blank headers to the headerMap in httpClient. Added check for if entity exist before calling readEntity. Fixed failing junits and updated way the body is obtained Added missing import statement for http client. Fixed mistakes and made updates caught during review. Removed post and httpPost methods from RESTClient and refactored references Refactored multiple http post references to use httpClient instead. Removed close connection method and randomized port in unit test Added http client unit test, coverage is currently at 90 percent Resolve conflict in sdnc adapter reste v1 method Began removing http delete and delete methods from RESTClient and aaiUtil. Removed http put method and executeput method, refactored references. fixed broken tests in the branch in jenkins build Fix Springboot 2.0 start up issues, and other issues added in implementation to generate self link if there isnt one removed dbcp2 from poms that still had them added rollbackstatusmessage to stub in testprocess added rollback_status_message to the schema sql file Added variable for rollbackStatusMessage Added rollbackStatusMessage to get response added rollback status message to archived infra request set rollback status message to successful on boolean added logic to split rollback and regular error message added rollback status message to infra active requests pushing the cloud config changes as well Added media type and fixed cast plural issue. Made various updated and fixes to code that was changed. Removed all no longer used RESTClient imports from classes Removed and refactored references for aaiUtil methods and all remaining RESTClient methods, removed RESTClient project and updated poms. Return canonical stack id on multicloud create Fix OOF Config Ingestion Fix variable to retrieve sdnc endpoint Prepare resources for service uuid req Fix swapped parameters for multicloud DELETE Update msb-java-sdk to resolve license issues cloud owner support for SDNC interface correlationId is now read from userParams Fix up request body of multicloud adapter body removed LinkedHashMap<?,?> from java classes Cut over logging project to release not snapshot Update unit tests, revert test code, fix comments Fix remaining number of Unit Tests, on avpn flow Fix JUNITS add callback url, fix BPMN issues Update SDNC interaction to support a-sync updated bpm assert import and corrected tests updated test case to be mockito 2 compliant additional changes to import statements and tests Change the place where the data for multistage gets set Update treatment of PENDING_ACTIVATION VF_MODULE CREATE entries to SILENT_SUCCESS to support first stage of multistage. Implement second stage of multistage design VF Module Creation removed LinkedHashMap<?,?> from java classes Removed SNAPSHOT from dependency Cut over logging project to release not snapshot Fixed failing BBInputSetup tests Update unit tests, revert test code, fix comments Updated apih tests to use networkInstanceGroup Updated ModelType enum and fixed compilation issues Fix remaining number of Unit Tests, on avpn flow Fix JUNITS add callback url, fix BPMN issues Implementation of the first stage of multistage design for VF Module creation. Update SDNC interaction to support a-sync no longer leave modified files after test runs Remove generated CSAR, that occurs during JUNIT Update Camunda Pods to use Flyway Migration in 1902 Updated hashcode method and removed comment. Added aggregate routes to the sdnw request and updated pom sdnw dependency. Began to set aggreagate route information for vrf configuration. modified remaining files with att-aic references Correct rollbackData setting and protect against potential null objects. correct AAIObjectPlurals enum value name Update POJO to use type URL for selfLink. Optional<URL> - construct SelfLink Url format. Construct SelfLink Url format from full Url. added missing properties to application-test.yaml fixed compliation error after merge of unit test restored files which should not have been deleted Fix SO vulnerabilities with cxf Fixing bpmn infra endpoint in so-monitoring yaml removed att-aic from codebase default cloud owner now configurable Set homingService in WorkflowAction Fix Java Ex in Homing Version should be 1.3.1 to release new dockers Pnf Spring Environment correction test property now has dynamic wiremock port removed test specific wiremock rule that was causing problems re-enabled and corrected integration tests for so-bpmn-tasks Test to get sniro homing v2 test working by splitting test suites for each spring application Reverted changes to old migration scripts.. Fixed spring context issue with test HomingV2. Removed unused import to fix compilation errors Fixed onap changes to homing, migrated homingV2 to homingBB, fixed broken junits again. - Updated isUseHttpsWithDmaapTest to check assertTrue rather than assertFalse. - Upgraded code to make the isUseHttpsWithDmaap configurable. It will default to true if no value is found in the config file. moved workflowaction test class to the test section added status message update for retry and rollback beefed up error message debug logging and req db msg added debug lines to workflowactionbbtasks reqdbcall Issue-ID: SO-1187 Change-Id: Iec1aff4ed30a43c0e0b2cdb06c28d8db8a99a830 Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'common/src')
-rw-r--r--common/src/main/java/org/onap/so/client/HttpClient.java39
-rw-r--r--common/src/main/java/org/onap/so/client/RestClient.java46
-rw-r--r--common/src/main/java/org/onap/so/client/aai/AAIObjectType.java2
-rw-r--r--common/src/main/java/org/onap/so/constants/Defaults.java2
-rw-r--r--common/src/main/java/org/onap/so/logger/LogConstants.java1
-rw-r--r--common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java12
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java12
-rw-r--r--common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java10
-rw-r--r--common/src/main/java/org/onap/so/utils/TargetEntity.java12
-rw-r--r--common/src/test/java/org/onap/so/client/HttpClientTest.java107
10 files changed, 207 insertions, 36 deletions
diff --git a/common/src/main/java/org/onap/so/client/HttpClient.java b/common/src/main/java/org/onap/so/client/HttpClient.java
index ad13745919..12f19ac607 100644
--- a/common/src/main/java/org/onap/so/client/HttpClient.java
+++ b/common/src/main/java/org/onap/so/client/HttpClient.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,10 +24,15 @@ import java.net.URL;
import java.util.Map;
import java.util.Optional;
+import static org.apache.commons.lang3.StringUtils.*;
+
import org.onap.so.utils.TargetEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HttpClient extends RestClient {
+ protected final Logger log = LoggerFactory.getLogger(HttpClient.class);
private TargetEntity targetEntity;
public HttpClient(URL host, String contentType, TargetEntity targetEntity) {
super(host, contentType);
@@ -50,4 +55,34 @@ public class HttpClient extends RestClient {
return Optional.empty();
}
+ /**
+ * Adds a basic authentication header to the request.
+ * @param auth the encrypted credentials
+ * @param key the key for decrypting the credentials
+ */
+ @Override
+ public void addBasicAuthHeader(String auth, String key) {
+ if(isNotBlank(auth) && isNotBlank(key)){
+ super.addBasicAuthHeader(auth, key);
+ }else{
+ log.warn("Not adding basic auth to headers.");
+ }
+ }
+
+ /**
+ * Adds an additional header to the header map
+ * @param encoded basic auth value
+ */
+ public void addAdditionalHeader(String name, String value) {
+ try {
+ if(isNotBlank(name) && isNotBlank(value)){
+ headerMap.put(name, value);
+ }else{
+ log.warn("Not adding " + name + " to headers.");
+ }
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ }
+ }
+
}
diff --git a/common/src/main/java/org/onap/so/client/RestClient.java b/common/src/main/java/org/onap/so/client/RestClient.java
index 1a453c6b2f..76134a42f4 100644
--- a/common/src/main/java/org/onap/so/client/RestClient.java
+++ b/common/src/main/java/org/onap/so/client/RestClient.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -61,7 +61,7 @@ public abstract class RestClient {
private static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
public static final String ECOMP_COMPONENT_NAME = "MSO";
-
+
private static final int MAX_PAYLOAD_SIZE = 1024 * 1024;
private WebTarget webTarget;
@@ -76,12 +76,12 @@ public abstract class RestClient {
protected RestProperties props;
protected RestClient(RestProperties props, Optional<URI> path) {
-
+
headerMap = new HashMap<>();
try {
host = props.getEndpoint();
} catch (MalformedURLException e) {
-
+
throw new RuntimeException(e);
}
this.props = props;
@@ -105,23 +105,23 @@ public abstract class RestClient {
/**
* Override method to return false to disable logging.
- *
+ *
* @return true - to enable logging, false otherwise
*/
protected boolean enableLogging() {
return true;
}
-
+
/**
* Override method to return custom value for max payload size.
- *
+ *
* @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024
*/
protected int getMaxPayloadSize()
{
return MAX_PAYLOAD_SIZE;
}
-
+
protected Builder getBuilder() {
if (webTarget == null) {
@@ -134,7 +134,7 @@ public abstract class RestClient {
}
return builder;
}
-
+
protected WebTarget getWebTarget() {
return this.webTarget;
}
@@ -148,7 +148,7 @@ public abstract class RestClient {
protected CommonObjectMapperProvider getCommonObjectMapperProvider() {
return new CommonObjectMapperProvider();
}
-
+
/**
* Adds a basic authentication header to the request.
* @param auth the encrypted credentials
@@ -188,7 +188,7 @@ public abstract class RestClient {
}
CommonObjectMapperProvider provider = this.getCommonObjectMapperProvider();
client.register(new JacksonJsonProvider(provider.getMapper()));
-
+
jaxRsClientLogging = new JaxRsClientLogging();
jaxRsClientLogging.setTargetService(getTargetEntity());
client.register(jaxRsClientLogging);
@@ -205,11 +205,11 @@ public abstract class RestClient {
this.contentType = MediaType.APPLICATION_JSON;
}
}
-
+
protected List<Predicate<Throwable>> retryOn() {
-
+
List<Predicate<Throwable>> result = new ArrayList<>();
-
+
result.add(e -> {
return e.getCause() instanceof SocketTimeoutException;
});
@@ -266,26 +266,26 @@ public abstract class RestClient {
public <T> T delete(Class<T> resultClass) {
return format(method("DELETE", null), resultClass).orElse(null);
}
-
+
public <T> T delete(Object obj, Class<T> resultClass) {
return format(method("DELETE", obj), resultClass).orElse(null);
}
-
+
public Response method(String method, Object entity) {
RetryPolicy policy = new RetryPolicy();
-
+
List<Predicate<Throwable>> items = retryOn();
-
+
Predicate<Throwable> pred = items.stream().reduce(Predicate::or).orElse(x -> false);
policy.retryOn(error -> pred.test(error));
-
+
policy.withDelay(this.props.getDelayBetweenRetries(), TimeUnit.MILLISECONDS)
.withMaxRetries(this.props.getRetries());
-
+
return Failsafe.with(policy).get(buildRequest(method, entity));
}
-
+
protected RestRequest buildRequest(String method, Object entity) {
return new RestRequest(this, method, entity);
}
@@ -295,7 +295,7 @@ public abstract class RestClient {
}
return Optional.of(response.readEntity(resultClass));
}
-
+
private <T> Optional<T> format(Response response, GenericType<T> resultClass) {
if (this.props.mapNotFoundToEmpty() && response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
return Optional.empty();
diff --git a/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java b/common/src/main/java/org/onap/so/client/aai/AAIObjectType.java
index 0e50818f0f..fbc2801e5e 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
@@ -49,6 +49,7 @@ import org.onap.aai.domain.yang.Pserver;
import org.onap.aai.domain.yang.RouteTableReferences;
import org.onap.aai.domain.yang.ServiceInstance;
import org.onap.aai.domain.yang.ServiceSubscription;
+import org.onap.aai.domain.yang.SpPartner;
import org.onap.aai.domain.yang.Subnet;
import org.onap.aai.domain.yang.Tenant;
import org.onap.aai.domain.yang.TunnelXconnect;
@@ -108,6 +109,7 @@ public enum AAIObjectType implements GraphInventoryObjectType {
CONNECTOR(AAINamespaceConstants.BUSINESS, Connector.class),
NETWORK_TECHNOLOGY(AAINamespaceConstants.CLOUD_INFRASTRUCTURE, NetworkTechnology.class),
SUBNET(AAIObjectType.L3_NETWORK.uriTemplate(), Subnet.class),
+ SP_PARTNER(AAINamespaceConstants.BUSINESS, SpPartner.class),
EXT_AAI_NETWORK(AAINamespaceConstants.NETWORK, ExtAaiNetwork.class),
UNKNOWN("", "");
diff --git a/common/src/main/java/org/onap/so/constants/Defaults.java b/common/src/main/java/org/onap/so/constants/Defaults.java
index 0dc084a899..5117f4de95 100644
--- a/common/src/main/java/org/onap/so/constants/Defaults.java
+++ b/common/src/main/java/org/onap/so/constants/Defaults.java
@@ -51,4 +51,4 @@ public enum Defaults {
protected Optional<ApplicationContext> getAppContext() {
return Optional.ofNullable(SpringContextHelper.getAppContext());
}
-} \ No newline at end of file
+}
diff --git a/common/src/main/java/org/onap/so/logger/LogConstants.java b/common/src/main/java/org/onap/so/logger/LogConstants.java
index ea3c8e2c4a..2639adf304 100644
--- a/common/src/main/java/org/onap/so/logger/LogConstants.java
+++ b/common/src/main/java/org/onap/so/logger/LogConstants.java
@@ -23,4 +23,5 @@ package org.onap.so.logger;
public class LogConstants {
public static final String TARGET_ENTITY_HEADER="X-Target-Entity";
public static final String UNKNOWN_TARGET_ENTITY="Unknown-Target-Entity";
+ public static final String HTTP_URL="Http-Url";
}
diff --git a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
index 4084ad3ff0..eeb8593725 100644
--- a/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
+++ b/common/src/main/java/org/onap/so/logging/spring/interceptor/LoggingInterceptor.java
@@ -30,6 +30,7 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Providers;
import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import org.onap.so.logger.LogConstants;
import org.onap.so.logging.jaxrs.filter.MDCSetup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -60,6 +61,7 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter {
setRequestId(headers);
setInvocationId(headers);
setServiceName(request);
+ setHttpUrl(request);
setMDCPartnerName(headers);
mdcSetup.setClientIPAddress(request);
mdcSetup.setEntryTimeStamp();
@@ -109,7 +111,15 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter {
protected void setServiceName(HttpServletRequest request) {
MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
}
-
+
+ protected void setHttpUrl(HttpServletRequest request) {
+ String queryParams = "";
+ if (request.getQueryString() != null) {
+ queryParams = "?" + request.getQueryString();
+ }
+ MDC.put(LogConstants.HTTP_URL, request.getRequestURL() + queryParams);
+ }
+
protected void setRequestId(Map<String, String> headers) {
String requestId=headers.get(ONAPLogConstants.Headers.REQUEST_ID.toLowerCase());
if(requestId == null || requestId.isEmpty())
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
index c30e39a028..088e414094 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestReferences.java
@@ -20,6 +20,8 @@
package org.onap.so.serviceinstancebeans;
+import java.net.URL;
+
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -32,7 +34,7 @@ public class RequestReferences {
String requestId;
String instanceId;
-
+ URL requestSelfLink;
public String getRequestId() {
return requestId;
@@ -46,9 +48,15 @@ public class RequestReferences {
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
+ public URL getRequestSelfLink() {
+ return requestSelfLink;
+ }
+ public void setRequestSelfLink(URL requestSelfLink) {
+ this.requestSelfLink = requestSelfLink;
+ }
@Override
public String toString() {
- return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId).toString();
+ return new ToStringBuilder(this).append("requestId", requestId).append("instanceId", instanceId).append("requestSelfLink", requestSelfLink).toString();
}
diff --git a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
index 527aa037ed..9619a943cd 100644
--- a/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
+++ b/common/src/main/java/org/onap/so/serviceinstancebeans/RequestStatus.java
@@ -29,6 +29,7 @@ public class RequestStatus {
protected String requestState;
protected String statusMessage;
+ protected String rollbackStatusMessage;
protected Integer percentProgress;
protected String finishTime;
@@ -45,6 +46,12 @@ public class RequestStatus {
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
+ public String getRollbackStatusMessage() {
+ return rollbackStatusMessage;
+ }
+ public void setRollbackStatusMessage(String rollbackStatusMessage) {
+ this.rollbackStatusMessage = rollbackStatusMessage;
+ }
public Integer getPercentProgress() {
return percentProgress;
}
@@ -60,6 +67,7 @@ public class RequestStatus {
@Override
public String toString() {
return new ToStringBuilder(this).append("requestState", requestState).append("statusMessage", statusMessage)
- .append("percentProgress", percentProgress).append("finishTime", finishTime).toString();
+ .append("rollbackStatusMessage", rollbackStatusMessage).append("percentProgress", percentProgress)
+ .append("finishTime", finishTime).toString();
}
}
diff --git a/common/src/main/java/org/onap/so/utils/TargetEntity.java b/common/src/main/java/org/onap/so/utils/TargetEntity.java
index 4d48d349b5..a4480f2d95 100644
--- a/common/src/main/java/org/onap/so/utils/TargetEntity.java
+++ b/common/src/main/java/org/onap/so/utils/TargetEntity.java
@@ -7,9 +7,9 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,14 +24,14 @@ import java.util.EnumSet;
public enum TargetEntity {
OPENSTACK_ADAPTER, BPMN, GRM ,AAI, DMAAP, POLICY, CATALOG_DB, REQUEST_DB,
- VNF_ADAPTER, SDNC_ADAPTER, NARAD, MULTICLOUD;
+ VNF_ADAPTER, SDNC_ADAPTER, SNIRO, SDC, EXTERNAL, MULTICLOUD;
private static final String PREFIX = "SO";
-
+
public static EnumSet<TargetEntity> getSOInternalComponents() {
return EnumSet.of(OPENSTACK_ADAPTER, BPMN,CATALOG_DB,REQUEST_DB,VNF_ADAPTER,SDNC_ADAPTER);
}
-
+
@Override
public String toString(){
if(getSOInternalComponents().contains(this))
@@ -39,4 +39,4 @@ public enum TargetEntity {
else
return this.name();
}
-} \ No newline at end of file
+}
diff --git a/common/src/test/java/org/onap/so/client/HttpClientTest.java b/common/src/test/java/org/onap/so/client/HttpClientTest.java
new file mode 100644
index 0000000000..221005cb7c
--- /dev/null
+++ b/common/src/test/java/org/onap/so/client/HttpClientTest.java
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP - SO
+ * ================================================================================
+ * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.so.client;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
+import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.exactly;
+import static com.github.tomakehurst.wiremock.client.WireMock.post;
+import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
+import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
+import static com.github.tomakehurst.wiremock.client.WireMock.verify;
+import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.onap.so.utils.TargetEntity;
+
+import com.github.tomakehurst.wiremock.junit.WireMockRule;
+
+public class HttpClientTest{
+
+
+ @Rule
+ public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicHttpsPort());
+
+ @Test(expected = Test.None.class)
+ public void testPost_success() throws MalformedURLException{
+
+ stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody("")));
+
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = new HttpClient(url, "application/json", TargetEntity.BPMN);
+
+ client.addBasicAuthHeader("97FF88AB352DA16E00DDD81E3876431DEF8744465DACA489EB3B3BE1F10F63EDA1715E626D0A4827A3E19CD88421BF", "123");
+ client.addAdditionalHeader("Accept", "application/json");
+
+ client.post("{}");
+
+ verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post")));
+ }
+
+ @Test(expected = Test.None.class)
+ public void testPost_nullHeader() throws MalformedURLException{
+
+ stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody("")));
+
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = new HttpClient(url, "application/json", TargetEntity.BPMN);
+
+ client.addAdditionalHeader("Accept", "application/json");
+ client.addAdditionalHeader("id", null);
+
+ client.post("{}");
+
+ verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post"))
+ .withHeader("Accept", equalTo("application/json")));
+ }
+
+ @Test(expected = Test.None.class)
+ public void testPost_nullBasicAuth() throws MalformedURLException{
+
+ stubFor(post(urlEqualTo("/services/sdnc/post"))
+ .willReturn(aResponse().withStatus(200)
+ .withHeader("Content-Type", "application/json")
+ .withBody("")));
+
+ URL url = new URL("http://localhost:" + wireMockConfig().portNumber() + "/services/sdnc/post");
+ HttpClient client = new HttpClient(url, "application/json", TargetEntity.BPMN);
+
+ client.addBasicAuthHeader("", "12345");
+ client.addAdditionalHeader("Accept", "application/json");
+
+ client.post("{}");
+
+ verify(exactly(1), postRequestedFor(urlEqualTo("/services/sdnc/post"))
+ .withHeader("Accept", equalTo("application/json")));
+ }
+
+}