diff options
Diffstat (limited to 'src/main/java/org')
33 files changed, 1285 insertions, 720 deletions
diff --git a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java index 20610275..568af480 100644 --- a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java +++ b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java @@ -58,30 +58,34 @@ public class AuthorizationController { private ClampProperties refProp; private SecurityContext securityContext = SecurityContextHolder.getContext(); - private final static String permPrefix = "security.permission.type."; - private final static String permInstance = "security.permission.instance"; + private static final String permPrefix = "security.permission.type."; + private static final String permInstance = "security.permission.instance"; public AuthorizationController() { } + /** - * Insert event using process variables. + * Insert authorize the api based on the permission * * @param camelExchange * The Camel Exchange object containing the properties - * @param actionState - * The action state that is used instead of the one in exchange property + * @param typeVar + * The type of the permissions + * @param instanceVar + * The instance of the permissions. e.g. dev + * @param action + * The action of the permissions. e.g. read */ - public void authorize (Exchange camelExchange, String typeVar, String instanceVar, String action) { String type = refProp.getStringValue(permPrefix + typeVar); String instance = refProp.getStringValue(permInstance); - + if (null == type || type.isEmpty()) { //authorization is turned off, since the permission is not defined return; } if (null != instanceVar && !instanceVar.isEmpty()) { - instance = instanceVar; + instance = instanceVar; } String principalName = PrincipalUtils.getPrincipalName(); SecureServicePermission perm = SecureServicePermission.create(type, instance, action); @@ -105,18 +109,22 @@ public class AuthorizationController { // check if the user has the permission key or the permission key with a // combination of all instance and/or all action. if (hasRole(inPermission.getKey())) { - auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for instance: {}", + principalName, inPermission.getKey()); authorized = true; // the rest of these don't seem to be required - isUserInRole method // appears to take * as a wildcard } else if (hasRole(inPermission.getKeyAllInstance())) { - auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for instance: {}", + principalName, inPermission.getKey()); authorized = true; } else if (hasRole(inPermission.getKeyAllInstanceAction())) { - auditLogger.info("{} authorized because user has permission with * for instance and * for action: {}", principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for instance and * for action: {}", + principalName, inPermission.getKey()); authorized = true; } else if (hasRole(inPermission.getKeyAllAction())) { - auditLogger.info("{} authorized because user has permission with * for action: {}", principalName, inPermission.getKey()); + auditLogger.info("{} authorized because user has permission with * for action: {}", + principalName, inPermission.getKey()); authorized = true; } else { throw new NotAuthorizedException(""); @@ -124,9 +132,15 @@ public class AuthorizationController { return authorized; } + /** + * Verify whether the user has the permission + * + * @param inPermission + * The permissions to verify + */ public boolean isUserPermittedNoException(SecureServicePermission inPermission) { try { - return isUserPermitted (inPermission); + return isUserPermitted(inPermission); } catch (NotAuthorizedException e) { return false; } @@ -138,8 +152,9 @@ public class AuthorizationController { return false; } for (GrantedAuthority auth : authentication.getAuthorities()) { - if (role.equals(auth.getAuthority())) + if (role.equals(auth.getAuthority())) { return true; + } } return false; } diff --git a/src/main/java/org/onap/clamp/clds/Application.java b/src/main/java/org/onap/clamp/clds/Application.java index 7e78504f..025dbabd 100644 --- a/src/main/java/org/onap/clamp/clds/Application.java +++ b/src/main/java/org/onap/clamp/clds/Application.java @@ -101,7 +101,7 @@ public class Application extends SpringBootServletInitializer { * This method is used to declare the camel servlet. * * @return A servlet bean - * @throws IOException + * @throws IOException IO Exception */ @Bean public ServletRegistrationBean camelServletRegistrationBean() throws IOException { diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index 008a9c74..e8fd83e2 100644 --- a/src/main/java/org/onap/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -50,7 +50,7 @@ import org.springframework.web.context.support.WebApplicationContextUtils; public class ClampServlet extends CamelHttpTransportServlet { /** - * + * The serial version ID. */ private static final long serialVersionUID = -4198841134910211542L; @@ -109,8 +109,8 @@ public class ClampServlet extends CamelHttpTransportServlet { @Override protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Principal p = request.getUserPrincipal(); - if (loadDynamicAuthenticationClass().isInstance(p)) { + Principal principal = request.getUserPrincipal(); + if (loadDynamicAuthenticationClass().isInstance(principal)) { // When AAF is enabled, there is a need to provision the permissions to Spring // system List<GrantedAuthority> grantedAuths = new ArrayList<>(); @@ -120,7 +120,7 @@ public class ClampServlet extends CamelHttpTransportServlet { grantedAuths.add(new SimpleGrantedAuthority(permString)); } } - Authentication auth = new UsernamePasswordAuthenticationToken(new User(p.getName(), "", grantedAuths), "", + Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", grantedAuths), "", grantedAuths); SecurityContextHolder.getContext().setAuthentication(auth); } diff --git a/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java b/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java index 1d9150ee..a0109a68 100644 --- a/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java +++ b/src/main/java/org/onap/clamp/clds/TomcatEmbeddedServletContainerFactoryRedirection.java @@ -32,10 +32,8 @@ import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactor * This class is a factory that redirects by default all HTTP to HTTPS * connector. It is used by the Application.java class and defined in a Spring * Bean. - * * In order to do this, the method postProcessContext has been overridden to * provide another behavior. - * */ public class TomcatEmbeddedServletContainerFactoryRedirection extends TomcatServletWebServerFactory { 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 68454525..63caf5a9 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeDispatcherServices.java @@ -63,6 +63,13 @@ public class DcaeDispatcherServices { 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++) {
@@ -81,7 +88,6 @@ public class DcaeDispatcherServices { /**
* Get the Operation Status from a specified URL.
- *
* @param statusUrl
* The URL provided by a previous DCAE Query
* @return The status
@@ -112,7 +118,6 @@ public class DcaeDispatcherServices { /**
* Returns status URL for createNewDeployment operation.
- *
* @param deploymentId
* The deployment ID
* @param serviceTypeId
@@ -150,7 +155,6 @@ public class DcaeDispatcherServices { /***
* Returns status URL for deleteExistingDeployment operation.
- *
* @param deploymentId
* The deployment ID
* @param serviceTypeId
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java index 8781fc34..30afddcd 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java @@ -42,9 +42,7 @@ import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.stereotype.Component; /** - * * This class manages the HTTP and HTTPS connections to DCAE. - * */ @Component public class DcaeHttpConnectionManager { diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java index e5ef3c67..ffd19d82 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeInventoryServices.java @@ -64,6 +64,9 @@ public class DcaeInventoryServices { private final CldsDao cldsDao;
private final DcaeHttpConnectionManager dcaeHttpConnectionManager;
+ /**
+ * Constructor.
+ */
@Autowired
public DcaeInventoryServices(ClampProperties refProp, CldsDao cldsDao,
DcaeHttpConnectionManager dcaeHttpConnectionManager) {
@@ -179,7 +182,6 @@ public class DcaeInventoryServices { */
public DcaeInventoryResponse getDcaeInformation(String artifactName, String serviceUuid, String resourceUuid)
throws IOException, ParseException, InterruptedException {
- Date startTime = new Date();
LoggingUtils.setTargetContext("DCAE", "getDcaeInformation");
String queryString = "?asdcResourceId=" + resourceUuid + "&asdcServiceId=" + serviceUuid + "&typeName="
+ artifactName;
@@ -187,6 +189,7 @@ public class DcaeInventoryServices { logger.info("Dcae Inventory Service full url - " + fullUrl);
DcaeInventoryResponse response = queryDcaeInventory(fullUrl);
LoggingUtils.setResponseContext("0", "Get Dcae Information success", this.getClass().getName());
+ Date startTime = new Date();
LoggingUtils.setTimeContext(startTime, new Date());
return response;
}
diff --git a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java index fb91d9c5..a758716b 100644 --- a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDelegate.java @@ -76,7 +76,8 @@ public class GuardPolicyDelegate { Policy policy = prop.getType(Policy.class); if (policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - for(PolicyItem policyItem:GuardPolicyAttributesConstructor.getAllPolicyGuardsFromPolicyChain(policyChain)) { + for (PolicyItem policyItem:GuardPolicyAttributesConstructor + .getAllPolicyGuardsFromPolicyChain(policyChain)) { prop.setCurrentModelElementId(policy.getId()); prop.setPolicyUniqueId(policyChain.getPolicyId()); prop.setGuardUniqueId(policyItem.getId()); diff --git a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java index 36eb147d..941f519e 100644 --- a/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/GuardPolicyDeleteDelegate.java @@ -70,7 +70,8 @@ public class GuardPolicyDeleteDelegate { String eventAction = (String) camelExchange.getProperty("eventAction"); if (!eventAction.equalsIgnoreCase(CldsEvent.ACTION_CREATE) && policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - for(PolicyItem policyItem:GuardPolicyAttributesConstructor.getAllPolicyGuardsFromPolicyChain(policyChain)) { + for (PolicyItem policyItem:GuardPolicyAttributesConstructor + .getAllPolicyGuardsFromPolicyChain(policyChain)) { prop.setCurrentModelElementId(policy.getId()); prop.setPolicyUniqueId(policyChain.getPolicyId()); prop.setGuardUniqueId(policyItem.getId()); diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java index 39377d4a..307c8e51 100644 --- a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java +++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java @@ -79,8 +79,8 @@ public class OperationalPolicyDelegate { Policy policy = prop.getType(Policy.class); if (policy.isFound()) { for (PolicyChain policyChain : prop.getType(Policy.class).getPolicyChains()) { - Map<AttributeType, Map<String, String>> attributes = OperationalPolicyAttributesConstructor.formatAttributes(refProp, - prop, prop.getType(Policy.class).getId(), policyChain); + Map<AttributeType, Map<String, String>> attributes = OperationalPolicyAttributesConstructor + .formatAttributes(refProp,prop, prop.getType(Policy.class).getId(), policyChain); responseMessage = policyClient.sendBrmsPolicy(attributes, prop, LoggingUtils.getRequestId()); } if (responseMessage != null) { diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java b/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java index f15d33df..bc82cb3d 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/GuardPolicyAttributesConstructor.java @@ -61,6 +61,11 @@ public class GuardPolicyAttributesConstructor { return createAttributesMap(matchingAttributes); } + /** + * Get all the Guard policies from the policy chain. + * @param policyChain The policy chain + * @return The list of guard policies + */ public static List<PolicyItem> getAllPolicyGuardsFromPolicyChain(PolicyChain policyChain) { List<PolicyItem> listItem = new ArrayList<>(); for (PolicyItem policyItem : policyChain.getPolicyItems()) { diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java index c28f700b..af23626d 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyAttributesConstructor.java @@ -59,6 +59,16 @@ public class OperationalPolicyAttributesConstructor { private OperationalPolicyAttributesConstructor() { } + /** + * Format the attributes. + * @param refProp The Clamp properties + * @param modelProperties The model properties + * @param modelElementId The model element ID + * @param policyChain The policy chain + * @return The attributes map + * @throws BuilderException Exception while building up the attributes map + * @throws UnsupportedEncodingException Unsupported encoding exception + */ public static Map<AttributeType, Map<String, String>> formatAttributes(ClampProperties refProp, ModelProperties modelProperties, String modelElementId, PolicyChain policyChain) @@ -75,7 +85,8 @@ public class OperationalPolicyAttributesConstructor { return createAttributesMap(matchingAttributes, ruleAttributes); } - private static Map<String, String> prepareRuleAttributes(ClampProperties clampProperties, ModelProperties modelProperties, + private static Map<String, String> prepareRuleAttributes(ClampProperties clampProperties, + ModelProperties modelProperties, String modelElementId, PolicyChain policyChain, String globalService) throws BuilderException, UnsupportedEncodingException { logger.info("Preparing rule attributes..."); @@ -112,7 +123,8 @@ public class OperationalPolicyAttributesConstructor { return attributes; } - private static ImmutableMap<String, String> createRuleAttributesFromPolicy(ClampProperties refProp, ModelProperties modelProperties, + private static ImmutableMap<String, String> createRuleAttributesFromPolicy(ClampProperties refProp, + ModelProperties modelProperties, String modelElementId, PolicyChain policyChain, String globalService, String operationTopic) throws BuilderException, UnsupportedEncodingException { @@ -127,7 +139,8 @@ public class OperationalPolicyAttributesConstructor { } } - private static ImmutableMap<String, String> createRuleAttributesFromPolicyItem(PolicyItem policyItem, String recipeTopic) { + private static ImmutableMap<String, String> createRuleAttributesFromPolicyItem(PolicyItem policyItem, + String recipeTopic) { logger.info("recipeTopic=" + recipeTopic); return ImmutableMap.<String, String>builder() .put(RECIPE_TOPIC, recipeTopic) diff --git a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java index b9ed0c09..f2536b1f 100644 --- a/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java +++ b/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyYamlFormatter.java @@ -21,6 +21,7 @@ * =================================================================== * */ + package org.onap.clamp.clds.client.req.policy; import com.att.eelf.configuration.EELFLogger; @@ -61,12 +62,12 @@ public class OperationalPolicyYamlFormatter { /** * Format Operational OpenLoop Policy yaml. * - * @param prop - * @param modelElementId - * @param policyChain - * @return - * @throws BuilderException - * @throws UnsupportedEncodingException + * @param prop The model properties + * @param modelElementId The model element ID + * @param policyChain The policy chain + * @return The operational openloop policy in yaml format + * @throws BuilderException The builder exception + * @throws UnsupportedEncodingException The unsupported encoding exception */ public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { @@ -87,6 +88,15 @@ public class OperationalPolicyYamlFormatter { return URLEncoder.encode(results.getSpecification(), "UTF-8"); } + /** + * Format Operational Policy yaml. + * @param prop The model properties + * @param modelElementId The model element ID + * @param policyChain The policy chain + * @return The operational policy properties in yaml format + * @throws BuilderException The builder exception + * @throws UnsupportedEncodingException The unsupported encoding exception + */ public static String formatYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException { // get property objects 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 c7051157..965c90f8 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 @@ -519,7 +519,7 @@ public class PolicyClient { } /** - * Method to return correct policy name with prefix + * Method to return correct policy name with prefix. * * @param prop * The ModelProperties @@ -527,7 +527,7 @@ public class PolicyClient { * Policy Prefix * @param policyNameWithPrefix * Policy Name With Prefix - * @return + * @return The policy name with the prefix */ protected String selectRightPolicyNameWithPrefix(ModelProperties prop, String policyPrefix, String policyNameWithPrefix) { @@ -561,8 +561,8 @@ public class PolicyClient { deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group")); deletePolicyParameters.setPolicyType(policyType); // send delete request - StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop)); logger.info("Deleting policy from PAP..."); + StringBuilder responseMessage = new StringBuilder(sendDeletePolicy(deletePolicyParameters, prop)); deletePolicyParameters.setPolicyComponent("PAP"); deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL); // send delete request @@ -605,7 +605,7 @@ public class PolicyClient { } /** - * Create a temp Tosca model file and perform import model to Policy Engine + * Create a temp Tosca model file and perform import model to Policy Engine. * * @param cldsToscaModel * Policy model details @@ -636,6 +636,7 @@ public class PolicyClient { } /** + * Import the model. * @param importParameters * The ImportParameters * @return The response message from policy @@ -671,6 +672,7 @@ public class PolicyClient { } /** + * Build file path for tosca file. * @param clampToscaPath * Temp directory path for writing tosca files * @param toscaModelName 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 eef63535..5da26b19 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -84,7 +84,7 @@ public class CldsDao { private static final String DATE_FORMAT = "MM-dd-yyyy HH:mm:ss"; /** - * Log message when instantiating + * Log message when instantiating. */ public CldsDao() { logger.info("CldsDao instantiating..."); @@ -92,6 +92,8 @@ public class CldsDao { /** * When dataSource is provided, instantiate spring jdbc objects. + * + * @param dataSource the data source */ public void setDataSource(DataSource dataSource) { this.jdbcTemplateObject = new JdbcTemplate(dataSource); @@ -114,18 +116,14 @@ public class CldsDao { /** * Get a model from the database given the model name. + * + * @param modelName the model name + * @return the model */ public CldsModel getModel(String modelName) { return getModel(modelName, null); } - /** - * Get a model from the database given the controlNameUuid. - */ - public CldsModel getModelByUuid(String controlNameUuid) { - return getModel(null, controlNameUuid); - } - // Get a model from the database given the model name or a controlNameUuid. private CldsModel getModel(String modelName, String controlNameUuid) { CldsModel model = new CldsModel(); @@ -138,11 +136,21 @@ public class CldsDao { } /** + * Get a model from the database given the controlNameUuid. + * + * @param controlNameUuid the control name uuid + * @return the model by uuid + */ + public CldsModel getModelByUuid(String controlNameUuid) { + return getModel(null, controlNameUuid); + } + /** * Get a model and template information from the database given the model name. * - * @param modelName - * @return model + * @param modelName the model name + * @return model model template */ + public CldsModel getModelTemplate(String modelName) { CldsModel model = new CldsModel(); model.setName(modelName); @@ -171,9 +179,9 @@ public class CldsDao { * Update model in the database using parameter values and return updated model * object. * - * @param model - * @param userid - * @return + * @param model the model + * @param userid the userid + * @return model */ public CldsModel setModel(CldsModel model, String userid) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", model.getName()) @@ -200,9 +208,8 @@ public class CldsDao { * Inserts new modelInstance in the database using parameter values and return * updated model object. * - * @param model - * @param modelInstancesList - * @return + * @param model the model + * @param modelInstancesList the model instances list */ public void insModelInstance(CldsModel model, List<CldsModelInstance> modelInstancesList) { // Delete all existing model instances for given controlNameUUID @@ -234,11 +241,11 @@ public class CldsDao { * Insert an event in the database - require either modelName or * controlNamePrefix/controlNameUuid. * - * @param modelName - * @param controlNamePrefix - * @param controlNameUuid - * @param cldsEvent - * @return + * @param modelName the model name + * @param controlNamePrefix the control name prefix + * @param controlNameUuid the control name uuid + * @param cldsEvent the clds event + * @return clds event */ public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) { CldsEvent event = new CldsEvent(); @@ -261,8 +268,8 @@ public class CldsDao { /** * Update event with process instance id. * - * @param eventId - * @param processInstanceId + * @param eventId the event id + * @param processInstanceId the process instance id */ public void updEvent(String eventId, String processInstanceId) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_event_id", eventId) @@ -271,7 +278,7 @@ public class CldsDao { } /** - * Return list of model names + * Return list of model names. * * @return model names */ @@ -284,8 +291,8 @@ public class CldsDao { * Update template in the database using parameter values and return updated * template object. * - * @param template - * @param userid + * @param template the template + * @param userid the userid */ public void setTemplate(CldsTemplate template, String userid) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", template.getName()) @@ -303,7 +310,7 @@ public class CldsDao { } /** - * Return list of template names + * Return list of template names. * * @return template names */ @@ -315,8 +322,8 @@ public class CldsDao { /** * Get a template from the database given the model name. * - * @param templateName - * @return model + * @param templateName the template name + * @return model template */ public CldsTemplate getTemplate(String templateName) { CldsTemplate template = new CldsTemplate(); @@ -345,6 +352,9 @@ public class CldsDao { } } + /** + * Do health check. + */ public void doHealthCheck() { jdbcTemplateObject.execute(HEALTHCHECK); } @@ -356,7 +366,8 @@ public class CldsDao { */ public List<CldsModelProp> getDeployedModelProperties() { List<CldsModelProp> cldsModelPropList = new ArrayList<>(); - String modelsSql = "select m.model_id, m.model_name, mp.model_prop_id, mp.model_prop_text FROM model m, model_properties mp, event e " + String modelsSql = "select m.model_id, m.model_name, mp.model_prop_id, mp.model_prop_text FROM model m, " + + "model_properties mp, event e " + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'"; List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql); CldsModelProp cldsModelProp = null; @@ -383,10 +394,11 @@ public class CldsDao { * TEMPLATE_NAME | Template used to generate the ClosedLoop model. * ACTION_CD | Current state of the ClosedLoop in CLDS application. */ - public List<CldsMonitoringDetails> getCLDSMonitoringDetails() { + public List<CldsMonitoringDetails> getCldsMonitoringDetails() { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsMonitoringDetails> cldsMonitoringDetailsList = new ArrayList<>(); - String modelsSql = "SELECT CONCAT(M.CONTROL_NAME_PREFIX, M.CONTROL_NAME_UUID) AS CLOSELOOP_NAME , M.MODEL_NAME, M.SERVICE_TYPE_ID, M.DEPLOYMENT_ID, T.TEMPLATE_NAME, E.ACTION_CD, E.USER_ID, E.TIMESTAMP " + String modelsSql = "SELECT CONCAT(M.CONTROL_NAME_PREFIX, M.CONTROL_NAME_UUID) AS CLOSELOOP_NAME , " + + "M.MODEL_NAME, M.SERVICE_TYPE_ID, M.DEPLOYMENT_ID, T.TEMPLATE_NAME, E.ACTION_CD, E.USER_ID, E.TIMESTAMP " + "FROM MODEL M, TEMPLATE T, EVENT E " + "WHERE M.TEMPLATE_ID = T.TEMPLATE_ID AND M.EVENT_ID = E.EVENT_ID " + "ORDER BY ACTION_CD"; List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(modelsSql); @@ -409,7 +421,7 @@ public class CldsDao { /** * Method to delete model from database. * - * @param modelName + * @param modelName the model name */ public void deleteModel(String modelName) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); @@ -440,7 +452,6 @@ public class CldsDao { /** * Method to retrieve a tosca models by Policy Type from database. * - * @param policyType * @return List of CldsToscaModel */ public List<CldsToscaModel> getAllToscaModels() { @@ -450,7 +461,7 @@ public class CldsDao { /** * Method to retrieve a tosca models by Policy Type from database. * - * @param policyType + * @param policyType the policy type * @return List of CldsToscaModel */ public List<CldsToscaModel> getToscaModelByPolicyType(String policyType) { @@ -460,7 +471,7 @@ public class CldsDao { /** * Method to retrieve a tosca models by toscaModelName, version from database. * - * @param policyType + * @param toscaModelName the tosca model name * @return List of CldsToscaModel */ public List<CldsToscaModel> getToscaModelByName(String toscaModelName) { @@ -473,12 +484,15 @@ public class CldsDao { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsToscaModel> cldsToscaModels = new ArrayList<>(); - String toscaModelSql = "SELECT tm.tosca_model_name, tm.tosca_model_id, tm.policy_type, tmr.tosca_model_revision_id, tmr.tosca_model_json, tmr.version, tmr.user_id, tmr.createdTimestamp, tmr.lastUpdatedTimestamp " + String toscaModelSql = "SELECT tm.tosca_model_name, tm.tosca_model_id, tm.policy_type, " + + "tmr.tosca_model_revision_id, tmr.tosca_model_json, tmr.version, tmr.user_id, tmr.createdTimestamp, " + + "tmr.lastUpdatedTimestamp " + ((toscaModelName != null) ? (", tmr.tosca_model_yaml ") : " ") + "FROM tosca_model tm, tosca_model_revision tmr WHERE tm.tosca_model_id = tmr.tosca_model_id " + ((toscaModelName != null) ? (" AND tm.tosca_model_name = '" + toscaModelName + "'") : " ") + ((policyType != null) ? (" AND tm.policy_type = '" + policyType + "'") : " ") - + "AND tmr.version = (select max(version) from tosca_model_revision st where tmr.tosca_model_id=st.tosca_model_id)"; + + "AND tmr.version = (select max(version) from tosca_model_revision st " + + "where tmr.tosca_model_id=st.tosca_model_id)"; List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(toscaModelSql); @@ -504,12 +518,11 @@ public class CldsDao { } /** - * Method to upload a new version of Tosca Model Yaml in Database - * - * @param cldsToscaModel - * @param userId - * @return CldsToscaModel + * Method to upload a new version of Tosca Model Yaml in Database. * + * @param cldsToscaModel the clds tosca model + * @param userId the user id + * @return CldsToscaModel clds tosca model */ public CldsToscaModel updateToscaModelWithNewVersion(CldsToscaModel cldsToscaModel, String userId) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_tosca_model_id", cldsToscaModel.getId()) @@ -524,9 +537,9 @@ public class CldsDao { /** * Method to upload a new Tosca model Yaml in DB. Default version is 1.0 * - * @param cldsToscaModel - * @param userId - * @return CldsToscaModel + * @param cldsToscaModel the clds tosca model + * @param userId the user id + * @return CldsToscaModel clds tosca model */ public CldsToscaModel insToscaModel(CldsToscaModel cldsToscaModel, String userId) { SqlParameterSource in = new MapSqlParameterSource() @@ -543,9 +556,9 @@ public class CldsDao { } /** - * Method to insert a new Dictionary in Database + * Method to insert a new Dictionary in Database. * - * @param cldsDictionary + * @param cldsDictionary the clds dictionary */ public void insDictionary(CldsDictionary cldsDictionary) { SqlParameterSource in = new MapSqlParameterSource() @@ -556,11 +569,11 @@ public class CldsDao { } /** - * Method to update Dictionary with new info in Database + * Method to update Dictionary with new info in Database. * - * @param dictionaryId - * @param cldsDictionary - * @param userId + * @param dictionaryId the dictionary id + * @param cldsDictionary the clds dictionary + * @param userId the user id */ public void updateDictionary(String dictionaryId, CldsDictionary cldsDictionary, String userId) { @@ -571,16 +584,17 @@ public class CldsDao { } /** - * Method to get list of Dictionaries from the Database + * Method to get list of Dictionaries from the Database. * - * @param dictionaryId - * @param dictionaryName - * @return + * @param dictionaryId the dictionary id + * @param dictionaryName the dictionary name + * @return dictionary */ public List<CldsDictionary> getDictionary(String dictionaryId, String dictionaryName) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsDictionary> dictionaries = new ArrayList<>(); - String dictionarySql = "SELECT dictionary_id, dictionary_name, created_by, modified_by, timestamp FROM dictionary" + String dictionarySql = "SELECT dictionary_id, dictionary_name, created_by, modified_by, " + + "timestamp FROM dictionary" + ((dictionaryId != null || dictionaryName != null) ? (" WHERE " + ((dictionaryName != null) ? ("dictionary_name = '" + dictionaryName + "'") : "") + ((dictionaryId != null && dictionaryName != null) ? (" AND ") : "") @@ -604,10 +618,10 @@ public class CldsDao { } /** - * Method to insert a new Dictionary Element for given dictionary in Database + * Method to insert a new Dictionary Element for given dictionary in Database. * - * @param cldsDictionaryItem - * @param userId + * @param cldsDictionaryItem the clds dictionary item + * @param userId the user id */ public void insDictionarElements(CldsDictionaryItem cldsDictionaryItem, String userId) { SqlParameterSource in = new MapSqlParameterSource() @@ -622,11 +636,11 @@ public class CldsDao { /** * Method to update Dictionary Elements with new info for a given dictionary in - * Database + * Database. * - * @param dictionaryElementId - * @param cldsDictionaryItem - * @param userId + * @param dictionaryElementId the dictionary element id + * @param cldsDictionaryItem the clds dictionary item + * @param userId the user id */ public void updateDictionaryElements(String dictionaryElementId, CldsDictionaryItem cldsDictionaryItem, String userId) { @@ -643,18 +657,20 @@ public class CldsDao { /** * Method to get list of all dictionary elements for a given dictionary in the - * Database + * Database. * - * @param dictionaryName - * @param dictionaryId - * @param dictElementShortName - * @return + * @param dictionaryName the dictionary name + * @param dictionaryId the dictionary id + * @param dictElementShortName the dict element short name + * @return dictionary elements */ public List<CldsDictionaryItem> getDictionaryElements(String dictionaryName, String dictionaryId, String dictElementShortName) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsDictionaryItem> dictionaryItems = new ArrayList<>(); - String dictionarySql = "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 " + String dictionarySql = "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 " + ((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "") + ((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'") @@ -683,9 +699,9 @@ public class CldsDao { /** * Method to get Map of all dictionary elements with key as dictionary short - * name and value as the full name + * name and value as the full name. * - * @param dictionaryElementType + * @param dictionaryElementType the dictionary element type * @return Map of dictionary elements as key value pair */ public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) { diff --git a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java index b993c637..cc57f9e7 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -29,31 +29,91 @@ import org.onap.clamp.clds.dao.CldsDao; * Represent a CLDS Event. */ public class CldsEvent { + /** + * The constant ACTION_TEST. + */ public static final String ACTION_TEST = "TEST"; + /** + * The constant ACTION_CREATE. + */ public static final String ACTION_CREATE = "CREATE"; + /** + * The constant ACTION_MODIFY. + */ public static final String ACTION_MODIFY = "MODIFY"; + /** + * The constant ACTION_SUBMIT. + */ public static final String ACTION_SUBMIT = "SUBMIT"; + /** + * The constant ACTION_RESUBMIT. + */ // an update before model is active public static final String ACTION_RESUBMIT = "RESUBMIT"; + /** + * The constant ACTION_SUBMITDCAE. + */ // For simplified models public static final String ACTION_SUBMITDCAE = "SUBMITDCAE"; + /** + * The constant ACTION_SUBMITPOLICY. + */ public static final String ACTION_SUBMITPOLICY = "SUBMITPOLICY"; + /** + * The constant ACTION_DISTRIBUTE. + */ // only from dcae public static final String ACTION_DISTRIBUTE = "DISTRIBUTE"; + /** + * The constant ACTION_DEPLOY. + */ // only from dcae public static final String ACTION_DEPLOY = "DEPLOY"; + /** + * The constant ACTION_UNDEPLOY. + */ // only from dcae public static final String ACTION_UNDEPLOY = "UNDEPLOY"; + /** + * The constant ACTION_UPDATE. + */ public static final String ACTION_UPDATE = "UPDATE"; + /** + * The constant ACTION_DELETE. + */ public static final String ACTION_DELETE = "DELETE"; + /** + * The constant ACTION_STOP. + */ public static final String ACTION_STOP = "STOP"; + /** + * The constant ACTION_RESTART. + */ public static final String ACTION_RESTART = "RESTART"; + /** + * The constant ACTION_STATE_INITIATED. + */ public static final String ACTION_STATE_INITIATED = "INITIATED"; + /** + * The constant ACTION_STATE_SENT. + */ public static final String ACTION_STATE_SENT = "SENT"; + /** + * The constant ACTION_STATE_COMPLETED. + */ public static final String ACTION_STATE_COMPLETED = "COMPLETED"; + /** + * The constant ACTION_STATE_RECEIVED. + */ public static final String ACTION_STATE_RECEIVED = "RECEIVED"; + /** + * The constant ACTION_STATE_ERROR. + */ public static final String ACTION_STATE_ERROR = "ERROR"; + /** + * The constant ACTION_STATE_ANY. + */ public static final String ACTION_STATE_ANY = null; private String id; @@ -62,22 +122,34 @@ public class CldsEvent { private String processInstanceId; private String userid; + /** + * Gets id. + * + * @return the id + */ public String getId() { return id; } + /** + * Sets id. + * + * @param id the id + */ public void setId(String id) { this.id = id; } /** - * @param cldsDao - * @param controlName - * @param userid - * @param actionCd - * @param actionStateCd - * @param processInstanceId - * @return + * Ins event clds event. + * + * @param cldsDao the clds dao + * @param controlName the control name + * @param userid the userid + * @param actionCd the action cd + * @param actionStateCd the action state cd + * @param processInstanceId the process instance id + * @return clds event */ public static CldsEvent insEvent(CldsDao cldsDao, String controlName, String userid, String actionCd, String actionStateCd, String processInstanceId) { @@ -89,13 +161,13 @@ public class CldsEvent { * Insert event using controlNameUuid to find the model. This method meant for * processing events from dcae. * - * @param cldsDao - * @param model - * @param userId - * @param actionCd - * @param actionStateCd - * @param processInstanceId - * @return + * @param cldsDao the clds dao + * @param model the model + * @param userId the user id + * @param actionCd the action cd + * @param actionStateCd the action state cd + * @param processInstanceId the process instance id + * @return clds event */ public static CldsEvent insEvent(CldsDao cldsDao, CldsModel model, String userId, String actionCd, String actionStateCd, String processInstanceId) { @@ -112,8 +184,8 @@ public class CldsEvent { * Check if actionCd is equal to the supplied checkActionCd checkActionCd should * not be null. * - * @param checkActionCd - * @return + * @param checkActionCd the check action cd + * @return boolean */ public boolean isActionCd(String checkActionCd) { if (actionCd == null) { @@ -127,9 +199,9 @@ public class CldsEvent { * and checkActionStateCd. Treat checkActionStateCd == null as a wildcard * checkActionCd should not be null. * - * @param checkActionCd - * @param checkActionStateCd - * @return + * @param checkActionCd the check action cd + * @param checkActionStateCd the check action state cd + * @return boolean */ public boolean isActionAndStateCd(String checkActionCd, String checkActionStateCd) { if (actionCd == null) { @@ -147,14 +219,16 @@ public class CldsEvent { * Check if actionStateCd is equal to the supplied checkActionStateCd. * checkActionCd should not be null. * - * @param checkActionStateCd - * @return + * @param checkActionStateCd the check action state cd + * @return boolean */ public boolean isActionStateCd(String checkActionStateCd) { return !(checkActionStateCd == null || actionStateCd == null) && actionStateCd.equals(checkActionStateCd); } /** + * Gets action cd. + * * @return the actionCd */ public String getActionCd() { @@ -162,14 +236,17 @@ public class CldsEvent { } /** - * @param actionCd - * the actionCd to set + * Sets action cd. + * + * @param actionCd the actionCd to set */ public void setActionCd(String actionCd) { this.actionCd = actionCd; } /** + * Gets action state cd. + * * @return the actionStateCd */ public String getActionStateCd() { @@ -177,14 +254,17 @@ public class CldsEvent { } /** - * @param actionStateCd - * the actionStateCd to set + * Sets action state cd. + * + * @param actionStateCd the actionStateCd to set */ public void setActionStateCd(String actionStateCd) { this.actionStateCd = actionStateCd; } /** + * Gets process instance id. + * * @return the processInstanceId */ public String getProcessInstanceId() { @@ -192,14 +272,17 @@ public class CldsEvent { } /** - * @param processInstanceId - * the processInstanceId to set + * Sets process instance id. + * + * @param processInstanceId the processInstanceId to set */ public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } /** + * Gets userid. + * * @return the userid */ public String getUserid() { @@ -207,8 +290,9 @@ public class CldsEvent { } /** - * @param userid - * the userid to set + * Sets userid. + * + * @param userid the userid to set */ public void setUserid(String userid) { this.userid = userid; diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModel.java b/src/main/java/org/onap/clamp/clds/model/CldsModel.java index 2c178eb8..223d3892 100644 --- a/src/main/java/org/onap/clamp/clds/model/CldsModel.java +++ b/src/main/java/org/onap/clamp/clds/model/CldsModel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -45,12 +45,33 @@ public class CldsModel { private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsModel.class); private static final int UUID_LENGTH = 36; + /** + * The constant STATUS_DESIGN. + */ public static final String STATUS_DESIGN = "DESIGN"; + /** + * The constant STATUS_DISTRIBUTED. + */ public static final String STATUS_DISTRIBUTED = "DISTRIBUTED"; + /** + * The constant STATUS_ACTIVE. + */ public static final String STATUS_ACTIVE = "ACTIVE"; + /** + * The constant STATUS_STOPPED. + */ public static final String STATUS_STOPPED = "STOPPED"; + /** + * The constant STATUS_DELETING. + */ public static final String STATUS_DELETING = "DELETING"; + /** + * The constant STATUS_ERROR. + */ public static final String STATUS_ERROR = "ERROR"; + /** + * The constant STATUS_UNKNOWN. + */ public static final String STATUS_UNKNOWN = "UNKNOWN"; private String id; private String templateId; @@ -70,7 +91,7 @@ public class CldsModel { // This is a transient value used to return the failure message to UI private String errorMessageForUi; /** - * The service type Id received from DCAE by querying it + * The service type Id received from DCAE by querying it. */ private String typeId; private String typeName; @@ -81,10 +102,20 @@ public class CldsModel { private static StatusHandler statusHandler = new StatusHandlerImpl(); private static ActionsHandler actionsHandler = new ActionsHandlerImpl(); + /** + * Sets status handler. + * + * @param statHandler the stat handler + */ public static synchronized void setStatusHandler(StatusHandler statHandler) { statusHandler = statHandler; } + /** + * Sets actions handler. + * + * @param cdHandler the cd handler + */ public static synchronized void setActionsHandler(ActionsHandler cdHandler) { actionsHandler = cdHandler; } @@ -98,6 +129,11 @@ public class CldsModel { /** * Retrieve from DB. + * + * @param cldsDao the clds dao + * @param name the name + * @param okIfNotFound the ok if not found + * @return the clds model */ public static CldsModel retrieve(CldsDao cldsDao, String name, boolean okIfNotFound) { // get from db @@ -110,6 +146,11 @@ public class CldsModel { return model; } + /** + * Can dcae inventory call boolean. + * + * @return the boolean + */ public boolean canDcaeInventoryCall() { boolean canCall = false; /* Below checks the clds event is submit/resubmit/distribute */ @@ -122,6 +163,10 @@ public class CldsModel { /** * Save model to DB. + * + * @param cldsDao the clds dao + * @param userid the userid + * @return the clds model */ public CldsModel save(CldsDao cldsDao, String userid) { CldsModel cldsModel = cldsDao.setModel(this, userid); @@ -131,7 +176,7 @@ public class CldsModel { } /** - * set the status in the model + * set the status in the model. */ public void determineStatus() { status = statusHandler.determineStatusOnLastEvent(event); @@ -151,6 +196,8 @@ public class CldsModel { * Validate requestedActionCd - determine permittedActionCd and then check if * contained in permittedActionCd Throw IllegalArgumentException if requested * actionCd is not permitted. + * + * @param requestedActionCd the requested action cd */ public void validateAction(String requestedActionCd) { determinePermittedActionCd(); @@ -166,6 +213,9 @@ public class CldsModel { * controlNameUuid). No fields are populated other than controlNamePrefix and * controlNameUuid. Throws BadRequestException if length of given control name * is less than UUID_LENGTH. + * + * @param fullControlName the full control name + * @return the clds model */ public static CldsModel createUsingControlName(String fullControlName) { if (fullControlName == null || fullControlName.length() < UUID_LENGTH) { @@ -180,6 +230,8 @@ public class CldsModel { } /** + * Gets control name. + * * @return the controlName (controlNamePrefix + controlNameUuid) */ public String getControlName() { @@ -187,7 +239,12 @@ public class CldsModel { } /** - * To insert modelInstance to the database + * To insert modelInstance to the database. + * + * @param cldsDao the clds dao + * @param dcaeEvent the dcae event + * @param userid the userid + * @return the clds model */ public static CldsModel insertModelInstance(CldsDao cldsDao, DcaeEvent dcaeEvent, String userid) { String controlName = dcaeEvent.getControlName(); @@ -205,6 +262,8 @@ public class CldsModel { } /** + * Gets name. + * * @return the name */ public String getName() { @@ -212,33 +271,53 @@ public class CldsModel { } /** - * @param name - * the name to set + * Sets name. + * + * @param name the name to set */ public void setName(String name) { this.name = name; } /** + * Gets type name. + * * @return the typeName */ public String getTypeName() { return typeName; } + /** + * Sets type name. + * + * @param typeName the type name + */ public void setTypeName(String typeName) { this.typeName = typeName; } + /** + * Gets template id. + * + * @return the template id + */ public String getTemplateId() { return templateId; } + /** + * Sets template id. + * + * @param templateId the template id + */ public void setTemplateId(String templateId) { this.templateId = templateId; } /** + * Gets control name prefix. + * * @return the controlNamePrefix */ public String getControlNamePrefix() { @@ -246,14 +325,17 @@ public class CldsModel { } /** - * @param controlNamePrefix - * the controlNamePrefix to set + * Sets control name prefix. + * + * @param controlNamePrefix the controlNamePrefix to set */ public void setControlNamePrefix(String controlNamePrefix) { this.controlNamePrefix = controlNamePrefix; } /** + * Gets control name uuid. + * * @return the controlNameUuid */ public String getControlNameUuid() { @@ -261,14 +343,17 @@ public class CldsModel { } /** - * @param controlNameUuid - * the controlNameUuid to set + * Sets control name uuid. + * + * @param controlNameUuid the controlNameUuid to set */ public void setControlNameUuid(String controlNameUuid) { this.controlNameUuid = controlNameUuid; } /** + * Gets prop text. + * * @return the propText */ public String getPropText() { @@ -276,45 +361,71 @@ public class CldsModel { } /** - * @param propText - * the propText to set + * Sets prop text. + * + * @param propText the propText to set */ public void setPropText(String propText) { this.propText = propText; } /** + * Gets event. + * * @return the event */ public CldsEvent getEvent() { return event; } + /** + * Gets id. + * + * @return the id + */ public String getId() { return id; } + /** + * Sets id. + * + * @param id the id + */ public void setId(String id) { this.id = id; } + /** + * Gets template name. + * + * @return the template name + */ public String getTemplateName() { return templateName; } + /** + * Sets template name. + * + * @param templateName the template name + */ public void setTemplateName(String templateName) { this.templateName = templateName; } /** - * @param event - * the event to set + * Sets event. + * + * @param event the event to set */ public void setEvent(CldsEvent event) { this.event = event; } /** + * Gets status. + * * @return the status */ public String getStatus() { @@ -322,53 +433,109 @@ public class CldsModel { } /** - * @param status - * the status to set + * Sets status. + * + * @param status the status to set */ public void setStatus(String status) { this.status = status; } + /** + * Gets blueprint text. + * + * @return the blueprint text + */ public String getBlueprintText() { return blueprintText; } + /** + * Sets blueprint text. + * + * @param blueprintText the blueprint text + */ public void setBlueprintText(String blueprintText) { this.blueprintText = blueprintText; } + /** + * Gets bpmn text. + * + * @return the bpmn text + */ public String getBpmnText() { return bpmnText; } + /** + * Sets bpmn text. + * + * @param bpmnText the bpmn text + */ public void setBpmnText(String bpmnText) { this.bpmnText = bpmnText; } + /** + * Gets image text. + * + * @return the image text + */ public String getImageText() { return imageText; } + /** + * Sets image text. + * + * @param imageText the image text + */ public void setImageText(String imageText) { this.imageText = imageText; } + /** + * Gets doc text. + * + * @return the doc text + */ public String getDocText() { return docText; } + /** + * Sets doc text. + * + * @param docText the doc text + */ public void setDocText(String docText) { this.docText = docText; } + /** + * Gets type id. + * + * @return the type id + */ public String getTypeId() { return typeId; } + /** + * Sets type id. + * + * @param typeId the type id + */ public void setTypeId(String typeId) { this.typeId = typeId; } + /** + * Gets clds model instance list. + * + * @return the clds model instance list + */ public List<CldsModelInstance> getCldsModelInstanceList() { if (cldsModelInstanceList == null) { cldsModelInstanceList = new ArrayList<>(); @@ -376,30 +543,65 @@ public class CldsModel { return cldsModelInstanceList; } + /** + * Gets deployment id. + * + * @return the deployment id + */ public String getDeploymentId() { return deploymentId; } + /** + * Sets deployment id. + * + * @param deploymentId the deployment id + */ public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } + /** + * Gets permitted action cd. + * + * @return the permitted action cd + */ public List<String> getPermittedActionCd() { return permittedActionCd; } + /** + * Gets error message for ui. + * + * @return the error message for ui + */ public String getErrorMessageForUi() { return errorMessageForUi; } + /** + * Sets error message for ui. + * + * @param errorMessageForUi the error message for ui + */ public void setErrorMessageForUi(String errorMessageForUi) { this.errorMessageForUi = errorMessageForUi; } + /** + * Gets deployment status url. + * + * @return the deployment status url + */ public String getDeploymentStatusUrl() { return deploymentStatusUrl; } + /** + * Sets deployment status url. + * + * @param deploymentStatusUrl the deployment status url + */ public void setDeploymentStatusUrl(String deploymentStatusUrl) { this.deploymentStatusUrl = deploymentStatusUrl; } diff --git a/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java b/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java index bafe48d9..9aed447d 100644 --- a/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java +++ b/src/main/java/org/onap/clamp/clds/model/actions/ActionsHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -68,68 +68,69 @@ public interface ActionsHandler { List<String> permittedActions; String actionCd = getCurrentActionCd(event); switch (actionCd) { - case CldsEvent.ACTION_CREATE: - permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST, CldsEvent.ACTION_DELETE); - if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { - permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_SUBMITPOLICY, - CldsEvent.ACTION_TEST, CldsEvent.ACTION_DELETE); - } - break; - case CldsEvent.ACTION_SUBMIT: - case CldsEvent.ACTION_RESUBMIT: - case CldsEvent.ACTION_DISTRIBUTE: - permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT, - CldsEvent.ACTION_DELETE); - if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { - permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE, - CldsEvent.ACTION_DELETE); - } - break; - case CldsEvent.ACTION_SUBMITDCAE: - permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); - break; - case CldsEvent.ACTION_SUBMITPOLICY: - permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); - break; - case CldsEvent.ACTION_UNDEPLOY: - permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, - CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); - if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { - permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, - CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); - } - break; - case CldsEvent.ACTION_DEPLOY: - permittedActions = Arrays.asList(CldsEvent.ACTION_UNDEPLOY, CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); - break; - case CldsEvent.ACTION_RESTART: - case CldsEvent.ACTION_UPDATE: - permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP, - CldsEvent.ACTION_UNDEPLOY); - if (isTypeModel(propText, ModelType.POLICY_MODEL)) { + case CldsEvent.ACTION_CREATE: + permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_TEST, + CldsEvent.ACTION_DELETE); + if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { + permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_SUBMITPOLICY, + CldsEvent.ACTION_TEST, CldsEvent.ACTION_DELETE); + } + break; + case CldsEvent.ACTION_SUBMIT: + case CldsEvent.ACTION_RESUBMIT: + case CldsEvent.ACTION_DISTRIBUTE: + permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_RESUBMIT, + CldsEvent.ACTION_DELETE); + if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { + permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_SUBMITDCAE, + CldsEvent.ACTION_DELETE); + } + break; + case CldsEvent.ACTION_SUBMITDCAE: + permittedActions = Arrays.asList(CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); + break; + case CldsEvent.ACTION_SUBMITPOLICY: permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); - } - break; - case CldsEvent.ACTION_STOP: - permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, - CldsEvent.ACTION_UNDEPLOY); - if (isTypeModel(propText, ModelType.POLICY_MODEL)) { + break; + case CldsEvent.ACTION_UNDEPLOY: + permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, + CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_DELETE); + if (isTypeModel(propText, ModelType.SIMPLE_MODEL)) { + permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_DEPLOY, + CldsEvent.ACTION_SUBMITDCAE, CldsEvent.ACTION_DELETE); + } + break; + case CldsEvent.ACTION_DEPLOY: + permittedActions = Arrays.asList(CldsEvent.ACTION_UNDEPLOY, CldsEvent.ACTION_UPDATE, + CldsEvent.ACTION_STOP); + break; + case CldsEvent.ACTION_RESTART: + case CldsEvent.ACTION_UPDATE: + permittedActions = Arrays.asList(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_UPDATE, + CldsEvent.ACTION_STOP, CldsEvent.ACTION_UNDEPLOY); + if (isTypeModel(propText, ModelType.POLICY_MODEL)) { + permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP); + } + break; + case CldsEvent.ACTION_STOP: permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, - CldsEvent.ACTION_DELETE); - } - break; - default: - getLogger().warn("Invalid current actionCd: " + actionCd); - permittedActions = Arrays.asList(); + CldsEvent.ACTION_UNDEPLOY); + if (isTypeModel(propText, ModelType.POLICY_MODEL)) { + permittedActions = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART, + CldsEvent.ACTION_DELETE); + } + break; + default: + getLogger().warn("Invalid current actionCd: " + actionCd); + permittedActions = Arrays.asList(); } return permittedActions; } /** - * This method returns the action of the event or a default one if not found. + * This returns the action of the event or a default one if not found. * - * @param event - * The last event + * @param event The last event * @return The action */ default String getCurrentActionCd(CldsEvent event) { @@ -157,8 +158,8 @@ public interface ActionsHandler { JsonObject modelJson = JsonUtils.GSON.fromJson(propText, JsonObject.class); JsonElement modelJsonOfType = modelJson.get(key.getType()); if (modelJsonOfType != null - && modelJsonOfType.isJsonPrimitive() - && modelJsonOfType.getAsJsonPrimitive().getAsBoolean()) { + && modelJsonOfType.isJsonPrimitive() + && modelJsonOfType.getAsJsonPrimitive().getAsBoolean()) { result = true; } } diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java index c9405d20..729ef496 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/SdcSingleController.java @@ -1,353 +1,397 @@ -/*-
- * ============LICENSE_START=======================================================
- * ONAP CLAMP
- * ================================================================================
- * Copyright (C) 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============================================
- * Modifications copyright (c) 2018 Nokia
- * ===================================================================
- *
- */
-
-package org.onap.clamp.clds.sdc.controller;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-import java.util.Date;
-import java.util.Map.Entry;
-import java.util.concurrent.ThreadLocalRandom;
-
-import org.onap.clamp.clds.config.ClampProperties;
-import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfiguration;
-import org.onap.clamp.clds.exception.policy.PolicyModelException;
-import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException;
-import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
-import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException;
-import org.onap.clamp.clds.exception.sdc.controller.SdcDownloadException;
-import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException;
-import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
-import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
-import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
-import org.onap.clamp.clds.util.LoggingUtils;
-import org.onap.sdc.api.IDistributionClient;
-import org.onap.sdc.api.consumer.IDistributionStatusMessage;
-import org.onap.sdc.api.consumer.INotificationCallback;
-import org.onap.sdc.api.notification.IArtifactInfo;
-import org.onap.sdc.api.notification.INotificationData;
-import org.onap.sdc.api.results.IDistributionClientDownloadResult;
-import org.onap.sdc.api.results.IDistributionClientResult;
-import org.onap.sdc.impl.DistributionClientFactory;
-import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
-import org.onap.sdc.utils.DistributionActionResultEnum;
-import org.onap.sdc.utils.DistributionStatusEnum;
-
-/**
- * This class handles one sdc controller defined in the config.
- */
-public class SdcSingleController {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcSingleController.class);
- private boolean isSdcClientAutoManaged = false;
- private CsarInstaller csarInstaller;
- private ClampProperties refProp;
- public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder";
- private int nbOfNotificationsOngoing = 0;
- private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED;
- private SdcSingleControllerConfiguration sdcConfig;
- private IDistributionClient distributionClient;
-
- /**
- * Inner class for Notification callback
- */
- private final class SdcNotificationCallBack implements INotificationCallback {
-
- private SdcSingleController sdcController;
-
- SdcNotificationCallBack(SdcSingleController controller) {
- sdcController = controller;
- }
-
- /**
- * This method can be called multiple times at the same moment. The controller
- * must be thread safe !
- */
- @Override
- public void activateCallback(INotificationData iNotif) {
- Date startTime = new Date();
- logger.info("Receive a callback notification in SDC, nb of resources: " + iNotif.getResources().size());
- sdcController.treatNotification(iNotif);
- LoggingUtils.setTimeContext(startTime, new Date());
- LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully",
- this.getClass().getName());
- }
- }
-
- public int getNbOfNotificationsOngoing() {
- return nbOfNotificationsOngoing;
- }
-
- private void changeControllerStatusIdle() {
- if (this.nbOfNotificationsOngoing > 1) {
- --this.nbOfNotificationsOngoing;
- } else {
- this.nbOfNotificationsOngoing = 0;
- this.controllerStatus = SdcSingleControllerStatus.IDLE;
- }
- }
-
- protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) {
- switch (newControllerStatus) {
- case BUSY:
- ++this.nbOfNotificationsOngoing;
- this.controllerStatus = newControllerStatus;
- break;
- case IDLE:
- this.changeControllerStatusIdle();
- break;
- default:
- this.controllerStatus = newControllerStatus;
- break;
- }
- }
-
- public final synchronized SdcSingleControllerStatus getControllerStatus() {
- return this.controllerStatus;
- }
-
- public SdcSingleController(ClampProperties clampProp, CsarInstaller csarInstaller,
- SdcSingleControllerConfiguration sdcSingleConfig, IDistributionClient distributionClient) {
- this.distributionClient = distributionClient;
- isSdcClientAutoManaged = (distributionClient == null);
- this.sdcConfig = sdcSingleConfig;
- this.refProp = clampProp;
- this.csarInstaller = csarInstaller;
- }
-
- /**
- * This method initializes the SDC Controller and the SDC Client.
- *
- * @throws SdcControllerException
- * It throws an exception if the SDC Client cannot be instantiated or if
- * an init attempt is done when already initialized
- * @throws SdcParametersException
- * If there is an issue with the parameters provided
- */
- public void initSdc() throws SdcControllerException {
- logger.info("Attempt to initialize the SDC Controller: " + sdcConfig.getSdcControllerName());
- if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) {
- throw new SdcControllerException("The controller is already initialized, call the closeSDC method first");
- }
- if (distributionClient == null) {
- distributionClient = DistributionClientFactory.createDistributionClient();
- }
- IDistributionClientResult result = distributionClient.init(sdcConfig, new SdcNotificationCallBack(this));
- if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
- logger.error("SDC distribution client init failed with reason:" + result.getDistributionMessageResult());
- this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
- throw new SdcControllerException(
- "Initialization of the SDC Controller failed with reason: " + result.getDistributionMessageResult());
- }
- logger.info("SDC Controller successfully initialized: " + sdcConfig.getSdcControllerName());
- logger.info("Attempt to start the SDC Controller: " + sdcConfig.getSdcControllerName());
- result = this.distributionClient.start();
- if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
- logger.error("SDC distribution client start failed with reason:" + result.getDistributionMessageResult());
- this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
- throw new SdcControllerException(
- "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult());
- }
- logger.info("SDC Controller successfully started: " + sdcConfig.getSdcControllerName());
- this.changeControllerStatus(SdcSingleControllerStatus.IDLE);
- }
-
- /**
- * This method closes the SDC Controller and the SDC Client.
- *
- * @throws SdcControllerException
- * It throws an exception if the SDC Client cannot be closed because
- * it's currently BUSY in processing notifications.
- */
- public void closeSdc() throws SdcControllerException {
- if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) {
- throw new SdcControllerException("Cannot close the SDC controller as it's currently in BUSY state");
- }
- if (this.distributionClient != null) {
- this.distributionClient.stop();
- // If auto managed we can set it to Null, SdcController controls it.
- // In the other case the client of this class has specified it, so
- // we can't reset it
- if (isSdcClientAutoManaged) {
- // Next init will initialize it with a new SDC Client
- this.distributionClient = null;
- }
- }
- this.changeControllerStatus(SdcSingleControllerStatus.STOPPED);
- }
-
- private void sendAllNotificationForCsarHandler(INotificationData iNotif, CsarHandler csar,
- NotificationType notificationType, DistributionStatusEnum distributionStatus, String errorMessage) {
- if (csar != null) {
- // Notify for the CSAR
- this.sendSdcNotification(notificationType, csar.getArtifactElement().getArtifactURL(),
- sdcConfig.getConsumerID(), iNotif.getDistributionID(), distributionStatus, errorMessage,
- System.currentTimeMillis());
- // Notify for all VF resources found
- for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
- // Normally always 1 artifact in resource for Clamp as we
- // specified
- // only VF_METADATA type
- this.sendSdcNotification(notificationType,
- blueprint.getValue().getResourceAttached().getArtifacts().get(0).getArtifactURL(),
- sdcConfig.getConsumerID(), iNotif.getDistributionID(), distributionStatus, errorMessage,
- System.currentTimeMillis());
- }
- } else {
- this.sendSdcNotification(notificationType, null, sdcConfig.getConsumerID(), iNotif.getDistributionID(),
- distributionStatus, errorMessage, System.currentTimeMillis());
- }
- }
-
- /**
- * This method processes the notification received from Sdc.
- *
- * @param iNotif
- * The INotificationData
- */
- public void treatNotification(INotificationData iNotif) {
- CsarHandler csar = null;
- try {
- // wait for a random time, so that 2 running Clamp will not treat
- // the same Notification at the same time
- Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10) * 1000L);
- logger.info("Notification received for service UUID:" + iNotif.getServiceUUID());
- this.changeControllerStatus(SdcSingleControllerStatus.BUSY);
- csar = new CsarHandler(iNotif, this.sdcConfig.getSdcControllerName(),
- refProp.getStringValue(CONFIG_SDC_FOLDER));
- csar.save(downloadTheArtifact(csar.getArtifactElement()));
- if (csarInstaller.isCsarAlreadyDeployed(csar)) {
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,
- DistributionStatusEnum.ALREADY_DOWNLOADED, null);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.ALREADY_DEPLOYED, null);
- } else {
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,
- DistributionStatusEnum.DOWNLOAD_OK, null);
- csarInstaller.installTheCsar(csar);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.DEPLOY_OK, null);
- }
- } catch (SdcArtifactInstallerException | SdcToscaParserException e) {
- logger.error("SdcArtifactInstallerException exception caught during the notification processing", e);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
- } catch (SdcDownloadException | CsarHandlerException e) {
- logger.error("SdcDownloadException exception caught during the notification processing", e);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DOWNLOAD,
- DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage());
- } catch (PolicyModelException e) {
- logger.error("PolicyModelException exception caught during the notification processing", e);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
- } catch (InterruptedException e) {
- logger.error("Interrupt exception caught during the notification processing", e);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
- Thread.currentThread().interrupt();
- } catch (RuntimeException e) {
- logger.error("Unexpected exception caught during the notification processing", e);
- sendAllNotificationForCsarHandler(iNotif, csar, NotificationType.DEPLOY,
- DistributionStatusEnum.DEPLOY_ERROR, e.getMessage());
- } finally {
- this.changeControllerStatus(SdcSingleControllerStatus.IDLE);
- }
- }
-
- private enum NotificationType {
- DOWNLOAD, DEPLOY
- }
-
- private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException {
- logger.info(
- "Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: " + artifact.getArtifactUUID());
- IDistributionClientDownloadResult downloadResult;
- try {
- downloadResult = distributionClient.download(artifact);
- if (null == downloadResult) {
- logger.info("downloadResult is Null for: " + artifact.getArtifactUUID());
- return null;
- }
- } catch (RuntimeException e) {
- throw new SdcDownloadException("Exception caught when downloading the artifact", e);
- }
- if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) {
- logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID "
- + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length);
- } else {
- throw new SdcDownloadException(
- "Artifact " + artifact.getArtifactName() + " could not be downloaded from SDC URL "
- + artifact.getArtifactURL() + " UUID " + artifact.getArtifactUUID() + ")" + System.lineSeparator()
- + "Error message is " + downloadResult.getDistributionMessageResult() + System.lineSeparator());
- }
- return downloadResult;
- }
-
- private void sendSdcNotification(NotificationType notificationType, String artifactURL, String consumerID,
- String distributionID, DistributionStatusEnum status, String errorReason, long timestamp) {
- String event = "Sending " + notificationType.name() + "(" + status.name() + ")"
- + " notification to SDC for artifact:" + artifactURL;
- if (errorReason != null) {
- event = event + "(" + errorReason + ")";
- }
- logger.info(event);
- String action = "";
- try {
- IDistributionStatusMessage message = new DistributionStatusMessage(artifactURL, consumerID, distributionID,
- status, timestamp);
- switch (notificationType) {
- case DOWNLOAD:
- this.sendDownloadStatus(message, errorReason);
- action = "sendDownloadStatus";
- break;
- case DEPLOY:
- this.sendDeploymentStatus(message, errorReason);
- action = "sendDeploymentdStatus";
- break;
- default:
- break;
- }
- } catch (RuntimeException e) {
- logger.warn("Unable to send the SDC Notification (" + action + ") due to an exception", e);
- }
- logger.info("SDC Notification sent successfully(" + action + ")");
- }
-
- private void sendDownloadStatus(IDistributionStatusMessage message, String errorReason) {
- if (errorReason != null) {
- this.distributionClient.sendDownloadStatus(message, errorReason);
- } else {
- this.distributionClient.sendDownloadStatus(message);
- }
- }
-
- private void sendDeploymentStatus(IDistributionStatusMessage message, String errorReason) {
- if (errorReason != null) {
- this.distributionClient.sendDeploymentStatus(message, errorReason);
- } else {
- this.distributionClient.sendDeploymentStatus(message);
- }
- }
-}
+/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2018-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============================================ + * Modifications copyright (c) 2018 Nokia + * =================================================================== + * + */ + +package org.onap.clamp.clds.sdc.controller; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Date; +import java.util.Map.Entry; +import java.util.concurrent.ThreadLocalRandom; + +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfiguration; +import org.onap.clamp.clds.exception.policy.PolicyModelException; +import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException; +import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; +import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; +import org.onap.clamp.clds.exception.sdc.controller.SdcDownloadException; +import org.onap.clamp.clds.exception.sdc.controller.SdcParametersException; +import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact; +import org.onap.clamp.clds.sdc.controller.installer.CsarHandler; +import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.sdc.api.IDistributionClient; +import org.onap.sdc.api.consumer.IDistributionStatusMessage; +import org.onap.sdc.api.consumer.INotificationCallback; +import org.onap.sdc.api.notification.IArtifactInfo; +import org.onap.sdc.api.notification.INotificationData; +import org.onap.sdc.api.results.IDistributionClientDownloadResult; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientFactory; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.sdc.utils.DistributionActionResultEnum; +import org.onap.sdc.utils.DistributionStatusEnum; + +/** + * This class handles one sdc controller defined in the config. + */ +public class SdcSingleController { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(SdcSingleController.class); + private boolean isSdcClientAutoManaged = false; + private CsarInstaller csarInstaller; + private ClampProperties refProp; + /** + * The constant CONFIG_SDC_FOLDER. + */ + public static final String CONFIG_SDC_FOLDER = "sdc.csarFolder"; + private int nbOfNotificationsOngoing = 0; + private SdcSingleControllerStatus controllerStatus = SdcSingleControllerStatus.STOPPED; + private SdcSingleControllerConfiguration sdcConfig; + private IDistributionClient distributionClient; + + /** + * Inner class for Notification callback. + */ + private final class SdcNotificationCallBack implements INotificationCallback { + + private SdcSingleController sdcController; + + /** + * Instantiates a new Sdc notification call back. + * + * @param controller the controller + */ + SdcNotificationCallBack(SdcSingleController controller) { + sdcController = controller; + } + + /** + * This method can be called multiple times at the same moment. The controller + * must be thread safe ! + */ + @Override + public void activateCallback(INotificationData notificationData) { + Date startTime = new Date(); + logger.info("Receive a callback notification in SDC, nb of resources: " + + notificationData.getResources().size()); + sdcController.treatNotification(notificationData); + LoggingUtils.setTimeContext(startTime, new Date()); + LoggingUtils.setResponseContext("0", "SDC Notification received and processed successfully", + this.getClass().getName()); + } + } + + /** + * Gets nb of notifications ongoing. + * + * @return the nb of notifications ongoing + */ + public int getNbOfNotificationsOngoing() { + return nbOfNotificationsOngoing; + } + + private void changeControllerStatusIdle() { + if (this.nbOfNotificationsOngoing > 1) { + --this.nbOfNotificationsOngoing; + } else { + this.nbOfNotificationsOngoing = 0; + this.controllerStatus = SdcSingleControllerStatus.IDLE; + } + } + + /** + * Change controller status. + * + * @param newControllerStatus the new controller status + */ + protected final synchronized void changeControllerStatus(SdcSingleControllerStatus newControllerStatus) { + switch (newControllerStatus) { + case BUSY: + ++this.nbOfNotificationsOngoing; + this.controllerStatus = newControllerStatus; + break; + case IDLE: + this.changeControllerStatusIdle(); + break; + default: + this.controllerStatus = newControllerStatus; + break; + } + } + + /** + * Gets controller status. + * + * @return the controller status + */ + public final synchronized SdcSingleControllerStatus getControllerStatus() { + return this.controllerStatus; + } + + /** + * Instantiates a new Sdc single controller. + * + * @param clampProp the clamp prop + * @param csarInstaller the csar installer + * @param sdcSingleConfig the sdc single config + * @param distributionClient the distribution client + */ + public SdcSingleController(ClampProperties clampProp, CsarInstaller csarInstaller, + SdcSingleControllerConfiguration sdcSingleConfig, + IDistributionClient distributionClient) { + this.distributionClient = distributionClient; + isSdcClientAutoManaged = (distributionClient == null); + this.sdcConfig = sdcSingleConfig; + this.refProp = clampProp; + this.csarInstaller = csarInstaller; + } + + /** + * This method initializes the SDC Controller and the SDC Client. + * + * @throws SdcControllerException It throws an exception if the SDC Client cannot be instantiated or if + * an init attempt is done when already initialized + */ + public void initSdc() throws SdcControllerException { + logger.info("Attempt to initialize the SDC Controller: " + sdcConfig.getSdcControllerName()); + if (this.getControllerStatus() != SdcSingleControllerStatus.STOPPED) { + throw new SdcControllerException("The controller is already initialized, call the closeSDC method first"); + } + if (distributionClient == null) { + distributionClient = DistributionClientFactory.createDistributionClient(); + } + IDistributionClientResult result = distributionClient.init(sdcConfig, + new SdcNotificationCallBack(this)); + if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) { + logger.error("SDC distribution client init failed with reason:" + result.getDistributionMessageResult()); + this.changeControllerStatus(SdcSingleControllerStatus.STOPPED); + throw new SdcControllerException( + "Initialization of the SDC Controller failed with reason: " + + result.getDistributionMessageResult()); + } + logger.info("SDC Controller successfully initialized: " + sdcConfig.getSdcControllerName()); + logger.info("Attempt to start the SDC Controller: " + sdcConfig.getSdcControllerName()); + result = this.distributionClient.start(); + if (!result.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) { + logger.error("SDC distribution client start failed with reason:" + result.getDistributionMessageResult()); + this.changeControllerStatus(SdcSingleControllerStatus.STOPPED); + throw new SdcControllerException( + "Startup of the SDC Controller failed with reason: " + result.getDistributionMessageResult()); + } + logger.info("SDC Controller successfully started: " + sdcConfig.getSdcControllerName()); + this.changeControllerStatus(SdcSingleControllerStatus.IDLE); + } + + /** + * This method closes the SDC Controller and the SDC Client. + * + * @throws SdcControllerException It throws an exception if the SDC Client cannot be closed because + * it's currently BUSY in processing notifications. + */ + public void closeSdc() throws SdcControllerException { + if (this.getControllerStatus() == SdcSingleControllerStatus.BUSY) { + throw new SdcControllerException("Cannot close the SDC controller as it's currently in BUSY state"); + } + if (this.distributionClient != null) { + this.distributionClient.stop(); + // If auto managed we can set it to Null, SdcController controls it. + // In the other case the client of this class has specified it, so + // we can't reset it + if (isSdcClientAutoManaged) { + // Next init will initialize it with a new SDC Client + this.distributionClient = null; + } + } + this.changeControllerStatus(SdcSingleControllerStatus.STOPPED); + } + + private void sendAllNotificationForCsarHandler(INotificationData notificationData, CsarHandler csar, + NotificationType notificationType, + DistributionStatusEnum distributionStatus, String errorMessage) { + if (csar != null) { + // Notify for the CSAR + this.sendSdcNotification(notificationType, csar.getArtifactElement().getArtifactURL(), + sdcConfig.getConsumerID(), notificationData.getDistributionID(), distributionStatus, errorMessage, + System.currentTimeMillis()); + // Notify for all VF resources found + for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { + // Normally always 1 artifact in resource for Clamp as we + // specified + // only VF_METADATA type + this.sendSdcNotification(notificationType, + blueprint.getValue().getResourceAttached().getArtifacts().get(0).getArtifactURL(), + sdcConfig.getConsumerID(), notificationData.getDistributionID(), distributionStatus, + errorMessage, + System.currentTimeMillis()); + } + } else { + this.sendSdcNotification(notificationType, null, sdcConfig.getConsumerID(), + notificationData.getDistributionID(), + distributionStatus, errorMessage, System.currentTimeMillis()); + } + } + + /** + * This method processes the notification received from Sdc. + * + * @param notificationData The INotificationData + */ + public void treatNotification(INotificationData notificationData) { + CsarHandler csar = null; + try { + // wait for a random time, so that 2 running Clamp will not treat + // the same Notification at the same time + Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10) * 1000L); + logger.info("Notification received for service UUID:" + notificationData.getServiceUUID()); + this.changeControllerStatus(SdcSingleControllerStatus.BUSY); + csar = new CsarHandler(notificationData, this.sdcConfig.getSdcControllerName(), + refProp.getStringValue(CONFIG_SDC_FOLDER)); + csar.save(downloadTheArtifact(csar.getArtifactElement())); + if (csarInstaller.isCsarAlreadyDeployed(csar)) { + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD, + DistributionStatusEnum.ALREADY_DOWNLOADED, null); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.ALREADY_DEPLOYED, null); + } else { + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD, + DistributionStatusEnum.DOWNLOAD_OK, null); + csarInstaller.installTheCsar(csar); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.DEPLOY_OK, null); + } + } catch (SdcArtifactInstallerException | SdcToscaParserException e) { + logger.error("SdcArtifactInstallerException exception caught during the notification processing", e); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.DEPLOY_ERROR, e.getMessage()); + } catch (SdcDownloadException | CsarHandlerException e) { + logger.error("SdcDownloadException exception caught during the notification processing", e); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DOWNLOAD, + DistributionStatusEnum.DOWNLOAD_ERROR, e.getMessage()); + } catch (PolicyModelException e) { + logger.error("PolicyModelException exception caught during the notification processing", e); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.DEPLOY_ERROR, e.getMessage()); + } catch (InterruptedException e) { + logger.error("Interrupt exception caught during the notification processing", e); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.DEPLOY_ERROR, e.getMessage()); + Thread.currentThread().interrupt(); + } catch (RuntimeException e) { + logger.error("Unexpected exception caught during the notification processing", e); + sendAllNotificationForCsarHandler(notificationData, csar, NotificationType.DEPLOY, + DistributionStatusEnum.DEPLOY_ERROR, e.getMessage()); + } finally { + this.changeControllerStatus(SdcSingleControllerStatus.IDLE); + } + } + + private enum NotificationType { + /** + * Download notification type. + */ + DOWNLOAD, + /** + * Deploy notification type. + */ + DEPLOY + } + + private IDistributionClientDownloadResult downloadTheArtifact(IArtifactInfo artifact) throws SdcDownloadException { + logger.info( + "Trying to download the artifact : " + artifact.getArtifactURL() + " UUID: " + + artifact.getArtifactUUID()); + IDistributionClientDownloadResult downloadResult; + try { + downloadResult = distributionClient.download(artifact); + if (null == downloadResult) { + logger.info("downloadResult is Null for: " + artifact.getArtifactUUID()); + return null; + } + } catch (RuntimeException e) { + throw new SdcDownloadException("Exception caught when downloading the artifact", e); + } + if (DistributionActionResultEnum.SUCCESS.equals(downloadResult.getDistributionActionResult())) { + logger.info("Successfully downloaded the artifact " + artifact.getArtifactURL() + " UUID " + + artifact.getArtifactUUID() + "Size of payload " + downloadResult.getArtifactPayload().length); + } else { + throw new SdcDownloadException( + "Artifact " + artifact.getArtifactName() + " could not be downloaded from SDC URL " + + artifact.getArtifactURL() + " UUID " + artifact.getArtifactUUID() + ")" + + System.lineSeparator() + + "Error message is " + downloadResult.getDistributionMessageResult() + + System.lineSeparator()); + } + return downloadResult; + } + + private void sendSdcNotification(NotificationType notificationType, String artifactUrl, String consumerID, + String distributionID, DistributionStatusEnum status, String errorReason, + long timestamp) { + String event = "Sending " + notificationType.name() + "(" + status.name() + ")" + + " notification to SDC for artifact:" + artifactUrl; + if (errorReason != null) { + event = event + "(" + errorReason + ")"; + } + logger.info(event); + String action = ""; + try { + IDistributionStatusMessage message = new DistributionStatusMessage(artifactUrl, consumerID, distributionID, + status, timestamp); + switch (notificationType) { + case DOWNLOAD: + this.sendDownloadStatus(message, errorReason); + action = "sendDownloadStatus"; + break; + case DEPLOY: + this.sendDeploymentStatus(message, errorReason); + action = "sendDeploymentdStatus"; + break; + default: + break; + } + } catch (RuntimeException e) { + logger.warn("Unable to send the SDC Notification (" + action + ") due to an exception", e); + } + logger.info("SDC Notification sent successfully(" + action + ")"); + } + + private void sendDownloadStatus(IDistributionStatusMessage message, String errorReason) { + if (errorReason != null) { + this.distributionClient.sendDownloadStatus(message, errorReason); + } else { + this.distributionClient.sendDownloadStatus(message); + } + } + + private void sendDeploymentStatus(IDistributionStatusMessage message, String errorReason) { + if (errorReason != null) { + this.distributionClient.sendDeploymentStatus(message, errorReason); + } else { + this.distributionClient.sendDeploymentStatus(message); + } + } +} 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 e3a379b3..b9cce087 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -81,23 +81,53 @@ import org.springframework.web.client.HttpClientErrorException; @Component public class CldsService extends SecureServiceBase { + /** + * The constant LIST_OF_SDC_SERVICE_INFO_TYPE. + */ public static final Type LIST_OF_SDC_SERVICE_INFO_TYPE = new TypeToken<List<SdcServiceInfo>>() { }.getType(); @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; + /** + * The constant securityLogger. + */ protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + /** + * The constant logger. + */ protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsService.class); + /** + * The constant GLOBAL_PROPERTIES_KEY. + */ public static final String GLOBAL_PROPERTIES_KEY = "files.globalProperties"; private final String cldsPermissionTypeClManage; private final String cldsPermissionTypeClEvent; private final String cldsPermissionTypeFilterVf; private final String cldsPermissionInstance; + /** + * The Permission read cl. + */ final SecureServicePermission permissionReadCl; + /** + * The Permission update cl. + */ final SecureServicePermission permissionUpdateCl; + /** + * The Permission read template. + */ final SecureServicePermission permissionReadTemplate; + /** + * The Permission update template. + */ final SecureServicePermission permissionUpdateTemplate; + /** + * The Permission read tosca. + */ final SecureServicePermission permissionReadTosca; + /** + * The Permission update tosca. + */ final SecureServicePermission permissionUpdateTosca; private final CldsDao cldsDao; @@ -110,17 +140,40 @@ public class CldsService extends SecureServiceBase { @Autowired private HttpServletRequest request; + /** + * Instantiates a new Clds service. + * + * @param cldsDao the clds dao + * @param cldsBpmnTransformer the clds bpmn transformer + * @param refProp the ref prop + * @param dcaeDispatcherServices the dcae dispatcher services + * @param dcaeInventoryServices the dcae inventory services + * @param cldsPersmissionTypeCl the clds persmission type cl + * @param cldsPermissionTypeClManage the clds permission type cl manage + * @param cldsPermissionTypeClEvent the clds permission type cl event + * @param cldsPermissionTypeFilterVf the clds permission type filter vf + * @param cldsPermissionTypeTemplate the clds permission type template + * @param cldsPermissionTypeTosca the clds permission type tosca + * @param cldsPermissionInstance the clds permission instance + */ @Autowired public CldsService(CldsDao cldsDao, XslTransformer cldsBpmnTransformer, ClampProperties refProp, DcaeDispatcherServices dcaeDispatcherServices, DcaeInventoryServices dcaeInventoryServices, - @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") String cldsPersmissionTypeCl, - @Value("${clamp.config.security.permission.type.cl.manage:permission-type-cl-manage}") String cldsPermissionTypeClManage, - @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") String cldsPermissionTypeClEvent, - @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") String cldsPermissionTypeFilterVf, - @Value("${clamp.config.security.permission.type.template:permission-type-template}") String cldsPermissionTypeTemplate, - @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") String cldsPermissionTypeTosca, - @Value("${clamp.config.security.permission.instance:dev}") String cldsPermissionInstance) { + @Value("${clamp.config.security.permission.type.cl:permission-type-cl}") + String cldsPersmissionTypeCl, + @Value("${clamp.config.security.permission.type.cl.manage:permission-type-cl-manage}") + String cldsPermissionTypeClManage, + @Value("${clamp.config.security.permission.type.cl.event:permission-type-cl-event}") + String cldsPermissionTypeClEvent, + @Value("${clamp.config.security.permission.type.filter.vf:permission-type-filter-vf}") + String cldsPermissionTypeFilterVf, + @Value("${clamp.config.security.permission.type.template:permission-type-template}") + String cldsPermissionTypeTemplate, + @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") + String cldsPermissionTypeTosca, + @Value("${clamp.config.security.permission.instance:dev}") + String cldsPermissionInstance) { this.cldsDao = cldsDao; this.cldsBpmnTransformer = cldsBpmnTransformer; this.refProp = refProp; @@ -141,8 +194,9 @@ public class CldsService extends SecureServiceBase { "update"); } - /* - * @return list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name + /** + * Gets clds details. + * list of CLDS-Monitoring-Details: CLOSELOOP_NAME | Close loop name * used in the CLDS application (prefix: ClosedLoop- + unique ClosedLoop ID) * MODEL_NAME | Model Name in CLDS application SERVICE_TYPE_ID | TypeId returned * from the DCAE application when the ClosedLoop is submitted @@ -150,11 +204,12 @@ public class CldsService extends SecureServiceBase { * generated when the ClosedLoop is deployed in DCAE. TEMPLATE_NAME | Template * used to generate the ClosedLoop model. ACTION_CD | Current state of the * ClosedLoop in CLDS application. + * @return the clds details */ public List<CldsMonitoringDetails> getCldsDetails() { util.entering(request, "CldsService: GET model details"); Date startTime = new Date(); - List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCLDSMonitoringDetails(); + List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET cldsDetails completed"); @@ -162,9 +217,11 @@ public class CldsService extends SecureServiceBase { return cldsMonitoringDetailsList; } - /* + /** + * Gets clds info. * CLDS IFO service will return 3 things 1. User Name 2. CLDS code version that * is currently installed from pom.xml file 3. User permissions + * @return the clds info */ public CldsInfo getCldsInfo() { util.entering(request, "CldsService: GET cldsInfo"); @@ -186,7 +243,7 @@ public class CldsService extends SecureServiceBase { * This is subset of the json getModel. This is only expected to be used for * testing purposes, not by the UI. * - * @param modelName + * @param modelName the model name * @return bpmn xml text - content of bpmn given name */ public String getBpmnXml(String modelName) { @@ -207,7 +264,7 @@ public class CldsService extends SecureServiceBase { * This is subset of the json getModel. This is only expected to be used for * testing purposes, not by the UI. * - * @param modelName + * @param modelName the model name * @return image xml text - content of image given name */ public String getImageXml(String modelName) { @@ -226,7 +283,7 @@ public class CldsService extends SecureServiceBase { /** * REST service that retrieves a CLDS model by name from the database. * - * @param modelName + * @param modelName the model name * @return clds model - clds model for the given model name */ public CldsModel getModel(String modelName) { @@ -266,7 +323,9 @@ public class CldsService extends SecureServiceBase { /** * REST service that saves a CLDS model by name in the database. * - * @param modelName + * @param modelName the model name + * @param cldsModel the clds model + * @return the clds model */ public CldsModel putModel(String modelName, CldsModel cldsModel) { util.entering(request, "CldsService: PUT model"); @@ -322,19 +381,13 @@ public class CldsService extends SecureServiceBase { /** * REST service that saves and processes an action for a CLDS model by name. * - * @param action - * @param modelName - * @param test - * @param model - * @return - * @throws TransformerException - * In case of issues when doing the XSLT of the BPMN flow - * @throws ParseException - * In case of issues when parsing the JSON - * @throws GeneralSecurityException - * In case of issues when decrypting the password - * @throws DecoderException - * In case of issues with the Hex String decoding + * @param action the action + * @param modelName the model name + * @param test the test + * @param model the model + * @return response entity + * @throws TransformerException In case of issues when doing the XSLT of the BPMN flow + * @throws ParseException In case of issues when parsing the JSON */ public ResponseEntity<?> putModelAndProcessAction(String action, String modelName, String test, CldsModel model) throws TransformerException, ParseException { @@ -418,8 +471,9 @@ public class CldsService extends SecureServiceBase { /** * REST service that accepts events for a model. * - * @param test - * @param dcaeEvent + * @param test the test + * @param dcaeEvent the dcae event + * @return the string */ public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { util.entering(request, "CldsService: Post dcae event"); @@ -462,10 +516,10 @@ public class CldsService extends SecureServiceBase { } /** - * REST service that retrieves total properties required by UI + * REST service that retrieves total properties required by UI. * - * @throws IOException - * In case of issues + * @return the sdc properties + * @throws IOException In case of issues */ public String getSdcProperties() throws IOException { return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString(); @@ -476,9 +530,8 @@ public class CldsService extends SecureServiceBase { * Determine if the user is authorized for a particular VF by its invariant * UUID. * - * @param vfInvariantUuid - * @throws NotAuthorizedException - * @return + * @param vfInvariantUuid the vf invariant uuid + * @return boolean or throws NotAuthorizedException */ public boolean isAuthorizedForVf(String vfInvariantUuid) { if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) { @@ -497,7 +550,7 @@ public class CldsService extends SecureServiceBase { * Determine if the user is authorized for a particular VF by its invariant * UUID. If not authorized, then NotAuthorizedException is thrown. * - * @param model + * @param model The clds model * @return */ private boolean isAuthorizedForVf(CldsModel model) { @@ -510,6 +563,13 @@ public class CldsService extends SecureServiceBase { } } + /** + * Deploy model response entity. + * + * @param modelName the model name + * @param model the model + * @return the response entity + */ public ResponseEntity<CldsModel> deployModel(String modelName, CldsModel model) { util.entering(request, "CldsService: Deploy model"); Date startTime = new Date(); @@ -559,6 +619,13 @@ public class CldsService extends SecureServiceBase { } } + /** + * Un deploy model response entity. + * + * @param modelName the model name + * @param model the model + * @return the response entity + */ public ResponseEntity<CldsModel> unDeployModel(String modelName, CldsModel model) { util.entering(request, "CldsService: Undeploy model"); Date startTime = new Date(); @@ -642,6 +709,11 @@ public class CldsService extends SecureServiceBase { } } + /** + * Sets logging util. + * + * @param utilP the util p + */ // Created for the integration test public void setLoggingUtil(LoggingUtils utilP) { util = utilP; diff --git a/src/main/java/org/onap/clamp/clds/tosca/JsonEditorSchemaConstants.java b/src/main/java/org/onap/clamp/clds/tosca/JsonEditorSchemaConstants.java index 58a2f6f0..fdc94231 100644 --- a/src/main/java/org/onap/clamp/clds/tosca/JsonEditorSchemaConstants.java +++ b/src/main/java/org/onap/clamp/clds/tosca/JsonEditorSchemaConstants.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP CLAMP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,61 +18,54 @@ * limitations under the License. * ============LICENSE_END============================================ * =================================================================== - * + * */ package org.onap.clamp.clds.tosca; public class JsonEditorSchemaConstants { - - //Data types in JSON Schema - public static final String TYPE_OBJECT = "object"; - public static final String TYPE_ARRAY = "array"; - public static final String TYPE_STRING = "string"; - public static final String TYPE_INTEGER = "integer"; - - //Key elements in JSON Schema - public static final String TYPE = "type"; - public static final String TITLE = "title"; - public static final String REQUIRED = "required"; - public static final String DEFAULT = "default"; - public static final String ENUM = "enum"; - public static final String ENUM_TITLES = "enum_titles"; - public static final String OPTIONS = "options"; - public static final String FORMAT = "format"; - public static final String ITEMS = "items"; - public static final String PROPERTIES = "properties"; - public static final String PROPERTY_ORDER = "propertyOrder"; - - public static final String MINIMUM = "minimum"; - public static final String MAXIMUM = "maximum"; - public static final String MIN_LENGTH = "minLength"; - public static final String MAX_LENGTH = "maxLength"; - public static final String EXCLUSIVE_MINIMUM = "exclusiveMinimum"; - public static final String EXCLUSIVE_MAXIMUM = "exclusiveMaximum"; - - public static final String CUSTOM_KEY_FORMAT = "format"; - public static final String CUSTOM_KEY_FORMAT_TABS_TOP = "tabs-top"; - public static final String FORMAT_SELECT = "select"; - public static final String UNIQUE_ITEMS = "uniqueItems"; - public static final String TRUE = "true"; - public static final String QSSCHEMA = "qschema"; - public static final String TYPE_QBLDR = "qbldr"; - - public static final String ID = "id"; - public static final String LABEL = "label"; - public static final String OPERATORS = "operators"; - public static final String FILTERS = "filters"; - - public static final String SCHEMA = "schema"; - public static final String CURRENT_VALUES = "currentValues"; - - - - - - - - - + + //Data types in JSON Schema + public static final String TYPE_OBJECT = "object"; + public static final String TYPE_ARRAY = "array"; + public static final String TYPE_STRING = "string"; + public static final String TYPE_INTEGER = "integer"; + + //Key elements in JSON Schema + public static final String TYPE = "type"; + public static final String TITLE = "title"; + public static final String REQUIRED = "required"; + public static final String DEFAULT = "default"; + public static final String ENUM = "enum"; + public static final String ENUM_TITLES = "enum_titles"; + public static final String OPTIONS = "options"; + public static final String FORMAT = "format"; + public static final String ITEMS = "items"; + public static final String PROPERTIES = "properties"; + public static final String PROPERTY_ORDER = "propertyOrder"; + + public static final String MINIMUM = "minimum"; + public static final String MAXIMUM = "maximum"; + public static final String MIN_LENGTH = "minLength"; + public static final String MAX_LENGTH = "maxLength"; + public static final String EXCLUSIVE_MINIMUM = "exclusiveMinimum"; + public static final String EXCLUSIVE_MAXIMUM = "exclusiveMaximum"; + + public static final String CUSTOM_KEY_FORMAT = "format"; + public static final String CUSTOM_KEY_FORMAT_TABS_TOP = "tabs-top"; + public static final String FORMAT_SELECT = "select"; + public static final String UNIQUE_ITEMS = "uniqueItems"; + public static final String TRUE = "true"; + public static final String QSSCHEMA = "qschema"; + public static final String TYPE_QBLDR = "qbldr"; + + public static final String ID = "id"; + public static final String LABEL = "label"; + public static final String OPERATORS = "operators"; + public static final String FILTERS = "filters"; + + public static final String SCHEMA = "schema"; + public static final String CURRENT_VALUES = "currentValues"; + + } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java index f746ab14..e9e589e0 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java @@ -17,6 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END============================================ + * Modifications copyright (c) 2019 AT&T. * =================================================================== * */ @@ -33,39 +34,39 @@ import java.awt.Rectangle; public class AwtUtils { private static final int ARROW_W = 4; private static final int ARROW_H = 2; - private static final int FONT_SIZE = 12; - private static final int FONT_STYLE = Font.PLAIN; + private static final int FONT_SIZE = 12; + private static final int FONT_STYLE = Font.PLAIN; private static final String FONT_FACE = "SansSerif"; - private static final Color TRANSPARENT = new Color(0.0f, 0.0f,0.0f,0.0f); + private static final Color TRANSPARENT = new Color(0.0f, 0.0f, 0.0f, 0.0f); - static void rectWithText(Graphics2D g2d, String text, Point p, int w, int h) { - Rectangle rect = new Rectangle(p.x, p.y, w, h); + static void rectWithText(Graphics2D g2d, String text, Point point, int width, int height) { + Rectangle rect = new Rectangle(point.x, point.y, width, height); g2d.draw(rect); Color oldColor = g2d.getColor(); g2d.setColor(TRANSPARENT); g2d.fill(rect); g2d.setColor(oldColor); - addText(g2d, text, p.x+w/2, p.y+h/2); + addText(g2d, text, point.x + width / 2, point.y + height / 2); } static void drawArrow(Graphics2D g2d, Point from, Point to, int lineThickness) { int x2 = to.x - lineThickness; - g2d.drawLine(from.x, from.y, x2-lineThickness, to.y); - g2d.drawPolygon(new int[] {x2-ARROW_W, x2-ARROW_W, x2},new int[] {to.y- ARROW_H, to.y+ ARROW_H, to.y},3); - g2d.fillPolygon(new int[] {x2-ARROW_W, x2-ARROW_W, x2},new int[] {to.y- ARROW_H, to.y+ ARROW_H, to.y},3); + g2d.drawLine(from.x, from.y, x2 - lineThickness, to.y); + g2d.drawPolygon(new int[]{x2 - ARROW_W, x2 - ARROW_W, x2}, new int[]{to.y - ARROW_H, to.y + ARROW_H, to.y}, 3); + g2d.fillPolygon(new int[]{x2 - ARROW_W, x2 - ARROW_W, x2}, new int[]{to.y - ARROW_H, to.y + ARROW_H, to.y}, 3); } - private static void addText(Graphics2D g2d, String text, int x, int y) { - Font f = new Font(FONT_FACE, FONT_STYLE, FONT_SIZE); - g2d.setFont(f); + private static void addText(Graphics2D g2d, String text, int abs, int ord) { + Font font = new Font(FONT_FACE, FONT_STYLE, FONT_SIZE); + g2d.setFont(font); FontMetrics fm1 = g2d.getFontMetrics(); int w1 = fm1.stringWidth(text); - int x1 = x - (w1 / 2); + int x1 = abs - (w1 / 2); - g2d.setFont(f); + g2d.setFont(font); g2d.setColor(Color.BLACK); - g2d.drawString(text, x1, y); + g2d.drawString(text, x1, ord); } } diff --git a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java index 65052888..fed2c65b 100644 --- a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java @@ -216,7 +216,7 @@ public class CsarInstallerImpl implements CsarInstaller { /** * ll get the latest version of the artifact (version can be specified to DCAE - * call) + * call). * * @return The DcaeInventoryResponse object containing the dcae values */ diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index 473364ae..64e0108e 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -57,7 +57,7 @@ import org.onap.clamp.policy.operational.OperationalPolicy; public class Loop implements Serializable { /** - * + * The serial version id. */ private static final long serialVersionUID = -286522707701388642L; @@ -105,7 +105,8 @@ public class Loop implements Serializable { @Expose @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) - @JoinTable(name = "loops_microservicepolicies", joinColumns = @JoinColumn(name = "loop_id"), inverseJoinColumns = @JoinColumn(name = "microservicepolicy_id")) + @JoinTable(name = "loops_microservicepolicies", joinColumns = @JoinColumn(name = "loop_id"), + inverseJoinColumns = @JoinColumn(name = "microservicepolicy_id")) private Set<MicroServicePolicy> microServicePolicies = new HashSet<>(); @Expose @@ -115,6 +116,9 @@ public class Loop implements Serializable { public Loop() { } + /** + * Constructor. + */ public Loop(String name, String blueprint, String svgRepresentation) { this.name = name; this.svgRepresentation = svgRepresentation; @@ -234,6 +238,14 @@ public class Loop implements Serializable { this.modelPropertiesJson = modelPropertiesJson; } + /** + * Generate the loop name. + * @param serviceName The service name + * @param serviceVersion The service version + * @param resourceName The resource name + * @param blueprintFileName The blueprint file name + * @return The generated loop name + */ public static String generateLoopName(String serviceName, String serviceVersion, String resourceName, String blueprintFilename) { StringBuilder buffer = new StringBuilder("LOOP_").append(serviceName).append("_v").append(serviceVersion) @@ -251,18 +263,23 @@ public class Loop implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Loop other = (Loop) obj; if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/src/main/java/org/onap/clamp/loop/LoopController.java b/src/main/java/org/onap/clamp/loop/LoopController.java index 8b64e9d7..a02fa933 100644 --- a/src/main/java/org/onap/clamp/loop/LoopController.java +++ b/src/main/java/org/onap/clamp/loop/LoopController.java @@ -42,9 +42,9 @@ public class LoopController { private final LoopService loopService; private static final Type OPERATIONAL_POLICY_TYPE = new TypeToken<List<OperationalPolicy>>() { - }.getType(); + }.getType(); private static final Type MICROSERVICE_POLICY_TYPE = new TypeToken<List<MicroServicePolicy>>() { - }.getType(); + }.getType(); @Autowired public LoopController(LoopService loopService) { @@ -59,26 +59,55 @@ public class LoopController { return loopService.getLoop(loopName); } + /** + * Update the Operational Policy properties. + * @param loopName The loop name + * @param operationalPoliciesJson The new Operational Policy properties + * @return The updated loop + */ public Loop updateOperationalPolicies(String loopName, JsonArray operationalPoliciesJson) { List<OperationalPolicy> operationalPolicies = JsonUtils.GSON .fromJson(operationalPoliciesJson, OPERATIONAL_POLICY_TYPE); return loopService.updateAndSaveOperationalPolicies(loopName, operationalPolicies); } + /** + * Update the whole array of MicroService policies properties + * @param loopName The loop name + * @param microServicePoliciesJson The array of all MicroService policies properties + * @return The updated loop + */ public Loop updateMicroservicePolicies(String loopName, JsonArray microServicePoliciesJson) { List<MicroServicePolicy> microservicePolicies = JsonUtils.GSON .fromJson(microServicePoliciesJson, MICROSERVICE_POLICY_TYPE); return loopService.updateAndSaveMicroservicePolicies(loopName, microservicePolicies); } - public Loop updateGlobalPropertiesJson(String loopName, JsonObject globalProperties){ + /** + * Update the global properties + * @param loopName The loop name + * @param globalProperties The updated global properties + * @return The updated loop + */ + public Loop updateGlobalPropertiesJson(String loopName, JsonObject globalProperties) { return loopService.updateAndSaveGlobalPropertiesJson(loopName, globalProperties); } + /** + * Update one MicroService policy properties + * @param loopName The loop name + * @param newMicroservicePolicy The new MicroService policy properties + * @return The updated MicroService policy + */ public MicroServicePolicy updateMicroservicePolicy(String loopName, MicroServicePolicy newMicroservicePolicy) { return loopService.updateMicroservicePolicy(loopName, newMicroservicePolicy); } + /** + * Get the SVG representation of the loop + * @param loopName The loop name + * @return The SVG representation + */ public String getSVGRepresentation(String loopName) { return loopService.getClosedLoopModelSVG(loopName); diff --git a/src/main/java/org/onap/clamp/loop/LoopService.java b/src/main/java/org/onap/clamp/loop/LoopService.java index 051ab6ed..b4995734 100644 --- a/src/main/java/org/onap/clamp/loop/LoopService.java +++ b/src/main/java/org/onap/clamp/loop/LoopService.java @@ -25,13 +25,15 @@ package org.onap.clamp.loop; import java.util.List; import java.util.Set; -import javax.persistence.EntityNotFoundException; import com.google.gson.JsonObject; -import org.onap.clamp.policy.microservice.MicroservicePolicyService; -import org.onap.clamp.policy.operational.OperationalPolicyService; + +import javax.persistence.EntityNotFoundException; + import org.onap.clamp.policy.microservice.MicroServicePolicy; +import org.onap.clamp.policy.microservice.MicroservicePolicyService; import org.onap.clamp.policy.operational.OperationalPolicy; +import org.onap.clamp.policy.operational.OperationalPolicyService; import org.springframework.stereotype.Service; @Service @@ -41,6 +43,9 @@ public class LoopService { private final MicroservicePolicyService microservicePolicyService; private final OperationalPolicyService operationalPolicyService; + /** + * Constructor. + */ public LoopService(LoopsRepository loopsRepository, MicroservicePolicyService microservicePolicyService, OperationalPolicyService operationalPolicyService) { @@ -57,7 +62,7 @@ public class LoopService { return loopsRepository.getAllLoopNames(); } - Loop getLoop(String loopName){ + Loop getLoop(String loopName) { return loopsRepository .findById(loopName) .orElse(null); @@ -87,7 +92,7 @@ public class LoopService { } MicroServicePolicy updateMicroservicePolicy(String loopName, MicroServicePolicy newMicroservicePolicy) { - Loop loop = findClosedLoopByName(loopName); + Loop loop = findClosedLoopByName(loopName); MicroServicePolicy newPolicies = microservicePolicyService .getAndUpdateMicroServicePolicy(loop, newMicroservicePolicy); return newPolicies; 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 7b7fe1b1..0c51c0c1 100644 --- a/src/main/java/org/onap/clamp/loop/log/LoopLog.java +++ b/src/main/java/org/onap/clamp/loop/log/LoopLog.java @@ -43,7 +43,6 @@ import javax.persistence.Table; import org.onap.clamp.loop.Loop; /** - * * This class holds the logs created by the Clamp Backend. The Instant is always * rounded to the nearest second as the nano seconds can't be stored in the * database. The logs can be therefore exposed to the UI or the client doing @@ -54,7 +53,7 @@ import org.onap.clamp.loop.Loop; @Table(name = "loop_logs") public class LoopLog implements Serializable { /** - * + * The serial version ID. */ private static final long serialVersionUID = 1988276670074437631L; @@ -130,18 +129,23 @@ public class LoopLog implements Serializable { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } LoopLog other = (LoopLog) obj; if (id == null) { - if (other.id != null) + if (other.id != null) { return false; - } else if (!id.equals(other.id)) + } + } else if (!id.equals(other.id)) { return false; + } return true; } diff --git a/src/main/java/org/onap/clamp/policy/Policy.java b/src/main/java/org/onap/clamp/policy/Policy.java index c104b13e..683881bf 100644 --- a/src/main/java/org/onap/clamp/policy/Policy.java +++ b/src/main/java/org/onap/clamp/policy/Policy.java @@ -31,6 +31,15 @@ public interface Policy { JsonObject getJsonRepresentation(); + /** + * Generate the policy name. + * @param policyType The policy type + * @param serviceName The service name + * @param serviceVersion The service version + * @param resourceName The resource name + * @param blueprintFilename The blueprint file name + * @return The generated policy name + */ static String generatePolicyName(String policyType, String serviceName, String serviceVersion, String resourceName, String blueprintFilename) { StringBuilder buffer = new StringBuilder(policyType).append("_").append(serviceName).append("_v") 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 857a3d74..3962a3d4 100644 --- a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java +++ b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java @@ -50,7 +50,7 @@ import org.onap.clamp.policy.Policy; @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) }) public class MicroServicePolicy implements Serializable, Policy { /** - * + * The serial version ID. */ private static final long serialVersionUID = 6271238288583332616L; @@ -83,6 +83,13 @@ public class MicroServicePolicy implements Serializable, Policy { // serialization } + /** + * The constructor. + * @param name The name of the MicroService + * @param policyTosca The policy Tosca of the MicroService + * @param shared The flag indicate whether the MicroService is shared + * @param usedByLoops The list of loops that uses this MicroService + */ public MicroServicePolicy(String name, String policyTosca, Boolean shared, Set<Loop> usedByLoops) { this.name = name; this.policyTosca = policyTosca; @@ -92,6 +99,14 @@ public class MicroServicePolicy implements Serializable, Policy { this.usedByLoops = usedByLoops; } + /** + * The constructor. + * @param name The name of the MicroService + * @param policyTosca The policy Tosca of the MicroService + * @param shared The flag indicate whether the MicroService is shared + * @param jsonRepresentation The UI representation in json format + * @param usedByLoops The list of loops that uses this MicroService + */ public MicroServicePolicy(String name, String policyTosca, Boolean shared, JsonObject jsonRepresentation, Set<Loop> usedByLoops) { this.name = name; @@ -157,18 +172,23 @@ public class MicroServicePolicy implements Serializable, Policy { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } MicroServicePolicy other = (MicroServicePolicy) obj; if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/src/main/java/org/onap/clamp/policy/microservice/MicroservicePolicyService.java b/src/main/java/org/onap/clamp/policy/microservice/MicroservicePolicyService.java index ee9ba537..f473d160 100644 --- a/src/main/java/org/onap/clamp/policy/microservice/MicroservicePolicyService.java +++ b/src/main/java/org/onap/clamp/policy/microservice/MicroservicePolicyService.java @@ -57,6 +57,12 @@ public class MicroservicePolicyService implements PolicyService<MicroServicePoli return repository.existsById(policyName); } + /** + * Get and update the MicroService policy properties. + * @param loop The loop + * @param policy The new MicroService policy + * @return The updated MicroService policy + */ @Transactional public MicroServicePolicy getAndUpdateMicroServicePolicy(Loop loop, MicroServicePolicy policy) { return repository.findById(policy.getName()).map(p -> updateMicroservicePolicyProperties(p, policy, loop)) 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 033b5397..c1e075da 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicy.java @@ -38,16 +38,16 @@ import javax.persistence.Table; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; 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.onap.clamp.dao.model.jsontype.StringJsonUserType; @Entity @Table(name = "operational_policies") @TypeDefs({ @TypeDef(name = "json", typeClass = StringJsonUserType.class) }) public class OperationalPolicy implements Serializable, Policy { /** - * + * The serial version ID. */ private static final long serialVersionUID = 6117076450841538255L; @@ -69,6 +69,12 @@ public class OperationalPolicy implements Serializable, Policy { //Serialization } + /** + * The constructor. + * @param name The name of the operational policy + * @param loop The loop that uses this operational policy + * @param configurationsJson The operational policy property in the format of json + */ public OperationalPolicy(String name, Loop loop, JsonObject configurationsJson) { this.name = name; this.loop = loop; @@ -83,7 +89,7 @@ public class OperationalPolicy implements Serializable, Policy { this.loop = loopName; } - public Loop getLoop(){ + public Loop getLoop() { return loop; } @@ -110,18 +116,23 @@ public class OperationalPolicy implements Serializable, Policy { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } OperationalPolicy other = (OperationalPolicy) obj; if (name == null) { - if (other.name != null) + if (other.name != null) { return false; - } else if (!name.equals(other.name)) + } + } else if (!name.equals(other.name)) { return false; + } return true; } diff --git a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyService.java b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyService.java index b24a2db1..95f4f7be 100644 --- a/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyService.java +++ b/src/main/java/org/onap/clamp/policy/operational/OperationalPolicyService.java @@ -27,8 +27,8 @@ import com.google.gson.JsonObject; import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import org.onap.clamp.policy.PolicyService; import org.onap.clamp.loop.Loop; +import org.onap.clamp.policy.PolicyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/src/main/java/org/onap/clamp/util/PrincipalUtils.java b/src/main/java/org/onap/clamp/util/PrincipalUtils.java index ec089834..d6b20f30 100644 --- a/src/main/java/org/onap/clamp/util/PrincipalUtils.java +++ b/src/main/java/org/onap/clamp/util/PrincipalUtils.java @@ -40,7 +40,7 @@ public class PrincipalUtils { /** * Get the Full name. * - * @return + * @return The user name */ public static String getUserName() { String name = userNameHandler.retrieveUserName(securityContext); @@ -53,7 +53,7 @@ public class PrincipalUtils { /** * Get the userId from AAF/CSP. * - * @return + * @return The user ID */ public static String getUserId() { return getUserName(); @@ -62,7 +62,7 @@ public class PrincipalUtils { /** * Get the principal name. * - * @return + * @return The principal name */ public static String getPrincipalName() { String principal = ((UserDetails)securityContext.getAuthentication().getPrincipal()).getUsername(); @@ -72,6 +72,7 @@ public class PrincipalUtils { } return name; } + public static void setSecurityContext(SecurityContext securityContext) { PrincipalUtils.securityContext = securityContext; } |