From: p.borelowski Date: Thu, 18 Apr 2019 13:11:53 +0000 (+0200) Subject: Fixed various sonar identified code smells X-Git-Tag: 4.0.0~14 X-Git-Url: https://gerrit.onap.org/r/gitweb?a=commitdiff_plain;h=a1ec959e3f5f8639117a5134ffbfb59f7b542f80;p=clamp.git Fixed various sonar identified code smells - introduced a few String constants, - removed unused code, - added @FunctionalInterface annotation, - made most fields private (when possible) Change-Id: If8c523125de6a5e5c756e18bd04efd548b19ba91 Issue-ID: CLAMP-346 Signed-off-by: p.borelowski --- diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index e8fd83e2..90d0693d 100644 --- a/src/main/java/org/onap/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -25,16 +27,6 @@ package org.onap.clamp.clds; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.camel.component.servlet.CamelHttpTransportServlet; import org.onap.clamp.clds.service.SecureServicePermission; import org.springframework.context.ApplicationContext; @@ -47,6 +39,14 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.web.context.support.WebApplicationContextUtils; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; + public class ClampServlet extends CamelHttpTransportServlet { /** @@ -54,24 +54,27 @@ public class ClampServlet extends CamelHttpTransportServlet { */ private static final long serialVersionUID = -4198841134910211542L; - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampServlet.class); - public static final String PERM_INSTANCE = "clamp.config.security.permission.instance"; - public static final String PERM_CL = "clamp.config.security.permission.type.cl"; - public static final String PERM_TEMPLATE = "clamp.config.security.permission.type.template"; - public static final String PERM_VF = "clamp.config.security.permission.type.filter.vf"; - public static final String PERM_MANAGE = "clamp.config.security.permission.type.cl.manage"; - public static final String PERM_TOSCA = "clamp.config.security.permission.type.tosca"; - public static final String AUTHENTICATION_CLASS = "clamp.config.security.authentication.class"; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ClampServlet.class); + private static final String PERM_INSTANCE = "clamp.config.security.permission.instance"; + private static final String PERM_CL = "clamp.config.security.permission.type.cl"; + private static final String PERM_TEMPLATE = "clamp.config.security.permission.type.template"; + private static final String PERM_VF = "clamp.config.security.permission.type.filter.vf"; + private static final String PERM_MANAGE = "clamp.config.security.permission.type.cl.manage"; + private static final String PERM_TOSCA = "clamp.config.security.permission.type.tosca"; + private static final String AUTHENTICATION_CLASS = "clamp.config.security.authentication.class"; + private static final String READ = "read"; + private static final String UPDATE = "update"; + private static List permissionList; private synchronized Class loadDynamicAuthenticationClass() { try { String authenticationObject = WebApplicationContextUtils.getWebApplicationContext(getServletContext()) - .getEnvironment().getProperty(AUTHENTICATION_CLASS); + .getEnvironment().getProperty(AUTHENTICATION_CLASS); return Class.forName(authenticationObject); } catch (ClassNotFoundException e) { logger.error( - "Exception caught when attempting to create associated class of config:" + AUTHENTICATION_CLASS, e); + "Exception caught when attempting to create associated class of config:" + AUTHENTICATION_CLASS, e); return Object.class; } } @@ -80,24 +83,24 @@ public class ClampServlet extends CamelHttpTransportServlet { if (permissionList == null) { permissionList = new ArrayList<>(); ApplicationContext applicationContext = WebApplicationContextUtils - .getWebApplicationContext(getServletContext()); + .getWebApplicationContext(getServletContext()); String cldsPermissionInstance = applicationContext.getEnvironment().getProperty(PERM_INSTANCE); permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_CL), - cldsPermissionInstance, "read")); + cldsPermissionInstance, READ)); permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_CL), - cldsPermissionInstance, "update")); + cldsPermissionInstance, UPDATE)); permissionList.add(SecureServicePermission.create( - applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, "read")); + applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, READ)); permissionList.add(SecureServicePermission.create( - applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, "update")); + applicationContext.getEnvironment().getProperty(PERM_TEMPLATE), cldsPermissionInstance, UPDATE)); permissionList.add(SecureServicePermission.create(applicationContext.getEnvironment().getProperty(PERM_VF), - cldsPermissionInstance, "*")); + cldsPermissionInstance, "*")); permissionList.add(SecureServicePermission - .create(applicationContext.getEnvironment().getProperty(PERM_MANAGE), cldsPermissionInstance, "*")); + .create(applicationContext.getEnvironment().getProperty(PERM_MANAGE), cldsPermissionInstance, "*")); permissionList.add(SecureServicePermission - .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, "read")); + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, READ)); permissionList.add(SecureServicePermission - .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, "update")); + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, UPDATE)); } return permissionList; } @@ -107,8 +110,7 @@ public class ClampServlet extends CamelHttpTransportServlet { * to isUserInRole will invoke a http call to AAF server. */ @Override - protected void doService(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { + protected void doService(HttpServletRequest request, HttpServletResponse response) { Principal principal = request.getUserPrincipal(); if (loadDynamicAuthenticationClass().isInstance(principal)) { // When AAF is enabled, there is a need to provision the permissions to Spring @@ -121,7 +123,7 @@ public class ClampServlet extends CamelHttpTransportServlet { } } Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", grantedAuths), "", - grantedAuths); + grantedAuths); SecurityContextHolder.getContext().setAuthentication(auth); } try { @@ -134,6 +136,5 @@ public class ClampServlet extends CamelHttpTransportServlet { logger.error("Exception caught when executing HTTP sendError in servlet", e); } } - } } \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java b/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java index a74f4c70..f6265982 100644 --- a/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java +++ b/src/main/java/org/onap/clamp/clds/camel/CamelProxy.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * 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 @@ -18,7 +20,7 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.camel; @@ -29,41 +31,32 @@ import org.apache.camel.ExchangeProperty; * This interface describes the CamelProxy parameters that must be passed to the * Camel flow. */ +@FunctionalInterface public interface CamelProxy { /** * This method is called when invoking a camel flow. - * - * @param actionCommand - * The action coming from the Clamp UI (like SUBMIT, UPDATE, - * DELETE, ...) - * @param modelProperties - * The Model properties created based on the BPMN Json and - * Properties Json - * @param modelBpmnProperties - * The Json with all the properties describing the flow - * @param modelName - * The model name - * @param controlName - * The control loop name - * @param docText - * The Global properties JSON containing YAML (coming from CLamp - * template) - * @param isTest - * Is a test or not (flag coming from the UI) - * @param userId - * The user ID coming from the UI - * @param isInsertTestEvent - * Is a test or not (flag coming from the UI) - * @param eventAction - * The latest event action in database (like CREATE, SUBMIT, ...) + * + * @param actionCommand The action coming from the Clamp UI (like SUBMIT, UPDATE, + * DELETE, ...) + * @param modelProperties The Model properties created based on the BPMN Json and + * Properties Json + * @param modelBpmnProperties The Json with all the properties describing the flow + * @param modelName The model name + * @param controlName The control loop name + * @param docText The Global properties JSON containing YAML (coming from CLamp + * template) + * @param isTest Is a test or not (flag coming from the UI) + * @param userId The user ID coming from the UI + * @param isInsertTestEvent Is a test or not (flag coming from the UI) + * @param eventAction The latest event action in database (like CREATE, SUBMIT, ...) * @return A string containing the result of the Camel flow execution */ String executeAction(@ExchangeProperty("actionCd") String actionCommand, - @ExchangeProperty("modelProp") String modelProperties, - @ExchangeProperty("modelBpmnProp") String modelBpmnProperties, - @ExchangeProperty("modelName") String modelName, @ExchangeProperty("controlName") String controlName, - @ExchangeProperty("docText") String docText, @ExchangeProperty("isTest") boolean isTest, - @ExchangeProperty("userid") String userId, @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent, - @ExchangeProperty("eventAction") String eventAction); + @ExchangeProperty("modelProp") String modelProperties, + @ExchangeProperty("modelBpmnProp") String modelBpmnProperties, + @ExchangeProperty("modelName") String modelName, @ExchangeProperty("controlName") String controlName, + @ExchangeProperty("docText") String docText, @ExchangeProperty("isTest") boolean isTest, + @ExchangeProperty("userid") String userId, @ExchangeProperty("isInsertTestEvent") boolean isInsertTestEvent, + @ExchangeProperty("eventAction") String eventAction); } 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 f7aff0ef..83401a3c 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -1,218 +1,216 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * 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.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import com.google.gson.JsonObject; -import java.io.IOException; -import java.util.Date; - -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException; -import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.util.HttpConnectionManager; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * This class implements the communication with DCAE for the service - * deployments. - */ -@Component -public class DcaeDispatcherServices { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class); - protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private final ClampProperties refProp; - private final HttpConnectionManager dcaeHttpConnectionManager; - 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"; - - @Autowired - public DcaeDispatcherServices(ClampProperties refProp, HttpConnectionManager dcaeHttpConnectionManager) { - this.refProp = refProp; - this.dcaeHttpConnectionManager = dcaeHttpConnectionManager; - } - - /** - * Get the Operation Status from a specified URL with retry. - * @param operationStatusUrl - * The URL of the DCAE - * @return The status - * @throws InterruptedException Exception during the retry - */ - public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException { - String operationStatus = ""; - for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) { - logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl); - operationStatus = getOperationStatus(operationStatusUrl); - logger.info("Current Status is:" + operationStatus); - if (!"processing".equalsIgnoreCase(operationStatus)) { - return operationStatus; - } else { - Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval"))); - } - } - logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method"); - return operationStatus; - } - - /** - * Get the Operation Status from a specified URL. - * @param statusUrl - * The URL provided by a previous DCAE Query - * @return The status - */ - public String getOperationStatus(String statusUrl) { - // Assigning processing status to monitor operation status further - String opStatus = "processing"; - Date startTime = new Date(); - LoggingUtils.setTargetContext("DCAE", "getOperationStatus"); - try { - String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null, - null, "DCAE", null, - null); - JSONObject jsonObj = parseResponse(responseStr); - String operationType = (String) jsonObj.get("operationType"); - String status = (String) jsonObj.get(DCAE_STATUS_FIELD); - logger.info("Operation Type - " + operationType + ", Status " + status); - LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName()); - opStatus = status; - } catch (Exception e) { - LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName()); - LoggingUtils.setErrorContext("900", "Get operation status error"); - logger.error("Exception occurred during getOperationStatus Operation with DCAE", e); - } finally { - LoggingUtils.setTimeContext(startTime, new Date()); - metricsLogger.info("getOperationStatus complete"); - } - return opStatus; - } - - /** - * Returns status URL for createNewDeployment operation. - * @param deploymentId - * The deployment ID - * @param serviceTypeId - * Service type ID - * @param blueprintInputJson - * The value for each blueprint parameters in a flat JSON - * @return The status URL - */ - public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) { - Date startTime = new Date(); - LoggingUtils.setTargetContext("DCAE", "createNewDeployment"); - try { - JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject(); - rootObject.addProperty("serviceTypeId", serviceTypeId); - if (blueprintInputJson != null) { - rootObject.add("inputs", blueprintInputJson); - } - String apiBodyString = rootObject.toString(); - logger.info("Dcae api Body String - " + apiBodyString); - String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; - String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD, - DCAE_STATUS_FIELD); - LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName()); - return statusUrl; - } catch (Exception e) { - LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName()); - LoggingUtils.setErrorContext("900", "Create new deployment error"); - logger.error("Exception occurred during createNewDeployment Operation with DCAE", e); - throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e); - } finally { - LoggingUtils.setTimeContext(startTime, new Date()); - metricsLogger.info("createNewDeployment complete"); - } - } - - /*** - * Returns status URL for deleteExistingDeployment operation. - * - * @param deploymentId - * The deployment ID - * @param serviceTypeId - * The service Type ID - * @return The status URL - */ - public String deleteExistingDeployment(String deploymentId, String serviceTypeId) { - Date startTime = new Date(); - LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment"); - try { - String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}"; - logger.info("Dcae api Body String - " + apiBodyString); - String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; - String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD, - DCAE_STATUS_FIELD); - LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName()); - return statusUrl; - - } catch (Exception e) { - LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName()); - LoggingUtils.setErrorContext("900", "Delete existing deployment error"); - logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e); - throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE", - e); - } finally { - LoggingUtils.setTimeContext(startTime, new Date()); - metricsLogger.info("deleteExistingDeployment complete"); - } - } - - private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node, - String nodeAttr) throws IOException, ParseException { - Date startTime = new Date(); - try { - String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null); - JSONObject jsonObj = parseResponse(responseStr); - JSONObject linksObj = (JSONObject) jsonObj.get(node); - String statusUrl = (String) linksObj.get(nodeAttr); - logger.info(STATUS_URL_LOG + statusUrl); - return statusUrl; - } catch (IOException | ParseException e) { - logger.error("Exception occurred getting response from DCAE", e); - throw e; - } finally { - LoggingUtils.setTimeContext(startTime, new Date()); - metricsLogger.info("getDcaeResponse complete"); - } - } - - private JSONObject parseResponse(String responseStr) throws ParseException { - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(responseStr); - JSONObject jsonObj = (JSONObject) obj0; - return jsonObj; - } +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import com.google.gson.JsonObject; +import java.io.IOException; +import java.util.Date; + +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.exception.dcae.DcaeDeploymentException; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.util.HttpConnectionManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * This class implements the communication with DCAE for the service + * deployments. + */ +@Component +public class DcaeDispatcherServices { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeDispatcherServices.class); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private final ClampProperties refProp; + private final HttpConnectionManager dcaeHttpConnectionManager; + 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"; + + @Autowired + public DcaeDispatcherServices(ClampProperties refProp, HttpConnectionManager dcaeHttpConnectionManager) { + this.refProp = refProp; + this.dcaeHttpConnectionManager = dcaeHttpConnectionManager; + } + + /** + * Get the Operation Status from a specified URL with retry. + * @param operationStatusUrl + * The URL of the DCAE + * @return The status + * @throws InterruptedException Exception during the retry + */ + public String getOperationStatusWithRetry(String operationStatusUrl) throws InterruptedException { + String operationStatus = ""; + for (int i = 0; i < Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.limit")); i++) { + logger.info("Trying to get Operation status on DCAE for url:" + operationStatusUrl); + operationStatus = getOperationStatus(operationStatusUrl); + logger.info("Current Status is:" + operationStatus); + if (!"processing".equalsIgnoreCase(operationStatus)) { + return operationStatus; + } else { + Thread.sleep(Integer.valueOf(refProp.getStringValue("dcae.dispatcher.retry.interval"))); + } + } + logger.warn("Number of attempts on DCAE is over, stopping the getOperationStatus method"); + return operationStatus; + } + + /** + * Get the Operation Status from a specified URL. + * @param statusUrl + * The URL provided by a previous DCAE Query + * @return The status + */ + public String getOperationStatus(String statusUrl) { + // Assigning processing status to monitor operation status further + String opStatus = "processing"; + Date startTime = new Date(); + LoggingUtils.setTargetContext("DCAE", "getOperationStatus"); + try { + String responseStr = dcaeHttpConnectionManager.doHttpRequest(statusUrl, "GET", null, + null, "DCAE", null, + null); + JSONObject jsonObj = parseResponse(responseStr); + String operationType = (String) jsonObj.get("operationType"); + String status = (String) jsonObj.get(DCAE_STATUS_FIELD); + logger.info("Operation Type - " + operationType + ", Status " + status); + LoggingUtils.setResponseContext("0", "Get operation status success", this.getClass().getName()); + opStatus = status; + } catch (Exception e) { + LoggingUtils.setResponseContext("900", "Get operation status failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Get operation status error"); + logger.error("Exception occurred during getOperationStatus Operation with DCAE", e); + } finally { + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("getOperationStatus complete"); + } + return opStatus; + } + + /** + * Returns status URL for createNewDeployment operation. + * @param deploymentId + * The deployment ID + * @param serviceTypeId + * Service type ID + * @param blueprintInputJson + * The value for each blueprint parameters in a flat JSON + * @return The status URL + */ + public String createNewDeployment(String deploymentId, String serviceTypeId, JsonObject blueprintInputJson) { + Date startTime = new Date(); + LoggingUtils.setTargetContext("DCAE", "createNewDeployment"); + try { + JsonObject rootObject = refProp.getJsonTemplate("dcae.deployment.template").getAsJsonObject(); + rootObject.addProperty("serviceTypeId", serviceTypeId); + if (blueprintInputJson != null) { + rootObject.add("inputs", blueprintInputJson); + } + String apiBodyString = rootObject.toString(); + logger.info("Dcae api Body String - " + apiBodyString); + String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; + String statusUrl = getDcaeResponse(url, "PUT", apiBodyString, "application/json", DCAE_LINK_FIELD, + DCAE_STATUS_FIELD); + LoggingUtils.setResponseContext("0", "Create new deployment failed", this.getClass().getName()); + return statusUrl; + } catch (Exception e) { + LoggingUtils.setResponseContext("900", "Create new deployment failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Create new deployment error"); + logger.error("Exception occurred during createNewDeployment Operation with DCAE", e); + throw new DcaeDeploymentException("Exception occurred during createNewDeployment Operation with DCAE", e); + } finally { + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("createNewDeployment complete"); + } + } + + /*** + * Returns status URL for deleteExistingDeployment operation. + * + * @param deploymentId + * The deployment ID + * @param serviceTypeId + * The service Type ID + * @return The status URL + */ + public String deleteExistingDeployment(String deploymentId, String serviceTypeId) { + Date startTime = new Date(); + LoggingUtils.setTargetContext("DCAE", "deleteExistingDeployment"); + try { + String apiBodyString = "{\"serviceTypeId\": \"" + serviceTypeId + "\"}"; + logger.info("Dcae api Body String - " + apiBodyString); + String url = refProp.getStringValue(DCAE_URL_PROPERTY_NAME) + DCAE_URL_PREFIX + deploymentId; + String statusUrl = getDcaeResponse(url, "DELETE", apiBodyString, "application/json", DCAE_LINK_FIELD, + DCAE_STATUS_FIELD); + LoggingUtils.setResponseContext("0", "Delete existing deployment success", this.getClass().getName()); + return statusUrl; + + } catch (Exception e) { + LoggingUtils.setResponseContext("900", "Delete existing deployment failed", this.getClass().getName()); + LoggingUtils.setErrorContext("900", "Delete existing deployment error"); + logger.error("Exception occurred during deleteExistingDeployment Operation with DCAE", e); + throw new DcaeDeploymentException("Exception occurred during deleteExistingDeployment Operation with DCAE", + e); + } finally { + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("deleteExistingDeployment complete"); + } + } + + private String getDcaeResponse(String url, String requestMethod, String payload, String contentType, String node, + String nodeAttr) throws IOException, ParseException { + Date startTime = new Date(); + try { + String responseStr = dcaeHttpConnectionManager.doHttpRequest(url, requestMethod, payload, contentType, "DCAE", null, null); + JSONObject jsonObj = parseResponse(responseStr); + JSONObject linksObj = (JSONObject) jsonObj.get(node); + String statusUrl = (String) linksObj.get(nodeAttr); + logger.info(STATUS_URL_LOG + statusUrl); + return statusUrl; + } catch (IOException | ParseException e) { + logger.error("Exception occurred getting response from DCAE", e); + throw e; + } finally { + LoggingUtils.setTimeContext(startTime, new Date()); + metricsLogger.info("getDcaeResponse complete"); + } + } + + private JSONObject parseResponse(String responseStr) throws ParseException { + JSONParser parser = new JSONParser(); + return (JSONObject) parser.parse(responseStr); + } } \ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java index 43209b29..68d8529c 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/PolicyClient.java @@ -65,7 +65,6 @@ import org.onap.policy.api.PolicyType; import org.onap.policy.api.PushPolicyParameters; import org.onap.policy.api.RuleProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @@ -76,22 +75,23 @@ import org.springframework.stereotype.Component; @Primary public class PolicyClient { - protected PolicyEngine policyEngine; - protected static final String LOG_POLICY_PREFIX = "Response is "; - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class); - protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - public static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type"; - public static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name"; - public static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix"; - public static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix"; + private PolicyEngine policyEngine; + private static final String LOG_POLICY_PREFIX = "Response is "; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyClient.class); + private static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final String POLICY_MSTYPE_PROPERTY_NAME = "policy.ms.type"; + private static final String POLICY_ONAPNAME_PROPERTY_NAME = "policy.onap.name"; + private static final String POLICY_BASENAME_PREFIX_PROPERTY_NAME = "policy.base.policyNamePrefix"; + private static final String POLICY_OP_NAME_PREFIX_PROPERTY_NAME = "policy.op.policyNamePrefix"; public static final String POLICY_MS_NAME_PREFIX_PROPERTY_NAME = "policy.ms.policyNamePrefix"; - public static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type"; - public static final String TOSCA_FILE_TEMP_PATH = "tosca.filePath"; + private static final String POLICY_OP_TYPE_PROPERTY_NAME = "policy.op.type"; + private static final String TOSCA_FILE_TEMP_PATH = "tosca.filePath"; + private static final String POLICY_COMMUNICATION_LOG_MESSAGE = "Exception occurred during policy communication"; + private static final String POLICY_COMMUNICATION_EXC_MESSAGE = "Exception while communicating with Policy"; + private static final String POLICY = "Policy"; @Autowired - protected ApplicationContext appContext; - @Autowired - protected ClampProperties refProp; + private ClampProperties refProp; @Autowired private PolicyConfiguration policyConfiguration; @@ -274,12 +274,12 @@ public class PolicyClient { if ((PolicyClass.Decision.equals(policyParameters.getPolicyClass()) && !checkDecisionPolicyExists(prop)) || (PolicyClass.Config.equals(policyParameters.getPolicyClass()) && !checkPolicyExists(prop, policyPrefix, policyNameWithPrefix))) { - LoggingUtils.setTargetContext("Policy", "createPolicy"); + LoggingUtils.setTargetContext(POLICY, "createPolicy"); logger.info("Attempting to create policy for action=" + prop.getActionCd()); response = getPolicyEngine().createPolicy(policyParameters); responseMessage = response.getResponseMessage(); } else { - LoggingUtils.setTargetContext("Policy", "updatePolicy"); + LoggingUtils.setTargetContext(POLICY, "updatePolicy"); logger.info("Attempting to update policy for action=" + prop.getActionCd()); response = getPolicyEngine().updatePolicy(policyParameters); responseMessage = response.getResponseMessage(); @@ -287,8 +287,8 @@ public class PolicyClient { } catch (Exception e) { LoggingUtils.setResponseContext("900", "Policy send failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Policy send error"); - logger.error("Exception occurred during policy communication", e); - throw new PolicyClientException("Exception while communicating with Policy", e); + logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e); + throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e); } logger.info(LOG_POLICY_PREFIX + responseMessage); LoggingUtils.setTimeContext(startTime, new Date()); @@ -329,7 +329,7 @@ public class PolicyClient { PolicyChangeResponse response; String responseMessage = ""; try { - LoggingUtils.setTargetContext("Policy", "pushPolicy"); + LoggingUtils.setTargetContext(POLICY, "pushPolicy"); logger.info("Attempting to push policy..."); response = getPolicyEngine().pushPolicy(pushPolicyParameters); if (response != null) { @@ -338,8 +338,8 @@ public class PolicyClient { } catch (Exception e) { LoggingUtils.setResponseContext("900", "Policy push failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Policy push error"); - logger.error("Exception occurred during policy communication", e); - throw new PolicyClientException("Exception while communicating with Policy", e); + logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e); + throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e); } logger.info(LOG_POLICY_PREFIX + responseMessage); if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) { @@ -466,8 +466,8 @@ public class PolicyClient { deletePolicyResponse = deletePolicy(prop, DictionaryType.Decision.toString(), null); } } catch (Exception e) { - logger.error("Exception occurred during policy communication", e); - throw new PolicyClientException("Exception while communicating with Policy", e); + logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e); + throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e); } return deletePolicyResponse; } @@ -492,8 +492,8 @@ public class PolicyClient { deletePolicyResponse = deletePolicy(prop, policyType, null); } } catch (Exception e) { - logger.error("Exception occurred during policy communication", e); - throw new PolicyClientException("Exception while communicating with Policy", e); + logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e); + throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e); } return deletePolicyResponse; } @@ -650,8 +650,8 @@ public class PolicyClient { } catch (Exception e) { LoggingUtils.setResponseContext("900", "Policy Model import failed", this.getClass().getName()); LoggingUtils.setErrorContext("900", "Policy Model import error"); - logger.error("Exception occurred during policy communication", e); - throw new PolicyClientException("Exception while communicating with Policy", e); + logger.error(POLICY_COMMUNICATION_LOG_MESSAGE, e); + throw new PolicyClientException(POLICY_COMMUNICATION_EXC_MESSAGE, e); } logger.info(LOG_POLICY_PREFIX + responseMessage); if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {