\r
protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class);\r
protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
- @Autowired\r
- private ClampProperties refProp;\r
+ private final ClampProperties refProp;\r
+ private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
private static final String STATUS_URL_LOG = "Status URL extracted: ";\r
private static final String DCAE_URL_PREFIX = "/dcae-deployments/";\r
private static final String DCAE_URL_PROPERTY_NAME = "dcae.dispatcher.url";\r
private static final String DCAE_LINK_FIELD = "links";\r
private static final String DCAE_STATUS_FIELD = "status";\r
\r
- /**\r
- * Delete the deployment on DCAE.\r
- * \r
- * @param deploymentId\r
- * The deployment ID\r
- * @return Return the URL Status\r
- */\r
- public String deleteDeployment(String deploymentId) {\r
- Date startTime = new Date();\r
- LoggingUtils.setTargetContext("DCAE", "deleteDeployment");\r
- try {\r
- String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId;\r
- String statusUrl = getDcaeResponse(url, "DELETE", null, null, DCAE_LINK_FIELD, DCAE_STATUS_FIELD);\r
- logger.info(STATUS_URL_LOG + statusUrl);\r
- LoggingUtils.setResponseContext("0", "Delete deployments success", this.getClass().getName());\r
- return statusUrl;\r
- } catch (Exception e) {\r
- LoggingUtils.setResponseContext("900", "Delete deployments failed", this.getClass().getName());\r
- LoggingUtils.setErrorContext("900", "Delete deployments error");\r
- logger.error("Exception occurred during Delete Deployment Operation with DCAE", e);\r
- throw new DcaeDeploymentException("Exception occurred during Delete Deployment Operation with DCAE", e);\r
- } finally {\r
- LoggingUtils.setTimeContext(startTime, new Date());\r
- metricsLogger.info("deleteDeployment complete");\r
- }\r
+ @Autowired\r
+ public DcaeDispatcherServices(ClampProperties refProp, DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
+ this.refProp = refProp;\r
+ this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
}\r
\r
+\r
public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException {\r
String operationStatus = "";\r
for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) {\r
Date startTime = new Date();\r
LoggingUtils.setTargetContext("DCAE", "getOperationStatus");\r
try {\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);\r
+ String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(statusUrl, "GET", null, null);\r
JSONObject jsonObj = parseResponse(responseStr);\r
String operationType = (String) jsonObj.get("operationType");\r
String status = (String) jsonObj.get(DCAE_STATUS_FIELD);\r
LoggingUtils.setTargetContext("DCAE", "getDeployments");\r
try {\r
String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX;\r
- DcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);\r
+ dcaeHttpConnectionManager.doDcaeHttpQuery(url, "GET", null, null);\r
LoggingUtils.setResponseContext("0", "Get deployments success", this.getClass().getName());\r
} catch (Exception e) {\r
LoggingUtils.setResponseContext("900", "Get deployments failed", this.getClass().getName());\r
String nodeAttr) throws IOException, ParseException {\r
Date startTime = new Date();\r
try {\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType);\r
+ String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(url, requestMethod, payload, contentType);\r
JSONObject jsonObj = parseResponse(responseStr);\r
JSONObject linksObj = (JSONObject) jsonObj.get(node);\r
String statusUrl = (String) linksObj.get(nodeAttr);\r
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
+ * Modifications copyright (c) 2018 Nokia
* ===================================================================
*
*/
import org.apache.commons.io.IOUtils;
import org.onap.clamp.clds.util.LoggingUtils;
+import org.springframework.stereotype.Component;
/**
*
* This class manages the HTTP and HTTPS connections to DCAE.
*
*/
+@Component
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() {
- }
- private static String doHttpsQuery(URL url, String requestMethod, String payload, String contentType)
+ private 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();
}
}
- private static String doHttpQuery(URL url, String requestMethod, String payload, String contentType)
+ private String doHttpQuery(URL url, String requestMethod, String payload, String contentType)
throws IOException {
LoggingUtils utils = new LoggingUtils (logger);
logger.info("Using HTTP URL to contact DCAE:" + url);
* @throws IOException
* In case of issue with the streams
*/
- public static String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType)
+ public String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType)
throws IOException {
URL urlObj = new URL(url);
if (url.contains("https://")) { // Support for HTTPS
* See the License for the specific language governing permissions and\r
* limitations under the License.\r
* ============LICENSE_END============================================\r
+ * Modifications copyright (c) 2018 Nokia\r
* ===================================================================\r
* \r
*/\r
protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeInventoryServices.class);\r
protected static final EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();\r
protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();\r
- public static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
- public static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
- public static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
+ private static final String DCAE_INVENTORY_URL = "dcae.inventory.url";\r
+ private static final String DCAE_INVENTORY_RETRY_INTERVAL = "dcae.intentory.retry.interval";\r
+ private static final String DCAE_INVENTORY_RETRY_LIMIT = "dcae.intentory.retry.limit";\r
public static final String DCAE_TYPE_NAME = "typeName";\r
public static final String DCAE_TYPE_ID = "typeId";\r
+ private final ClampProperties refProp;\r
+ private final CldsDao cldsDao;\r
+ private final DcaeHttpConnectionManager dcaeHttpConnectionManager;\r
+\r
@Autowired\r
- private ClampProperties refProp;\r
- @Autowired\r
- private CldsDao cldsDao;\r
+ public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao, DcaeHttpConnectionManager dcaeHttpConnectionManager) {\r
+ this.refProp = refProp;\r
+ this.cldsDao = cldsDao;\r
+ this.dcaeHttpConnectionManager = dcaeHttpConnectionManager;\r
+ }\r
+\r
\r
/**\r
* Set the event inventory.\r
}\r
for (int i = 0; i < retryLimit; i++) {\r
metricsLogger.info("Attempt n°" + i + " to contact DCAE inventory");\r
- String response = DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
+ String response = dcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "GET", null, null);\r
int totalCount = getTotalCountFromDcaeInventoryResponse(response);\r
metricsLogger.info("getDcaeInformation complete: totalCount returned=" + totalCount);\r
if (totalCount > 0) {\r
String apiBodyString = dcaeServiceTypeRequest.toString();\r
logger.info("Dcae api Body String - " + apiBodyString);\r
String url = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types";\r
- String responseStr = DcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
+ String responseStr = dcaeHttpConnectionManager.doDcaeHttpQuery(url, "POST", apiBodyString,\r
"application/json");\r
// If the DCAEServiceTypeRequest is created successfully it will\r
// return a json object responce containing a node for newly created\r
if (inventoryResponse != null && inventoryResponse.getTypeId() != null) {\r
String fullUrl = refProp.getStringValue(DCAE_INVENTORY_URL) + "/dcae-service-types/"\r
+ inventoryResponse.getTypeId();\r
- DcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null);\r
+ dcaeHttpConnectionManager.doDcaeHttpQuery(fullUrl, "DELETE", null, null);\r
}\r
result = true;\r
} catch (IOException | ParseException e) {\r
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * ONAP CLAMP
- * ================================================================================
- * 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.clamp.clds.exception;
-
-/**
- * New exception to CldsDelegate errors.
- */
-public class CldsDelegateException extends RuntimeException {
-
- /**
- *
- */
- private static final long serialVersionUID = -2705212640916671093L;
-
- /**
- * This constructor can be used to create a new CldsDelegateException.
- *
- * @param message
- * A string message detailing the problem
- * @param e
- * The exception sent by the code
- */
- public CldsDelegateException(String message, Throwable e) {
- super(message, e);
- }
-
- /**
- * This constructor can be used to create a new CldsDelegateException. Use
- * this constructor only if you are creating a new exception stack, not if
- * an exception was already raised by another code.
- *
- * @param message
- * A string message detailing the problem
- */
- public CldsDelegateException(String message) {
- super(message);
- }
-}
--- /dev/null
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2018 Nokia 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.clamp.clds.client;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import org.assertj.core.api.Assertions;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Matchers;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.clamp.clds.config.ClampProperties;
+
+
+
+@RunWith(MockitoJUnitRunner.class)
+public class DcaeDispatcherServicesTest {
+
+ private static final String DEPLOYMENT_STATUS_URL = "http://portal.api.simpledemo.onap.org:30297/dcae-deployments/"
+ + "closedLoop_c9c8b281-6fbd-4702-ba13-affa90411152_deploymentId/"
+ + "operation/a97b46f6-d77c-42a1-9449-d5ae71e8f688";
+ private static final String DCAE_URL = "dcae_url";
+ private static final String DEPLOY_RESPONSE_STRING = "{\"links\":"
+ + "{\"status\":\"http://deployment-handler.onap:8443/dcae-deployments/"
+ + "closedLoop_152367c8-b172-47b3-9e58-c53add75d869_deploymentId/"
+ + "operation/366eb098-7977-4966-ae82-abd2087edb10\"}}";
+
+ @Mock
+ private ClampProperties clampProperties;
+
+ @Mock
+ DcaeHttpConnectionManager dcaeHttpConnectionManager;
+
+ @InjectMocks
+ DcaeDispatcherServices dcaeDispatcherServices;
+
+ private final String STATUS_RESPONSE_PROCESSING = "{\"operationType\": \"deploy\",\"status\": \"processing\"}";
+ private final String STATUS_RESPONSE_ACTIVE = "{\"operationType\": \"deploy\",\"status\": \"succeeded\"}";
+
+ @Before
+ public void setUp() {
+ ImmutableMap.<String, String>builder()
+ .put("dcae.dispatcher.retry.limit", "3")
+ .put("dcae.dispatcher.retry.interval", "0")
+ .put("dcae.dispatcher.url", DCAE_URL)
+ .build()
+ .forEach((property, value) -> {
+ Mockito.when(clampProperties.getStringValue(Matchers.matches(property), Matchers.any()))
+ .thenReturn(value);
+ Mockito.when(clampProperties.getStringValue(Matchers.matches(property))).thenReturn(value);
+ });
+ }
+
+ @Test
+ public void shouldReturnDcaeOperationSataus() throws IOException {
+ //given
+ Mockito.when(dcaeHttpConnectionManager.doDcaeHttpQuery(DEPLOYMENT_STATUS_URL, "GET", null, null))
+ .thenReturn(STATUS_RESPONSE_PROCESSING);
+ //when
+ String operationStatus = dcaeDispatcherServices.getOperationStatus(DEPLOYMENT_STATUS_URL);
+
+ //then
+ Assertions.assertThat(operationStatus).isEqualTo("processing");
+ }
+
+ @Test
+ public void shouldTryMultipleTimesWhenProcessing() throws IOException, InterruptedException {
+ //given
+ Mockito.when(dcaeHttpConnectionManager.doDcaeHttpQuery(DEPLOYMENT_STATUS_URL, "GET",
+ null, null))
+ .thenReturn(STATUS_RESPONSE_PROCESSING, STATUS_RESPONSE_PROCESSING, STATUS_RESPONSE_ACTIVE);
+ //when
+ String operationStatus = dcaeDispatcherServices.getOperationStatusWithRetry(DEPLOYMENT_STATUS_URL);
+
+ //then
+ Assertions.assertThat(operationStatus).isEqualTo("succeeded");
+ Mockito.verify(dcaeHttpConnectionManager, Mockito.times(3))
+ .doDcaeHttpQuery(DEPLOYMENT_STATUS_URL, "GET", null, null);
+
+ }
+
+ @Test
+ public void shouldTryOnlyAsManyTimesAsConfigured() throws IOException, InterruptedException {
+ //given
+ Mockito.when(dcaeHttpConnectionManager
+ .doDcaeHttpQuery(DEPLOYMENT_STATUS_URL, "GET", null, null))
+ .thenReturn(STATUS_RESPONSE_PROCESSING, STATUS_RESPONSE_PROCESSING, STATUS_RESPONSE_PROCESSING,
+ STATUS_RESPONSE_PROCESSING, STATUS_RESPONSE_PROCESSING);
+ //when
+ String operationStatus = dcaeDispatcherServices.getOperationStatusWithRetry(DEPLOYMENT_STATUS_URL);
+
+ //then
+ Assertions.assertThat(operationStatus).isEqualTo("processing");
+ Mockito.verify(dcaeHttpConnectionManager, Mockito.times(3))
+ .doDcaeHttpQuery(DEPLOYMENT_STATUS_URL, "GET", null, null);
+
+ }
+
+ @Test
+ public void shouldTriggerDeploymentCreation() throws IOException {
+ //given
+ String deploymentID = "closedLoop_152367c8-b172-47b3-9e58-c53add75d869_deploymentId";
+ String serviceTypeId = "e2ba40f7-bf42-41e7-acd7-48fd07586d90";
+ Mockito.when(clampProperties.getJsonTemplate("dcae.deployment.template"))
+ .thenReturn(new ObjectMapper().readTree("{}"));
+
+ Mockito.when(dcaeHttpConnectionManager
+ .doDcaeHttpQuery(DCAE_URL
+ + "/dcae-deployments/closedLoop_152367c8-b172-47b3-9e58-c53add75d869_deploymentId",
+ "PUT",
+ "{\"serviceTypeId\":\"e2ba40f7-bf42-41e7-acd7-48fd07586d90\",\"inputs\":{}}",
+ "application/json"))
+ .thenReturn(DEPLOY_RESPONSE_STRING);
+ JsonNode blueprintInputJson = new ObjectMapper().readTree("{}");
+
+ //when
+ String operationStatus = dcaeDispatcherServices
+ .createNewDeployment(deploymentID, serviceTypeId, blueprintInputJson);
+
+ //then
+ Assertions.assertThat(operationStatus).isEqualTo("http://deployment-handler.onap:8443/"
+ + "dcae-deployments/closedLoop_152367c8-b172-47b3-9e58-c53add75d869_deploymentId/"
+ + "operation/366eb098-7977-4966-ae82-abd2087edb10");
+
+ }
+}
\ No newline at end of file
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
-
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.NotFoundException;
import javax.xml.transform.TransformerException;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
+import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END============================================
+ * Modifications copyright (c) 2018 Nokia
* ===================================================================
*
*/
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.clamp.clds.client.DcaeHttpConnectionManager;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
private String httpsPort;
@Value("${server.http-to-https-redirection.port}")
private String httpPort;
+
+ @Autowired
+ DcaeHttpConnectionManager dcaeHttpConnectionManager;
+
private static TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Test
public void testHttpGet() throws Exception {
- String response = DcaeHttpConnectionManager
+ String response = dcaeHttpConnectionManager
.doDcaeHttpQuery("http://localhost:" + this.httpPort + "/designer/index.html", "GET", null, null);
assertNotNull(response);
// Should be a redirection so 302, so empty
@Test
public void testHttpsGet() throws Exception {
- String response = DcaeHttpConnectionManager
+ String response = dcaeHttpConnectionManager
.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index.html", "GET", null, null);
assertNotNull(response);
// Should contain something
@Test(expected = BadRequestException.class)
public void testHttpsGet404() throws IOException {
- DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
+ dcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
"GET", null, null);
fail("Should have raised an BadRequestException");
}
@Test(expected = BadRequestException.class)
public void testHttpsPost404() throws IOException {
- DcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
+ dcaeHttpConnectionManager.doDcaeHttpQuery("https://localhost:" + this.httpsPort + "/designer/index1.html",
"POST", "", "application/json");
fail("Should have raised an BadRequestException");
}
@Test(expected = BadRequestException.class)
public void testHttpException() throws IOException {
- DcaeHttpConnectionManager.doDcaeHttpQuery("http://localhost:" + this.httpsPort + "/designer/index.html", "GET",
+ dcaeHttpConnectionManager.doDcaeHttpQuery("http://localhost:" + this.httpsPort + "/designer/index.html", "GET",
null, null);
fail("Should have raised an BadRequestException");
}
.getForEntity("https://localhost:" + this.httpsPort + "/restservices/clds/v1/api-doc", String.class);
assertThat(httpsEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(httpsEntity.getBody()).contains("swagger");
- FileUtils.writeStringToFile(new File("docs/swagger/swagger.json"), httpsEntity.getBody(),Charset.defaultCharset());
+ FileUtils.writeStringToFile(
+ new File("docs/swagger/swagger.json"), httpsEntity.getBody(), Charset.defaultCharset());
}
/**
@Test
public void formatSdcReqTest() throws JSONException {
- String jsonResult = sdcReq.formatSdcReq("payload", "artifactName", "artifactLabel", "artifactType");
+ String jsonResult = sdcReq.formatSdcReq("payload", "artifactName",
+ "artifactLabel", "artifactType");
JSONAssert.assertEquals(
- "{\"payloadData\" : \"cGF5bG9hZA==\",\"artifactLabel\" : \"artifactLabel\",\"artifactName\" :\"artifactName\",\"artifactType\" : \"artifactType\","
+ "{\"payloadData\" : \"cGF5bG9hZA==\",\"artifactLabel\" : \"artifactLabel\"," +
+ "\"artifactName\" :\"artifactName\",\"artifactType\" : \"artifactType\","
+ "\"artifactGroupType\" : \"DEPLOYMENT\",\"description\" : \"from CLAMP Cockpit\"}",
jsonResult, true);
}
assertNotNull(listUrls);
assertTrue(listUrls.size() == 1);
assertTrue(listUrls.get(0).contains(
- "/sdc/v1/catalog/services/56441b4b-0467-41dc-9a0e-e68613838219/resourceInstances/vpacketgen0/artifacts"));
+ "/sdc/v1/catalog/services/56441b4b-0467-41dc-9a0e-e68613838219/resourceInstances/vpacketgen0/artifacts"));
}
}