From 627badaf69987c01811c477219fd943757a635f5 Mon Sep 17 00:00:00 2001 From: "Christopher Lott (Christopher) (cl778h)" Date: Mon, 12 Jun 2017 09:49:00 -0400 Subject: [PORTAL-16 PORTAL-18] Widget ms; staging Remove staging repositories from poms. Add widget microservice code base. Add portal unit tests. Repair defects. Normalize line endings. Change-Id: Ia5e48da2a3141b352439ecd548cddf918f4df585 Signed-off-by: Christopher Lott (cl778h) --- .../widget/service/InitializationService.java | 7 + .../widget/service/MicroserviceService.java | 17 + .../portalapp/widget/service/StorageService.java | 34 ++ .../widget/service/WidgetCatalogService.java | 29 ++ .../service/impl/InitializationServiceImpl.java | 128 ++++++ .../service/impl/MicroserviceServiceImpl.java | 87 ++++ .../widget/service/impl/StorageServiceImpl.java | 487 +++++++++++++++++++++ .../service/impl/WidgetCatalogServiceImpl.java | 240 ++++++++++ 8 files changed, 1029 insertions(+) create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/InitializationService.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/MicroserviceService.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/StorageService.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/WidgetCatalogService.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/InitializationServiceImpl.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/MicroserviceServiceImpl.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/StorageServiceImpl.java create mode 100644 ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/WidgetCatalogServiceImpl.java (limited to 'ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service') diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/InitializationService.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/InitializationService.java new file mode 100644 index 00000000..4a34606a --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/InitializationService.java @@ -0,0 +1,7 @@ +package org.openecomp.portalapp.widget.service; + +public interface InitializationService { + + void initialize(); + +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/MicroserviceService.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/MicroserviceService.java new file mode 100644 index 00000000..32eb48b1 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/MicroserviceService.java @@ -0,0 +1,17 @@ +package org.openecomp.portalapp.widget.service; + +import org.openecomp.portalapp.widget.domain.MicroserviceData; +import org.openecomp.portalapp.widget.domain.MicroserviceParameter; + +/** + * TODO: moved all microservice-related code (domain, controller, service) + * from ecomp portal Backend to widget microservice + */ +public interface MicroserviceService { + + Long saveMicroserivce(MicroserviceData newService); + + void saveMicroserviceParameter(MicroserviceParameter newParameter); + + Long getMicroserviceIdByName(String newServiceName); +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/StorageService.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/StorageService.java new file mode 100644 index 00000000..1eb14704 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/StorageService.java @@ -0,0 +1,34 @@ +package org.openecomp.portalapp.widget.service; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import org.openecomp.portalapp.widget.domain.ValidationRespond; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; +import org.openecomp.portalapp.widget.domain.WidgetFile; +import org.springframework.web.multipart.MultipartFile; + +public interface StorageService { + + void deleteWidgetFile(long widgetId); + + WidgetFile getWidgetFile(long widgetId); + + String getWidgetMarkup(long widgetId) throws UnsupportedEncodingException; + + String getWidgetController(long widgetId) throws UnsupportedEncodingException; + + String getWidgetFramework(long widgetId) throws UnsupportedEncodingException; + + String getWidgetCSS(long widgetId) throws UnsupportedEncodingException; + + ValidationRespond checkZipFile(MultipartFile file); + + void save(MultipartFile file, WidgetCatalog newWidget, long widgetId); + + void initSave(File file, WidgetCatalog newWidget, long widgetId); + + void update(MultipartFile file, WidgetCatalog newWidget, long widgetId); + + byte[] getWidgetCatalogContent(long widgetId) throws Exception; +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/WidgetCatalogService.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/WidgetCatalogService.java new file mode 100644 index 00000000..82853dcd --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/WidgetCatalogService.java @@ -0,0 +1,29 @@ +package org.openecomp.portalapp.widget.service; + +import java.util.List; + +import org.openecomp.portalapp.widget.domain.RoleApp; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; + +public interface WidgetCatalogService { + + List getWidgetCatalog(); + + List getUserWidgetCatalog(String loginName); + + WidgetCatalog getWidgetCatalog(Long widgetCatalogId); + + void deleteWidgetCatalog(long WidgetCatalogId); + + long saveWidgetCatalog(WidgetCatalog newWidgetCatalog); + + void updateWidgetCatalog(Long widgetCatalogId, WidgetCatalog newWidgetCatalog); + + Long getServiceIdByWidget(Long widgetCatalogId); + + boolean getWidgetIdByName(String newWidgetName); + + List getWidgetsByServiceId(Long serviceId); + + +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/InitializationServiceImpl.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/InitializationServiceImpl.java new file mode 100644 index 00000000..31635f74 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/InitializationServiceImpl.java @@ -0,0 +1,128 @@ +package org.openecomp.portalapp.widget.service.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.HashSet; + +import javax.transaction.Transactional; + +import org.openecomp.portalapp.widget.controller.WidgetsCatalogController; +import org.openecomp.portalapp.widget.domain.MicroserviceData; +import org.openecomp.portalapp.widget.domain.MicroserviceParameter; +import org.openecomp.portalapp.widget.domain.RoleApp; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; +import org.openecomp.portalapp.widget.service.InitializationService; +import org.openecomp.portalapp.widget.service.MicroserviceService; +import org.openecomp.portalapp.widget.service.StorageService; +import org.openecomp.portalapp.widget.service.WidgetCatalogService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("initService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class InitializationServiceImpl implements InitializationService{ + + private static final String BASIC_AUTH = "Basic Authentication"; + private static final String PARAMETER_KEY = "resourceType"; + private static final Logger logger = LoggerFactory.getLogger(WidgetsCatalogController.class); + + @Autowired + WidgetCatalogService widgetCatalogService; + + @Autowired + StorageService storageService; + + @Autowired + MicroserviceService microserviceService; + + @Value("${account.user.name}") + String account_user; + + @Value("${account.user.password}") + String account_password; + + @Value("${initialization.widgetData.url}") + String widgetData_url; + + @Override + public void initialize() { + initCommonWidget("News"); + initCommonWidget("Events"); + initCommonWidget("Resources"); + } + + private void initCommonWidget(String name){ + + final String newServiceName = name + " Microservice"; + final String newWidgetName = name + " Widget"; + + Long serviceId = microserviceService.getMicroserviceIdByName(newServiceName); + + if(serviceId == null){ + MicroserviceData newService = new MicroserviceData(); + newService.setName(newServiceName); + newService.setDesc(name); + newService.setAppId(1); + newService.setUrl(widgetData_url); + newService.setSecurityType(BASIC_AUTH); + newService.setUsername(account_user); + newService.setPassword(account_password); + newService.setActive("Y"); + serviceId = microserviceService.saveMicroserivce(newService); + + + MicroserviceParameter parameter = new MicroserviceParameter(); + parameter.setServiceId(serviceId); + parameter.setPara_key(PARAMETER_KEY); + String parameter_value = null; + switch(name.toLowerCase()){ + case "news": + parameter_value = "NEWS"; + break; + case "events": + parameter_value = "EVENTS"; + break; + case "resources": + parameter_value = "IMPORTANTRESOURCES"; + break; + } + parameter.setPara_value(parameter_value); + microserviceService.saveMicroserviceParameter(parameter); + } + + if(!widgetCatalogService.getWidgetIdByName(newWidgetName)){ + WidgetCatalog newWidget = new WidgetCatalog(); + newWidget.setName(newWidgetName); + newWidget.setDesc(name); + newWidget.setAllowAllUser("1"); + String fileLocation = name.toLowerCase() + "-widget.zip"; + newWidget.setFileLocation(fileLocation); + newWidget.setServiceId(serviceId); + newWidget.setWidgetRoles(new HashSet()); + long widgetId = widgetCatalogService.saveWidgetCatalog(newWidget); + + File file = new File("/tmp/" + fileLocation); + try{ + + InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream(fileLocation); + OutputStream outputStream = new FileOutputStream(file); + int read = 0; + byte[] bytes = new byte[4096]; + while ((read = fileInputStream.read(bytes)) != -1) { + outputStream.write(bytes, 0, read); + } + }catch(Exception e){ + logger.error("Exception occurred while performing InitializationServiceImpl.initCommonWidget in widget microservices. Details:" + e.getMessage()); + } + storageService.initSave(file, newWidget, widgetId); + } + } +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/MicroserviceServiceImpl.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/MicroserviceServiceImpl.java new file mode 100644 index 00000000..395d4283 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/MicroserviceServiceImpl.java @@ -0,0 +1,87 @@ +package org.openecomp.portalapp.widget.service.impl; + +import java.util.List; + +import javax.transaction.Transactional; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalapp.widget.domain.MicroserviceData; +import org.openecomp.portalapp.widget.domain.MicroserviceParameter; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; +import org.openecomp.portalapp.widget.service.MicroserviceService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +/** + * TODO: moved all microservice-related code (domain, controller, service) + * from ecomp portal Backend to widget microservice + */ +@Service("microserviceService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class MicroserviceServiceImpl implements MicroserviceService{ + + private static final Logger logger = LoggerFactory.getLogger(MicroserviceServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + + @Override + public Long saveMicroserivce(MicroserviceData newService) { + try{ + logger.debug("MicroserviceServiceImpl.saveMicroserivce: microservice={}", newService); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.save(newService); + tx.commit(); + session.flush(); + session.close(); + } + catch(Exception e){ + logger.error("Exception occurred while performing MicroserviceServiceImpl.saveMicroserivce in widget microservices. Details:" + e.getMessage()); + } + return newService.getId(); + } + + @Override + public void saveMicroserviceParameter(MicroserviceParameter newParameter) { + try{ + logger.debug("MicroserviceServiceImpl.saveMicroserviceData: microservice={}", newParameter); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.save(newParameter); + tx.commit(); + session.flush(); + session.close(); + } + catch(Exception e){ + logger.error("Exception occurred while performing MicroserviceServiceImpl.saveMicroserviceData in widget microservices. Details:" + e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + @Override + public Long getMicroserviceIdByName(String newServiceName) { + + Session session = sessionFactory.openSession(); + Criteria criteria = session.createCriteria(MicroserviceData.class) + .add(Restrictions.eq("name", newServiceName)) + .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + + List services = criteria.list(); + logger.debug("MicroserviceServiceImpl.getMicroserviceByName: result={}", services); + session.flush(); + session.close(); + + return (services.size() > 0) ? services.get(0).getId() : null; + } + +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/StorageServiceImpl.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/StorageServiceImpl.java new file mode 100644 index 00000000..046b5ac4 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/StorageServiceImpl.java @@ -0,0 +1,487 @@ +package org.openecomp.portalapp.widget.service.impl; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalapp.widget.constant.WidgetConstant; +import org.openecomp.portalapp.widget.controller.DatabaseFileUploadController; +import org.openecomp.portalapp.widget.domain.ValidationRespond; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; +import org.openecomp.portalapp.widget.domain.WidgetFile; +import org.openecomp.portalapp.widget.excetpion.StorageException; +import org.openecomp.portalapp.widget.service.StorageService; +import org.openecomp.portalapp.widget.service.WidgetCatalogService; +import org.openecomp.portalapp.widget.utils.UnzipUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +@Service +public class StorageServiceImpl implements StorageService { + + private static final Logger logger = LoggerFactory.getLogger(StorageServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + + @Autowired + WidgetCatalogService widgetCatalogService; + + @Override + @Transactional + public void deleteWidgetFile(long widgetId) { + WidgetFile widgetFile = getWidgetFile(widgetId); + logger.debug("StorageServiceImpl.deleteWidgetFile: deleting widget file {}", widgetId); + if (widgetFile == null){ + logger.debug("StorageServiceImpl.deleteWidgetFile: No widget file found in database while performing StorageServiceImpl.deleteWidgetFile."); + return; + } + Session session = sessionFactory.getCurrentSession(); + Transaction tx = session.beginTransaction(); + session.delete(widgetFile); + tx.commit(); + } + + @Override + @SuppressWarnings("unchecked") + @Transactional + public WidgetFile getWidgetFile(long widgetId) { + logger.debug("StorageServiceImpl.getWidgetFile: getting widget file {}", widgetId); + WidgetFile widgetFile = null; + Session session = sessionFactory.openSession(); + Criteria criteria = session.createCriteria(WidgetFile.class); + criteria.add(Restrictions.eq("widgetId", widgetId)); + List widgetFiles = criteria.list(); + session.flush(); + session.close(); + if (widgetFiles.size() > 0) + widgetFile = widgetFiles.get(0); + return widgetFile; + } + + @Override + public ValidationRespond checkZipFile(MultipartFile file){ + StringBuilder error_msg = new StringBuilder(); + UnzipUtil unzipper = new UnzipUtil(); + Map map; + File convFile; + boolean isValid = true; + if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.')).equals(".zip")) { + isValid = false; + error_msg.append(WidgetConstant.VALIDATION_MESSAGE_ZIP); + logger.error("StorageServiceImpl.checkZipFile: invalid file format"); + } + try { + if (file.isEmpty()) { + logger.error("StorageServiceImpl.checkZipFile: Failed to store empty file " + file.getOriginalFilename()); + throw new StorageException("StorageServiceImpl.checkZipFile: Failed to store empty file " + file.getOriginalFilename()); + } + String fileLocation = file.getOriginalFilename(); + logger.debug("StorageServiceImpl.checkZipFile: store the widget to:" + fileLocation); + convFile = new File(fileLocation); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + map = unzipper.unzip_db(fileLocation, ".", "tempWidgets"); + convFile.delete(); + } catch (IOException e) { + logger.error("StorageServiceImpl.checkZipFile: Failed to store file " + file.getOriginalFilename(), e); + throw new StorageException("torageServiceImpl.checkZipFile: Failed to store file " + file.getOriginalFilename(), e); + } + + for(byte[] b: map.values()){ + if(isValid && b == null){ + isValid = false; + error_msg.append(WidgetConstant.VALIDATION_MESSAGE_FILES); + break; + } + } + return new ValidationRespond(isValid, error_msg.toString()); + } + + @Override + @Transactional + public void save(MultipartFile file, WidgetCatalog newWidget, long widgetId) { + + UnzipUtil unzipper = new UnzipUtil(); + Map map; + File convFile; + try { + if (file.isEmpty()) { + logger.error("Failed to store empty file " + file.getOriginalFilename()); + throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); + } + String fileLocation = file.getOriginalFilename(); + logger.debug("StorageServiceImpl.save: store the widget to:" + fileLocation); + convFile = new File(fileLocation); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + map = unzipper.unzip_db(fileLocation, ".", "tempWidgets"); + convFile.delete(); + } catch (IOException e) { + logger.error("StorageServiceImpl.save: Failed to store file " + file.getOriginalFilename(), e); + throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); + } + saveHelper(newWidget, widgetId, map); + } + + + @Override + @Transactional + public void initSave(File file, WidgetCatalog newWidget, long widgetId) { + + UnzipUtil unzipper = new UnzipUtil(); + Map map; + + try { + String fileLocation = file.getPath(); + logger.debug("StorageServiceImpl.save: store the widget to:" + fileLocation); + map = unzipper.unzip_db(fileLocation, ".", "tempWidgets"); + } catch (IOException e) { + logger.error("StorageServiceImpl.save: Failed to store file " + file.getName(), e); + throw new StorageException("Failed to store file " + file.getName(), e); + } + saveHelper(newWidget, widgetId, map); + } + + + /** + * Helper method for saving widget files (controller.js, framework.js, markup.html and style.css) + * to ep_widget_catalog_files table in database + * + * @param newWidget + * @param widgetId + * @param map + */ + private void saveHelper(WidgetCatalog newWidget, long widgetId, Map map){ + + WidgetFile widgetFile = new WidgetFile(); + widgetFile.setName(newWidget.getName()); + widgetFile.setWidgetId(widgetId); + + + InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("framework-template.js"); + + String sb = null; + try { + byte[] bytes = new byte[fileInputStream.available()]; + fileInputStream.read(bytes); + sb = new String(bytes, "UTF-8"); + } catch (IOException e) { + logger.error("StorageServiceImpl.save: Failed to load framework-template.js file ", e); + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + logger.error("StorageServiceImpl.update: Failed to close the fileInputStream ", e); + e.printStackTrace(); + } + } + } + + + String namespace = "Portal" + widgetId + "Widget"; + String controllerName = "Portal" + widgetId + "Ctrl"; + String cssName = "portal" + widgetId + "-css-ready"; + String colorArg1 = "color: #fff"; + String framework = sb + .replaceAll("ARUGMENT1", namespace) + .replaceAll("ARUGMENT2", controllerName) + .replaceAll("ARUGMENT3", cssName) + .replaceAll("CSS_ARG1", colorArg1) + .replaceAll("MICROSERVICE_ID", newWidget.getServiceId().toString()) + .replaceAll("WIDGET_ID", Long.toString(widgetId)); + + widgetFile.setFramework(framework.getBytes()); + + String javascript = new String(map.get(WidgetConstant.WIDGET_CONTROLLER_LOCATION)); + String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")")+1); + String functionName = functionHeader.substring(functionHeader.indexOf(" "), functionHeader.indexOf("(")).trim(); + javascript = javascript.replaceFirst(functionName, controllerName); + String functionParam = functionHeader.substring(functionHeader.indexOf("(")+1, functionHeader.indexOf(")")); + List paramList = Arrays.asList(functionParam.split(",")); + + int left_bracket_index = javascript.indexOf("{") + 1; + String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;"; + javascript = javascript.substring(0, left_bracket_index) + widgetData + javascript.substring(left_bracket_index); + + StringBuilder injectStr = new StringBuilder().append("["); + for(int i = 0; i < paramList.size(); i++){ + if(i == paramList.size()-1) + injectStr.append("'" + paramList.get(i).trim() + "'];"); + else + injectStr.append("'" + paramList.get(i).trim() + "',"); + } + javascript = namespace + ".controller = " + javascript + ";" + namespace + ".controller.$inject = " + injectStr.toString(); + + String html = new String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName, controllerName);; + + Pattern cssPattern = Pattern.compile("#.*-css-ready"); + Matcher cssMatcher = cssPattern.matcher(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION))); + if (cssMatcher.find( )) { + widgetFile.setCss(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION)).replace(cssMatcher.group(0), "#" + cssName).getBytes()); + } + + widgetFile.setMarkup(html.getBytes()); + widgetFile.setController(javascript.getBytes()); + Session session = sessionFactory.openSession(); + session.save(widgetFile); + session.flush(); + session.close(); + //sessionFactory.getCurrentSession().save(widgetFile); + logger.debug("StorageServiceImpl.save: saved fraemwork.js controller.js, markup.html and style.css files to the database for widget {}", widgetId); + + } + + @Override + public void update(MultipartFile file, WidgetCatalog newWidget, long widgetId) { + UnzipUtil unzipper = new UnzipUtil(); + Map map; + File convFile; + try { + if (file.isEmpty()) { + logger.error("StorageServiceImpl.update: Failed to store empty file " + file.getOriginalFilename()); + throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); + } + String fileLocation = file.getOriginalFilename(); + logger.debug("StorageServiceImpl.update: store the widget to:" + fileLocation); + convFile = new File(fileLocation); + FileOutputStream fos = new FileOutputStream(convFile); + fos.write(file.getBytes()); + fos.close(); + map = unzipper.unzip_db(fileLocation, ".", "tempWidgets"); + convFile.delete(); + } catch (IOException e) { + logger.error("StorageServiceImpl.update: Failed to store file " + file.getOriginalFilename(), e); + throw new StorageException("StorageServiceImpl.update: Failed to store file " + file.getOriginalFilename(), e); + } + WidgetFile widgetFile = getWidgetFile(widgetId); + + InputStream fileInputStream = this.getClass().getClassLoader().getResourceAsStream("framework-template.js"); + String sb = null; + try { + byte[] bytes = new byte[fileInputStream.available()]; + fileInputStream.read(bytes); + sb = new String(bytes, "UTF-8"); + } catch (IOException e) { + logger.error("StorageServiceImpl.save: Failed to load framework-template.js file ", e); + e.printStackTrace(); + } finally { + if (fileInputStream != null) { + try { + fileInputStream.close(); + } catch (IOException e) { + logger.error("StorageServiceImpl.update: Failed to close the fileInputStream ", e); + e.printStackTrace(); + } + } + } + + String namespace = "Portal" + widgetId + "Widget"; + String controllerName = "Portal" + widgetId + "Ctrl"; + String cssName = "portal" + widgetId + "-css-ready"; + String colorArg1 = "color: #fff"; + String framework = sb + .replaceAll("ARUGMENT1", namespace) + .replaceAll("ARUGMENT2", controllerName) + .replaceAll("ARUGMENT3", cssName) + .replaceAll("CSS_ARG1", colorArg1) + .replaceAll("MICROSERVICE_ID", newWidget.getServiceId().toString()) + .replaceAll("WIDGET_ID", Long.toString(widgetId)); + widgetFile.setFramework(framework.getBytes()); + + String javascript = new String(map.get(WidgetConstant.WIDGET_CONTROLLER_LOCATION)); + String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")")+1); + String functionName = functionHeader.substring(functionHeader.indexOf(" "), functionHeader.indexOf("(")).trim(); + javascript = javascript.replaceFirst(functionName, controllerName); + String functionParam = functionHeader.substring(functionHeader.indexOf("(")+1, functionHeader.indexOf(")")); + List paramList = Arrays.asList(functionParam.split(",")); + + int left_bracket_index = javascript.indexOf("{") + 1; + String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;"; + javascript = javascript.substring(0, left_bracket_index) + widgetData + javascript.substring(left_bracket_index); + + StringBuilder injectStr = new StringBuilder().append("["); + for(int i = 0; i < paramList.size(); i++){ + if(i == paramList.size()-1) + injectStr.append("'" + paramList.get(i).trim() + "'];"); + else + injectStr.append("'" + paramList.get(i).trim() + "',"); + } + javascript = namespace + ".controller = " + javascript + ";" + namespace + ".controller.$inject = " + injectStr.toString(); + + String html = new String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName, controllerName);; + + Pattern cssPattern = Pattern.compile("#.*-css-ready"); + Matcher cssMatcher = cssPattern.matcher(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION))); + if (cssMatcher.find( )) { + widgetFile.setCss(new String(map.get(WidgetConstant.WIDGET_STYLE_LOCATION)).replace(cssMatcher.group(0), "#" + cssName).getBytes()); + } + + widgetFile.setMarkup(html.getBytes()); + widgetFile.setController(javascript.getBytes()); + //widgetFile.setCss(map.get(WidgetConstant.WIDGET_STYLE_LOCATION)); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.update(widgetFile); + tx.commit(); + session.flush(); + session.close(); + logger.debug("StorageServiceImpl.save: updated fraemwork.js controller.js, markup.html and style.css files to the database for widget {}", widgetId); + } + + + @Override + @SuppressWarnings("unchecked") + @Transactional + public String getWidgetMarkup(long widgetId) throws UnsupportedEncodingException { + String markup = null; + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetFile.class); + criteria.add(Restrictions.eq("widgetId", widgetId)); + List widgetFile = criteria.list(); + logger.debug("StorageServiceImpl.getWidgetMarkup: getting widget markup result={}", widgetFile); + + if(widgetFile.size() > 0 ) + markup = new String(widgetFile.get(0).getMarkup(), "UTF-8"); + return markup; + } + + @Override + @SuppressWarnings("unchecked") + @Transactional + public String getWidgetController(long widgetId) throws UnsupportedEncodingException { + String controller = null; + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetFile.class); + criteria.add(Restrictions.eq("widgetId", widgetId)); + List widgetFile = criteria.list(); + logger.debug("StorageServiceImpl.getWidgetController: getting widget controller result={}", widgetFile); + + if(widgetFile.size() > 0 ) + controller = new String(widgetFile.get(0).getController(), "UTF-8"); + return controller; + } + + @Override + @SuppressWarnings("unchecked") + @Transactional + public String getWidgetFramework(long widgetId) throws UnsupportedEncodingException { + String framework = null; + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetFile.class); + criteria.add(Restrictions.eq("widgetId", widgetId)); + List widgetFile = criteria.list(); + logger.debug("StorageServiceImpl.getWidgetFramework: getting widget framework result={}", widgetFile); + + if(widgetFile.size() > 0 ) + framework = new String(widgetFile.get(0).getFramework(), "UTF-8"); + return framework; + } + + @Override + @SuppressWarnings("unchecked") + @Transactional + public String getWidgetCSS(long widgetId) throws UnsupportedEncodingException { + String css = null; + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetFile.class); + criteria.add(Restrictions.eq("widgetId", widgetId)); + List widgetFile = criteria.list(); + logger.debug("StorageServiceImpl.getWidgetCSS: getting widget css result={}", widgetFile); + + if(widgetFile.size() > 0 ) + css = new String(widgetFile.get(0).getCss(), "UTF-8"); + return css; + } + + + @Override + @Transactional + public byte[] getWidgetCatalogContent(long widgetId) throws Exception{ + + + WidgetCatalog widget = widgetCatalogService.getWidgetCatalog(widgetId); + String namespace = "Portal" + widgetId + "Widget"; + String controllerName = "Portal" + widgetId + "Ctrl"; + String cssName = "portal" + widgetId + "-css-ready"; + + + String styles = getWidgetCSS(widgetId).replaceAll(cssName, widget.getName() + "-css-ready"); + File f = File.createTempFile("temp", ".zip"); + ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f)); + ZipEntry e = new ZipEntry(widget.getName() + "/styles/styles.css"); + out.putNextEntry(new ZipEntry(widget.getName() + "/")); + out.putNextEntry(new ZipEntry(widget.getName() + "/styles/")); + out.putNextEntry(e); + byte[] data = styles.getBytes(); + out.write(data, 0, data.length); + + + String widgetData = namespace + "=" + namespace + "||{};" + "var res = " + namespace + ".widgetData;"; + String javascript = getWidgetController(widgetId).replace(widgetData, "") + .replace(namespace + ".controller =", ""); + + String functionHeader = javascript.substring(javascript.indexOf("function"), javascript.indexOf(")")+1); + javascript = javascript.replaceFirst(controllerName, widget.getName() + "Ctrl"); + String functionParam = functionHeader.substring(functionHeader.indexOf("(")+1, functionHeader.indexOf(")")); + StringBuilder injectStr = new StringBuilder().append("["); + List paramList = Arrays.asList(functionParam.split(",")); + for(int i = 0; i < paramList.size(); i++){ + if(i == paramList.size()-1) + injectStr.append("'" + paramList.get(i).trim() + "'];"); + else + injectStr.append("'" + paramList.get(i).trim() + "',"); + } + javascript = javascript.replace(";" + namespace + ".controller.$inject = " + injectStr.toString(), ""); + + e = new ZipEntry(widget.getName() + "/js/controller.js"); + out.putNextEntry(new ZipEntry(widget.getName() + "/js/")); + out.putNextEntry(e); + data = javascript.getBytes(); + out.write(data, 0, data.length); + + String html = getWidgetMarkup(widgetId).replaceFirst(controllerName, widget.getName() + "Ctrl"); + + //new String(map.get(WidgetConstant.WIDGET_MARKUP_LOCATION)).replaceFirst(functionName, controllerName);; + + + e = new ZipEntry(widget.getName() + "/markup/markup.html"); + out.putNextEntry(new ZipEntry(widget.getName() + "/markup/")); + out.putNextEntry(e); + data = html.getBytes(); + out.write(data, 0, data.length); + out.closeEntry(); + out.close(); + byte[] result = Files.readAllBytes(Paths.get(f.getPath())); + f.delete(); + return result; + } + +} diff --git a/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/WidgetCatalogServiceImpl.java b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/WidgetCatalogServiceImpl.java new file mode 100644 index 00000000..700274e2 --- /dev/null +++ b/ecomp-portal-widget-ms/src/main/java/org/openecomp/portalapp/widget/service/impl/WidgetCatalogServiceImpl.java @@ -0,0 +1,240 @@ +package org.openecomp.portalapp.widget.service.impl; + +import java.util.List; +import java.util.Set; + +import javax.transaction.Transactional; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.portalapp.widget.domain.MicroserviceData; +import org.openecomp.portalapp.widget.domain.RoleApp; +import org.openecomp.portalapp.widget.domain.WidgetCatalog; +import org.openecomp.portalapp.widget.service.WidgetCatalogService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; + +@Service("widgetCatalogService") +@Transactional +@org.springframework.context.annotation.Configuration +@EnableAspectJAutoProxy +public class WidgetCatalogServiceImpl implements WidgetCatalogService { + + private static final Logger logger = LoggerFactory.getLogger(WidgetCatalogServiceImpl.class); + + @Autowired + private SessionFactory sessionFactory; + + @SuppressWarnings("unchecked") + @Override + @Transactional + public List getWidgetCatalog(){ + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetCatalog.class) + .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + List widgets = criteria.list(); + logger.debug("WidgetCatalogServiceImpl.getWidgetCatalog: result={}", widgets); + return widgets; + } + + @SuppressWarnings("unchecked") + @Transactional + public List getUserWidgetCatalog(String loginName){ + Session session = sessionFactory.getCurrentSession(); + StringBuilder sql = new StringBuilder() + + + .append(" select userWidgets.widget_id, userWidgets.wdg_name, userWidgets.wdg_desc, b.x, b.status_cd, b.y, b.height, b.width from ") + .append(" ( ") + .append(" select distinct w.widget_id, w.wdg_name, w.wdg_desc from ") + .append(" ep_widget_catalog w, ") + .append(" ep_widget_catalog_role wr, ") + .append(" fn_user_role ur, ") + .append(" fn_user u ") + .append(" where ") + .append(" w.widget_id = wr.WIDGET_ID and ") + .append(" wr.role_id = ur.role_id and ") + .append(" ur.user_id = u.user_id and ") + .append(" u.login_id = '" + loginName + "' and (w.all_user_flag = 'N' or w.all_user_flag is null) ") + .append(" ") + .append(" union all ") + .append(" ") + .append(" ") + .append(" select distinct w.widget_id, w.wdg_name, w.wdg_desc from ") + .append(" ep_widget_catalog w ") + .append(" where w.all_user_flag = 'Y' ") + .append(" ") + .append(" ) userWidgets ") + .append(" ") + .append(" left join ") + .append(" ") + .append(" ( ") + .append(" select case when pers.user_id is null then sel.user_id else pers.user_id end as 'user_id', case when sel.widget_id is null then ") + .append(" pers.widget_id else sel.widget_id end as 'widget_id', pers.x, sel.status_cd, pers.y, pers.height, pers.width ") + .append(" from (select * from ep_pers_user_widget_placement where user_id = (select user_id from fn_user where login_id = '" + loginName + "')) pers ") + .append(" left outer join ") + .append(" (select * from ep_pers_user_widget_sel where user_id = (select user_id from fn_user where login_id = '" + loginName + "')) sel ") + .append(" on (pers.user_id = sel.user_id and pers.widget_id = sel.widget_id) ") + .append(" ") + .append(" union ") + .append(" ") + .append(" select case when pers.user_id is null then sel.user_id else pers.user_id end as 'user_id', case when sel.widget_id is null ") + .append(" then pers.widget_id else sel.widget_id end as 'widget_id', pers.x, sel.status_cd, pers.y, pers.height, pers.width ") + .append(" from (select * from ep_pers_user_widget_placement where user_id = (select user_id from fn_user where login_id = '" + loginName + "')) pers ") + .append(" right outer join ") + .append(" (select * from ep_pers_user_widget_sel where user_id = (select user_id from fn_user where login_id = '" + loginName + "')) sel ") + .append(" on (pers.user_id = sel.user_id and pers.widget_id = sel.widget_id) ") + .append(" ") + .append(" order by user_id, widget_id ") + .append(" )b ") + .append(" on ") + .append(" (userWidgets.widget_id = b.widget_id) order by b.x; "); + + + + Query query = session.createSQLQuery(sql.toString()); + List widgets = query.list(); + logger.debug("WidgetCatalogServiceImpl.getUserWidgetCatalog: result size={}", widgets); + return widgets; + } + + @Override + public WidgetCatalog getWidgetCatalog(Long widgetCatalogId) { + Session session = sessionFactory.getCurrentSession(); + Transaction tx = session.beginTransaction(); + WidgetCatalog widget = (WidgetCatalog) session.get(WidgetCatalog.class, widgetCatalogId); + tx.commit(); + logger.debug("WidgetCatalogServiceImpl.getWidgetCatalog: getting widget={}", widget); + return widget; + } + + @Override + public void deleteWidgetCatalog(long widgetCatalogId) { + logger.debug("WidgetCatalogServiceImpl.deleteWidgetCatalog: deleting the widget with widgetId={}", widgetCatalogId); + WidgetCatalog widget = getWidgetCatalog(widgetCatalogId); + if (widget == null){ + logger.error("No widget found in database while performing WidgetCatalogServiceImpl.deleteWidgetCatalog."); + return; + } + Session session = sessionFactory.getCurrentSession(); + Transaction tx = session.beginTransaction(); + Query query = session.createSQLQuery("delete from ep_pers_user_widget_sel where widget_id = :widgetId ").setParameter("widgetId", widgetCatalogId); + query.executeUpdate(); + query = session.createSQLQuery("delete from ep_pers_user_widget_placement where widget_id = :widgetId ").setParameter("widgetId", widgetCatalogId); + query.executeUpdate(); + query = session.createSQLQuery("delete from ep_widget_catalog_files where widget_id = :widgetId ").setParameter("widgetId", widgetCatalogId); + query.executeUpdate(); + query = session.createSQLQuery("delete from ep_widget_catalog_parameter where widget_id = :widgetId ").setParameter("widgetId", widgetCatalogId); + query.executeUpdate(); + session.delete(widget); + tx.commit(); + } + + @Override + public long saveWidgetCatalog(WidgetCatalog newWidgetCatalog) { + + try{ + if(newWidgetCatalog.getAllowAllUser().equals("1")) + newWidgetCatalog.setAllowAllUser("Y"); + else + newWidgetCatalog.setAllowAllUser("N"); + + logger.debug("WidgetCatalogServiceImpl.saveWidgetCatalog: widget={}", newWidgetCatalog); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.save(newWidgetCatalog); + tx.commit(); + session.flush(); + session.close(); + updateAppId(newWidgetCatalog.getId(), newWidgetCatalog.getWidgetRoles()); + } + catch(Exception e){ + logger.error("Exception occurred while performing WidgetCatalogServiceImpl.saveWidgetCatalog in widget microservices. Details:" + e.getMessage()); + } + return newWidgetCatalog.getId(); + } + + @Override + public void updateWidgetCatalog(Long widgetCatalogId, WidgetCatalog newWidgetCatalog) { + logger.debug("WidgetCatalogServiceImpl.updateWidgetCatalog: widget={}", newWidgetCatalog); + WidgetCatalog oldWidget = getWidgetCatalog(widgetCatalogId); + try{ + if (newWidgetCatalog.getAllowAllUser().equals("1")) + newWidgetCatalog.setAllowAllUser("Y"); + else + newWidgetCatalog.setAllowAllUser("N"); + + newWidgetCatalog.setId(widgetCatalogId); + newWidgetCatalog.setServiceId(oldWidget.getServiceId()); + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + session.update(newWidgetCatalog); + tx.commit(); + session.flush(); + session.close(); + updateAppId(newWidgetCatalog.getId(), newWidgetCatalog.getWidgetRoles()); + }catch(Exception e){ + logger.error("Exception occurred while performing WidgetCatalogServiceImpl.updateWidgetCatalog in widget microservices. Details:" + e.getMessage()); + } + + } + + @Override + public Long getServiceIdByWidget(Long widgetCatalogId) { + Session session = sessionFactory.getCurrentSession(); + WidgetCatalog widget = (WidgetCatalog) session.get(WidgetCatalog.class, widgetCatalogId); + logger.debug("WidgetCatalogServiceImpl.getServiceIdByWidget: result={}", widget); + return widget.getServiceId(); + } + + @Override + public List getWidgetsByServiceId(Long serviceId) { + Session session = sessionFactory.getCurrentSession(); + Criteria criteria = session.createCriteria(WidgetCatalog.class) + .add(Restrictions.eq("serviceId", serviceId)) + .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + List widgets = criteria.list(); + logger.debug("WidgetCatalogServiceImpl.getWidgetCatalog: result={}", widgets); + return widgets; + } + + + + + + private void updateAppId(long widgetId, Set roles){ + Session session = sessionFactory.openSession(); + for(RoleApp role: roles){ + String sql = "UPDATE ep_widget_catalog_role SET app_id = " + role.getApp().getAppId() + " WHERE widget_id = " + widgetId + " AND ROLE_ID = " + role.getRoleId() ; + Query query = session.createSQLQuery(sql); + query.executeUpdate(); + } + session.flush(); + session.close(); + } + + @Override + public boolean getWidgetIdByName(String newWidgetName) { + Session session = sessionFactory.openSession(); + Criteria criteria = session.createCriteria(WidgetCatalog.class) + .add(Restrictions.eq("name", newWidgetName)) + .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); + + List widgets = criteria.list(); + logger.debug("WidgetCatalogServiceImpl.getWidgetIdByName: result={}", widgets); + session.flush(); + session.close(); + + return (widgets.size() > 0) ? true : false; + } + + +} + -- cgit 1.2.3-korg