diff options
author | sebdet <sebastien.determe@intl.att.com> | 2019-09-09 17:32:53 +0200 |
---|---|---|
committer | sebdet <sebastien.determe@intl.att.com> | 2019-09-09 17:33:57 +0200 |
commit | 0387f232b4a56e98092519ccc2e0ee7985f6701c (patch) | |
tree | 70651cfc52f1d3149ef8ff44363d5712080dc72c /src/main/java/org | |
parent | e77e0ff6c8655d8afe20d9e333ebff5833b08d52 (diff) |
Remove dead code
Removal of dead code not used anymore as part of the V1 interface + new
swagger without old v1 interface
Issue-ID: CLAMP-487
Change-Id: I56c80c26082b5119f14afc41e26bae1c52b1ba59
Signed-off-by: sebdet <sebastien.determe@intl.att.com>
Diffstat (limited to 'src/main/java/org')
11 files changed, 135 insertions, 1894 deletions
diff --git a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java index 2e43495b7..f9e618c83 100644 --- a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java +++ b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java @@ -44,7 +44,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; /** - * Create CLDS Event. + * Verify user has right permissions. */ @Component public class AuthorizationController { diff --git a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java deleted file mode 100644 index bee0d4c05..000000000 --- a/src/main/java/org/onap/clamp/clds/config/spring/CldsSdcControllerConfiguration.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * * Modifications copyright (c) 2019 Nokia - * =================================================================== - * - */ - -package org.onap.clamp.clds.config.spring; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.util.ArrayList; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.config.sdc.SdcControllersConfiguration; -import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; -import org.onap.clamp.clds.sdc.controller.SdcSingleController; -import org.onap.clamp.clds.sdc.controller.SdcSingleControllerStatus; -import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Profile; -import org.springframework.scheduling.annotation.Scheduled; - -@Configuration -@ComponentScan(basePackages = "org.onap.clamp.clds") -@Profile("clamp-sdc-controller") -public class CldsSdcControllerConfiguration { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsSdcControllerConfiguration.class); - private List<SdcSingleController> sdcControllersList = new ArrayList<>(); - private final ClampProperties clampProp; - private final CsarInstaller csarInstaller; - - public CldsSdcControllerConfiguration(ClampProperties clampProp, @Qualifier("oldModelInstaller") CsarInstaller csarInstaller) { - this.clampProp = clampProp; - this.csarInstaller = csarInstaller; - } - - /** - * Loads SDC controllers configuration. - */ - @PostConstruct - public void loadSdcControllers() { - SdcControllersConfiguration sdcControllersConfig = getSdcControllersConfiguration(); - sdcControllersConfig.getAllDefinedControllers().forEach((k, v) -> { - logger.info("Creating controller instance:" + k); - SdcSingleController sdcController = new SdcSingleController(clampProp, csarInstaller, v, null); - sdcControllersList.add(sdcController); - }); - } - - /** - * Checks whether all SDC controllers defined are up and running. - */ - @Scheduled(fixedRate = 120000) - public void checkAllSdcControllers() { - logger.info("Checking that all SDC Controllers defined are up and running"); - for (SdcSingleController controller : sdcControllersList) { - try { - if (SdcSingleControllerStatus.STOPPED.equals(controller.getControllerStatus())) { - controller.initSdc(); - } - } catch (SdcControllerException e) { - logger.error("Exception caught when booting sdc controller", e); - } - } - logger.info("SDC Controllers check completed"); - } - - /** - * Closes all SDC Controller and the SDC Client. - */ - @PreDestroy - public void killSdcControllers() { - sdcControllersList.forEach(e -> { - try { - e.closeSdc(); - } catch (SdcControllerException e1) { - logger.error("Exception caught when stopping sdc controller", e1); - } - }); - } - - @Bean(name = "sdcControllersConfiguration") - public SdcControllersConfiguration getSdcControllersConfiguration() { - return new SdcControllersConfiguration(); - } -}
\ No newline at end of file diff --git a/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java b/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java index 8b8ee932b..b4794c940 100644 --- a/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/spring/SdcControllerConfiguration.java @@ -25,10 +25,13 @@ package org.onap.clamp.clds.config.spring; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; + import java.util.ArrayList; import java.util.List; + import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; + import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.config.sdc.SdcControllersConfiguration; import org.onap.clamp.clds.exception.sdc.controller.SdcControllerException; @@ -44,7 +47,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.scheduling.annotation.Scheduled; @Configuration -@ComponentScan(basePackages = {"org.onap.clamp.loop", "org.onap.clamp.clds.config"}) +@ComponentScan(basePackages = { "org.onap.clamp.loop", "org.onap.clamp.clds.config" }) @Profile("clamp-sdc-controller-new") public class SdcControllerConfiguration { @@ -54,7 +57,8 @@ public class SdcControllerConfiguration { private final CsarInstaller csarInstaller; @Autowired - public SdcControllerConfiguration(ClampProperties clampProp, @Qualifier("loopInstaller") CsarInstaller csarInstaller) { + public SdcControllerConfiguration(ClampProperties clampProp, + @Qualifier("loopInstaller") CsarInstaller csarInstaller) { this.clampProp = clampProp; this.csarInstaller = csarInstaller; } 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 16a6a748c..91ddfc480 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -42,7 +42,6 @@ import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.CldsModel; import org.onap.clamp.clds.model.CldsModelInstance; import org.onap.clamp.clds.model.CldsModelProp; -import org.onap.clamp.clds.model.CldsMonitoringDetails; import org.onap.clamp.clds.model.CldsTemplate; import org.onap.clamp.clds.model.CldsToscaModel; import org.onap.clamp.clds.model.ValueItem; @@ -95,8 +94,7 @@ public class CldsDao { /** * When dataSource is provided, instantiate spring jdbc objects. * - * @param dataSource - * the data source + * @param dataSource the data source */ public void setDataSource(DataSource dataSource) { this.jdbcTemplateObject = new JdbcTemplate(dataSource); @@ -112,7 +110,7 @@ public class CldsDao { this.procDeleteModel = new SimpleJdbcCall(dataSource).withProcedureName("del_model"); this.procInsertToscaModel = new SimpleJdbcCall(dataSource).withProcedureName("set_tosca_model"); this.procInsertNewToscaModelVersion = new SimpleJdbcCall(dataSource) - .withProcedureName("set_new_tosca_model_version"); + .withProcedureName("set_new_tosca_model_version"); this.procInsertDictionary = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary"); this.procInsertDictionaryElement = new SimpleJdbcCall(dataSource).withProcedureName("set_dictionary_elements"); } @@ -120,8 +118,7 @@ public class CldsDao { /** * Get a model from the database given the model name. * - * @param modelName - * the model name + * @param modelName the model name * @return the model */ public CldsModel getModel(String modelName) { @@ -133,7 +130,7 @@ public class CldsDao { CldsModel model = new CldsModel(); model.setName(modelName); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue(V_CONTROL_NAME_UUID, controlNameUuid); + .addValue(V_CONTROL_NAME_UUID, controlNameUuid); Map<String, Object> out = logSqlExecution(procGetModel, in); populateModelProperties(model, out); return model; @@ -142,8 +139,7 @@ public class CldsDao { /** * Get a model from the database given the controlNameUuid. * - * @param controlNameUuid - * the control name uuid + * @param controlNameUuid the control name uuid * @return the model by uuid */ public CldsModel getModelByUuid(String controlNameUuid) { @@ -153,8 +149,7 @@ public class CldsDao { /** * Get a model and template information from the database given the model name. * - * @param modelName - * the model name + * @param modelName the model name * @return model model template */ @@ -186,21 +181,19 @@ public class CldsDao { * Update model in the database using parameter values and return updated model * object. * - * @param model - * the model - * @param userid - * the userid + * @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()) - .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid) - .addValue("v_model_prop_text", model.getPropText()) - .addValue("v_model_blueprint_text", model.getBlueprintText()) - .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId()) - .addValue("v_deployment_status_url", model.getDeploymentStatusUrl()) - .addValue(V_CONTROL_NAME_PREFIX, model.getControlNamePrefix()) - .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()); + .addValue("v_template_id", model.getTemplateId()).addValue("v_user_id", userid) + .addValue("v_model_prop_text", model.getPropText()) + .addValue("v_model_blueprint_text", model.getBlueprintText()) + .addValue("v_service_type_id", model.getTypeId()).addValue("v_deployment_id", model.getDeploymentId()) + .addValue("v_deployment_status_url", model.getDeploymentStatusUrl()) + .addValue(V_CONTROL_NAME_PREFIX, model.getControlNamePrefix()) + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()); Map<String, Object> out = logSqlExecution(procSetModel, in); model.setControlNamePrefix((String) out.get(V_CONTROL_NAME_PREFIX)); model.setControlNameUuid((String) out.get(V_CONTROL_NAME_UUID)); @@ -213,10 +206,8 @@ public class CldsDao { * Inserts new modelInstance in the database using parameter values and return * updated model object. * - * @param model - * the model - * @param modelInstancesList - * the model instances list + * @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 @@ -230,9 +221,9 @@ public class CldsDao { logger.debug("v_vm_name={}", currModelInstance.getVmName()); logger.debug("v_location={}", currModelInstance.getLocation()); SqlParameterSource in = new MapSqlParameterSource() - .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()) - .addValue("v_vm_name", currModelInstance.getVmName()) - .addValue("v_location", currModelInstance.getLocation()); + .addValue(V_CONTROL_NAME_UUID, model.getControlNameUuid()) + .addValue("v_vm_name", currModelInstance.getVmName()) + .addValue("v_location", currModelInstance.getLocation()); Map<String, Object> out = logSqlExecution(procInsModelInstance, in); model.setId((String) (out.get("v_model_id"))); CldsModelInstance modelInstance = new CldsModelInstance(); @@ -248,23 +239,19 @@ public class CldsDao { * Insert an event in the database - require either modelName or * controlNamePrefix/controlNameUuid. * - * @param modelName - * the model name - * @param controlNamePrefix - * the control name prefix - * @param controlNameUuid - * the control name uuid - * @param cldsEvent - * the clds event + * @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(); SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName) - .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid) - .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd()) - .addValue("v_action_state_cd", cldsEvent.getActionStateCd()) - .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId()); + .addValue(V_CONTROL_NAME_PREFIX, controlNamePrefix).addValue(V_CONTROL_NAME_UUID, controlNameUuid) + .addValue("v_user_id", cldsEvent.getUserid()).addValue("v_action_cd", cldsEvent.getActionCd()) + .addValue("v_action_state_cd", cldsEvent.getActionStateCd()) + .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId()); Map<String, Object> out = logSqlExecution(procInsEvent, in); event.setId((String) (out.get("v_event_id"))); return event; @@ -279,14 +266,12 @@ public class CldsDao { /** * Update event with process instance id. * - * @param eventId - * the event id - * @param processInstanceId - * the process instance id + * @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) - .addValue("v_process_instance_id", processInstanceId); + .addValue("v_process_instance_id", processInstanceId); logSqlExecution(procUpdEvent, in); } @@ -304,16 +289,14 @@ public class CldsDao { * Update template in the database using parameter values and return updated * template object. * - * @param template - * the template - * @param userid - * the 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()) - .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText()) - .addValue("v_template_image_text", template.getImageText()) - .addValue("v_template_doc_text", template.getPropText()); + .addValue("v_user_id", userid).addValue("v_template_bpmn_text", template.getBpmnText()) + .addValue("v_template_image_text", template.getImageText()) + .addValue("v_template_doc_text", template.getPropText()); // properties to setup the template is return from the logSqlExecution method setTemplateBaseProp(template, logSqlExecution(procSetTemplate, in)); @@ -332,8 +315,7 @@ public class CldsDao { /** * Get a template from the database given the model name. * - * @param templateName - * the template name + * @param templateName the template name * @return model template */ public CldsTemplate getTemplate(String templateName) { @@ -354,10 +336,8 @@ public class CldsDao { /** * Helper method to setup the base template properties. * - * @param template - * the template - * @param prop - * collection with the properties + * @param template the template + * @param prop collection with the properties */ private void setTemplateBaseProp(CldsTemplate template, Map prop) { template.setId((String) prop.get("v_template_id")); @@ -393,8 +373,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 " - + "WHERE m.model_prop_id = mp.model_prop_id and m.event_id = e.event_id and e.action_cd = 'DEPLOY'"; + + "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; for (Map<String, Object> row : rows) { @@ -409,46 +389,9 @@ public class CldsDao { } /** - * Method to get deployed/active models with model properties. - * - * @return 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 (DCAEServiceTypeRequest generated in DCAE application). - * DEPLOYMENT_ID | Id 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. - */ - 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 " - + "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); - CldsMonitoringDetails cldsMonitoringDetails = null; - for (Map<String, Object> row : rows) { - cldsMonitoringDetails = new CldsMonitoringDetails(); - cldsMonitoringDetails.setCloseloopName((String) row.get("CLOSELOOP_NAME")); - cldsMonitoringDetails.setModelName((String) row.get("MODEL_NAME")); - cldsMonitoringDetails.setServiceTypeId((String) row.get("SERVICE_TYPE_ID")); - cldsMonitoringDetails.setDeploymentId((String) row.get("DEPLOYMENT_ID")); - cldsMonitoringDetails.setTemplateName((String) row.get("TEMPLATE_NAME")); - cldsMonitoringDetails.setAction((String) row.get("ACTION_CD")); - cldsMonitoringDetails.setUserid((String) row.get("USER_ID")); - cldsMonitoringDetails.setTimestamp(sdf.format(row.get("TIMESTAMP"))); - cldsMonitoringDetailsList.add(cldsMonitoringDetails); - } - return cldsMonitoringDetailsList; - } - - /** * Method to delete model from database. * - * @param modelName - * the model name + * @param modelName the model name */ public void deleteModel(String modelName) { SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName); @@ -476,10 +419,8 @@ public class CldsDao { /** * Helper method to setup the event prop to the CldsEvent class. * - * @param event - * the clds event - * @param prop - * collection with the configuration + * @param event the clds event + * @param prop collection with the configuration */ private void setEventProp(CldsEvent event, Map prop) { event.setId((String) prop.get("v_event_id")); @@ -501,8 +442,7 @@ public class CldsDao { /** * Method to retrieve a tosca models by Policy Type from database. * - * @param policyType - * the policy type + * @param policyType the policy type * @return List of CldsToscaModel */ public List<CldsToscaModel> getToscaModelByPolicyType(String policyType) { @@ -512,8 +452,7 @@ public class CldsDao { /** * Method to retrieve a tosca models by toscaModelName, version from database. * - * @param toscaModelName - * the tosca model name + * @param toscaModelName the tosca model name * @return List of CldsToscaModel */ public List<CldsToscaModel> getToscaModelByName(String toscaModelName) { @@ -528,13 +467,13 @@ public class CldsDao { String toscaModelSql = new StringBuilder("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").append(toscaModelName != null ? (", tmr.tosca_model_yaml") : "") - .append(" FROM tosca_model tm, tosca_model_revision tmr WHERE tm.tosca_model_id = tmr.tosca_model_id") - .append(toscaModelName != null ? (" AND tm.tosca_model_name = '" + toscaModelName + "'") : "") - .append(policyType != null ? (" AND tm.policy_type = '" + policyType + "'") : "") - .append(" AND tmr.version = (select max(version) from tosca_model_revision st where tmr.tosca_model_id" - + "=st.tosca_model_id)") - .toString(); + + "tmr.lastUpdatedTimestamp").append(toscaModelName != null ? (", tmr.tosca_model_yaml") : "").append( + " FROM tosca_model tm, tosca_model_revision tmr WHERE tm.tosca_model_id = tmr.tosca_model_id") + .append(toscaModelName != null ? (" AND tm.tosca_model_name = '" + toscaModelName + "'") : "") + .append(policyType != null ? (" AND tm.policy_type = '" + policyType + "'") : "") + .append(" AND tmr.version = (select max(version) from tosca_model_revision st where tmr.tosca_model_id" + + "=st.tosca_model_id)") + .toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(toscaModelSql); @@ -562,17 +501,15 @@ public class CldsDao { /** * Method to upload a new version of Tosca Model Yaml in Database. * - * @param cldsToscaModel - * the clds tosca model - * @param userId - * the user id + * @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()) - .addValue("v_version", cldsToscaModel.getVersion()) - .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) - .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()).addValue("v_user_id", userId); + .addValue("v_version", cldsToscaModel.getVersion()) + .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) + .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()).addValue("v_user_id", userId); Map<String, Object> out = logSqlExecution(procInsertNewToscaModelVersion, in); cldsToscaModel.setRevisionId((String) out.get("v_revision_id")); return cldsToscaModel; @@ -581,19 +518,17 @@ public class CldsDao { /** * Method to upload a new Tosca model Yaml in DB. Default version is 1.0 * - * @param cldsToscaModel - * the clds tosca model - * @param userId - * the user id + * @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() - .addValue("v_tosca_model_name", cldsToscaModel.getToscaModelName()) - .addValue("v_policy_type", cldsToscaModel.getPolicyType()) - .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) - .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()) - .addValue("v_version", cldsToscaModel.getVersion()).addValue("v_user_id", userId); + .addValue("v_tosca_model_name", cldsToscaModel.getToscaModelName()) + .addValue("v_policy_type", cldsToscaModel.getPolicyType()) + .addValue("v_tosca_model_yaml", cldsToscaModel.getToscaModelYaml()) + .addValue("v_tosca_model_json", cldsToscaModel.getToscaModelJson()) + .addValue("v_version", cldsToscaModel.getVersion()).addValue("v_user_id", userId); Map<String, Object> out = logSqlExecution(procInsertToscaModel, in); cldsToscaModel.setId((String) (out.get("v_tosca_model_id"))); cldsToscaModel.setRevisionId((String) (out.get("v_revision_id"))); @@ -604,13 +539,12 @@ public class CldsDao { /** * Method to insert a new Dictionary in Database. * - * @param cldsDictionary - * the clds dictionary + * @param cldsDictionary the clds dictionary */ public void insDictionary(CldsDictionary cldsDictionary) { SqlParameterSource in = new MapSqlParameterSource() - .addValue("v_dictionary_name", cldsDictionary.getDictionaryName()) - .addValue("v_user_id", cldsDictionary.getCreatedBy()); + .addValue("v_dictionary_name", cldsDictionary.getDictionaryName()) + .addValue("v_user_id", cldsDictionary.getCreatedBy()); Map<String, Object> out = logSqlExecution(procInsertDictionary, in); cldsDictionary.setDictionaryId((String) out.get("v_dictionary_id")); } @@ -618,20 +552,15 @@ public class CldsDao { /** * Method to update Dictionary with new info in Database. * - * @param dictionaryId - * the dictionary id - * @param cldsDictionary - * the clds dictionary - * @param userId - * the user id + * @param dictionaryId the dictionary id + * @param cldsDictionary the clds dictionary + * @param userId the user id */ public void updateDictionary(String dictionaryId, CldsDictionary cldsDictionary, String userId) { String dictionarySql = new StringBuilder("UPDATE dictionary SET dictionary_name = '") - .append(cldsDictionary.getDictionaryName()) - .append("', modified_by = '").append(userId) - .append("'WHERE dictionary_id = '").append(dictionaryId).append("'") - .toString(); + .append(cldsDictionary.getDictionaryName()).append("', modified_by = '").append(userId) + .append("'WHERE dictionary_id = '").append(dictionaryId).append("'").toString(); jdbcTemplateObject.update(dictionarySql); cldsDictionary.setUpdatedBy(userId); } @@ -639,10 +568,8 @@ public class CldsDao { /** * Method to get list of Dictionaries from the Database. * - * @param dictionaryId - * the dictionary id - * @param dictionaryName - * the dictionary name + * @param dictionaryId the dictionary id + * @param dictionaryName the dictionary name * @return dictionary */ public List<CldsDictionary> getDictionary(String dictionaryId, String dictionaryName) { @@ -660,9 +587,9 @@ public class CldsDao { } else { whereFilter = ""; } - String dictionarySql = new StringBuilder("SELECT dictionary_id, dictionary_name, created_by, " - + "modified_by, timestamp FROM dictionary") - .append(whereFilter).toString(); + String dictionarySql = new StringBuilder( + "SELECT dictionary_id, dictionary_name, created_by, " + "modified_by, timestamp FROM dictionary") + .append(whereFilter).toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); @@ -683,18 +610,16 @@ public class CldsDao { /** * Method to insert a new Dictionary Element for given dictionary in Database. * - * @param cldsDictionaryItem - * the clds dictionary item - * @param userId - * the user id + * @param cldsDictionaryItem the clds dictionary item + * @param userId the user id */ public void insDictionarElements(CldsDictionaryItem cldsDictionaryItem, String userId) { SqlParameterSource in = new MapSqlParameterSource() - .addValue("v_dictionary_id", cldsDictionaryItem.getDictionaryId()) - .addValue("v_dict_element_name", cldsDictionaryItem.getDictElementName()) - .addValue("v_dict_element_short_name", cldsDictionaryItem.getDictElementShortName()) - .addValue("v_dict_element_description", cldsDictionaryItem.getDictElementDesc()) - .addValue("v_dict_element_type", cldsDictionaryItem.getDictElementType()).addValue("v_user_id", userId); + .addValue("v_dictionary_id", cldsDictionaryItem.getDictionaryId()) + .addValue("v_dict_element_name", cldsDictionaryItem.getDictElementName()) + .addValue("v_dict_element_short_name", cldsDictionaryItem.getDictElementShortName()) + .addValue("v_dict_element_description", cldsDictionaryItem.getDictElementDesc()) + .addValue("v_dict_element_type", cldsDictionaryItem.getDictElementType()).addValue("v_user_id", userId); Map<String, Object> out = logSqlExecution(procInsertDictionaryElement, in); cldsDictionaryItem.setDictElementId((String) out.get("v_dict_element_id")); } @@ -703,25 +628,19 @@ public class CldsDao { * Method to update Dictionary Elements with new info for a given dictionary in * Database. * - * @param dictionaryElementId - * the dictionary element id - * @param cldsDictionaryItem - * the clds dictionary item - * @param userId - * the user id + * @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) { + String userId) { String dictionarySql = new StringBuilder().append("UPDATE dictionary_elements SET dict_element_name = '") - .append(cldsDictionaryItem.getDictElementName()) - .append("', dict_element_short_name = '").append(cldsDictionaryItem.getDictElementShortName()) - .append("', dict_element_description= '").append(cldsDictionaryItem.getDictElementDesc()) - .append("', dict_element_type = '").append(cldsDictionaryItem.getDictElementType()) - .append("', modified_by = '").append(userId).append("'") - .append(" WHERE dict_element_id = '") - .append(dictionaryElementId).append("'") - .toString(); + .append(cldsDictionaryItem.getDictElementName()).append("', dict_element_short_name = '") + .append(cldsDictionaryItem.getDictElementShortName()).append("', dict_element_description= '") + .append(cldsDictionaryItem.getDictElementDesc()).append("', dict_element_type = '") + .append(cldsDictionaryItem.getDictElementType()).append("', modified_by = '").append(userId).append("'") + .append(" WHERE dict_element_id = '").append(dictionaryElementId).append("'").toString(); jdbcTemplateObject.update(dictionarySql); cldsDictionaryItem.setUpdatedBy(userId); } @@ -730,26 +649,25 @@ public class CldsDao { * Method to get list of all dictionary elements for a given dictionary in the * Database. * - * @param dictionaryName - * the dictionary name - * @param dictionaryId - * the dictionary id - * @param dictElementShortName - * the dict element short name + * @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) { + String dictElementShortName) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsDictionaryItem> dictionaryItems = new ArrayList<>(); String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " + "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " + "de.modified_by, de.timestamp FROM dictionary_elements de, " + "dictionary d WHERE de.dictionary_id = d.dictionary_id") - .append((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "") - .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName - + "'") : "") - .append((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "").toString(); + .append((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "") + .append((dictElementShortName != null) + ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'") + : "") + .append((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "") + .toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); @@ -775,22 +693,21 @@ public class CldsDao { * Method to get Map of all dictionary elements with key as dictionary short * name and value as the full name. * - * @param dictionaryElementType - * the dictionary element type + * @param dictionaryElementType the dictionary element type * @return Map of dictionary elements as key value pair */ public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) { Map<String, String> dictionaryItems = new HashMap<>(); String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " - + "FROM dictionary_elements WHERE dict_element_type = '") - .append(dictionaryElementType).append("'").toString(); + + "FROM dictionary_elements WHERE dict_element_type = '").append(dictionaryElementType).append("'") + .toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); if (rows != null) { rows.forEach(row -> { dictionaryItems.put(((String) row.get("dict_element_short_name")), - ((String) row.get("dict_element_name"))); + ((String) row.get("dict_element_name"))); }); } return dictionaryItems; diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java b/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java deleted file mode 100644 index 2fc047813..000000000 --- a/src/main/java/org/onap/clamp/clds/dao/CldsServiceDataMapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.dao; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.apache.commons.io.serialization.ValidatingObjectInputStream; -import org.onap.clamp.clds.model.CldsServiceData; -import org.onap.clamp.clds.model.CldsVfData; -import org.onap.clamp.clds.model.CldsVfKPIData; -import org.onap.clamp.clds.model.CldsVfcData; -import org.springframework.jdbc.core.RowMapper; - -/** - * Generic mapper for CldsDBServiceCache. - */ -public final class CldsServiceDataMapper implements RowMapper<CldsServiceData> { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(CldsDao.class); - - @Override - public CldsServiceData mapRow(ResultSet rs, int rowNum) throws SQLException { - CldsServiceData cldsServiceData = new CldsServiceData(); - try (ValidatingObjectInputStream oip = new ValidatingObjectInputStream(rs.getBlob(4).getBinaryStream())) { - oip.accept(CldsServiceData.class, ArrayList.class, CldsVfData.class, CldsVfcData.class, - CldsVfKPIData.class); - cldsServiceData = (CldsServiceData) oip.readObject(); - cldsServiceData.setAgeOfRecord(rs.getLong(5)); - } catch (IOException | ClassNotFoundException e) { - logger.error("Error caught while deserializing cldsServiceData from database", e); - return null; - } - return cldsServiceData; - } -} diff --git a/src/main/java/org/onap/clamp/clds/model/CldsMonitoringDetails.java b/src/main/java/org/onap/clamp/clds/model/CldsMonitoringDetails.java deleted file mode 100644 index eb05fe406..000000000 --- a/src/main/java/org/onap/clamp/clds/model/CldsMonitoringDetails.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============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============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.model; - -/** - * Maintains model and template details. - */ -public class CldsMonitoringDetails { - - private String closeloopName; - private String modelId; - private String modelName; - private String serviceTypeId; - private String deploymentId; - private String templateName; - private String action; - private String userid; - private String timestamp; - - public String getCloseloopName() { - return closeloopName; - } - - public void setCloseloopName(String closeloopName) { - this.closeloopName = closeloopName; - } - - public String getModelId() { - return modelId; - } - - public void setModelId(String modelId) { - this.modelId = modelId; - } - - public String getModelName() { - return modelName; - } - - public void setModelName(String modelName) { - this.modelName = modelName; - } - - public String getServiceTypeId() { - return serviceTypeId; - } - - public void setServiceTypeId(String serviceTypeId) { - this.serviceTypeId = serviceTypeId; - } - - public String getDeploymentId() { - return deploymentId; - } - - public void setDeploymentId(String deploymentId) { - this.deploymentId = deploymentId; - } - - public String getTemplateName() { - return templateName; - } - - public void setTemplateName(String templateName) { - this.templateName = templateName; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getUserid() { - return userid; - } - - public void setUserid(String userid) { - this.userid = userid; - } - - public String getTimestamp() { - return timestamp; - } - - public void setTimestamp(String time) { - this.timestamp = time; - } - -} diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java deleted file mode 100644 index 441a7ac11..000000000 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ /dev/null @@ -1,350 +0,0 @@ -/*- - * ============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) 2019 Nokia - * =================================================================== - * - */ - -package org.onap.clamp.clds.sdc.controller.installer; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonObject; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import javax.annotation.PostConstruct; -import javax.xml.transform.TransformerException; -import org.apache.commons.io.IOUtils; -import org.json.simple.parser.ParseException; -import org.onap.clamp.clds.client.DcaeInventoryServices; -import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration; -import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration; -import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.exception.policy.PolicyModelException; -import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException; -import org.onap.clamp.clds.model.CldsModel; -import org.onap.clamp.clds.model.CldsTemplate; -import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse; -import org.onap.clamp.clds.model.properties.ModelProperties; -import org.onap.clamp.clds.service.CldsService; -import org.onap.clamp.clds.service.CldsTemplateService; -import org.onap.clamp.clds.transform.XslTransformer; -import org.onap.clamp.clds.util.JsonUtils; -import org.onap.clamp.clds.util.drawing.SvgFacade; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; -import org.yaml.snakeyaml.Yaml; - -/** - * This class will be instantiated by spring config, and used by Sdc Controller. - * There is no state kept by the bean. It's used to deploy the csar/notification - * received from SDC in DB. - */ -@Component -@Qualifier("oldModelInstaller") -public class CsarInstallerImpl implements CsarInstaller { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class); - private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>(); - public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-"; - public static final String CONTROL_NAME_PREFIX = "ClosedLoop-"; - public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input"; - // This will be used later as the policy scope - public static final String MODEL_NAME_PREFIX = "CLAMP"; - /** - * The file name that will be loaded by Spring. - */ - @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}") - protected String blueprintMappingFile; - protected ApplicationContext appContext; - private CldsDao cldsDao; - CldsTemplateService cldsTemplateService; - CldsService cldsService; - DcaeInventoryServices dcaeInventoryService; - private XslTransformer cldsBpmnTransformer; - - @Autowired - public CsarInstallerImpl(ApplicationContext appContext, - CldsDao cldsDao, CldsTemplateService cldsTemplateService, CldsService cldsService, - DcaeInventoryServices dcaeInventoryService, XslTransformer cldsBpmnTransformer) { - this.appContext = appContext; - this.cldsDao = cldsDao; - this.cldsTemplateService = cldsTemplateService; - this.cldsService = cldsService; - this.dcaeInventoryService = dcaeInventoryService; - this.cldsBpmnTransformer = cldsBpmnTransformer; - } - - @Autowired - private BlueprintParser blueprintParser; - - @Autowired - private ChainGenerator chainGenerator; - - @Autowired - private SvgFacade svgFacade; - - @PostConstruct - public void loadConfiguration() throws IOException { - BlueprintParserMappingConfiguration - .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream() - .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles())); - } - - @Override - public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException { - boolean alreadyInstalled = true; - for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { - alreadyInstalled = alreadyInstalled - && CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getValue()), true).getId() != null; - } - return alreadyInstalled; - } - - public static String buildModelName(CsarHandler csar, BlueprintArtifact artifact) - throws SdcArtifactInstallerException { - String policyScopePrefix = searchForPolicyScopePrefix(artifact); - if (policyScopePrefix.contains("*")) { - // This is policy_filter type - policyScopePrefix = policyScopePrefix.replaceAll("\\*", ""); - } else { - // This is normally the get_input case - policyScopePrefix = MODEL_NAME_PREFIX; - } - return (policyScopePrefix + "_" + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v" - + csar.getSdcNotification().getServiceVersion() + "_" - + artifact.getResourceAttached().getResourceInstanceName().replaceAll(" ", "") + "_" - + artifact.getBlueprintArtifactName().replace(".yaml", "")).replace('.', '_'); - } - - @Override - @Transactional - public void installTheCsar(CsarHandler csar) - throws SdcArtifactInstallerException, InterruptedException, PolicyModelException { - try { - logger.info("Installing the CSAR " + csar.getFilePath()); - for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { - logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName()); - createFakeCldsModel(csar, blueprint.getValue(), - createFakeCldsTemplate(csar, blueprint.getValue(), - this.searchForRightMapping(blueprint.getValue())), - queryDcaeToGetServiceTypeId(blueprint.getValue())); - } - createPolicyModel(csar); - logger.info("Successfully installed the CSAR " + csar.getFilePath()); - } catch (IOException e) { - throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e); - } catch (ParseException e) { - throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e); - } - } - - BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact) - throws SdcArtifactInstallerException { - List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>(); - Yaml yaml = new Yaml(); - Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml - .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates")); - bpmnMapping.entrySet().forEach(e -> { - if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) { - listConfig.add(e.getValue()); - } - }); - if (listConfig.size() > 1) { - throw new SdcArtifactInstallerException( - "The code does not currently support multiple MicroServices in the blueprint"); - } else if (listConfig.isEmpty()) { - throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint"); - } - logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is " - + listConfig.get(0).getBpmnXmlFilePath()); - return listConfig.get(0); - } - - String getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) { - JsonObject node = new JsonObject(); - Yaml yaml = new Yaml(); - Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml - .load(blueprintArtifact.getDcaeBlueprint())).get("inputs")); - inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> { - Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default"); - if (defaultValue != null) { - addPropertyToNode(node, elem.getKey(), defaultValue); - } else { - node.addProperty(elem.getKey(), ""); - } - }); - node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT"); - return node.toString(); - } - - private void createPolicyModel(CsarHandler csar) throws PolicyModelException { - try { - Optional<String> policyModelYaml = csar.getPolicyModelYaml(); - // save policy model into the database - } catch (IOException e) { - throw new PolicyModelException("TransformerException when decoding the YamlText", e); - } - } - - private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact) - throws SdcArtifactInstallerException { - String policyName = null; - Yaml yaml = new Yaml(); - List<String> policyNameList = new ArrayList<>(); - Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml - .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates")); - templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> { - String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue()) - .get("properties")).get("policy_filter"); - if (policyName != null) { - policyNameList.add(filteredPolicyName); - } else { - String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) - ef.getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM); - if (inputPolicyName != null) { - policyNameList.add(GET_INPUT_BLUEPRINT_PARAM); - } - } - }); - if (policyNameList.size() > 1) { - throw new SdcArtifactInstallerException( - "The code does not currently support multiple Policy MicroServices in the blueprint"); - } else if (policyNameList.isEmpty()) { - throw new SdcArtifactInstallerException( - "There is no recognized Policy MicroService found in the blueprint"); - } - logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is " - + policyNameList.get(0)); - return policyNameList.get(0); - } - - /** - * This call must be done when deploying the SDC notification as this call get - * the latest version of the artifact (version can be specified to DCAE call). - * - * @return The DcaeInventoryResponse object containing the dcae values - */ - private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact) - throws IOException, ParseException, InterruptedException { - return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(), - blueprintArtifact.getBlueprintInvariantServiceUuid(), - blueprintArtifact.getResourceAttached().getResourceInvariantUUID()); - } - - private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact, - BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException { - - Set<MicroService> microServicesFromBlueprint = blueprintParser.getMicroServices( - blueprintArtifact.getDcaeBlueprint()) ; - List<MicroService> microServicesChain = chainGenerator.getChainOfMicroServices(microServicesFromBlueprint); - if (microServicesChain.isEmpty()) { - microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint()); - } - String imageText = svgFacade.getSvgImage(microServicesChain); - - CldsTemplate template = new CldsTemplate(); - template.setBpmnId("Sdc-Generated"); - template.setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream(), - StandardCharsets.UTF_8)); - template.setPropText( - "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}"); - template - .setImageText(imageText); - template.setName(TEMPLATE_NAME_PREFIX + buildModelName(csar, blueprintArtifact)); - template.save(cldsDao, null); - logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName() - + " with name " + template.getName()); - return template; - } - - private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact, - CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse) throws SdcArtifactInstallerException { - - if (dcaeInventoryResponse == null) { - throw new SdcArtifactInstallerException( - "DCAE inventory response is NULL, query to DCAE fail to be answered properly, " - + "this is required to deploy CSAR properly !!!"); - } - try { - CldsModel cldsModel = new CldsModel(); - cldsModel.setName(buildModelName(csar, blueprintArtifact)); - cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint()); - cldsModel.setTemplateName(cldsTemplate.getName()); - cldsModel.setTemplateId(cldsTemplate.getId()); - cldsModel.setBpmnText(cldsTemplate.getBpmnText()); - cldsModel.setTypeId(dcaeInventoryResponse.getTypeId()); - cldsModel.setTypeName(dcaeInventoryResponse.getTypeName()); - cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX); - // We must save it otherwise object won't be created in db - // and proptext will always be null - cldsModel.setPropText("{\"global\":[]}"); - // Must save first to have the generated id available to generate - // the policyId - cldsModel = cldsModel.save(cldsDao, null); - cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate); - logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName() - + " with name " + cldsModel.getName()); - return cldsModel; - } catch (TransformerException e) { - throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e); - } - } - - private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact, - CldsTemplate cldsTemplate) throws TransformerException { - // Do a test to validate the BPMN - new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false, - cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}"); - String inputParams = "{\"name\":\"deployParameters\",\"value\":" - + getAllBlueprintParametersInJson(blueprintArtifact) + "}"; - cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\"" - + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\"" - + blueprintArtifact.getResourceAttached().getResourceInvariantUUID() - + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]}," - + inputParams + "]}"); - return cldsModel.save(cldsDao, null); - } - - private void addPropertyToNode(JsonObject node, String key, Object value) { - if (value instanceof String) { - node.addProperty(key, (String) value); - } else if (value instanceof Number) { - node.addProperty(key, (Number) value); - } else if (value instanceof Boolean) { - node.addProperty(key, (Boolean) value); - } else if (value instanceof Character) { - node.addProperty(key, (Character) value); - } else { - node.addProperty(key, JsonUtils.GSON.toJson(value)); - } - } -} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java b/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java deleted file mode 100644 index 454056cd3..000000000 --- a/src/main/java/org/onap/clamp/clds/service/CldsDictionaryService.java +++ /dev/null @@ -1,179 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.service; - -import java.util.Date; -import java.util.List; - -import javax.annotation.PostConstruct; - -import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.model.CldsDictionary; -import org.onap.clamp.clds.model.CldsDictionaryItem; -import org.onap.clamp.clds.util.LoggingUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; - -/** - * REST services to manage dictionary and dictionary items for Tosca Model. - */ -@Component -public class CldsDictionaryService extends SecureServiceBase { - - @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") - private String cldsPermissionTypeTosca; - @Value("${clamp.config.security.permission.instance:dev}") - private String cldsPermissionInstance; - private SecureServicePermission permissionReadTosca; - private SecureServicePermission permissionUpdateTosca; - - @Autowired - private CldsDao cldsDao; - - private LoggingUtils util = new LoggingUtils(logger); - - - @PostConstruct - private void initConstruct() { - permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); - permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, - "update"); - } - - /** - * REST Service that creates a Dictionary. - * - * @param dictionaryName dictionary name - * @return CldsDictionary that was created in DB. - */ - public CldsDictionary createDictionary(String dictionaryName) { - CldsDictionary cldsDictionary = new CldsDictionary(); - cldsDictionary.setDictionaryName(dictionaryName); - cldsDictionary.save(cldsDictionary.getDictionaryName(), cldsDao, getUserId()); - return cldsDictionary; - } - - /** - * REST Service that creates or Updates a Dictionary. - * Used in clds-services.xml - * - * @param cldsDictionary clds dictionary - * @return ResponseEntity with CldsDictionary that was created in DB. - */ - public ResponseEntity<CldsDictionary> createOrUpdateDictionary(String dictionaryName, - CldsDictionary cldsDictionary) { - - Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionary", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionUpdateTosca); - - if (cldsDictionary == null) { - - cldsDictionary = createDictionary(dictionaryName); - } else { - - if (cldsDictionary.getDictionaryName() == null) { - cldsDictionary.setDictionaryName(dictionaryName); - } - - cldsDictionary.save(cldsDictionary.getDictionaryName(), cldsDao, getUserId()); - } - - LoggingUtils.setTimeContext(startTime, new Date()); - LoggingUtils.setResponseContext("0", "createOrUpdateDictionary success", this.getClass().getName()); - auditLogger.info("createOrUpdateDictionary completed"); - - return new ResponseEntity<>(cldsDictionary, HttpStatus.OK); - } - - /** - * REST Service that creates or Updates a Dictionary Elements for dictionary - * in DB. - * - * @param dictionaryName dictionary name - * @param dictionaryItem dictionary item - * @return CldsDictionaryItem A dictionary items that was created or updated - * in DB - */ - public ResponseEntity<CldsDictionaryItem> createOrUpdateDictionaryElements(String dictionaryName, - CldsDictionaryItem dictionaryItem) { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsDictionaryService: createOrUpdateDictionaryElements", - getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionUpdateTosca); - dictionaryItem.save(dictionaryName, cldsDao, getUserId()); - auditLogInfo("createOrUpdateDictionaryElements", startTime); - return new ResponseEntity<>(dictionaryItem, HttpStatus.OK); - } - - /** - * Rest Service that retrieves all CLDS dictionary in DB. - * - * @return CldsDictionary List List of CldsDictionary available in DB - */ - public ResponseEntity<List<CldsDictionary>> getAllDictionaryNames() { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsDictionaryService: getAllDictionaryNames", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionReadTosca); - List<CldsDictionary> dictionaries = cldsDao.getDictionary(null, null); - auditLogInfo("getAllDictionaryNames", startTime); - return new ResponseEntity<>(dictionaries, HttpStatus.OK); - } - - /** - * Rest Service that retrieves all CLDS dictionary items in DB for a give - * dictionary name. - * - * @param dictionaryName dictionary name - * @return CldsDictionaryItem list List of CLDS Dictionary items for a given - * dictionary name - */ - public ResponseEntity<List<CldsDictionaryItem>> getDictionaryElementsByName(String dictionaryName) { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsDictionaryService: getDictionaryElementsByName", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionReadTosca); - List<CldsDictionaryItem> dictionaryItems = cldsDao.getDictionaryElements(dictionaryName, null, null); - auditLogInfo("getDictionaryElementsByName", startTime); - return new ResponseEntity<>(dictionaryItems, HttpStatus.OK); - } - - public ResponseEntity<?> deleteDictionary() { - return null; - } - - // Created for the integration test - public void setLoggingUtil(LoggingUtils utilP) { - util = utilP; - } - -}
\ No newline at end of file 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 d9956e3ad..3a2cb0926 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -28,48 +28,24 @@ package org.onap.clamp.clds.service; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; -import java.io.IOException; + import java.lang.reflect.Type; import java.util.Date; import java.util.List; -import java.util.UUID; + import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.BadRequestException; -import javax.xml.transform.TransformerException; + import org.apache.camel.Produce; -import org.json.simple.parser.ParseException; import org.onap.clamp.clds.camel.CamelProxy; -import org.onap.clamp.clds.client.DcaeDispatcherServices; -import org.onap.clamp.clds.client.DcaeInventoryServices; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.exception.policy.PolicyClientException; -import org.onap.clamp.clds.exception.sdc.SdcCommunicationException; -import org.onap.clamp.clds.model.CldsEvent; import org.onap.clamp.clds.model.CldsInfo; -import org.onap.clamp.clds.model.CldsModel; -import org.onap.clamp.clds.model.CldsModelProp; -import org.onap.clamp.clds.model.CldsMonitoringDetails; -import org.onap.clamp.clds.model.CldsTemplate; -import org.onap.clamp.clds.model.DcaeEvent; -import org.onap.clamp.clds.model.ValueItem; -import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.model.sdc.SdcServiceInfo; -import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; -import org.onap.clamp.clds.transform.XslTransformer; -import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.LoggingUtils; import org.onap.clamp.clds.util.ONAPLogConstants; import org.slf4j.event.Level; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpClientErrorException; /** * Service to save and retrieve the CLDS model attributes. @@ -81,7 +57,7 @@ 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(); + }.getType(); @Produce(uri = "direct:processSubmit") private CamelProxy camelProxy; /** @@ -93,12 +69,6 @@ public class CldsService extends SecureServiceBase { */ 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; /** @@ -126,11 +96,6 @@ public class CldsService extends SecureServiceBase { */ final SecureServicePermission permissionUpdateTosca; - private final CldsDao cldsDao; - private final XslTransformer cldsBpmnTransformer; - private final ClampProperties refProp; - private final DcaeDispatcherServices dcaeDispatcherServices; - private final DcaeInventoryServices dcaeInventoryServices; private LoggingUtils util = new LoggingUtils(logger); @Autowired @@ -139,11 +104,6 @@ public class CldsService extends SecureServiceBase { /** * 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 @@ -153,72 +113,32 @@ public class CldsService extends SecureServiceBase { * @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) { - this.cldsDao = cldsDao; - this.cldsBpmnTransformer = cldsBpmnTransformer; - this.refProp = refProp; - this.dcaeDispatcherServices = dcaeDispatcherServices; - this.dcaeInventoryServices = dcaeInventoryServices; - this.cldsPermissionTypeClManage = cldsPermissionTypeClManage; - this.cldsPermissionTypeClEvent = cldsPermissionTypeClEvent; + public CldsService( + @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.cldsPermissionTypeFilterVf = cldsPermissionTypeFilterVf; this.cldsPermissionInstance = cldsPermissionInstance; permissionReadCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "read"); permissionUpdateCl = SecureServicePermission.create(cldsPersmissionTypeCl, cldsPermissionInstance, "update"); permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "read"); + "read"); permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance, - "update"); + "update"); permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, - "update"); - } - - /** - * 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 - * (DCAEServiceTypeRequest generated in DCAE application). DEPLOYMENT_ID | Id - * 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"); - - final Date startTime = new Date(); - List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); - - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET cldsDetails completed"); - util.exiting("200", "Get cldsDetails success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return cldsMonitoringDetailsList; + "update"); } /** - * 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 + * 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() { @@ -237,294 +157,6 @@ public class CldsService extends SecureServiceBase { } /** - * REST service that retrieves BPMN for a CLDS model name from the database. - * This is subset of the json getModel. This is only expected to be used for - * testing purposes, not by the UI. - * - * @param modelName the model name - * @return bpmn xml text - content of bpmn given name - */ - public String getBpmnXml(String modelName) { - util.entering(request, "CldsService: GET model bpmn"); - final Date startTime = new Date(); - isAuthorized(permissionReadCl); - logger.info("GET bpmnText for modelName={}", modelName); - final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET model bpmn completed"); - util.exiting("200", "Get model bpmn success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return model.getBpmnText(); - } - - /** - * REST service that retrieves image for a CLDS model name from the database. - * This is subset of the json getModel. This is only expected to be used for - * testing purposes, not by the UI. - * - * @param modelName the model name - * @return image xml text - content of image given name - */ - public String getImageXml(String modelName) { - util.entering(request, "CldsService: GET model image"); - final Date startTime = new Date(); - isAuthorized(permissionReadCl); - logger.info("GET imageText for modelName={}", modelName); - final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET model image completed"); - util.exiting("200", "Get model image success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return model.getImageText(); - } - - /** - * REST service that retrieves a CLDS model by name from the database. - * - * @param modelName the model name - * @return clds model - clds model for the given model name - */ - public CldsModel getModel(String modelName) { - util.entering(request, "CldsService: GET model"); - final Date startTime = new Date(); - isAuthorized(permissionReadCl); - logger.debug("GET model for modelName={}", modelName); - CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false); - isAuthorizedForVf(cldsModel); - // Try an update for DCAE status - // Checking condition whether our CLDS model can call Inventory Method - try { - // Method to call dcae inventory and invoke insert event method - if (cldsModel.canDcaeInventoryCall() - && !cldsModel.getTemplateName().startsWith(CsarInstaller.TEMPLATE_NAME_PREFIX)) { - dcaeInventoryServices.setEventInventory(cldsModel, getUserId()); - } - // This is a blocking call - if (cldsModel.getEvent().isActionCd(CldsEvent.ACTION_DEPLOY) - && !CldsModel.STATUS_ACTIVE.equals(cldsModel.getStatus()) && cldsModel.getDeploymentId() != null - && cldsModel.getDeploymentStatusUrl() != null) { - checkDcaeDeploymentStatus(cldsModel, CldsEvent.ACTION_DEPLOY, false); - // Refresh the model object in any cases for new event - cldsModel = CldsModel.retrieve(cldsDao, cldsModel.getName(), false); - } - } catch (Exception e) { - LoggingUtils.setErrorContext("900", "Set event inventory error"); - logger.error("getModel set event Inventory error:" + e); - } - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET model completed"); - util.exiting("200", "Get model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return cldsModel; - } - - /** - * REST service that saves a CLDS model by name in the database. - * - * @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"); - final Date startTime = new Date(); - isAuthorized(permissionUpdateCl); - isAuthorizedForVf(cldsModel); - logger.info("PUT model for modelName={}", modelName); - logger.info("PUT bpmnText={}", cldsModel.getBpmnText()); - logger.info("PUT propText={}", cldsModel.getPropText()); - logger.info("PUT imageText={}", cldsModel.getImageText()); - fillInCldsModel(cldsModel); - cldsModel.save(cldsDao, getUserId()); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("PUT model completed"); - util.exiting("200", "Put model success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return cldsModel; - } - - /** - * REST service that retrieves a list of CLDS model names. - * - * @return model names in JSON - */ - public List<ValueItem> getModelNames() { - util.entering(request, "CldsService: GET model names"); - final Date startTime = new Date(); - isAuthorized(permissionReadCl); - logger.info("GET list of model names"); - final List<ValueItem> names = cldsDao.getModelNames(); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("GET model names completed"); - util.exiting("200", "Get model names success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return names; - } - - private void fillInCldsModel(CldsModel model) { - if (model.getTemplateName() != null) { - CldsTemplate template = cldsDao.getTemplate(model.getTemplateName()); - if (template != null) { - model.setTemplateId(template.getId()); - model.setDocText(template.getPropText()); - // This is to provide the Bpmn XML when Template part in UI - // is - // disabled - model.setBpmnText(template.getBpmnText()); - } - } - } - - /** - * REST service that saves and processes an action for a CLDS model by name. - * - * @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 { - util.entering(request, "CldsService: Process model action"); - final Date startTime = new Date(); - String errorMessage = ""; - String actionCd = ""; - try { - actionCd = action.toUpperCase(); - SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, - cldsPermissionInstance, actionCd); - isAuthorized(permisionManage); - isAuthorizedForVf(model); - String userId = getUserId(); - logger.info("PUT actionCd={}", actionCd); - logger.info("PUT modelName={}", modelName); - logger.info("PUT test={}", test); - logger.info("PUT bpmnText={}", model.getBpmnText()); - logger.info("PUT propText={}", model.getPropText()); - logger.info("PUT userId={}", userId); - logger.info("PUT getTypeId={}", model.getTypeId()); - logger.info("PUT deploymentId={}", model.getDeploymentId()); - this.fillInCldsModel(model); - // save model to db just in case - model.save(cldsDao, getUserId()); - - // get vars and format if necessary - final String prop = model.getPropText(); - final String bpmn = model.getBpmnText(); - final String docText = model.getDocText(); - final String controlName = model.getControlName(); - final String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); - logger.info("PUT bpmnJson={}", bpmnJson); - // Test flag coming from UI or from Clamp config - boolean isTest = Boolean.parseBoolean(test) - || Boolean.parseBoolean(refProp.getStringValue("action.test.override")); - logger.info("PUT isTest={}", isTest); - boolean isInsertTestEvent = Boolean.parseBoolean(refProp.getStringValue("action.insert.test.event")); - logger.info("PUT isInsertTestEvent={}", isInsertTestEvent); - // determine if requested action is permitted - model.validateAction(actionCd); - logger.info("modelProp - " + prop); - logger.info("docText - " + docText); - try { - String result = camelProxy.executeAction(actionCd, prop, bpmnJson, modelName, controlName, docText, - isTest, userId, isInsertTestEvent, model.getEvent().getActionCd()); - logger.info("Starting Camel flow on request, result is: ", result); - } catch (SdcCommunicationException | PolicyClientException | BadRequestException e) { - logger.error("Exception occured during invoking Camel process", e); - errorMessage = e.getMessage(); - } - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Process model action completed"); - } catch (Exception e) { - logger.error("Exception occured during putModelAndProcessAction", e); - errorMessage = e.getMessage(); - } - - if (null == errorMessage || (null != errorMessage && !errorMessage.isEmpty())) { - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), actionCd, CldsEvent.ACTION_STATE_ERROR, - null); - // Need a refresh as new events have been inserted - model = CldsModel.retrieve(cldsDao, modelName, false); - if (null == errorMessage) { - errorMessage = "No response from Policy"; - } - model.setErrorMessageForUi(errorMessage); - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "putModelAndProcessAction failed", Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); - } else { - // Need a refresh as new events have been inserted, could have been deleted so - // not blocking call - model = CldsModel.retrieve(cldsDao, modelName, true); - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return new ResponseEntity<>(model, HttpStatus.OK); - } - } - - /** - * REST service that accepts events for a model. - * - * @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"); - final Date startTime = new Date(); - String userid = null; - // TODO: allow auth checking to be turned off by removing the permission - // type property - if (cldsPermissionTypeClEvent != null && cldsPermissionTypeClEvent.length() > 0) { - SecureServicePermission permissionEvent = SecureServicePermission.create(cldsPermissionTypeClEvent, - cldsPermissionInstance, dcaeEvent.getEvent()); - isAuthorized(permissionEvent); - userid = getUserId(); - } - // Flag indicates whether it is triggered by Validation Test button from - // UI - boolean isTest = Boolean.parseBoolean(test); - int instanceCount = 0; - if (dcaeEvent.getInstances() != null) { - instanceCount = dcaeEvent.getInstances().size(); - } - String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID() - + " resourceUUID=" + dcaeEvent.getResourceUUID() - + " artifactName=" + dcaeEvent.getArtifactName() - + " instance count=" + instanceCount + " isTest=" + isTest; - logger.info("POST dcae event {}", msgInfo); - if (isTest) { - logger.warn("Ignorning test event from DCAE"); - } else { - if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) { - CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid); - } else { - CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(), - CldsEvent.ACTION_STATE_RECEIVED, null); - } - } - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Post dcae event completed"); - util.exiting("200", "Post dcae event success", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return msgInfo; - } - - /** - * REST service that retrieves total properties required by UI. - * - * @return the sdc properties - * @throws IOException In case of issues - */ - public String getSdcProperties() throws IOException { - return refProp.getJsonTemplate(GLOBAL_PROPERTIES_KEY).toString(); - } - - - /** * Determine if the user is authorized for a particular VF by its invariant * UUID. * @@ -534,7 +166,7 @@ public class CldsService extends SecureServiceBase { public boolean isAuthorizedForVf(String vfInvariantUuid) { if (cldsPermissionTypeFilterVf != null && !cldsPermissionTypeFilterVf.isEmpty()) { SecureServicePermission permission = SecureServicePermission.create(cldsPermissionTypeFilterVf, - cldsPermissionInstance, vfInvariantUuid); + cldsPermissionInstance, vfInvariantUuid); return isAuthorized(permission); } else { // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then @@ -545,169 +177,6 @@ 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 The clds model - * @return boolean or throws NotAuthorizedException - */ - private boolean isAuthorizedForVf(CldsModel model) { - String vf = ModelProperties.getVf(model); - if (vf == null || vf.length() == 0) { - logger.info("VF not found in model"); - return true; - } else { - return isAuthorizedForVf(vf); - } - } - - /** - * 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"); - final Date startTime = new Date(); - String errorMessage = ""; - try { - fillInCldsModel(model); - String bpmnJson = cldsBpmnTransformer.doXslTransformToString(model.getBpmnText()); - logger.info("PUT bpmnJson={}", bpmnJson); - SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, - cldsPermissionInstance, CldsEvent.ACTION_DEPLOY); - isAuthorized(permisionManage); - isAuthorizedForVf(model); - ModelProperties modelProp = new ModelProperties(modelName, model.getControlName(), CldsEvent.ACTION_DEPLOY, - false, bpmnJson, model.getPropText()); - checkForDuplicateServiceVf(modelName, model.getPropText()); - String deploymentId = ""; - // If model is already deployed then pass same deployment id - if (model.getDeploymentId() != null && !model.getDeploymentId().isEmpty()) { - deploymentId = model.getDeploymentId(); - } else { - model.setDeploymentId(deploymentId = "closedLoop_" + UUID.randomUUID() + "_deploymentId"); - } - model.setDeploymentStatusUrl(dcaeDispatcherServices.createNewDeployment(deploymentId, model.getTypeId(), - modelProp.getGlobal().getDeployParameters())); - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_DEPLOY, - CldsEvent.ACTION_STATE_INITIATED, null); - model.save(cldsDao, getUserId()); - // This is a blocking call - checkDcaeDeploymentStatus(model, CldsEvent.ACTION_DEPLOY, true); - // Refresh the model object in any cases for new event - model = CldsModel.retrieve(cldsDao, model.getName(), false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Deploy model completed"); - } catch (Exception e) { - errorMessage = e.getMessage(); - logger.error("Exception occured during deployModel", e); - } - if (!errorMessage.isEmpty()) { - model.setErrorMessageForUi(errorMessage); - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DeployModel failed", Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); - } else { - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return new ResponseEntity<>(model, HttpStatus.OK); - } - } - - /** - * 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"); - final Date startTime = new Date(); - String errorMessage = ""; - try { - SecureServicePermission permisionManage = SecureServicePermission.create(cldsPermissionTypeClManage, - cldsPermissionInstance, CldsEvent.ACTION_UNDEPLOY); - isAuthorized(permisionManage); - isAuthorizedForVf(model); - model.setDeploymentStatusUrl( - dcaeDispatcherServices.deleteExistingDeployment(model.getDeploymentId(), model.getTypeId())); - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), CldsEvent.ACTION_UNDEPLOY, - CldsEvent.ACTION_STATE_INITIATED, null); - // clean the deployment ID - model.setDeploymentId(null); - model.save(cldsDao, getUserId()); - // This is a blocking call - checkDcaeDeploymentStatus(model, CldsEvent.ACTION_UNDEPLOY, true); - // Refresh the model object in any cases for new event - model = CldsModel.retrieve(cldsDao, model.getName(), false); - // audit log - LoggingUtils.setTimeContext(startTime, new Date()); - auditLogger.info("Undeploy model completed"); - } catch (Exception e) { - errorMessage = e.getMessage(); - logger.error("Exception occured during unDeployModel", e); - } - if (!errorMessage.isEmpty()) { - model.setErrorMessageForUi(errorMessage); - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "UndeployModel failed", Level.INFO, - ONAPLogConstants.ResponseStatus.ERROR); - return new ResponseEntity<>(model, HttpStatus.INTERNAL_SERVER_ERROR); - } else { - util.exiting(HttpStatus.OK.toString(), "Successful", Level.INFO, ONAPLogConstants.ResponseStatus.COMPLETED); - return new ResponseEntity<>(model, HttpStatus.OK); - } - } - - private void checkDcaeDeploymentStatus(CldsModel model, String cldsEvent, boolean withRetry) - throws InterruptedException { - String operationStatus = withRetry - ? dcaeDispatcherServices.getOperationStatusWithRetry(model.getDeploymentStatusUrl()) - : dcaeDispatcherServices.getOperationStatus(model.getDeploymentStatusUrl()); - if ("succeeded".equalsIgnoreCase(operationStatus)) { - logger.info(cldsEvent + " model (" + model.getName() + ") succeeded...Deployment Id is - " - + model.getDeploymentId()); - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent, - CldsEvent.ACTION_STATE_COMPLETED, null); - } else { - String info = "DCAE " + cldsEvent + " (" + model.getName() + ") failed...Operation Status is - " - + operationStatus; - logger.info(info); - CldsEvent.insEvent(cldsDao, model.getControlName(), getUserId(), cldsEvent, CldsEvent.ACTION_STATE_ERROR, - null); - util.exiting(HttpStatus.INTERNAL_SERVER_ERROR.toString(), "DCAE operation(" + cldsEvent + ") failed", - Level.INFO, ONAPLogConstants.ResponseStatus.ERROR); - throw new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, info); - } - } - - private void checkForDuplicateServiceVf(String modelName, String modelPropText) throws IOException { - JsonElement globalNode = JsonUtils.GSON.fromJson(modelPropText, JsonObject.class).get("global"); - String service = JsonUtils.getStringValueByName(globalNode, "service"); - List<String> resourceVf = JsonUtils.getStringValuesByName(globalNode, "vf"); - if (service != null && resourceVf != null && !resourceVf.isEmpty()) { - List<CldsModelProp> cldsModelPropList = cldsDao.getDeployedModelProperties(); - for (CldsModelProp cldsModelProp : cldsModelPropList) { - JsonElement currentNode = JsonUtils.GSON - .fromJson(cldsModelProp.getPropText(), JsonObject.class) - .get("global"); - String currentService = JsonUtils.getStringValueByName(currentNode, "service"); - List<String> currentVf = JsonUtils.getStringValuesByName(currentNode, "vf"); - if (currentVf != null && !currentVf.isEmpty()) { - if (!modelName.equalsIgnoreCase(cldsModelProp.getName()) && service.equalsIgnoreCase(currentService) - && resourceVf.get(0).equalsIgnoreCase(currentVf.get(0))) { - throw new BadRequestException("Same Service/VF already exists in " + cldsModelProp.getName() - + " model, please select different Service/VF."); - } - } - } - } - } - - /** * Sets logging util. * * @param utilP the util p diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java deleted file mode 100644 index 183db8bdb..000000000 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.service; - -import java.util.Date; -import java.util.List; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; - -import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.model.CldsTemplate; -import org.onap.clamp.clds.model.ValueItem; -import org.onap.clamp.clds.util.LoggingUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - -/** - * Service to save and retrieve the CLDS model attributes. - */ -@Component -public class CldsTemplateService extends SecureServiceBase { - - @Value("${clamp.config.security.permission.type.template:permission-type-template}") - private String cldsPermissionTypeTemplate; - @Value("${clamp.config.security.permission.instance:dev}") - private String cldsPermissionInstance; - private SecureServicePermission permissionReadTemplate; - private SecureServicePermission permissionUpdateTemplate; - @Autowired - private HttpServletRequest request; - - @PostConstruct - private final void afterConstruction() { - permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, - cldsPermissionInstance, "read"); - permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, - cldsPermissionInstance, "update"); - } - - @Autowired - private CldsDao cldsDao; - private LoggingUtils util = new LoggingUtils(logger); - - /** - * REST service that retrieves BPMN for a CLDS template name from the - * database. This is subset of the json getModel. This is only expected to - * be used for testing purposes, not by the UI. - * - * @param templateName template name - * @return bpmn xml text - content of bpmn given name - */ - public String getBpmnTemplate(String templateName) { - util.entering(request, "CldsTemplateService: GET template bpmn"); - final Date startTime = new Date(); - isAuthorized(permissionReadTemplate); - logger.info("GET bpmnText for templateName=" + templateName); - - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); - auditLogInfo(util, "GET template bpmn", startTime); - return template.getBpmnText(); - } - - /** - * REST service that retrieves image for a CLDS template name from the - * database. This is subset of the json getModel. This is only expected to - * be used for testing purposes, not by the UI. - * - * @param templateName template name - * @return image xml text - content of image given name - */ - public String getImageXml(String templateName) { - util.entering(request, "CldsTemplateService: GET template image"); - final Date startTime = new Date(); - isAuthorized(permissionReadTemplate); - logger.info("GET imageText for templateName=" + templateName); - - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); - auditLogInfo(util, "GET template image", startTime); - return template.getImageText(); - } - - /** - * REST service that retrieves a CLDS template by name from the database. - * - * @param templateName template name - * @return clds template - clds template for the given template name - */ - public CldsTemplate getTemplate(String templateName) { - util.entering(request, "CldsTemplateService: GET template"); - final Date startTime = new Date(); - isAuthorized(permissionReadTemplate); - logger.info("GET model for templateName=" + templateName); - - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); - template.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateTemplate)); - auditLogInfo(util, "GET template", startTime); - return template; - } - - /** - * REST service that saves a CLDS template by name in the database. - * - * @param templateName template name - * @param cldsTemplate clds template - * @return The CldsTemplate modified and saved in DB - */ - public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { - util.entering(request, "CldsTemplateService: PUT template"); - final Date startTime = new Date(); - isAuthorized(permissionUpdateTemplate); - logger.info("PUT Template for templateName=" + templateName); - logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText()); - logger.info("PUT propText=" + cldsTemplate.getPropText()); - logger.info("PUT imageText=" + cldsTemplate.getImageText()); - cldsTemplate.setName(templateName); - cldsTemplate.save(cldsDao, null); - auditLogInfo(util, "PUT template", startTime); - return cldsTemplate; - } - - /** - * REST service that retrieves a list of CLDS template names. - * - * @return template names in JSON - */ - public List<ValueItem> getTemplateNames() { - util.entering(request, "CldsTemplateService: GET template names"); - final Date startTime = new Date(); - isAuthorized(permissionReadTemplate); - logger.info("GET list of template names"); - - List<ValueItem> names = cldsDao.getTemplateNames(); - auditLogInfo(util, "GET template names", startTime); - return names; - } - - // Created for the integration test - public void setLoggingUtil(LoggingUtils utilP) { - util = utilP; - } -} diff --git a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java deleted file mode 100644 index 0d53e9155..000000000 --- a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.clds.service; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Optional; - -import javax.annotation.PostConstruct; - -import org.onap.clamp.clds.client.req.policy.PolicyClient; -import org.onap.clamp.clds.config.ClampProperties; -import org.onap.clamp.clds.dao.CldsDao; -import org.onap.clamp.clds.model.CldsToscaModel; -import org.onap.clamp.clds.util.LoggingUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Component; - -/** - * REST services to manage Tosca Model. - */ -@Component -public class CldsToscaService extends SecureServiceBase { - - @Value("${clamp.config.security.permission.type.tosca:permission-type-tosca}") - private String cldsPermissionTypeTosca; - @Value("${clamp.config.security.permission.instance:dev}") - private String cldsPermissionInstance; - private SecureServicePermission permissionReadTosca; - private SecureServicePermission permissionUpdateTosca; - - @Autowired - private CldsDao cldsDao; - - @Autowired - private ClampProperties refProp; - - @Autowired - private PolicyClient policyClient; - private LoggingUtils util = new LoggingUtils(logger); - - @PostConstruct - private final void initConstruct() { - permissionReadTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, "read"); - permissionUpdateTosca = SecureServicePermission.create(cldsPermissionTypeTosca, cldsPermissionInstance, - "update"); - } - - /** - * REST service to upload a new Tosca Model or update an existing Tosca - * model with new version. This API will parse the Tosca model yaml and - * generates a JSON schema out of it. - * - * @param toscaModelName - * Tosca model name to be used as a key - * @param cldsToscaModel - * Object containing the tosca model yaml - * - * @return clds tosca models - list of CLDS tosca models for a given policy - * type - */ - public ResponseEntity<?> parseToscaModelAndSave(String toscaModelName, CldsToscaModel cldsToscaModel) { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsToscaService: Parse Tosca model and save", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionUpdateTosca); - cldsToscaModel.setToscaModelName(toscaModelName); - cldsToscaModel = cldsToscaModel.save(cldsDao, refProp, policyClient, getUserId()); - auditLogInfo("Parse Tosca model and save", startTime); - return new ResponseEntity<>(cldsToscaModel, HttpStatus.CREATED); - } - - /** - * REST service to retrieve all Tosca models from the CLDS database. - * - * @return clds tosca models - list of CLDS tosca models - */ - public List<CldsToscaModel> getAllToscaModels() { - // TODO revisit based on new permissions - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); - isAuthorized(permissionReadTosca); - - Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()); - auditLogInfo("Get All tosca models", startTime); - return cldsToscaModels.orElse(Collections.emptyList()); - } - - /** - * REST service that retrieves a CLDS Tosca model by model name from the - * database. - * - * @param toscaModelName - * Path param with tosca model name - * - * @return clds tosca model - CLDS tosca model for a given tosca model name - */ - public CldsToscaModel getToscaModel(String toscaModelName) { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionReadTosca); - - Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable( - cldsDao.getToscaModelByName(toscaModelName)); - auditLogInfo("Get tosca models by model name", startTime); - return cldsToscaModels.map(models -> models.get(0)).orElse(null); - } - - /** - * REST service that retrieves a CLDS Tosca model lists for a policy type - * from the database. - * @param policyType - * The type of the policy - * @return clds tosca model - CLDS tosca model for a given policy type - */ - public CldsToscaModel getToscaModelsByPolicyType(String policyType) { - final Date startTime = new Date(); - LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName()); - // TODO revisit based on new permissions - isAuthorized(permissionReadTosca); - - Optional<List<CldsToscaModel>> cldsToscaModels = Optional.ofNullable( - cldsDao.getToscaModelByPolicyType(policyType)); - auditLogInfo("Get tosca models by policyType", startTime); - return cldsToscaModels.map(models -> models.get(0)).orElse(null); - } - - public ResponseEntity<?> deleteToscaModelById(String toscaModeId) { - // TODO - return null; - } - - // Created for the integration test - public void setLoggingUtil(LoggingUtils utilP) { - util = utilP; - } - -} |