diff options
author | Determe, Sebastien (sd378r) <sd378r@intl.att.com> | 2017-11-05 20:46:52 +0100 |
---|---|---|
committer | Determe, Sebastien (sd378r) <sd378r@intl.att.com> | 2017-11-05 20:46:52 +0100 |
commit | 81305e6875977b25afd6320c6870c41fb65e040a (patch) | |
tree | 6d3aceae500db6d27b9a29e2caf353921a2e701a | |
parent | da4caf492050e17c1aaa8915064659a16e060d8d (diff) |
Fix DCAE connection issue
Code has been added to support http/https protocols for DCAE
Change-Id: Ib1259310b801a19cacd08c22292509156624ac9b
Issue-ID: CLAMP-65
Signed-off-by: Determe, Sebastien (sd378r) <sd378r@intl.att.com>
5 files changed, 356 insertions, 248 deletions
@@ -468,6 +468,11 @@ </exclusions> </dependency> <dependency> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + <version>2.6.3</version> + </dependency> + <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.6.3</version> diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java index f285dc27c..51e4abcb3 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -27,17 +27,7 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.node.ObjectNode;
-import java.io.BufferedReader;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URL;
import java.util.Date;
-import java.util.stream.Collectors;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.ws.rs.BadRequestException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@@ -52,11 +42,16 @@ import org.springframework.beans.factory.annotation.Autowired; *
*/
public class DcaeDispatcherServices {
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);
- protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
-
+ protected static final EELFLogger logger = EELFManager.getInstance()
+ .getLogger(DcaeDispatcherServices.class);
+ protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
@Autowired
private RefProp refProp;
+ private static final String STATUS_URL_LOG = "Status URL extracted: ";
+ private static final String DCAE_URL_PREFIX = "/dcae-deployments/";
+ private static final String DCAE_URL_PROPERTY_NAME = "DCAE_DISPATCHER_URL";
+ private static final String DCAE_LINK_FIELD = "links";
+ private static final String DCAE_STATUS_FIELD = "status";
/**
* Delete the deployment on DCAE.
@@ -64,74 +59,27 @@ public class DcaeDispatcherServices { * @param deploymentId
* The deployment ID
* @return Return the URL Status
- * @throws IOException
- * In case of issues with the Stream
*/
- public String deleteDeployment(String deploymentId) throws IOException {
-
- String statusUrl = null;
- InputStream in = null;
+ public String deleteDeployment(String deploymentId) {
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "deleteDeployment");
try {
- String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;
- logger.info("Dcae Dispatcher url - " + url);
- URL obj = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
- conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
- conn.setRequestMethod("DELETE");
- int responseCode = conn.getResponseCode();
-
- boolean requestFailed = true;
- logger.info("responseCode=" + responseCode);
- if (responseCode == 200 || responseCode == 202) {
- requestFailed = false;
- }
-
- InputStream inStream = conn.getErrorStream();
- if (inStream == null) {
- inStream = conn.getInputStream();
- }
-
- String responseStr = null;
- if (inStream != null) {
- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream));
- String inputLine = null;
- StringBuilder response = new StringBuilder();
- while ((inputLine = bufferedReader.readLine()) != null) {
- response.append(inputLine);
- }
- responseStr = response.toString();
- }
-
- if (responseStr != null && requestFailed) {
- logger.error("requestFailed - responseStr=" + responseStr);
- throw new BadRequestException(responseStr);
- }
-
- logger.debug("response code " + responseCode);
- in = conn.getInputStream();
- logger.debug("res:" + responseStr);
+ String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", null, null);
JSONParser parser = new JSONParser();
Object obj0 = parser.parse(responseStr);
JSONObject jsonObj = (JSONObject) obj0;
- JSONObject linksObj = (JSONObject) jsonObj.get("links");
- statusUrl = (String) linksObj.get("status");
- logger.debug("Status URL: " + statusUrl);
-
+ JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);
+ String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);
+ logger.info(STATUS_URL_LOG + statusUrl);
+ return statusUrl;
} catch (Exception e) {
logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);
throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);
} finally {
- if (in != null) {
- in.close();
- }
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("deleteDeployment complete");
}
-
- return statusUrl;
-
}
/**
@@ -140,43 +88,25 @@ public class DcaeDispatcherServices { * @param statusUrl
* The URL provided by a previous DCAE Query
* @return The status
- * @throws IOException
- * In case of issues with the Stream
*
*/
- public String getOperationStatus(String statusUrl) throws IOException {
-
+ public String getOperationStatus(String statusUrl) {
// Assigning processing status to monitor operation status further
String opStatus = "processing";
- InputStream in = null;
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "getOperationStatus");
try {
- URL obj = new URL(statusUrl);
- HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
- conn.setRequestMethod("GET");
- conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
- int responseCode = conn.getResponseCode();
- logger.debug("Deployment operation status response code - " + responseCode);
- if (responseCode == 200) {
- in = conn.getInputStream();
- String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
- JSONParser parser = new JSONParser();
- Object obj0 = parser.parse(res);
- JSONObject jsonObj = (JSONObject) obj0;
- String operationType = (String) jsonObj.get("operationType");
- String status = (String) jsonObj.get("status");
- logger.debug("Operation Type - " + operationType + ", Status " + status);
- opStatus = status;
- }
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);
+ JSONParser parser = new JSONParser();
+ Object obj0 = parser.parse(responseStr);
+ JSONObject jsonObj = (JSONObject) obj0;
+ String operationType = (String) jsonObj.get("operationType");
+ String status = (String) jsonObj.get("status");
+ logger.info("Operation Type - " + operationType + ", Status " + status);
+ opStatus = status;
} catch (Exception e) {
logger.error("Exception occurred during getOperationStatus Operation with DCAE", e);
- logger.debug(e.getMessage()
- + " : got exception while retrieving status, trying again until we get 200 response code");
} finally {
- if (in != null) {
- in.close();
- }
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("getOperationStatus complete");
}
@@ -186,32 +116,17 @@ public class DcaeDispatcherServices { /**
* This method send a getDeployments operation to DCAE.
*
- * @throws IOException
- * In case of issues with the Stream
*/
- public void getDeployments() throws IOException {
- InputStream in = null;
+ public void getDeployments() {
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "getDeployments");
try {
- String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments";
- logger.info("Dcae Dispatcher deployments url - " + url);
- URL obj = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
- conn.setRequestMethod("GET");
- conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
- int responseCode = conn.getResponseCode();
- logger.debug("response code " + responseCode);
- in = conn.getInputStream();
- String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
- logger.debug("res:" + res);
+ String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX;
+ DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);
} catch (Exception e) {
logger.error("Exception occurred during getDeployments Operation with DCAE", e);
throw new DcaeDeploymentException("Exception occurred during getDeployments Operation with DCAE", e);
} finally {
- if (in != null) {
- in.close();
- }
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("getDeployments complete");
}
@@ -225,88 +140,32 @@ public class DcaeDispatcherServices { * @param serviceTypeId
* Service type ID
* @return The status URL
- * @throws IOException
- * In case of issues with the Stream
*/
- public String createNewDeployment(String deploymentId, String serviceTypeId) throws IOException {
-
- String statusUrl = null;
- InputStream inStream = null;
- BufferedReader in = null;
+ public String createNewDeployment(String deploymentId, String serviceTypeId) {
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "createNewDeployment");
try {
ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.deployment.template");
- ((ObjectNode) rootNode).put("serviceTypeId", serviceTypeId);
+ rootNode.put("serviceTypeId", serviceTypeId);
String apiBodyString = rootNode.toString();
-
logger.info("Dcae api Body String - " + apiBodyString);
- String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;
- logger.info("Dcae Dispatcher Service url - " + url);
- URL obj = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
- conn.setRequestMethod("PUT");
- conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
- conn.setRequestProperty("Content-Type", "application/json");
- conn.setDoOutput(true);
- try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
- wr.writeBytes(apiBodyString);
- wr.flush();
- }
-
- boolean requestFailed = true;
- int responseCode = conn.getResponseCode();
- logger.info("responseCode=" + responseCode);
- if (responseCode == 200 || responseCode == 202) {
- requestFailed = false;
- }
-
- inStream = conn.getErrorStream();
- if (inStream == null) {
- inStream = conn.getInputStream();
- }
-
- String responseStr = null;
- if (inStream != null) {
- in = new BufferedReader(new InputStreamReader(inStream));
-
- String inputLine = null;
-
- StringBuilder response = new StringBuilder();
-
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
-
- responseStr = response.toString();
- }
-
- if (responseStr != null && requestFailed) {
- logger.error("requestFailed - responseStr=" + responseStr);
- throw new BadRequestException(responseStr);
- }
-
- logger.debug("response code " + responseCode);
+ String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "PUT", apiBodyString,
+ "application/json");
JSONParser parser = new JSONParser();
Object obj0 = parser.parse(responseStr);
JSONObject jsonObj = (JSONObject) obj0;
- JSONObject linksObj = (JSONObject) jsonObj.get("links");
- statusUrl = (String) linksObj.get("status");
- logger.debug("Status URL: " + statusUrl);
+ JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);
+ String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);
+ logger.info(STATUS_URL_LOG + statusUrl);
+ return statusUrl;
} catch (Exception e) {
logger.error("Exception occurred during createNewDeployment Operation with DCAE", e);
throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e);
} finally {
- if (inStream != null) {
- inStream.close();
- }
- if (in != null) {
- in.close();
- }
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("createNewDeployment complete");
}
- return statusUrl;
}
/**
@@ -317,53 +176,30 @@ public class DcaeDispatcherServices { * @param serviceTypeId
* The service Type ID
* @return The status URL
- * @throws IOException
- * In case of issues with the Stream
*/
- public String deleteExistingDeployment(String deploymentId, String serviceTypeId) throws IOException {
-
- String statusUrl = null;
- InputStream in = null;
+ public String deleteExistingDeployment(String deploymentId, String serviceTypeId) {
Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment");
try {
String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}";
- logger.debug(apiBodyString);
- String url = refProp.getStringValue("DCAE_DISPATCHER_URL") + "/dcae-deployments/" + deploymentId;
- logger.info("Dcae Dispatcher deployments url - " + url);
- URL obj = new URL(url);
- HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
- conn.setRequestMethod("DELETE");
- conn.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId());
- conn.setRequestProperty("Content-Type", "application/json");
- conn.setDoOutput(true);
- DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
- wr.writeBytes(apiBodyString);
- wr.flush();
-
- int responseCode = conn.getResponseCode();
- logger.debug("response code " + responseCode);
- in = conn.getInputStream();
- String res = new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n"));
- logger.debug("res:" + res);
+ logger.info("Dcae api Body String - " + apiBodyString);
+ String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "DELETE", apiBodyString,
+ "application/json");
JSONParser parser = new JSONParser();
- Object obj0 = parser.parse(res);
+ Object obj0 = parser.parse(responseStr);
JSONObject jsonObj = (JSONObject) obj0;
- JSONObject linksObj = (JSONObject) jsonObj.get("links");
- statusUrl = (String) linksObj.get("status");
- logger.debug("Status URL: " + statusUrl);
+ JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD);
+ String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD);
+ logger.info(STATUS_URL_LOG + statusUrl);
+ return statusUrl;
} catch (Exception e) {
logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e);
throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE",
e);
} finally {
- if (in != null) {
- in.close();
- }
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("deleteExistingDeployment complete");
}
- return statusUrl;
}
-
}
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java new file mode 100644 index 000000000..cff955f1c --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.client; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import javax.ws.rs.BadRequestException; + +import org.apache.commons.io.IOUtils; +import org.onap.clamp.clds.util.LoggingUtils; + +public class DcaeHttpConnectionManager { + protected static final EELFLogger logger = EELFManager.getInstance() + .getLogger(DcaeHttpConnectionManager.class); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final String DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload="; + + private DcaeHttpConnectionManager() { + } + + static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + } }; + + private static void enableSslNoCheck() { + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HostnameVerifier allHostsValid = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + // set the allTrusting verifier + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + } catch (KeyManagementException | NoSuchAlgorithmException e) { + logger.error("Error when disabling security on SSL", e); + } + } + + private static String doHttpsQuery(URL url, String requestMethod, String payload, String contentType) + throws IOException { + logger.info("Using HTTPS URL to contact DCAE:" + url.toString()); + HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection(); + secureConnection.setRequestMethod(requestMethod); + secureConnection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId()); + if (payload != null && contentType != null) { + secureConnection.setRequestProperty("Content-Type", contentType); + secureConnection.setDoOutput(true); + try (DataOutputStream wr = new DataOutputStream(secureConnection.getOutputStream())) { + wr.writeBytes(payload); + wr.flush(); + } + } + int responseCode = secureConnection.getResponseCode(); + logger.info("Response Code: " + responseCode); + if (responseCode < 400) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getInputStream()))) { + String responseStr = IOUtils.toString(reader); + logger.info("Response Content: " + responseStr); + return responseStr; + } + } else { + // In case of connection failure just check whether there is a + // content or not + try (BufferedReader reader = new BufferedReader(new InputStreamReader(secureConnection.getErrorStream()))) { + String responseStr = IOUtils.toString(reader); + logger.error(DCAE_REQUEST_FAILED_LOG + responseStr); + throw new BadRequestException(responseStr); + } + } + } + + private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType) + throws IOException { + logger.info("Using HTTP URL to contact DCAE:" + url); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod(requestMethod); + connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId()); + if (payload != null && contentType != null) { + connection.setRequestProperty("Content-Type", contentType); + connection.setDoOutput(true); + try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) { + wr.writeBytes(payload); + wr.flush(); + } + } + int responseCode = connection.getResponseCode(); + logger.info("Response Code: " + responseCode); + if (responseCode < 400) { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String responseStr = IOUtils.toString(reader); + logger.info("Response Content: " + responseStr); + return responseStr; + } + } else { + // In case of connection failure just check whether there is a + // content or not + try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) { + String responseStr = IOUtils.toString(reader); + logger.error(DCAE_REQUEST_FAILED_LOG + responseStr); + throw new BadRequestException(responseStr); + } + } + } + + /** + * This method does a HTTP query to DCAE with parameters specified. + * + * @param url + * The string HTTP or HTTPS that mustr be used to connect + * @param requestMethod + * The Request Method (PUT, POST, GET, DELETE, etc ...) + * @param payload + * The payload if any, in that case an ouputstream is opened + * @param contentType + * The "application/json or application/xml, or whatever" + * @return The payload of the answer + * @throws IOException + * In case of issue with the streams + */ + public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType) + throws IOException { + return doDcaeHttpQuery(url, requestMethod, payload, contentType, false); + } + + /** + * This method does a HTTP/HTTPS query to DCAE with parameters specified. + * + * @param url + * The string HTTP or HTTPS that mustr be used to connect + * @param requestMethod + * The Request Method (PUT, POST, GET, DELETE, etc ...) + * @param payload + * The payload if any, in that case an ouputstream is opened + * @param contentType + * The "application/json or application/xml, or whatever" + * @param withoutSecurity + * Disable or not the SSL security (certificate,hostname, etc...) + * @return The payload of the answer + * @throws IOException + * In case of issue with the streams + */ + public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType, + boolean withoutSecurity) throws IOException { + URL urlObj = new URL(url); + if (url.contains("https://")) { // Support for HTTPS + if (withoutSecurity) { + enableSslNoCheck(); + } + return doHttpsQuery(urlObj, requestMethod, payload, contentType); + } else { // Support for HTTP + return doHttpQuery(urlObj, requestMethod, payload, contentType); + } + } +} diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index a53ea6475..7662a9fc1 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -27,17 +27,11 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.core.JsonProcessingException;
-import java.io.BufferedReader;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.HttpURLConnection;
-import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
-import javax.ws.rs.BadRequestException;
-
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
@@ -67,8 +61,6 @@ public class DcaeInventoryServices { private RefProp refProp;
@Autowired
private CldsDao cldsDao;
- @Autowired
- private SdcCatalogServices sdcCatalogServices;
/**
*
@@ -117,7 +109,7 @@ public class DcaeInventoryServices { } catch (JsonProcessingException e) {
logger.error("Error during JSON decoding", e);
} catch (IOException ex) {
- logger.error("Error during JSON decoding", ex);
+ logger.error("Error during DCAE communication", ex);
} finally {
LoggingUtils.setTimeContext(startTime, new Date());
metricsLogger.info("setEventInventory complete");
@@ -160,9 +152,7 @@ public class DcaeInventoryServices { * The resource UUID
* @return The DCAE inventory for the artifact
* @throws IOException
- * In case of issues with the stream
* @throws ParseException
- * In case of issues with the Json parsing
*
*/
public String getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)
@@ -174,34 +164,9 @@ public class DcaeInventoryServices { String fullUrl = refProp.getStringValue("DCAE_INVENTORY_URL") + "/dcae-service-types" + queryString;
logger.info("Dcae Inventory Service full url - " + fullUrl);
String daceInventoryResponse = null;
- URL inventoryUrl = new URL(fullUrl);
- HttpURLConnection conn = (HttpURLConnection) inventoryUrl.openConnection();
- conn.setRequestMethod("GET");
- String reqid = LoggingUtils.getRequestId();
- logger.info("reqid set to " + reqid);
- conn.setRequestProperty("X-ECOMP-RequestID", reqid);
- boolean requestFailed = true;
- int responseCode = conn.getResponseCode();
- if (responseCode == 200) {
- requestFailed = false;
- }
- StringBuilder response = new StringBuilder();
- try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
- String inputLine = null;
- while ((inputLine = in.readLine()) != null) {
- response.append(inputLine);
- }
- }
- String responseStr = response.toString();
- if (responseStr != null) {
- if (requestFailed) {
- logger.error("requestFailed - responseStr=" + response);
- throw new BadRequestException(responseStr);
- }
- }
- String jsonResponseString = response.toString();
+ String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);
JSONParser parser = new JSONParser();
- Object obj0 = parser.parse(jsonResponseString);
+ Object obj0 = parser.parse(responseStr);
JSONObject jsonObj = (JSONObject) obj0;
Long totalCount = (Long) jsonObj.get("totalCount");
int numServices = totalCount.intValue();
diff --git a/src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java b/src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java new file mode 100644 index 000000000..7714270d0 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/it/DcaeHttpConnectionManagerItCase.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.clamp.clds.it; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; + +import javax.ws.rs.BadRequestException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.clamp.clds.AbstractItCase; +import org.onap.clamp.clds.client.DcaeHttpConnectionManager; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Test HTTP and HTTPS settings + redirection of HTTP to HTTPS. + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT) +@TestPropertySource(locations = "classpath:https/https-test.properties") +public class DcaeHttpConnectionManagerItCase extends AbstractItCase { + @Value("${server.port}") + private String httpsPort; + @Value("${server.http-to-https-redirection.port}") + private String httpPort; + + @Test + public void testHttpGet() throws Exception { + String response = DcaeHttpConnectionManager + .doDcaeHttpQuery("http://localhost:" + this.httpPort + "/designer/index.html", "GET", null, null, true); + assertNotNull(response); + // Should be a redirection so 302, so empty + assertTrue(response.isEmpty()); + } + + @Test + public void testHttpsGet() throws Exception { + String response = DcaeHttpConnectionManager.doDcaeHttpQuery( + "https://localhost:" + this.httpsPort + "/designer/index.html", "GET", null, null, true); + assertNotNull(response); + // Should contain something + assertTrue(!response.isEmpty()); + } + + @Test(expected = BadRequestException.class) + public void testHttpsGet404() throws IOException { + DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html", + "GET", null, null, true); + fail("Should have raised an BadRequestException exception"); + } + + @Test(expected = BadRequestException.class) + public void testHttpsPost404() throws IOException { + DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html", + "POST", "", "application/json", true); + fail("Should have raised an BadRequestException exception"); + } + + @Test(expected = IOException.class) + public void testHttpException() throws IOException { + DcaeHttpConnectionManager.doDcaeHttpQuery("http://localhost:" + this.httpsPort + "/designer/index.html", "GET", + null, null, true); + fail("Should have raised an IOException exception"); + } +} |