diff options
Diffstat (limited to 'src/main/java')
35 files changed, 1478 insertions, 929 deletions
diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index e8fd83e2..86524d1c 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 @@ -30,7 +32,6 @@ 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; @@ -54,24 +55,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<SecureServicePermission> 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 +84,25 @@ 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 +112,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 @@ -120,8 +124,8 @@ public class ClampServlet extends CamelHttpTransportServlet { grantedAuths.add(new SimpleGrantedAuthority(permString)); } } - Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", grantedAuths), "", - grantedAuths); + Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", + grantedAuths), "", grantedAuths); SecurityContextHolder.getContext().setAuthentication(auth); } try { @@ -134,6 +138,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)) { diff --git a/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java index 3a98788f..3dc80738 100644 --- a/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java @@ -22,11 +22,34 @@ package org.onap.clamp.clds.config; +import java.io.IOException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; + import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.http4.HttpClientConfigurer; +import org.apache.camel.component.http4.HttpComponent; import org.apache.camel.model.rest.RestBindingMode; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; import org.onap.clamp.clds.util.ClampVersioning; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component @@ -35,15 +58,69 @@ public class CamelConfiguration extends RouteBuilder { @Autowired CamelContext camelContext; + @Autowired + private Environment env; + + private void configureDefaultSslProperties() { + if (env.getProperty("server.ssl.trust-store") != null) { + URL storeResource = CamelConfiguration.class + .getResource(env.getProperty("server.ssl.trust-store").replaceAll("classpath:", "")); + System.setProperty("javax.net.ssl.trustStore", storeResource.getPath()); + System.setProperty("javax.net.ssl.trustStorePassword", env.getProperty("server.ssl.trust-store-password")); + System.setProperty("javax.net.ssl.trustStoreType", "jks"); + System.setProperty("ssl.TrustManagerFactory.algorithm", "PKIX"); + storeResource = CamelConfiguration.class + .getResource(env.getProperty("server.ssl.key-store").replaceAll("classpath:", "")); + System.setProperty("javax.net.ssl.keyStore", storeResource.getPath()); + System.setProperty("javax.net.ssl.keyStorePassword", env.getProperty("server.ssl.key-store-password")); + System.setProperty("javax.net.ssl.keyStoreType", env.getProperty("server.ssl.key-store-type")); + } + } + + private void registerTrustStore() + throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, CertificateException, IOException { + if (env.getProperty("server.ssl.trust-store") != null) { + KeyStore truststore = KeyStore.getInstance("JKS"); + truststore.load( + getClass().getClassLoader() + .getResourceAsStream(env.getProperty("server.ssl.trust-store").replaceAll("classpath:", "")), + env.getProperty("server.ssl.trust-store-password").toCharArray()); + + TrustManagerFactory trustFactory = TrustManagerFactory.getInstance("PKIX"); + trustFactory.init(truststore); + SSLContext sslcontext = SSLContext.getInstance("TLS"); + sslcontext.init(null, trustFactory.getTrustManagers(), null); + SSLSocketFactory factory = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + SchemeRegistry registry = new SchemeRegistry(); + final Scheme scheme = new Scheme("https4", 443, factory); + registry.register(scheme); + ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); + HttpComponent http4 = camelContext.getComponent("https4", HttpComponent.class); + http4.setHttpClientConfigurer(new HttpClientConfigurer() { + + @Override + public void configureHttpClient(HttpClientBuilder builder) { + builder.setSSLSocketFactory(factory); + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("https", factory).register("http", plainsf).build(); + builder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); + } + }); + } + } + @Override - public void configure() { + public void configure() + throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { restConfiguration().component("servlet").bindingMode(RestBindingMode.json).jsonDataFormat("clamp-gson") .dataFormatProperty("prettyPrint", "true")// .enableCORS(true) // turn on swagger api-doc .apiContextPath("api-doc").apiVendorExtension(true).apiProperty("api.title", "Clamp Rest API") .apiProperty("api.version", ClampVersioning.getCldsVersionFromProps()) .apiProperty("base.path", "/restservices/clds/"); - // .apiProperty("cors", "true"); - camelContext.setTracing(true); + // camelContext.setTracing(true); + + configureDefaultSslProperties(); + registerTrustStore(); } } diff --git a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java index 6ec2221d..a8ff1206 100644 --- a/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/DefaultUserConfiguration.java @@ -5,6 +5,8 @@ * 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 @@ -54,6 +56,7 @@ public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DefaultUserConfiguration.class); protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final String SETUP_WEB_USERS_EXCEPTION_MSG = "Exception occurred during the setup of the Web users in memory"; @Autowired private ClampProperties refProp; @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") @@ -76,8 +79,8 @@ public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { .and().invalidSessionUrl("/designer/timeout.html"); } catch (Exception e) { - logger.error("Exception occurred during the setup of the Web users in memory", e); - throw new CldsUsersException("Exception occurred during the setup of the Web users in memory", e); + logger.error(SETUP_WEB_USERS_EXCEPTION_MSG, e); + throw new CldsUsersException(SETUP_WEB_USERS_EXCEPTION_MSG, e); } } @@ -105,8 +108,8 @@ public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { .authorities(user.getPermissionsString()).and().passwordEncoder(passwordEncoder); } } catch (Exception e) { - logger.error("Exception occurred during the setup of the Web users in memory", e); - throw new CldsUsersException("Exception occurred during the setup of the Web users in memory", e); + logger.error(SETUP_WEB_USERS_EXCEPTION_MSG, e); + throw new CldsUsersException(SETUP_WEB_USERS_EXCEPTION_MSG, e); } } diff --git a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java index 92b0272a..bee0d4c0 100644 --- a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java @@ -39,23 +39,27 @@ import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; import org.onap.clamp.clds.sdc.controller.SdcSingleController; import org.onap.clamp.clds.sdc.controller.SdcSingleControllerStatus; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; -import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; -import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; @Configuration +@ComponentScan(basePackages = "org.onap.clamp.clds") @Profile("clamp-sdc-controller") public class CldsSdcControllerConfiguration { private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsSdcControllerConfiguration.class); private List<SdcSingleController> sdcControllersList = new ArrayList<>(); - @Autowired - private ClampProperties clampProp; - @Autowired - protected CsarInstaller csarInstaller; + private final ClampProperties clampProp; + private final CsarInstaller csarInstaller; + + public CldsSdcControllerConfiguration(ClampProperties clampProp, @Qualifier("oldModelInstaller") CsarInstaller csarInstaller) { + this.clampProp = clampProp; + this.csarInstaller = csarInstaller; + } /** * Loads SDC controllers configuration. diff --git a/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java index 55b90cc5..8b8ee932 100644 --- a/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java @@ -25,36 +25,39 @@ package org.onap.clamp.clds.config.spring; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - import java.util.ArrayList; import java.util.List; - import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; - import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.config.sdc.SdcControllersConfiguration; import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; import org.onap.clamp.clds.sdc.controller.SdcSingleController; import org.onap.clamp.clds.sdc.controller.SdcSingleControllerStatus; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; -import org.onap.clamp.loop.CsarInstallerImpl; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; @Configuration +@ComponentScan(basePackages = {"org.onap.clamp.loop", "org.onap.clamp.clds.config"}) @Profile("clamp-sdc-controller-new") public class SdcControllerConfiguration { private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcControllerConfiguration.class); private List<SdcSingleController> sdcControllersList = new ArrayList<>(); + private final ClampProperties clampProp; + private final CsarInstaller csarInstaller; + @Autowired - private ClampProperties clampProp; - @Autowired - protected CsarInstaller csarInstaller; + public SdcControllerConfiguration(ClampProperties clampProp, @Qualifier("loopInstaller") CsarInstaller csarInstaller) { + this.clampProp = clampProp; + this.csarInstaller = csarInstaller; + } /** * Loads SDC controller configuration. @@ -101,11 +104,6 @@ public class SdcControllerConfiguration { }); } - @Bean(name = "csarInstaller") - public CsarInstaller getCsarInstaller() { - return new CsarInstallerImpl(); - } - @Bean(name = "sdcControllersConfiguration") public SdcControllersConfiguration getSdcControllersConfiguration() { return new SdcControllersConfiguration(); diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java index 44228b22..16a6a748 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -352,7 +352,7 @@ public class CldsDao { } /** - * Helper method to setup the base template properties + * Helper method to setup the base template properties. * * @param template * the template @@ -474,7 +474,7 @@ public class CldsDao { } /** - * Helper method to setup the event prop to the CldsEvent class + * Helper method to setup the event prop to the CldsEvent class. * * @param event * the clds event @@ -742,12 +742,13 @@ public class CldsDao { String dictElementShortName) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsDictionaryItem> dictionaryItems = new ArrayList<>(); - String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " + - "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " + - "de.modified_by, de.timestamp FROM dictionary_elements de, " + - "dictionary d WHERE de.dictionary_id = d.dictionary_id") + String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " + + "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " + + "de.modified_by, de.timestamp FROM dictionary_elements de, " + + "dictionary d WHERE de.dictionary_id = d.dictionary_id") .append((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "") - .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'") : "") + .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + + "'") : "") .append((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "").toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); @@ -780,8 +781,8 @@ public class CldsDao { */ public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) { Map<String, String> dictionaryItems = new HashMap<>(); - String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " + - "FROM dictionary_elements WHERE dict_element_type = '") + String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " + + "FROM dictionary_elements WHERE dict_element_type = '") .append(dictionaryElementType).append("'").toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); diff --git a/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java b/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java index a93b09cf..a56c57d1 100644 --- a/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java +++ b/src/main/java/org/onap/clamp/clds/model/properties/Holmes.java @@ -26,11 +26,11 @@ package org.onap.clamp.clds.model.properties; import com.google.gson.JsonObject; + import org.onap.clamp.clds.util.JsonUtils; /** - * Parse Holmes bpmn parameters json properties. - * Example json: + * Parse Holmes bpmn parameters json properties. Example json: * [{"name":"correlationalLogic","value":"vcwx"},{"name":"configPolicyName","value":"cccc"}] */ public class Holmes extends AbstractModelElement { @@ -43,14 +43,18 @@ public class Holmes extends AbstractModelElement { /** * Default constructor for Holmes Element. * - * @param modelBpmn The model bpmn - * @param modelJson The model json + * @param modelBpmn + * The model bpmn + * @param modelJson + * The model json */ public Holmes(ModelBpmn modelBpmn, JsonObject modelJson) { super(TYPE_HOLMES, modelBpmn, modelJson); - correlationLogic = JsonUtils.getStringValueByName(modelElementJsonNode, "correlationalLogic"); - configPolicyName = JsonUtils.getStringValueByName(modelElementJsonNode, "configPolicyName"); + if (modelElementJsonNode != null) { + correlationLogic = JsonUtils.getStringValueByName(modelElementJsonNode, "correlationalLogic"); + configPolicyName = JsonUtils.getStringValueByName(modelElementJsonNode, "configPolicyName"); + } } public static final String getType() { diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java index 5dcffd61..3792c172 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/BlueprintParser.java @@ -29,6 +29,7 @@ import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import java.util.AbstractMap; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -52,21 +53,23 @@ public class BlueprintParser { private static final String TYPE = "type"; private static final String PROPERTIES = "properties"; private static final String NAME = "name"; - private static final String POLICYID = "policy_id"; - private static final String POLICY_TYPEID = "policy_type_id"; + private static final String INPUT = "inputs"; + private static final String GET_INPUT = "get_input"; + private static final String POLICY_MODELID = "policy_model_id"; private static final String RELATIONSHIPS = "relationships"; private static final String CLAMP_NODE_RELATIONSHIPS_GETS_INPUT_FROM = "clamp_node.relationships.gets_input_from"; private static final String TARGET = "target"; public Set<MicroService> getMicroServices(String blueprintString) { Set<MicroService> microServices = new HashSet<>(); - JsonObject jsonObject = BlueprintParser.convertToJson(blueprintString); - JsonObject results = jsonObject.get(NODE_TEMPLATES).getAsJsonObject(); + JsonObject blueprintJson = BlueprintParser.convertToJson(blueprintString); + JsonObject nodeTemplateList = blueprintJson.get(NODE_TEMPLATES).getAsJsonObject(); + JsonObject inputList = blueprintJson.get(INPUT).getAsJsonObject(); - for (Entry<String, JsonElement> entry : results.entrySet()) { + for (Entry<String, JsonElement> entry : nodeTemplateList.entrySet()) { JsonObject nodeTemplate = entry.getValue().getAsJsonObject(); if (nodeTemplate.get(TYPE).getAsString().contains(DCAE_NODES)) { - MicroService microService = getNodeRepresentation(entry); + MicroService microService = getNodeRepresentation(entry, nodeTemplateList, inputList); microServices.add(microService); } } @@ -89,7 +92,7 @@ public class BlueprintParser { } String msName = theBiggestMicroServiceKey.toLowerCase().contains(HOLMES_PREFIX) ? HOLMES : TCA; return Collections - .singletonList(new MicroService(msName, "onap.policy.monitoring.cdap.tca.hi.lo.app", "", "", "")); + .singletonList(new MicroService(msName, "onap.policies.monitoring.cdap.tca.hi.lo.app", "", "")); } String getName(Entry<String, JsonElement> entry) { @@ -118,30 +121,48 @@ public class BlueprintParser { return ""; } - String getModelType(Entry<String, JsonElement> entry) { + String findModelTypeInTargetArray(JsonArray jsonArray, JsonObject nodeTemplateList, JsonObject inputList) { + for (JsonElement elem : jsonArray) { + String modelType = getModelType( + new AbstractMap.SimpleEntry<String, JsonElement>(elem.getAsJsonObject().get(TARGET).getAsString(), + nodeTemplateList.get(elem.getAsJsonObject().get(TARGET).getAsString()).getAsJsonObject()), + nodeTemplateList, inputList); + if (!modelType.isEmpty()) { + return modelType; + } + } + return ""; + } + + String getModelType(Entry<String, JsonElement> entry, JsonObject nodeTemplateList, JsonObject inputList) { JsonObject ob = entry.getValue().getAsJsonObject(); + // Search first in this node template if (ob.has(PROPERTIES)) { JsonObject properties = ob.get(PROPERTIES).getAsJsonObject(); - if (properties.has(POLICYID)) { - JsonObject policyIdObj = properties.get(POLICYID).getAsJsonObject(); - if (policyIdObj.has(POLICY_TYPEID)) { - return policyIdObj.get(POLICY_TYPEID).getAsString(); + if (properties.has(POLICY_MODELID)) { + if (properties.get(POLICY_MODELID).isJsonObject()) { + // it's a blueprint parameter + return inputList.get(properties.get(POLICY_MODELID).getAsJsonObject().get(GET_INPUT).getAsString()) + .getAsJsonObject().get("default").getAsString(); + } else { + // It's a direct value + return properties.get(POLICY_MODELID).getAsString(); } } } + // Or it's may be defined in a relationship + if (ob.has(RELATIONSHIPS)) { + return findModelTypeInTargetArray(ob.get(RELATIONSHIPS).getAsJsonArray(), nodeTemplateList, inputList); + } return ""; } - String getBlueprintName(Entry<String, JsonElement> entry) { - return entry.getKey(); - } - - MicroService getNodeRepresentation(Entry<String, JsonElement> entry) { + MicroService getNodeRepresentation(Entry<String, JsonElement> entry, JsonObject nodeTemplateList, + JsonObject inputList) { String name = getName(entry); String getInputFrom = getInput(entry); - String modelType = getModelType(entry); - String blueprintName = getBlueprintName(entry); - return new MicroService(name, modelType, getInputFrom, "", blueprintName); + String modelType = getModelType(entry, nodeTemplateList, inputList); + return new MicroService(name, modelType, getInputFrom, ""); } private String getTarget(JsonObject elementObject) { diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java index 5a21a1f8..7ef217b4 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java @@ -132,7 +132,7 @@ public class CsarHandler { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - if (entry.getName().contains(BLUEPRINT_TYPE)) { + if (!entry.isDirectory() && entry.getName().contains(BLUEPRINT_TYPE)) { BlueprintArtifact blueprintArtifact = new BlueprintArtifact(); blueprintArtifact.setBlueprintArtifactName( entry.getName().substring(entry.getName().lastIndexOf('/') + 1, entry.getName().length())); diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstaller.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstaller.java index 12a761db..a1f8897f 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstaller.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstaller.java @@ -27,6 +27,7 @@ import org.onap.clamp.clds.exception.policy.PolicyModelException; import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; public interface CsarInstaller { + String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-"; boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException; diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java index 6dc41834..6c41e9c6 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java @@ -56,6 +56,7 @@ import org.onap.clamp.clds.transform.XslTransformer; import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.drawing.SvgFacade; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @@ -68,6 +69,7 @@ import org.yaml.snakeyaml.Yaml; * received from SDC in DB. */ @Component +@Qualifier("oldModelInstaller") public class CsarInstallerImpl implements CsarInstaller { private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class); diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java index ac4daeff..9bc7a022 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/MicroService.java @@ -29,16 +29,14 @@ import java.util.Objects; public class MicroService { private final String name; private final String modelType; - private final String blueprintName; private final String inputFrom; private String mappedNameJpa; - public MicroService(String name, String modelType, String inputFrom, String mappedNameJpa, String blueprintName) { + public MicroService(String name, String modelType, String inputFrom, String mappedNameJpa) { this.name = name; this.inputFrom = inputFrom; this.mappedNameJpa = mappedNameJpa; - this.modelType = modelType; - this.blueprintName = blueprintName; + this.modelType = modelType; } public String getName() { @@ -53,15 +51,10 @@ public class MicroService { return inputFrom; } - public String getBlueprintName() { - return blueprintName; - } - @Override public String toString() { return "MicroService{" + "name='" + name + '\'' + ", modelType='" + modelType + '\'' + ", inputFrom='" - + inputFrom + '\'' + ", mappedNameJpa='" + mappedNameJpa + '\'' + ", blueprintName='" - + blueprintName + '\'' + '}'; + + inputFrom + '\'' + ", mappedNameJpa='" + mappedNameJpa + '\'' + '}'; } public String getMappedNameJpa() { @@ -81,11 +74,12 @@ public class MicroService { return false; } MicroService that = (MicroService) o; - return name.equals(that.name) && modelType.equals(that.modelType) && inputFrom.equals(that.inputFrom) && mappedNameJpa.equals(that.mappedNameJpa) && blueprintName.equals(that.blueprintName); + return name.equals(that.name) && modelType.equals(that.modelType) && inputFrom.equals(that.inputFrom) + && mappedNameJpa.equals(that.mappedNameJpa); } @Override public int hashCode() { - return Objects.hash(name, modelType, inputFrom, mappedNameJpa, blueprintName); + return Objects.hash(name, modelType, inputFrom, mappedNameJpa); } } diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java index bf7c502a..63a91331 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -5,6 +5,8 @@ * Copyright (C) 2017-2019 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 @@ -26,7 +28,6 @@ package org.onap.clamp.clds.service; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; - import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; @@ -35,11 +36,9 @@ import java.lang.reflect.Type; import java.util.Date; import java.util.List; import java.util.UUID; - import javax.servlet.http.HttpServletRequest; import javax.ws.rs.BadRequestException; import javax.xml.transform.TransformerException; - import org.apache.camel.Produce; import org.json.simple.parser.ParseException; import org.onap.clamp.clds.camel.CamelProxy; @@ -59,7 +58,7 @@ import org.onap.clamp.clds.model.DcaeEvent; import org.onap.clamp.clds.model.ValueItem; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.sdc.SdcServiceInfo; -import org.onap.clamp.clds.sdc.controller.installer.CsarInstallerImpl; +import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; import org.onap.clamp.clds.transform.XslTransformer; import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.LoggingUtils; @@ -206,7 +205,7 @@ public class CldsService extends SecureServiceBase { public List<CldsMonitoringDetails> getCldsDetails() { util.entering(request, "CldsService: GET model details"); Date startTime = new Date(); - List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); + final List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET cldsDetails completed"); @@ -226,7 +225,7 @@ public class CldsService extends SecureServiceBase { LoggingUtils.setTimeContext(startTime, new Date()); CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this); - CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo(); + final CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); @@ -248,7 +247,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET bpmnText for modelName={}", modelName); - CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); + final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model bpmn completed"); @@ -269,7 +268,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET imageText for modelName={}", modelName); - CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); + final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model image completed"); @@ -285,7 +284,7 @@ public class CldsService extends SecureServiceBase { */ public CldsModel getModel(String modelName) { util.entering(request, "CldsService: GET model"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadCl); logger.debug("GET model for modelName={}", modelName); CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false); @@ -295,7 +294,7 @@ public class CldsService extends SecureServiceBase { try { // Method to call dcae inventory and invoke insert event method if (cldsModel.canDcaeInventoryCall() - && !cldsModel.getTemplateName().startsWith(CsarInstallerImpl.TEMPLATE_NAME_PREFIX)) { + && !cldsModel.getTemplateName().startsWith(CsarInstaller.TEMPLATE_NAME_PREFIX)) { dcaeInventoryServices.setEventInventory(cldsModel, getUserId()); } // This is a blocking call @@ -326,7 +325,7 @@ public class CldsService extends SecureServiceBase { */ public CldsModel putModel(String modelName, CldsModel cldsModel) { util.entering(request, "CldsService: PUT model"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionUpdateCl); isAuthorizedForVf(cldsModel); logger.info("PUT model for modelName={}", modelName); @@ -353,7 +352,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET list of model names"); - List<ValueItem> names = cldsDao.getModelNames(); + final List<ValueItem> names = cldsDao.getModelNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model names completed"); @@ -412,11 +411,11 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); // get vars and format if necessary - String prop = model.getPropText(); - String bpmn = model.getBpmnText(); - String docText = model.getDocText(); - String controlName = model.getControlName(); - String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); + final String prop = model.getPropText(); + final String bpmn = model.getBpmnText(); + final String docText = model.getDocText(); + final String controlName = model.getControlName(); + final String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); logger.info("PUT bpmnJson={}", bpmnJson); // Test flag coming from UI or from Clamp config boolean isTest = Boolean.parseBoolean(test) @@ -474,7 +473,7 @@ public class CldsService extends SecureServiceBase { */ public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { util.entering(request, "CldsService: Post dcae event"); - Date startTime = new Date(); + final Date startTime = new Date(); String userid = null; // TODO: allow auth checking to be turned off by removing the permission // type property diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index f60c6383..d107731b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -5,6 +5,8 @@ * 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 @@ -79,7 +81,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET bpmnText for templateName=" + templateName); - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template bpmn completed"); @@ -100,7 +102,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET imageText for templateName=" + templateName); - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template image completed"); @@ -116,7 +118,7 @@ public class CldsTemplateService extends SecureServiceBase { */ public CldsTemplate getTemplate(String templateName) { util.entering(request, "CldsTemplateService: GET template"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET model for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); @@ -137,7 +139,7 @@ public class CldsTemplateService extends SecureServiceBase { */ public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { util.entering(request, "CldsTemplateService: PUT template"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionUpdateTemplate); logger.info("PUT Template for templateName=" + templateName); logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText()); @@ -162,7 +164,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET list of template names"); - List<ValueItem> names = cldsDao.getTemplateNames(); + final List<ValueItem> names = cldsDao.getTemplateNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template names completed"); diff --git a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java index f2c75ead..81bafef4 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.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 @@ -84,7 +86,7 @@ public class CldsToscaService extends SecureServiceBase { * type */ public ResponseEntity<?> parseToscaModelAndSave(String toscaModelName, CldsToscaModel cldsToscaModel) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsToscaService: Parse Tosca model and save", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionUpdateTosca); @@ -107,7 +109,7 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get All tosca models success", this.getClass().getName()); auditLogger.info("Get All tosca models"); @@ -128,7 +130,8 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)) + .get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get tosca models by model name success", this.getClass().getName()); auditLogger.info("GET tosca models by model name completed"); @@ -140,6 +143,7 @@ public class CldsToscaService extends SecureServiceBase { * from the database. * * @param policyType + * The type of the policy * @return clds tosca model - CLDS tosca model for a given policy type */ public CldsToscaModel getToscaModelsByPolicyType(String policyType) { @@ -147,7 +151,8 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)) + .get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get tosca models by policyType success", this.getClass().getName()); auditLogger.info("GET tosca models by policyType completed"); diff --git a/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java b/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java index f1344723..595b1805 100644 --- a/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java +++ b/src/main/java/org/onap/clamp/clds/tosca/ToscaSchemaConstants.java @@ -58,7 +58,7 @@ public class ToscaSchemaConstants { public static final String PATTERN = "pattern"; // Prefix for policy nodes - public static final String POLICY_NODE = "onap.policy."; + public static final String POLICY_NODE = "onap.policies."; // Prefix for data nodes public static final String POLICY_DATA = "onap.datatypes."; diff --git a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java index f08bf7b2..85aae0a5 100644 --- a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java @@ -162,7 +162,7 @@ public final class CryptoUtils { private static SecretKeySpec readSecretKeySpec(String propertiesFileName) { Properties props = new Properties(); try { - //Workaround fix to make encryption key configurable + // Workaround fix to make encryption key configurable // System environment variable takes precedence for over clds/key.properties String encryptionKey = System.getenv(AES_ENCRYPTION_KEY); if(encryptionKey != null && encryptionKey.trim().length() > 0) { diff --git a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java index 08bb9760..cbe7eba9 100644 --- a/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/LoggingUtils.java @@ -1,373 +1,413 @@ -/*-
- * ============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.util;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import java.net.HttpURLConnection;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Date;
-import java.util.TimeZone;
-import java.util.UUID;
-
-import javax.net.ssl.HttpsURLConnection;
-import javax.servlet.http.HttpServletRequest;
-import javax.validation.constraints.NotNull;
-
-import org.onap.clamp.clds.service.DefaultUserNameHandler;
-import org.slf4j.MDC;
-import org.slf4j.event.Level;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-/**
- * This class handles the special info that appear in the log, like RequestID,
- * time context, ...
- */
-public class LoggingUtils {
- protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class);
-
- private static final DateFormat DATE_FORMAT = createDateFormat();
-
- /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */
- private static final String EMPTY_MESSAGE = "";
-
- /** Logger delegate. */
- private EELFLogger mlogger;
- /** Automatic UUID, overrideable per adapter or per invocation. */
- private static UUID sInstanceUUID = UUID.randomUUID();
-
- /**
- * Constructor.
- */
- public LoggingUtils(final EELFLogger loggerP) {
- this.mlogger = checkNotNull(loggerP);
- }
-
- /**
- * Set request related logging variables in thread local data via MDC
- *
- * @param service Service Name of API (ex. "PUT template")
- * @param partner Partner name (client or user invoking API)
- */
- public static void setRequestContext(String service, String partner) {
- MDC.put("RequestId", UUID.randomUUID().toString());
- MDC.put("ServiceName", service);
- MDC.put("PartnerName", partner);
- //Defaulting to HTTP/1.1 protocol
- MDC.put("Protocol", "HTTP/1.1");
- try {
- MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName());
- MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress());
- } catch (UnknownHostException e) {
- logger.error("Failed to initiate setRequestContext", e);
- }
- }
-
- /**
- * Set time related logging variables in thread local data via MDC.
- *
- * @param beginTimeStamp Start time
- * @param endTimeStamp End time
- */
- public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) {
- MDC.put("BeginTimestamp", generateTimestampStr(beginTimeStamp));
- MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp));
- MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime()));
- }
-
- /**
- * Set response related logging variables in thread local data via MDC.
- *
- * @param code Response code ("0" indicates success)
- * @param description Response description
- * @param className class name of invoking class
- */
- public static void setResponseContext(String code, String description, String className) {
- MDC.put("ResponseCode", code);
- MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR");
- MDC.put("ResponseDescription", description != null ? description : "");
- MDC.put("ClassName", className != null ? className : "");
- }
-
- /**
- * Set target related logging variables in thread local data via MDC
- *
- * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
- * @param targetServiceName Target service name (name of API invoked on target)
- */
- public static void setTargetContext(String targetEntity, String targetServiceName) {
- MDC.put("TargetEntity", targetEntity != null ? targetEntity : "");
- MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : "");
- }
-
- /**
- * Set error related logging variables in thread local data via MDC.
- *
- * @param code Error code
- * @param description Error description
- */
- public static void setErrorContext(String code, String description) {
- MDC.put("ErrorCode", code);
- MDC.put("ErrorDescription", description != null ? description : "");
- }
-
- private static String generateTimestampStr(Date timeStamp) {
- return DATE_FORMAT.format(timeStamp);
- }
-
- /**
- * Get a previously stored RequestID for the thread local data via MDC. If
- * one was not previously stored, generate one, store it, and return that
- * one.
- *
- * @return A string with the request ID
- */
- public static String getRequestId() {
- String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
- if (requestId == null || requestId.isEmpty()) {
- requestId = UUID.randomUUID().toString();
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
- }
- return requestId;
- }
-
- private static DateFormat createDateFormat() {
- DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
- dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
- return dateFormat;
- }
-
-
-
- /*********************************************************************************************
- * Method for ONAP Application Logging Specification v1.2
- ********************************************************************************************/
-
- /**
- * Report <tt>ENTERING</tt> marker.
- *
- * @param request non-null incoming request (wrapper)
- * @param serviceName service name
- */
- public void entering(HttpServletRequest request, String serviceName) {
- MDC.clear();
- checkNotNull(request);
- // Extract MDC values from standard HTTP headers.
- final String requestId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID));
- final String invocationId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID));
- final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME));
-
- // Default the partner name to the user name used to login to clamp
- if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) {
- MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler()
- .retrieveUserName(SecurityContextHolder.getContext()));
- }
-
- // Set standard MDCs. Override this entire method if you want to set
- // others, OR set them BEFORE or AFTER the invocation of #entering,
- // depending on where you need them to appear, OR extend the
- // ServiceDescriptor to add them.
- MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP,
- ZonedDateTime.now(ZoneOffset.UTC)
- .format(DateTimeFormatter.ISO_INSTANT));
- MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId);
- MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId);
- MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr()));
- MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName()));
- MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID));
-
- // Default the service name to the requestURI, in the event that
- // no value has been provided.
- if (serviceName == null
- || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) {
- MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI());
- } else {
- MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName);
- }
-
- this.mlogger.info(ONAPLogConstants.Markers.ENTRY);
- }
-
- /**
- * Report <tt>EXITING</tt> marker.
- *
- * @param code response code
- * @param descrption response description
- * @param severity response severity
- * @param status response status code
- */
- public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) {
- try {
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity));
- MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status));
- this.mlogger.info(ONAPLogConstants.Markers.EXIT);
- }
- finally {
- MDC.clear();
- }
- }
-
- /**
- * Report pending invocation with <tt>INVOKE</tt> marker,
- * setting standard ONAP logging headers automatically.
- *
- * @param con http URL connection
- * @param targetEntity target entity
- * @param targetServiceName target service name
- * @return invocation ID to be passed with invocation
- */
- public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) {
- final String invocationId = UUID.randomUUID().toString();
-
- // Set standard HTTP headers on (southbound request) builder.
- con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
- defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
- con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
- invocationId);
- con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
- defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
-
- invokeContext(targetEntity, targetServiceName, invocationId);
-
- // Log INVOKE*, with the invocationID as the message body.
- // (We didn't really want this kind of behavior in the standard,
- // but is it worse than new, single-message MDC?)
- this.mlogger.info(ONAPLogConstants.Markers.INVOKE);
- this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
- return con;
- }
-
- /**
- * Report pending invocation with <tt>INVOKE</tt> marker,
- * setting standard ONAP logging headers automatically.
- *
- * @param con http URL connection
- * @param targetEntity target entity
- * @param targetServiceName target service name
- * @return invocation ID to be passed with invocation
- */
- public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) {
- final String invocationId = UUID.randomUUID().toString();
-
- // Set standard HTTP headers on (southbound request) builder.
- con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID,
- defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)));
- con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID,
- invocationId);
- con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME,
- defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)));
-
- invokeContext(targetEntity, targetServiceName, invocationId);
-
- // Log INVOKE*, with the invocationID as the message body.
- // (We didn't really want this kind of behavior in the standard,
- // but is it worse than new, single-message MDC?)
- this.mlogger.info(ONAPLogConstants.Markers.INVOKE);
- this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}");
- return con;
- }
-
- /**
- * Invokes return context.
- */
- public void invokeReturn() {
- // Add the Invoke-return marker and clear the needed MDC
- this.mlogger.info(ONAPLogConstants.Markers.INVOKE_RETURN);
- invokeReturnContext();
- }
-
- /**
- * Dependency-free nullcheck.
- *
- * @param in to be checked
- * @param <T> argument (and return) type
- * @return input arg
- */
- private static <T> T checkNotNull(final T in) {
- if (in == null) {
- throw new NullPointerException();
- }
- return in;
- }
-
- /**
- * Dependency-free string default.
- *
- * @param in to be filtered
- * @return input string or null
- */
- private static String defaultToEmpty(final Object in) {
- if (in == null) {
- return "";
- }
- return in.toString();
- }
-
- /**
- * Dependency-free string default.
- *
- * @param in to be filtered
- * @return input string or null
- */
- private static String defaultToUUID(final String in) {
- if (in == null) {
- return UUID.randomUUID().toString();
- }
- return in;
- }
-
- /**
- * Set target related logging variables in thread local data via MDC.
- *
- * @param targetEntity Target entity (an external/sub component, for ex. "sdc")
- * @param targetServiceName Target service name (name of API invoked on target)
- * @param invocationID The invocation ID
- */
- private void invokeContext(String targetEntity, String targetServiceName, String invocationID) {
- MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, defaultToEmpty(targetEntity));
- MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName));
- MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID);
- MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP,
- ZonedDateTime.now(ZoneOffset.UTC)
- .format(DateTimeFormatter.ISO_INSTANT));
- }
-
- /**
- * Clear target related logging variables in thread local data via MDC.
- */
- private void invokeReturnContext() {
- MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY);
- MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME);
- MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT);
- }
-}
+/*- + * ============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.util; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.TimeZone; +import java.util.UUID; + +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.http.HttpServletRequest; +import javax.validation.constraints.NotNull; + +import org.onap.clamp.clds.service.DefaultUserNameHandler; +import org.slf4j.MDC; +import org.slf4j.event.Level; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * This class handles the special info that appear in the log, like RequestID, + * time context, ... + */ +public class LoggingUtils { + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoggingUtils.class); + + private static final DateFormat DATE_FORMAT = createDateFormat(); + + /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */ + private static final String EMPTY_MESSAGE = ""; + + /** Logger delegate. */ + private EELFLogger mlogger; + + /** Automatic UUID, overrideable per adapter or per invocation. */ + private static UUID sInstanceUUID = UUID.randomUUID(); + + /** + * Constructor. + */ + public LoggingUtils(final EELFLogger loggerP) { + this.mlogger = checkNotNull(loggerP); + } + + /** + * Set request related logging variables in thread local data via MDC. + * + * @param service Service Name of API (ex. "PUT template") + * @param partner Partner name (client or user invoking API) + */ + public static void setRequestContext(String service, String partner) { + MDC.put("RequestId", UUID.randomUUID().toString()); + MDC.put("ServiceName", service); + MDC.put("PartnerName", partner); + //Defaulting to HTTP/1.1 protocol + MDC.put("Protocol", "HTTP/1.1"); + try { + MDC.put("ServerFQDN", InetAddress.getLocalHost().getCanonicalHostName()); + MDC.put("ServerIPAddress", InetAddress.getLocalHost().getHostAddress()); + } catch (UnknownHostException e) { + logger.error("Failed to initiate setRequestContext", e); + } + } + + /** + * Set time related logging variables in thread local data via MDC. + * + * @param beginTimeStamp Start time + * @param endTimeStamp End time + */ + public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) { + MDC.put("EntryTimestamp", generateTimestampStr(beginTimeStamp)); + MDC.put("EndTimestamp", generateTimestampStr(endTimeStamp)); + MDC.put("ElapsedTime", String.valueOf(endTimeStamp.getTime() - beginTimeStamp.getTime())); + } + + /** + * Set response related logging variables in thread local data via MDC. + * + * @param code Response code ("0" indicates success) + * @param description Response description + * @param className class name of invoking class + */ + public static void setResponseContext(String code, String description, String className) { + MDC.put("ResponseCode", code); + MDC.put("StatusCode", code.equals("0") ? "COMPLETE" : "ERROR"); + MDC.put("ResponseDescription", description != null ? description : ""); + MDC.put("ClassName", className != null ? className : ""); + } + + /** + * Set target related logging variables in thread local data via MDC. + * + * @param targetEntity Target entity (an external/sub component, for ex. "sdc") + * @param targetServiceName Target service name (name of API invoked on target) + */ + public static void setTargetContext(String targetEntity, String targetServiceName) { + MDC.put("TargetEntity", targetEntity != null ? targetEntity : ""); + MDC.put("TargetServiceName", targetServiceName != null ? targetServiceName : ""); + } + + /** + * Set error related logging variables in thread local data via MDC. + * + * @param code Error code + * @param description Error description + */ + public static void setErrorContext(String code, String description) { + MDC.put("ErrorCode", code); + MDC.put("ErrorDescription", description != null ? description : ""); + } + + private static String generateTimestampStr(Date timeStamp) { + return DATE_FORMAT.format(timeStamp); + } + + /** + * Get a previously stored RequestID for the thread local data via MDC. If + * one was not previously stored, generate one, store it, and return that + * one. + * + * @return A string with the request ID + */ + public static String getRequestId() { + String requestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + if (requestId == null || requestId.isEmpty()) { + requestId = UUID.randomUUID().toString(); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + } + return requestId; + } + + private static DateFormat createDateFormat() { + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateFormat; + } + + + + /********************************************************************************************* + * Method for ONAP Application Logging Specification v1.2 + ********************************************************************************************/ + + /** + * Report <tt>ENTERING</tt> marker. + * + * @param request non-null incoming request (wrapper) + * @param serviceName service name + */ + public void entering(HttpServletRequest request, String serviceName) { + MDC.clear(); + checkNotNull(request); + // Extract MDC values from standard HTTP headers. + final String requestId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.REQUEST_ID)); + final String invocationId = defaultToUUID(request.getHeader(ONAPLogConstants.Headers.INVOCATION_ID)); + final String partnerName = defaultToEmpty(request.getHeader(ONAPLogConstants.Headers.PARTNER_NAME)); + + // Default the partner name to the user name used to login to clamp + if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) { + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, new DefaultUserNameHandler() + .retrieveUserName(SecurityContextHolder.getContext())); + } + + // Set standard MDCs. Override this entire method if you want to set + // others, OR set them BEFORE or AFTER the invocation of #entering, + // depending on where you need them to appear, OR extend the + // ServiceDescriptor to add them. + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, requestId); + MDC.put(ONAPLogConstants.MDCs.INVOCATION_ID, invocationId); + MDC.put(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); + MDC.put(ONAPLogConstants.MDCs.SERVER_FQDN, defaultToEmpty(request.getServerName())); + MDC.put(ONAPLogConstants.MDCs.INSTANCE_UUID, defaultToEmpty(sInstanceUUID)); + + // Default the service name to the requestURI, in the event that + // no value has been provided. + if (serviceName == null + || serviceName.equalsIgnoreCase(EMPTY_MESSAGE)) { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, request.getRequestURI()); + } else { + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, serviceName); + } + + this.mlogger.info(ONAPLogConstants.Markers.ENTRY); + } + + /** + * Report <tt>EXITING</tt> marker. + * + + * @param code response code + * @param descrption response description + * @param severity response severity + * @param status response status code + */ + public void exiting(String code, String descrption, Level severity, ONAPLogConstants.ResponseStatus status) { + try { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_CODE, defaultToEmpty(code)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, defaultToEmpty(severity)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); + + ZonedDateTime startTime = ZonedDateTime.parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), + DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC)); + ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC); + MDC.put(ONAPLogConstants.MDCs.END_TIMESTAMP, endTime.format(DateTimeFormatter.ISO_INSTANT)); + long duration = ChronoUnit.MILLIS.between(startTime, endTime); + MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIMESTAMP, String.valueOf(duration)); + this.mlogger.info(ONAPLogConstants.Markers.EXIT); + } + finally { + MDC.clear(); + } + } + + /** + * Get the property value. + * + * @param name The name of the property + * @return The value of the property + */ + public String getProperties(String name) { + return MDC.get(name); + } + + /** + * Report pending invocation with <tt>INVOKE</tt> marker, + * setting standard ONAP logging headers automatically. + * + * @param con The HTTP url connection + * @param targetEntity The target entity + * @param targetServiceName The target service name + * @return The HTTP url connection + */ + public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, String targetServiceName) { + final String invocationId = UUID.randomUUID().toString(); + + // Set standard HTTP headers on (southbound request) builder. + con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); + con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, + invocationId); + con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); + + invokeContext(targetEntity, targetServiceName, invocationId); + + // Log INVOKE*, with the invocationID as the message body. + // (We didn't really want this kind of behavior in the standard, + // but is it worse than new, single-message MDC?) + this.mlogger.info(ONAPLogConstants.Markers.INVOKE); + this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); + return con; + } + + /** + * Report pending invocation with <tt>INVOKE</tt> marker, + * setting standard ONAP logging headers automatically. + * + * @param targetEntity The target entity + * @param targetServiceName The target service name + */ + public void invoke(String targetEntity, String targetServiceName) { + final String invocationId = UUID.randomUUID().toString(); + + invokeContext(targetEntity, targetServiceName, invocationId); + + // Log INVOKE*, with the invocationID as the message body. + // (We didn't really want this kind of behavior in the standard, + // but is it worse than new, single-message MDC?) + this.mlogger.info(ONAPLogConstants.Markers.INVOKE); + this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); + } + + /** + * Report pending invocation with <tt>INVOKE</tt> marker, + * setting standard ONAP logging headers automatically. + * + * @param con The HTTPS url connection + * @param targetEntity The target entity + * @param targetServiceName The target service name + * @return The HTTPS url connection + */ + public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, String targetServiceName) { + final String invocationId = UUID.randomUUID().toString(); + + // Set standard HTTP headers on (southbound request) builder. + con.setRequestProperty(ONAPLogConstants.Headers.REQUEST_ID, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID))); + con.setRequestProperty(ONAPLogConstants.Headers.INVOCATION_ID, + invocationId); + con.setRequestProperty(ONAPLogConstants.Headers.PARTNER_NAME, + defaultToEmpty(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME))); + + invokeContext(targetEntity, targetServiceName, invocationId); + + // Log INVOKE*, with the invocationID as the message body. + // (We didn't really want this kind of behavior in the standard, + // but is it worse than new, single-message MDC?) + this.mlogger.info(ONAPLogConstants.Markers.INVOKE); + this.mlogger.info(ONAPLogConstants.Markers.INVOKE_SYNC + "{" + invocationId + "}"); + return con; + } + + /** + * Report pending invocation with <tt>INVOKE-RETURN</tt> marker. + */ + public void invokeReturn() { + // Add the Invoke-return marker and clear the needed MDC + this.mlogger.info(ONAPLogConstants.Markers.INVOKE_RETURN); + invokeReturnContext(); + } + + /** + * Dependency-free nullcheck. + * + * @param in to be checked + * @param <T> argument (and return) type + * @return input arg + */ + private static <T> T checkNotNull(final T in) { + if (in == null) { + throw new NullPointerException(); + } + return in; + } + + /** + * Dependency-free string default. + * + * @param in to be filtered + * @return input string or null + */ + private static String defaultToEmpty(final Object in) { + if (in == null) { + return ""; + } + return in.toString(); + } + + /** + * Dependency-free string default. + * + * @param in to be filtered + * @return input string or null + */ + private static String defaultToUUID(final String in) { + if (in == null) { + return UUID.randomUUID().toString(); + } + return in; + } + + /** + * Set target related logging variables in thread local data via MDC. + * + * @param targetEntity Target entity (an external/sub component, for ex. "sdc") + * @param targetServiceName Target service name (name of API invoked on target) + * @param invocationID The invocation ID + */ + private void invokeContext(String targetEntity, String targetServiceName, String invocationID) { + MDC.put(ONAPLogConstants.MDCs.TARGET_ENTITY, defaultToEmpty(targetEntity)); + MDC.put(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); + MDC.put(ONAPLogConstants.MDCs.INVOCATIONID_OUT, invocationID); + MDC.put(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ISO_INSTANT)); + } + + /** + * Clear target related logging variables in thread local data via MDC. + */ + private void invokeReturnContext() { + MDC.remove(ONAPLogConstants.MDCs.TARGET_ENTITY); + MDC.remove(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + MDC.remove(ONAPLogConstants.MDCs.INVOCATIONID_OUT); + MDC.remove(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP); + } +} diff --git a/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java b/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java index eea01a39..906f8e03 100644 --- a/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java +++ b/src/main/java/org/onap/clamp/clds/util/ONAPLogConstants.java @@ -122,7 +122,8 @@ public final class ONAPLogConstants { * </p> * */ public static final String ENTRY_TIMESTAMP = "EntryTimestamp"; - + public static final String END_TIMESTAMP = "EndTimestamp"; + public static final String ELAPSED_TIMESTAMP = "ElapsedTime"; /** MDC recording timestamp at the start of the current invocation. */ public static final String INVOKE_TIMESTAMP = "InvokeTimestamp"; diff --git a/src/main/java/org/onap/clamp/clds/util/XmlTools.java b/src/main/java/org/onap/clamp/clds/util/XmlTools.java index a812fa12..a7d4ed9f 100644 --- a/src/main/java/org/onap/clamp/clds/util/XmlTools.java +++ b/src/main/java/org/onap/clamp/clds/util/XmlTools.java @@ -24,6 +24,7 @@ package org.onap.clamp.clds.util; import java.io.StringWriter; +import javax.xml.XMLConstants; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; @@ -39,6 +40,12 @@ import org.w3c.dom.Document; public class XmlTools { /** + * Private constructor to avoid creating instances of util class. + */ + private XmlTools(){ + } + + /** * Transforms document to XML string. * * @param doc XML document @@ -47,6 +54,7 @@ public class XmlTools { public static String exportXmlDocumentAsString(Document doc) { try { TransformerFactory tf = TransformerFactory.newInstance(); + tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java index fe2d5cb3..d88a17e8 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java @@ -64,7 +64,7 @@ public class Painter { adjustGraphics2DProperties(); - Point origin = new Point(0, rectHeight / 2); + Point origin = new Point(1, rectHeight / 2); ImageBuilder ib = new ImageBuilder(g2d, documentBuilder, origin, baseLength, rectHeight); doTheActualDrawing(collector, microServices, policy, ib); diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java b/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java index f5bd6e79..f7bf92bf 100644 --- a/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/SvgFacade.java @@ -41,7 +41,7 @@ public class SvgFacade { Painter p = new Painter(svgGraphics2D, dp); ClampGraphBuilder cgp = new ClampGraphBuilder(p).collector("VES"); cgp.addAllMicroServices(microServicesChain); - ClampGraph cg = cgp.policy("Policy").build(); + ClampGraph cg = cgp.policy("OperationalPolicy").build(); return cg.getAsSVG(); } diff --git a/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java b/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java new file mode 100644 index 00000000..3da93b26 --- /dev/null +++ b/src/main/java/org/onap/clamp/flow/log/FlowLogOperation.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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.flow.log; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.camel.Exchange; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.clds.util.ONAPLogConstants; +import org.slf4j.event.Level; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Component; + +/** + * The Flow log operations. + */ +@Component +public class FlowLogOperation { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(FlowLogOperation.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); + private LoggingUtils util = new LoggingUtils(logger); + + @Autowired + private HttpServletRequest request; + + /** + * Generate the entry log. + * + * @param serviceDesc + * The service description the loop name + */ + public void startLog(Exchange exchange, String serviceDesc) { + util.entering(request, serviceDesc); + exchange.setProperty(ONAPLogConstants.Headers.REQUEST_ID, util.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)); + exchange.setProperty(ONAPLogConstants.Headers.INVOCATION_ID, + util.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)); + exchange.setProperty(ONAPLogConstants.Headers.PARTNER_NAME, + util.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)); + } + + /** + * Generate the exiting log. + */ + public void endLog() { + util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); + } + + /** + * Generate the error exiting log. + */ + public void errorLog() { + util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "Failed", Level.INFO, + ONAPLogConstants.ResponseStatus.ERROR); + } + + /** + * Generate the error exiting log. + */ + public void httpErrorLog() { + + } + + /** + * Generate the invoke log. + */ + public void invokeLog(String targetEntity, String targetServiceName) { + util.invoke(targetEntity, targetServiceName); + } + + /** + * Generate the invoke return marker. + */ + public void invokeReturnLog() { + util.invokeReturn(); + } +} diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index 0041c589..6de2863e 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -23,6 +23,8 @@ package org.onap.clamp.loop; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; @@ -45,7 +47,9 @@ import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; +import javax.persistence.OrderBy; import javax.persistence.Table; +import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; @@ -65,6 +69,9 @@ public class Loop implements Serializable { */ private static final long serialVersionUID = -286522707701388642L; + @Transient + private static final EELFLogger logger = EELFManager.getInstance().getLogger(Loop.class); + @Id @Expose @Column(nullable = false, name = "name", unique = true) @@ -114,6 +121,7 @@ public class Loop implements Serializable { @Expose @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop") + @OrderBy("id DESC") private Set<LoopLog> loopLogs = new HashSet<>(); public Loop() { @@ -277,7 +285,9 @@ public class Loop implements Serializable { jsonArray.add(policyNode); policyNode.addProperty("policy-id", policyName); } - return new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject); + String payload = new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject); + logger.info("PdpGroup policy payload: " + payload); + return payload; } /** diff --git a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/loop/LoopCsarInstaller.java index f407aa94..ad13ad34 100644 --- a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/loop/LoopCsarInstaller.java @@ -25,7 +25,6 @@ package org.onap.clamp.loop; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.google.gson.Gson; import com.google.gson.JsonObject; import java.io.IOException; @@ -51,9 +50,16 @@ import org.onap.clamp.clds.util.drawing.SvgFacade; import org.onap.clamp.policy.Policy; import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.clamp.policy.operational.OperationalPolicy; +import org.onap.sdc.tosca.parser.api.IEntityDetails; +import org.onap.sdc.tosca.parser.elements.queries.EntityQuery; +import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery; +import org.onap.sdc.tosca.parser.enums.EntityTemplateType; import org.onap.sdc.tosca.parser.enums.SdcTypes; import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.Property; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.yaml.snakeyaml.Yaml; @@ -63,10 +69,11 @@ import org.yaml.snakeyaml.Yaml; * There is no state kept by the bean. It's used to deploy the csar/notification * received from SDC in DB. */ -public class CsarInstallerImpl implements CsarInstaller { +@Component +@Qualifier("loopInstaller") +public class LoopCsarInstaller implements CsarInstaller { - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class); - public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-"; + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopCsarInstaller.class); public static final String CONTROL_NAME_PREFIX = "ClosedLoop-"; public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input"; // This will be used later as the policy scope @@ -179,21 +186,49 @@ public class CsarInstallerImpl implements CsarInstaller { return globalProperties; } - private JsonObject createModelPropertiesJson(CsarHandler csar) { - JsonObject modelProperties = new JsonObject(); - Gson gson = new Gson(); - modelProperties.add("serviceDetails", - gson.fromJson(gson.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class)); + private static JsonObject createVfModuleProperties(CsarHandler csar) { + JsonObject vfModuleProps = new JsonObject(); + // Loop on all Groups defined in the service (VFModule entries type: + // org.openecomp.groups.VfModule) + for (IEntityDetails entity : csar.getSdcCsarHelper().getEntity( + EntityQuery.newBuilder(EntityTemplateType.GROUP).build(), + TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false)) { + // Get all metadata info + JsonObject allVfProps = (JsonObject) JsonUtils.GSON.toJsonTree(entity.getMetadata().getAllProperties()); + vfModuleProps.add(entity.getMetadata().getAllProperties().get("vfModuleModelName"), allVfProps); + // now append the properties section so that we can also have isBase, + // volume_group, etc ... fields under the VFmodule name + for (Entry<String, Property> additionalProp : entity.getProperties().entrySet()) { + allVfProps.add(additionalProp.getValue().getName(), + JsonUtils.GSON.toJsonTree(additionalProp.getValue().getValue())); + } + } + return vfModuleProps; + } + private static JsonObject createServicePropertiesByType(CsarHandler csar) { JsonObject resourcesProp = new JsonObject(); + // Iterate on all types defined in the tosca lib for (SdcTypes type : SdcTypes.values()) { JsonObject resourcesPropByType = new JsonObject(); + // For each type, get the metadata of each nodetemplate for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) { - resourcesPropByType.add(nodeTemplate.getName(), JsonUtils.GSON_JPA_MODEL - .fromJson(new Gson().toJson(nodeTemplate.getMetaData().getAllProperties()), JsonObject.class)); + resourcesPropByType.add(nodeTemplate.getName(), + JsonUtils.GSON.toJsonTree(nodeTemplate.getMetaData().getAllProperties())); } resourcesProp.add(type.getValue(), resourcesPropByType); } + return resourcesProp; + } + + private static JsonObject createModelPropertiesJson(CsarHandler csar) { + JsonObject modelProperties = new JsonObject(); + // Add service details + modelProperties.add("serviceDetails", JsonUtils.GSON.fromJson( + JsonUtils.GSON.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class)); + // Add properties details for each type, VfModule, VF, VFC, .... + JsonObject resourcesProp = createServicePropertiesByType(csar); + resourcesProp.add("VFModule", createVfModuleProperties(csar)); modelProperties.add("resourceDetails", resourcesProp); return modelProperties; } diff --git a/src/main/java/org/onap/clamp/loop/LoopOperation.java b/src/main/java/org/onap/clamp/loop/LoopOperation.java index d9ea2487..87effa5f 100644 --- a/src/main/java/org/onap/clamp/loop/LoopOperation.java +++ b/src/main/java/org/onap/clamp/loop/LoopOperation.java @@ -25,191 +25,241 @@ package org.onap.clamp.loop; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonNull; import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import java.lang.reflect.Array; -import java.util.Collection; -import java.util.Date; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.Iterator; +import java.util.Set; +import java.util.UUID; import org.apache.camel.Exchange; -import org.onap.clamp.clds.client.DcaeDispatcherServices; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; -import org.onap.clamp.exception.OperationException; -import org.onap.clamp.util.HttpConnectionManager; -import org.slf4j.event.Level; +import org.apache.camel.Message; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import org.onap.clamp.policy.operational.OperationalPolicy; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; -import org.yaml.snakeyaml.Yaml; /** - * Closed loop operations + * Closed loop operations. */ @Component public class LoopOperation { protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class); protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); - private final DcaeDispatcherServices dcaeDispatcherServices; + private static final String DCAE_LINK_FIELD = "links"; + private static final String DCAE_STATUS_FIELD = "status"; + private static final String DCAE_SERVICETYPE_ID = "serviceTypeId"; + private static final String DCAE_INPUTS = "inputs"; + private static final String DCAE_DEPLOYMENT_PREFIX = "CLAMP_"; + private static final String DEPLOYMENT_PARA = "dcaeDeployParameters"; private final LoopService loopService; - private LoggingUtils util = new LoggingUtils(logger); - @Autowired - private HttpServletRequest request; + public enum TempLoopState { + NOT_SUBMITTED, SUBMITTED, DEPLOYED, NOT_DEPLOYED, PROCESSING, IN_ERROR; + } + /** + * The constructor. + * + * @param loopService + * The loop service + * @param refProp + * The clamp properties + */ @Autowired - public LoopOperation(LoopService loopService, DcaeDispatcherServices dcaeDispatcherServices, - ClampProperties refProp, HttpConnectionManager httpConnectionManager) { + public LoopOperation(LoopService loopService) { this.loopService = loopService; - this.dcaeDispatcherServices = dcaeDispatcherServices; } /** - * Deploy the closed loop. + * Get the payload used to send the deploy closed loop request. * - * @param loopName - * the loop name - * @return the updated loop - * @throws Exceptions - * during the operation + * @param loop + * The loop + * @return The payload used to send deploy closed loop request + * @throws IOException + * IOException */ - public Loop deployLoop(Exchange camelExchange, String loopName) throws OperationException { - util.entering(request, "CldsService: Deploy model"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Deploy loop exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } + public String getDeployPayload(Loop loop) throws IOException { + JsonObject globalProp = loop.getGlobalPropertiesJson(); + JsonObject deploymentProp = globalProp.getAsJsonObject(DEPLOYMENT_PARA); + + String serviceTypeId = loop.getDcaeBlueprintId(); - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.SUBMITTED) { - String msg = "Deploy loop exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be deployed only when it is in SUBMITTED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); + JsonObject rootObject = new JsonObject(); + rootObject.addProperty(DCAE_SERVICETYPE_ID, serviceTypeId); + if (deploymentProp != null) { + rootObject.add(DCAE_INPUTS, deploymentProp); } + String apiBodyString = rootObject.toString(); + logger.info("Dcae api Body String - " + apiBodyString); + return apiBodyString; + } + + /** + * Get the deployment id. + * + * @param loop + * The loop + * @return The deployment id + * @throws IOException + * IOException + */ + public String getDeploymentId(Loop loop) { // Set the deploymentId if not present yet String deploymentId = ""; // If model is already deployed then pass same deployment id if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) { deploymentId = loop.getDcaeDeploymentId(); } else { - loop.setDcaeDeploymentId(deploymentId = "closedLoop_" + loopName + "_deploymentId"); + deploymentId = DCAE_DEPLOYMENT_PREFIX + UUID.randomUUID(); } - - Yaml yaml = new Yaml(); - Map<String, Object> yamlMap = yaml.load(loop.getBlueprint()); - JsonObject bluePrint = wrapSnakeObject(yamlMap).getAsJsonObject(); - - loop.setDcaeDeploymentStatusUrl( - dcaeDispatcherServices.createNewDeployment(deploymentId, loop.getDcaeBlueprintId(), bluePrint)); - loop.setLastComputedState(LoopState.DEPLOYED); - // save the updated loop - loopService.saveOrUpdateLoop(loop); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deploy model completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; + return deploymentId; } /** - * Un deploy closed loop. + * Update the loop info. * - * @param loopName - * the loop name - * @return the updated loop + * @param camelExchange + * The camel exchange + * @param loop + * The loop + * @param deploymentId + * The deployment id + * @throws ParseException + * The parse exception */ - public Loop unDeployLoop(String loopName) throws OperationException { - util.entering(request, "LoopOperation: Undeploy the closed loop"); - Date startTime = new Date(); - Loop loop = loopService.getLoop(loopName); - - if (loop == null) { - String msg = "Undeploy loop exception: Not able to find closed loop:" + loopName; - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), msg, Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } - - // verify the current closed loop state - if (loop.getLastComputedState() != LoopState.DEPLOYED) { - String msg = "Unploy loop exception: This closed loop is in state:" + loop.getLastComputedState() - + ". It could be undeployed only when it is in DEPLOYED state."; - util.exiting(HttpStatus.CONFLICT.toString(), msg, Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); - throw new OperationException(msg); - } + public void updateLoopInfo(Exchange camelExchange, Loop loop, String deploymentId) throws ParseException { + Message in = camelExchange.getIn(); + String msg = in.getBody(String.class); - loop.setDcaeDeploymentStatusUrl( - dcaeDispatcherServices.deleteExistingDeployment(loop.getDcaeDeploymentId(), loop.getDcaeBlueprintId())); + JSONParser parser = new JSONParser(); + Object obj0 = parser.parse(msg); + JSONObject jsonObj = (JSONObject) obj0; - // clean the deployment ID - loop.setDcaeDeploymentId(null); - loop.setLastComputedState(LoopState.SUBMITTED); + JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD); + String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD); - // save the updated loop + if (deploymentId == null) { + loop.setDcaeDeploymentId(null); + loop.setDcaeDeploymentStatusUrl(null); + } else { + loop.setDcaeDeploymentId(deploymentId); + loop.setDcaeDeploymentStatusUrl(statusUrl.replaceAll("http:", "http4:").replaceAll("https:", "https4:")); + } loopService.saveOrUpdateLoop(loop); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Undeploy model completed"); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return loop; } - private JsonElement wrapSnakeObject(Object o) { - // NULL => JsonNull - if (o == null) - return JsonNull.INSTANCE; - - // Collection => JsonArray - if (o instanceof Collection) { - JsonArray array = new JsonArray(); - for (Object childObj : (Collection<?>) o) - array.add(wrapSnakeObject(childObj)); - return array; + /** + * Get the Closed Loop status based on the reply from Policy. + * + * @param statusCode + * The status code + * @return The state based on policy response + * @throws ParseException + * The parse exception + */ + public String analysePolicyResponse(int statusCode) { + if (statusCode == 200) { + return TempLoopState.SUBMITTED.toString(); + } else if (statusCode == 404) { + return TempLoopState.NOT_SUBMITTED.toString(); } + return TempLoopState.IN_ERROR.toString(); + } - // Array => JsonArray - if (o.getClass().isArray()) { - JsonArray array = new JsonArray(); + /** + * Get the name of the first Operational policy. + * + * @param loop + * The closed loop + * @return The name of the first operational policy + */ + public String getOperationalPolicyName(Loop loop) { + Set<OperationalPolicy> opSet = loop.getOperationalPolicies(); + Iterator<OperationalPolicy> iterator = opSet.iterator(); + while (iterator.hasNext()) { + OperationalPolicy policy = iterator.next(); + return policy.getName(); + } + return null; + } - int length = Array.getLength(array); - for (int i = 0; i < length; i++) - array.add(wrapSnakeObject(Array.get(array, i))); - return array; + /** + * Get the Closed Loop status based on the reply from DCAE. + * + * @param camelExchange + * The camel exchange + * @return The state based on DCAE response + * @throws ParseException + * The parse exception + */ + public String analyseDcaeResponse(Exchange camelExchange, Integer statusCode) throws ParseException { + if (statusCode == null) { + return TempLoopState.NOT_DEPLOYED.toString(); } + if (statusCode == 200) { + Message in = camelExchange.getIn(); + String msg = in.getBody(String.class); + + JSONParser parser = new JSONParser(); + Object obj0 = parser.parse(msg); + JSONObject jsonObj = (JSONObject) obj0; - // Map => JsonObject - if (o instanceof Map) { - Map<?, ?> map = (Map<?, ?>) o; + String opType = (String) jsonObj.get("operationType"); + String status = (String) jsonObj.get("status"); - JsonObject jsonObject = new JsonObject(); - for (final Map.Entry<?, ?> entry : map.entrySet()) { - final String name = String.valueOf(entry.getKey()); - final Object value = entry.getValue(); - jsonObject.add(name, wrapSnakeObject(value)); + // status = processing/successded/failed + if (status.equals("succeeded")) { + if (opType.equals("install")) { + return TempLoopState.DEPLOYED.toString(); + } else if (opType.equals("uninstall")) { + return TempLoopState.NOT_DEPLOYED.toString(); + } + } else if (status.equals("processing")) { + return TempLoopState.PROCESSING.toString(); } - return jsonObject; + } else if (statusCode == 404) { + return TempLoopState.NOT_DEPLOYED.toString(); } + return TempLoopState.IN_ERROR.toString(); + } - // otherwise take it as a string - return new JsonPrimitive(String.valueOf(o)); + /** + * Update the status of the closed loop based on the response from Policy and + * DCAE. + * + * @param loop + * The closed loop + * @param policyState + * The state get from Policy + * @param dcaeState + * The state get from DCAE + * @throws ParseException + * The parse exception + */ + public LoopState updateLoopStatus(Loop loop, TempLoopState policyState, TempLoopState dcaeState) { + LoopState clState = LoopState.IN_ERROR; + if (policyState == TempLoopState.SUBMITTED) { + if (dcaeState == TempLoopState.DEPLOYED) { + clState = LoopState.DEPLOYED; + } else if (dcaeState == TempLoopState.PROCESSING) { + clState = LoopState.WAITING; + } else if (dcaeState == TempLoopState.NOT_DEPLOYED) { + clState = LoopState.SUBMITTED; + } + } else if (policyState == TempLoopState.NOT_SUBMITTED) { + if (dcaeState == TempLoopState.NOT_DEPLOYED) { + clState = LoopState.DESIGN; + } + } + loop.setLastComputedState(clState); + loopService.saveOrUpdateLoop(loop); + return clState; } } diff --git a/src/main/java/org/onap/clamp/loop/log/LoopLog.java b/src/main/java/org/onap/clamp/loop/log/LoopLog.java index 3edb2ee5..cea49571 100644 --- a/src/main/java/org/onap/clamp/loop/log/LoopLog.java +++ b/src/main/java/org/onap/clamp/loop/log/LoopLog.java @@ -69,7 +69,7 @@ public class LoopLog implements Serializable { private LogType logType; @Expose - @Column(name = "message", nullable = false) + @Column(name = "message", columnDefinition = "MEDIUMTEXT", nullable = false) private String message; @ManyToOne(fetch = FetchType.LAZY) diff --git a/src/main/java/org/onap/clamp/policy/Policy.java b/src/main/java/org/onap/clamp/policy/Policy.java index f4efab0d..fc097bd6 100644 --- a/src/main/java/org/onap/clamp/policy/Policy.java +++ b/src/main/java/org/onap/clamp/policy/Policy.java @@ -25,13 +25,15 @@ package org.onap.clamp.policy; import com.google.gson.JsonObject; +import java.io.UnsupportedEncodingException; + public interface Policy { String getName(); JsonObject getJsonRepresentation(); - String createPolicyPayload(); + String createPolicyPayload() throws UnsupportedEncodingException; /** * Generate the policy name. diff --git a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java index 2bbb9118..d8d15a5b 100644 --- a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java +++ b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java @@ -23,6 +23,8 @@ package org.onap.clamp.policy.microservice; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -40,6 +42,7 @@ import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; @@ -61,6 +64,9 @@ public class MicroServicePolicy implements Serializable, Policy { */ private static final long serialVersionUID = 6271238288583332616L; + @Transient + private static final EELFLogger logger = EELFManager.getInstance().getLogger(MicroServicePolicy.class); + @Expose @Id @Column(nullable = false, name = "name", unique = true) @@ -271,7 +277,9 @@ public class MicroServicePolicy implements Serializable, Policy { JsonObject policyProperties = new JsonObject(); policyDetails.add("properties", policyProperties); policyProperties.add(this.getMicroServicePropertyNameFromTosca(toscaJson), this.getProperties()); - return new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult); + String policyPayload = new GsonBuilder().setPrettyPrinting().create().toJson(policyPayloadResult); + logger.info("Micro service policy payload: " + policyPayload); + return policyPayload; } } diff --git a/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java b/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java new file mode 100644 index 00000000..33148f0b --- /dev/null +++ b/src/main/java/org/onap/clamp/policy/operational/LegacyOperationalPolicy.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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.policy.operational; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; + +import org.apache.commons.lang3.math.NumberUtils; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.ScalarStyle; +import org.yaml.snakeyaml.Yaml; + +/** + * + * This class contains the code required to support the sending of Legacy + * operational payload to policy engine. This will probably disappear in El + * Alto. + * + */ +public class LegacyOperationalPolicy { + + private LegacyOperationalPolicy() { + + } + + private static void translateStringValues(String jsonKey, String stringValue, JsonElement parentJsonElement) { + if (stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("false")) { + parentJsonElement.getAsJsonObject().addProperty(jsonKey, Boolean.valueOf(stringValue)); + + } else if (NumberUtils.isParsable(stringValue)) { + parentJsonElement.getAsJsonObject().addProperty(jsonKey, Long.parseLong(stringValue)); + } + } + + private static JsonElement removeAllQuotes(JsonElement jsonElement) { + if (jsonElement.isJsonArray()) { + for (JsonElement element : jsonElement.getAsJsonArray()) { + removeAllQuotes(element); + } + } else if (jsonElement.isJsonObject()) { + for (Entry<String, JsonElement> entry : jsonElement.getAsJsonObject().entrySet()) { + if (entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isString()) { + translateStringValues(entry.getKey(), entry.getValue().getAsString(), jsonElement); + } else { + removeAllQuotes(entry.getValue()); + } + } + } + return jsonElement; + } + + public static JsonElement reworkPayloadAttributes(JsonElement policyJson) { + for (JsonElement policy : policyJson.getAsJsonObject().get("policies").getAsJsonArray()) { + JsonElement payloadElem = policy.getAsJsonObject().get("payload"); + String payloadString = payloadElem != null ? payloadElem.getAsString() : ""; + if (!payloadString.isEmpty()) { + Map<String, String> testMap = new Yaml().load(payloadString); + String json = new GsonBuilder().create().toJson(testMap); + policy.getAsJsonObject().add("payload", new GsonBuilder().create().fromJson(json, JsonElement.class)); + } + } + return policyJson; + } + + private static void replacePropertiesIfEmpty(JsonElement policy, String key, String valueIfEmpty) { + JsonElement payloadElem = policy.getAsJsonObject().get(key); + String payloadString = payloadElem != null ? payloadElem.getAsString() : ""; + if (payloadString.isEmpty()) { + policy.getAsJsonObject().addProperty(key, valueIfEmpty); + } + } + + private static JsonElement fulfillPoliciesTreeField(JsonElement policyJson) { + for (JsonElement policy : policyJson.getAsJsonObject().get("policies").getAsJsonArray()) { + replacePropertiesIfEmpty(policy, "success", "final_success"); + replacePropertiesIfEmpty(policy, "failure", "final_failure"); + replacePropertiesIfEmpty(policy, "failure_timeout", "final_failure_timeout"); + replacePropertiesIfEmpty(policy, "failure_retries", "final_failure_retries"); + replacePropertiesIfEmpty(policy, "failure_exception", "final_failure_exception"); + replacePropertiesIfEmpty(policy, "failure_guard", "final_failure_guard"); + } + return policyJson; + } + + private static Map<String, Object> createMap(JsonElement jsonElement) { + Map<String, Object> mapResult = new TreeMap<>(); + + if (jsonElement.isJsonObject()) { + for (Entry<String, JsonElement> entry : jsonElement.getAsJsonObject().entrySet()) { + if (entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isString()) { + mapResult.put(entry.getKey(), entry.getValue().getAsString()); + } else if (entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isBoolean()) { + mapResult.put(entry.getKey(), entry.getValue().getAsBoolean()); + } else if (entry.getValue().isJsonPrimitive() && entry.getValue().getAsJsonPrimitive().isNumber()) { + // Only int ro long normally, we don't need float here + mapResult.put(entry.getKey(), entry.getValue().getAsLong()); + } else if (entry.getValue().isJsonArray()) { + List<Map<String, Object>> newArray = new ArrayList<>(); + mapResult.put(entry.getKey(), newArray); + for (JsonElement element : entry.getValue().getAsJsonArray()) { + newArray.add(createMap(element)); + } + } else if (entry.getValue().isJsonObject()) { + mapResult.put(entry.getKey(), createMap(entry.getValue())); + } + } + } + return mapResult; + } + + public static String createPolicyPayloadYamlLegacy(JsonElement operationalPolicyJsonElement) { + JsonElement opPolicy = fulfillPoliciesTreeField( + removeAllQuotes(reworkPayloadAttributes(operationalPolicyJsonElement.getAsJsonObject().deepCopy()))); + Map<?, ?> jsonMap = createMap(opPolicy); + DumperOptions options = new DumperOptions(); + options.setDefaultScalarStyle(ScalarStyle.PLAIN); + options.setIndent(2); + options.setPrettyFlow(true); + // Policy can't support { } in the yaml + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + return (new Yaml(options)).dump(jsonMap); + } +} diff --git a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java index 1e35ad6c..62c5a1e9 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java @@ -23,6 +23,8 @@ package org.onap.clamp.policy.operational; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; @@ -31,6 +33,9 @@ import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import java.io.Serializable; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; @@ -42,6 +47,7 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; +import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; @@ -49,6 +55,7 @@ import org.hibernate.annotations.TypeDefs; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.Loop; import org.onap.clamp.policy.Policy; +import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; @Entity @@ -60,6 +67,9 @@ public class OperationalPolicy implements Serializable, Policy { */ private static final long serialVersionUID = 6117076450841538255L; + @Transient + private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicy.class); + @Id @Expose @Column(nullable = false, name = "name", unique = true) @@ -150,8 +160,7 @@ public class OperationalPolicy implements Serializable, Policy { return true; } - @Override - public String createPolicyPayload() { + public String createPolicyPayloadYaml() { JsonObject policyPayloadResult = new JsonObject(); policyPayloadResult.addProperty("tosca_definitions_version", "tosca_simple_yaml_1_0_0"); @@ -174,11 +183,33 @@ public class OperationalPolicy implements Serializable, Policy { operationalPolicyDetails.add("metadata", metadata); metadata.addProperty("policy-id", this.name); - operationalPolicyDetails.add("properties", this.configurationsJson.get("operational_policy")); + operationalPolicyDetails.add("properties", LegacyOperationalPolicy + .reworkPayloadAttributes(this.configurationsJson.get("operational_policy").deepCopy())); Gson gson = new GsonBuilder().create(); + Map<?, ?> jsonMap = gson.fromJson(gson.toJson(policyPayloadResult), Map.class); - return (new Yaml()).dump(jsonMap); + + DumperOptions options = new DumperOptions(); + options.setIndent(2); + options.setPrettyFlow(true); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + + return (new Yaml(options)).dump(jsonMap); + } + + @Override + public String createPolicyPayload() throws UnsupportedEncodingException { + + // Now using the legacy payload fo Dublin + JsonObject payload = new JsonObject(); + payload.addProperty("policy-id", this.getName()); + payload.addProperty("content", URLEncoder.encode( + LegacyOperationalPolicy.createPolicyPayloadYamlLegacy(this.configurationsJson.get("operational_policy")), + StandardCharsets.UTF_8.toString())); + String opPayload = new GsonBuilder().setPrettyPrinting().create().toJson(payload); + logger.info("Operational policy payload: " + opPayload); + return opPayload; } /** @@ -194,10 +225,11 @@ public class OperationalPolicy implements Serializable, Policy { for (Entry<String, JsonElement> guardElem : guardsList.getAsJsonObject().entrySet()) { JsonObject guard = new JsonObject(); guard.addProperty("policy-id", guardElem.getKey()); - guard.add("contents", guardElem.getValue()); + guard.add("content", guardElem.getValue()); result.put(guardElem.getKey(), new GsonBuilder().create().toJson(guard)); } } + logger.info("Guard policy payload: " + result); return result; } diff --git a/src/main/java/org/onap/clamp/util/PrincipalUtils.java b/src/main/java/org/onap/clamp/util/PrincipalUtils.java index d6b20f30..d6dfacbd 100644 --- a/src/main/java/org/onap/clamp/util/PrincipalUtils.java +++ b/src/main/java/org/onap/clamp/util/PrincipalUtils.java @@ -38,6 +38,12 @@ public class PrincipalUtils { private static SecurityContext securityContext = SecurityContextHolder.getContext(); /** + * Private constructor to avoid creating instances of util class. + */ + private PrincipalUtils(){ + } + + /** * Get the Full name. * * @return The user name |