diff options
67 files changed, 3132 insertions, 1546 deletions
diff --git a/docs/index.rst b/docs/index.rst index 61e49c6b..1f41485e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -3,7 +3,7 @@ .. Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved. CLAMP - Control Loop Automation Management Platform -================================================== +=================================================== .. High level architecture, design, and packaging information for release planning and delivery. .. include:: architecture.rst diff --git a/extra/sql/bulkload/create-tables.sql b/extra/sql/bulkload/create-tables.sql index da39ca5f..121c5e68 100644 --- a/extra/sql/bulkload/create-tables.sql +++ b/extra/sql/bulkload/create-tables.sql @@ -7,6 +7,7 @@ create table loop_logs ( id bigint not null, + log_component varchar(255) not null, log_instant datetime(6) not null, log_type varchar(255) not null, message MEDIUMTEXT not null, @@ -61,12 +61,9 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> - <project.scm.id>git-server</project.scm.id> - <java.version>1.8</java.version> - <eelf.core.version>1.0.0</eelf.core.version> - <camel.version>2.23.2</camel.version> - <springboot.version>2.1.4.RELEASE</springboot.version> + <camel.version>2.24.0</camel.version> + <springboot.version>2.1.5.RELEASE</springboot.version> <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin> <sonar.surefire.reportsPath>${project.build.directory}/surefire-reports</sonar.surefire.reportsPath> @@ -89,7 +86,7 @@ <docker.skip.tag>true</docker.skip.tag> <skip.staging.artifacts>false</skip.staging.artifacts> <python.http.proxy.param/> - <tomcat.version>9.0.16</tomcat.version> + <tomcat.version>9.0.20</tomcat.version> </properties> <profiles> diff --git a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java index 4a35f458..2e43495b 100644 --- a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java +++ b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java @@ -30,7 +30,7 @@ import com.att.eelf.configuration.EELFManager; import java.util.Date; -import javax.ws.rs.NotAuthorizedException; +import org.onap.clamp.clds.exception.NotAuthorizedException; import org.apache.camel.Exchange; import org.onap.clamp.clds.config.ClampProperties; @@ -57,7 +57,7 @@ public class AuthorizationController { @Autowired private ClampProperties refProp; - private static final String PERM_PREFIX = "security.permission.type."; + public static final String PERM_PREFIX = "security.permission.type."; private static final String PERM_INSTANCE = "security.permission.instance"; /** diff --git a/src/main/java/org/onap/clamp/clds/Application.java b/src/main/java/org/onap/clamp/clds/Application.java index f6dfdc0c..bac328d6 100644 --- a/src/main/java/org/onap/clamp/clds/Application.java +++ b/src/main/java/org/onap/clamp/clds/Application.java @@ -29,15 +29,21 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Enumeration; import org.apache.catalina.connector.Connector; import org.onap.clamp.clds.model.properties.Holmes; import org.onap.clamp.clds.model.properties.ModelProperties; import org.onap.clamp.clds.util.ClampVersioning; import org.onap.clamp.clds.util.ResourceFileUtil; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @@ -51,6 +57,7 @@ import org.springframework.boot.web.servlet.server.ServletWebServerFactory; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @@ -82,6 +89,9 @@ public class Application extends SpringBootServletInitializer { @Value("${server.ssl.key-store:none}") private String sslKeystoreFile; + @Autowired + private Environment env; + @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); @@ -102,14 +112,15 @@ public class Application extends SpringBootServletInitializer { * This method is used to declare the camel servlet. * * @return A servlet bean - * @throws IOException IO Exception + * @throws IOException + * IO Exception */ @Bean public ServletRegistrationBean camelServletRegistrationBean() throws IOException { - eelfLogger.info(ResourceFileUtil.getResourceAsString("boot-message.txt") + "(v" - + ClampVersioning.getCldsVersionFromProps() + ")" + System.getProperty("line.separator")); - ServletRegistrationBean registration = new ServletRegistrationBean(new ClampServlet(), - "/restservices/clds/*"); + eelfLogger.info( + ResourceFileUtil.getResourceAsString("boot-message.txt") + "(v" + ClampVersioning.getCldsVersionFromProps() + + ")" + System.getProperty("line.separator") + getSslExpirationDate()); + ServletRegistrationBean registration = new ServletRegistrationBean(new ClampServlet(), "/restservices/clds/*"); registration.setName("CamelServlet"); return registration; } @@ -135,9 +146,8 @@ public class Application extends SpringBootServletInitializer { private Connector createRedirectConnector(int redirectSecuredPort) { if (redirectSecuredPort <= 0) { - eelfLogger.warn( - "HTTP port redirection to HTTPS is disabled because the HTTPS port is 0 (random port) or -1" - + " (Connector disabled)"); + eelfLogger.warn("HTTP port redirection to HTTPS is disabled because the HTTPS port is 0 (random port) or -1" + + " (Connector disabled)"); return null; } Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); @@ -147,4 +157,33 @@ public class Application extends SpringBootServletInitializer { connector.setRedirectPort(redirectSecuredPort); return connector; } + + private String getSslExpirationDate() throws IOException { + StringBuilder result = new StringBuilder(" :: SSL Certificates :: "); + try { + if (env.getProperty("server.ssl.key-store") != null) { + + KeyStore keystore = KeyStore.getInstance(env.getProperty("server.ssl.key-store-type")); + keystore.load( + ResourceFileUtil + .getResourceAsStream(env.getProperty("server.ssl.key-store").replaceAll("classpath:", "")), + env.getProperty("server.ssl.key-store-password").toCharArray()); + Enumeration<String> aliases = keystore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if ("X.509".equals(keystore.getCertificate(alias).getType())) { + result.append("* " + alias + " expires " + + ((X509Certificate) keystore.getCertificate(alias)).getNotAfter() + + System.getProperty("line.separator")); + } + } + } else { + result.append("* NONE HAS been configured"); + } + } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException e) { + eelfLogger.warn("SSL certificate access error ", e); + + } + return result.toString(); + } } diff --git a/src/main/java/org/onap/clamp/clds/ClampServlet.java b/src/main/java/org/onap/clamp/clds/ClampServlet.java index 90d0693d..86524d1c 100644 --- a/src/main/java/org/onap/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/clamp/clds/ClampServlet.java @@ -27,6 +27,15 @@ package org.onap.clamp.clds; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; + +import java.io.IOException; +import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.camel.component.servlet.CamelHttpTransportServlet; import org.onap.clamp.clds.service.SecureServicePermission; import org.springframework.context.ApplicationContext; @@ -39,14 +48,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; import org.springframework.web.context.support.WebApplicationContextUtils; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.List; - public class ClampServlet extends CamelHttpTransportServlet { /** @@ -100,7 +101,8 @@ public class ClampServlet extends CamelHttpTransportServlet { permissionList.add(SecureServicePermission .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, READ)); permissionList.add(SecureServicePermission - .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, UPDATE)); + .create(applicationContext.getEnvironment().getProperty(PERM_TOSCA), cldsPermissionInstance, + UPDATE)); } return permissionList; } @@ -122,8 +124,8 @@ public class ClampServlet extends CamelHttpTransportServlet { grantedAuths.add(new SimpleGrantedAuthority(permString)); } } - Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", grantedAuths), "", - grantedAuths); + Authentication auth = new UsernamePasswordAuthenticationToken(new User(principal.getName(), "", + grantedAuths), "", grantedAuths); SecurityContextHolder.getContext().setAuthentication(auth); } try { diff --git a/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java index 3dc80738..271dc84f 100644 --- a/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java +++ b/src/main/java/org/onap/clamp/clds/config/CamelConfiguration.java @@ -63,13 +63,13 @@ public class CamelConfiguration extends RouteBuilder { private void configureDefaultSslProperties() { if (env.getProperty("server.ssl.trust-store") != null) { - URL storeResource = CamelConfiguration.class + URL storeResource = Thread.currentThread().getContextClassLoader() .getResource(env.getProperty("server.ssl.trust-store").replaceAll("classpath:", "")); System.setProperty("javax.net.ssl.trustStore", storeResource.getPath()); System.setProperty("javax.net.ssl.trustStorePassword", env.getProperty("server.ssl.trust-store-password")); System.setProperty("javax.net.ssl.trustStoreType", "jks"); System.setProperty("ssl.TrustManagerFactory.algorithm", "PKIX"); - storeResource = CamelConfiguration.class + storeResource = Thread.currentThread().getContextClassLoader() .getResource(env.getProperty("server.ssl.key-store").replaceAll("classpath:", "")); System.setProperty("javax.net.ssl.keyStore", storeResource.getPath()); System.setProperty("javax.net.ssl.keyStorePassword", env.getProperty("server.ssl.key-store-password")); @@ -82,7 +82,7 @@ public class CamelConfiguration extends RouteBuilder { if (env.getProperty("server.ssl.trust-store") != null) { KeyStore truststore = KeyStore.getInstance("JKS"); truststore.load( - getClass().getClassLoader() + Thread.currentThread().getContextClassLoader() .getResourceAsStream(env.getProperty("server.ssl.trust-store").replaceAll("classpath:", "")), env.getProperty("server.ssl.trust-store-password").toCharArray()); @@ -118,6 +118,7 @@ public class CamelConfiguration extends RouteBuilder { .apiContextPath("api-doc").apiVendorExtension(true).apiProperty("api.title", "Clamp Rest API") .apiProperty("api.version", ClampVersioning.getCldsVersionFromProps()) .apiProperty("base.path", "/restservices/clds/"); + // camelContext.setTracing(true); configureDefaultSslProperties(); diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java index 44228b22..16a6a748 100644 --- a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java +++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java @@ -352,7 +352,7 @@ public class CldsDao { } /** - * Helper method to setup the base template properties + * Helper method to setup the base template properties. * * @param template * the template @@ -474,7 +474,7 @@ public class CldsDao { } /** - * Helper method to setup the event prop to the CldsEvent class + * Helper method to setup the event prop to the CldsEvent class. * * @param event * the clds event @@ -742,12 +742,13 @@ public class CldsDao { String dictElementShortName) { SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); List<CldsDictionaryItem> dictionaryItems = new ArrayList<>(); - String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " + - "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " + - "de.modified_by, de.timestamp FROM dictionary_elements de, " + - "dictionary d WHERE de.dictionary_id = d.dictionary_id") + String dictionarySql = new StringBuilder("SELECT de.dict_element_id, de.dictionary_id, de.dict_element_name, " + + "de.dict_element_short_name, de.dict_element_description, de.dict_element_type, de.created_by, " + + "de.modified_by, de.timestamp FROM dictionary_elements de, " + + "dictionary d WHERE de.dictionary_id = d.dictionary_id") .append((dictionaryId != null) ? (" AND d.dictionary_id = '" + dictionaryId + "'") : "") - .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + "'") : "") + .append((dictElementShortName != null) ? (" AND de.dict_element_short_name = '" + dictElementShortName + + "'") : "") .append((dictionaryName != null) ? (" AND dictionary_name = '" + dictionaryName + "'") : "").toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); @@ -780,8 +781,8 @@ public class CldsDao { */ public Map<String, String> getDictionaryElementsByType(String dictionaryElementType) { Map<String, String> dictionaryItems = new HashMap<>(); - String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " + - "FROM dictionary_elements WHERE dict_element_type = '") + String dictionarySql = new StringBuilder("SELECT dict_element_name, dict_element_short_name " + + "FROM dictionary_elements WHERE dict_element_type = '") .append(dictionaryElementType).append("'").toString(); List<Map<String, Object>> rows = jdbcTemplateObject.queryForList(dictionarySql); diff --git a/src/main/java/org/onap/clamp/clds/model/dcae/DcaeInventoryResponse.java b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeInventoryResponse.java index 74582a86..97245066 100644 --- a/src/main/java/org/onap/clamp/clds/model/dcae/DcaeInventoryResponse.java +++ b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeInventoryResponse.java @@ -24,12 +24,17 @@ package org.onap.clamp.clds.model.dcae; +import com.google.gson.annotations.Expose; + /** * This class maps the DCAE inventory answer to a nice pojo. */ public class DcaeInventoryResponse { + @Expose private String typeName; + + @Expose private String typeId; public String getTypeName() { diff --git a/src/main/java/org/onap/clamp/clds/model/dcae/DcaeLinks.java b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeLinks.java new file mode 100644 index 00000000..368e1b8e --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeLinks.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model.dcae; + +import com.google.gson.annotations.Expose; + +public class DcaeLinks { + @Expose + private String self; + @Expose + private String status; + @Expose + private String uninstall; + + public String getSelf() { + return self; + } + + public void setSelf(String self) { + this.self = self; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getUninstall() { + return uninstall; + } + + public void setUninstall(String uninstall) { + this.uninstall = uninstall; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/model/dcae/DcaeOperationStatusResponse.java b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeOperationStatusResponse.java new file mode 100644 index 00000000..aee7d061 --- /dev/null +++ b/src/main/java/org/onap/clamp/clds/model/dcae/DcaeOperationStatusResponse.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.clds.model.dcae; + +import com.google.gson.annotations.Expose; + +/** + * This class maps the DCAE deployment handler response to a nice pojo. + */ +public class DcaeOperationStatusResponse { + + @Expose + private String operationType; + + @Expose + private String status; + + @Expose + private String requestId; + + @Expose + private String error; + + @Expose + private DcaeLinks links; + + public String getOperationType() { + return operationType; + } + + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public DcaeLinks getLinks() { + return links; + } + + public void setLinks(DcaeLinks links) { + this.links = links; + } + +} 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 e81cc15f..63a91331 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java @@ -5,6 +5,8 @@ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -203,7 +205,7 @@ public class CldsService extends SecureServiceBase { public List<CldsMonitoringDetails> getCldsDetails() { util.entering(request, "CldsService: GET model details"); Date startTime = new Date(); - List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); + final List<CldsMonitoringDetails> cldsMonitoringDetailsList = cldsDao.getCldsMonitoringDetails(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET cldsDetails completed"); @@ -223,7 +225,7 @@ public class CldsService extends SecureServiceBase { LoggingUtils.setTimeContext(startTime, new Date()); CldsInfoProvider cldsInfoProvider = new CldsInfoProvider(this); - CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo(); + final CldsInfo cldsInfo = cldsInfoProvider.getCldsInfo(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); @@ -245,7 +247,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET bpmnText for modelName={}", modelName); - CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); + final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model bpmn completed"); @@ -266,7 +268,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET imageText for modelName={}", modelName); - CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); + final CldsModel model = CldsModel.retrieve(cldsDao, modelName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model image completed"); @@ -282,7 +284,7 @@ public class CldsService extends SecureServiceBase { */ public CldsModel getModel(String modelName) { util.entering(request, "CldsService: GET model"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadCl); logger.debug("GET model for modelName={}", modelName); CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false); @@ -323,7 +325,7 @@ public class CldsService extends SecureServiceBase { */ public CldsModel putModel(String modelName, CldsModel cldsModel) { util.entering(request, "CldsService: PUT model"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionUpdateCl); isAuthorizedForVf(cldsModel); logger.info("PUT model for modelName={}", modelName); @@ -350,7 +352,7 @@ public class CldsService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadCl); logger.info("GET list of model names"); - List<ValueItem> names = cldsDao.getModelNames(); + final List<ValueItem> names = cldsDao.getModelNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET model names completed"); @@ -409,11 +411,11 @@ public class CldsService extends SecureServiceBase { model.save(cldsDao, getUserId()); // get vars and format if necessary - String prop = model.getPropText(); - String bpmn = model.getBpmnText(); - String docText = model.getDocText(); - String controlName = model.getControlName(); - String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); + final String prop = model.getPropText(); + final String bpmn = model.getBpmnText(); + final String docText = model.getDocText(); + final String controlName = model.getControlName(); + final String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmn); logger.info("PUT bpmnJson={}", bpmnJson); // Test flag coming from UI or from Clamp config boolean isTest = Boolean.parseBoolean(test) @@ -471,7 +473,7 @@ public class CldsService extends SecureServiceBase { */ public String postDcaeEvent(String test, DcaeEvent dcaeEvent) { util.entering(request, "CldsService: Post dcae event"); - Date startTime = new Date(); + final Date startTime = new Date(); String userid = null; // TODO: allow auth checking to be turned off by removing the permission // type property diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java index f60c6383..d107731b 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java @@ -5,6 +5,8 @@ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -79,7 +81,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET bpmnText for templateName=" + templateName); - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template bpmn completed"); @@ -100,7 +102,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET imageText for templateName=" + templateName); - CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); + final CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template image completed"); @@ -116,7 +118,7 @@ public class CldsTemplateService extends SecureServiceBase { */ public CldsTemplate getTemplate(String templateName) { util.entering(request, "CldsTemplateService: GET template"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET model for templateName=" + templateName); CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false); @@ -137,7 +139,7 @@ public class CldsTemplateService extends SecureServiceBase { */ public CldsTemplate putTemplate(String templateName, CldsTemplate cldsTemplate) { util.entering(request, "CldsTemplateService: PUT template"); - Date startTime = new Date(); + final Date startTime = new Date(); isAuthorized(permissionUpdateTemplate); logger.info("PUT Template for templateName=" + templateName); logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText()); @@ -162,7 +164,7 @@ public class CldsTemplateService extends SecureServiceBase { Date startTime = new Date(); isAuthorized(permissionReadTemplate); logger.info("GET list of template names"); - List<ValueItem> names = cldsDao.getTemplateNames(); + final List<ValueItem> names = cldsDao.getTemplateNames(); // audit log LoggingUtils.setTimeContext(startTime, new Date()); auditLogger.info("GET template names completed"); diff --git a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java index f2c75ead..81bafef4 100644 --- a/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java +++ b/src/main/java/org/onap/clamp/clds/service/CldsToscaService.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -84,7 +86,7 @@ public class CldsToscaService extends SecureServiceBase { * type */ public ResponseEntity<?> parseToscaModelAndSave(String toscaModelName, CldsToscaModel cldsToscaModel) { - Date startTime = new Date(); + final Date startTime = new Date(); LoggingUtils.setRequestContext("CldsToscaService: Parse Tosca model and save", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionUpdateTosca); @@ -107,7 +109,7 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get All tosca models", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getAllToscaModels()).get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get All tosca models success", this.getClass().getName()); auditLogger.info("Get All tosca models"); @@ -128,7 +130,8 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by model name", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByName(toscaModelName)) + .get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get tosca models by model name success", this.getClass().getName()); auditLogger.info("GET tosca models by model name completed"); @@ -140,6 +143,7 @@ public class CldsToscaService extends SecureServiceBase { * from the database. * * @param policyType + * The type of the policy * @return clds tosca model - CLDS tosca model for a given policy type */ public CldsToscaModel getToscaModelsByPolicyType(String policyType) { @@ -147,7 +151,8 @@ public class CldsToscaService extends SecureServiceBase { LoggingUtils.setRequestContext("CldsToscaService: Get tosca models by policyType", getPrincipalName()); // TODO revisit based on new permissions isAuthorized(permissionReadTosca); - List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)).get(); + final List<CldsToscaModel> cldsToscaModels = Optional.ofNullable(cldsDao.getToscaModelByPolicyType(policyType)) + .get(); LoggingUtils.setTimeContext(startTime, new Date()); LoggingUtils.setResponseContext("0", "Get tosca models by policyType success", this.getClass().getName()); auditLogger.info("GET tosca models by policyType completed"); diff --git a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java index f08bf7b2..85aae0a5 100644 --- a/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/CryptoUtils.java @@ -162,7 +162,7 @@ public final class CryptoUtils { private static SecretKeySpec readSecretKeySpec(String propertiesFileName) { Properties props = new Properties(); try { - //Workaround fix to make encryption key configurable + // Workaround fix to make encryption key configurable // System environment variable takes precedence for over clds/key.properties String encryptionKey = System.getenv(AES_ENCRYPTION_KEY); if(encryptionKey != null && encryptionKey.trim().length() > 0) { diff --git a/src/main/java/org/onap/clamp/clds/util/XmlTools.java b/src/main/java/org/onap/clamp/clds/util/XmlTools.java index a812fa12..a7d4ed9f 100644 --- a/src/main/java/org/onap/clamp/clds/util/XmlTools.java +++ b/src/main/java/org/onap/clamp/clds/util/XmlTools.java @@ -24,6 +24,7 @@ package org.onap.clamp.clds.util; import java.io.StringWriter; +import javax.xml.XMLConstants; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; @@ -39,6 +40,12 @@ import org.w3c.dom.Document; public class XmlTools { /** + * Private constructor to avoid creating instances of util class. + */ + private XmlTools(){ + } + + /** * Transforms document to XML string. * * @param doc XML document @@ -47,6 +54,7 @@ public class XmlTools { public static String exportXmlDocumentAsString(Document doc) { try { TransformerFactory tf = TransformerFactory.newInstance(); + tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java index 1ece484b..7a1f122e 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/AwtUtils.java @@ -40,6 +40,7 @@ public class AwtUtils { private static final int FONT_STYLE = Font.PLAIN; private static final String FONT_FACE = "SansSerif"; private static final Color TRANSPARENT = new Color(0.0f, 0.0f, 0.0f, 0.0f); + private static final int TEXT_PADDING = 5; private AwtUtils() { } @@ -51,7 +52,7 @@ public class AwtUtils { g2d.setColor(TRANSPARENT); g2d.fill(rect); g2d.setColor(oldColor); - addText(g2d, text, point.x + width / 2, point.y + height / 2); + addText(g2d, text, rect); } static void drawArrow(Graphics2D g2d, Point from, Point to, int lineThickness) { @@ -61,17 +62,30 @@ public class AwtUtils { g2d.fillPolygon(new int[]{x2 - ARROW_W, x2 - ARROW_W, x2}, new int[]{to.y - ARROW_H, to.y + ARROW_H, to.y}, 3); } - private static void addText(Graphics2D g2d, String text, int abs, int ord) { + private static void addText(Graphics2D g2d, String text, Rectangle rect) { + int textBoundingBoxLimit = rect.width - 2* TEXT_PADDING; Font font = new Font(FONT_FACE, FONT_STYLE, FONT_SIZE); - g2d.setFont(font); - - FontMetrics fm1 = g2d.getFontMetrics(); - int w1 = fm1.stringWidth(text); - int x1 = abs - (w1 / 2); + font = scaleFontToFit(text, textBoundingBoxLimit, g2d, font); + Font oldFont = g2d.getFont(); g2d.setFont(font); g2d.setColor(Color.BLACK); - g2d.drawString(text, x1, ord); + FontMetrics fm1 = g2d.getFontMetrics(); + float x1 = rect.x + (float)(rect.width - fm1.stringWidth(text)) / 2; + float y1 = rect.y + (float)(rect.height - fm1.getHeight()) / 2 + fm1.getAscent(); + g2d.drawString(text, x1, y1); + + g2d.setFont(oldFont); + } + + private static Font scaleFontToFit(String text, int width, Graphics2D g2d, Font pFont) { + float fontSize = pFont.getSize(); + float fWidth = g2d.getFontMetrics(pFont).stringWidth(text); + if(fWidth <= width) { + return pFont; + } + fontSize = ((float)width / fWidth) * fontSize; + return pFont.deriveFont(fontSize); } } diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java b/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java index ce21c4cf..5d37701f 100644 --- a/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/ImageBuilder.java @@ -36,6 +36,7 @@ public class ImageBuilder { public static final int POLICY_LINE_RATIO = 2; public static final int COLLECTOR_LINE_RATIO = 6; public static final float MS_LINE_TO_HEIGHT_RATIO = 0.75f; + public static final float ARROW_TO_BASELINE_RATIO = 0.75f; private Point currentPoint; private final int baseLength; @@ -68,7 +69,7 @@ public class ImageBuilder { ImageBuilder arrow() { String dataElementId = "Arrow-" + UUID.randomUUID().toString(); - Point to = new Point(currentPoint.x + baseLength, currentPoint.y); + Point to = new Point(currentPoint.x + (int)(baseLength*ARROW_TO_BASELINE_RATIO), currentPoint.y); AwtUtils.drawArrow(g2d, currentPoint, to, LINE_THICKNESS); documentBuilder.pushChangestoDocument(g2d, dataElementId); currentPoint = to; diff --git a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java index d88a17e8..ebb267f7 100755 --- a/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java +++ b/src/main/java/org/onap/clamp/clds/util/drawing/Painter.java @@ -43,6 +43,7 @@ public class Painter { private static final int THICK_LINE = 4; private static final double RECT_RATIO = 3.0 / 2.0; private static final int CIRCLE_RADIUS = 17; + private static final int MINIMUM_BASE_LENGTH = 120; /** * Constructor to create instance of Painter. @@ -60,6 +61,9 @@ public class Painter { int numOfRectangles = 2 + microServices.size(); int numOfArrows = numOfRectangles + 1; int baseLength = (canvasSize - 2 * CIRCLE_RADIUS) / (numOfArrows + numOfRectangles); + if(baseLength < MINIMUM_BASE_LENGTH) { + baseLength = MINIMUM_BASE_LENGTH; + } int rectHeight = (int) (baseLength / RECT_RATIO); adjustGraphics2DProperties(); diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index 6de2863e..2393f249 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -23,18 +23,16 @@ package org.onap.clamp.loop; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import java.io.Serializable; -import java.util.ArrayList; +import java.util.HashMap; import java.util.HashSet; -import java.util.List; +import java.util.Map; import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import javax.persistence.CascadeType; import javax.persistence.Column; @@ -47,14 +45,17 @@ import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; -import javax.persistence.OrderBy; import javax.persistence.Table; import javax.persistence.Transient; +import org.hibernate.annotations.SortNatural; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; +import org.onap.clamp.loop.components.external.DcaeComponent; +import org.onap.clamp.loop.components.external.ExternalComponent; +import org.onap.clamp.loop.components.external.PolicyComponent; import org.onap.clamp.loop.log.LoopLog; import org.onap.clamp.policy.microservice.MicroServicePolicy; import org.onap.clamp.policy.operational.OperationalPolicy; @@ -69,9 +70,6 @@ public class Loop implements Serializable { */ private static final long serialVersionUID = -286522707701388642L; - @Transient - private static final EELFLogger logger = EELFManager.getInstance().getLogger(Loop.class); - @Id @Expose @Column(nullable = false, name = "name", unique = true) @@ -111,6 +109,10 @@ public class Loop implements Serializable { private LoopState lastComputedState; @Expose + @Transient + private final Map<String, ExternalComponent> components = new HashMap<>(); + + @Expose @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop") private Set<OperationalPolicy> operationalPolicies = new HashSet<>(); @@ -121,10 +123,16 @@ public class Loop implements Serializable { @Expose @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "loop") - @OrderBy("id DESC") - private Set<LoopLog> loopLogs = new HashSet<>(); + @SortNatural + private SortedSet<LoopLog> loopLogs = new TreeSet<>(); + + private void initializeExternalComponents() { + this.addComponent(new PolicyComponent()); + this.addComponent(new DcaeComponent()); + } public Loop() { + initializeExternalComponents(); } /** @@ -136,6 +144,7 @@ public class Loop implements Serializable { this.blueprint = blueprint; this.lastComputedState = LoopState.DESIGN; this.globalPropertiesJson = new JsonObject(); + initializeExternalComponents(); } public String getName() { @@ -214,7 +223,7 @@ public class Loop implements Serializable { return loopLogs; } - void setLoopLogs(Set<LoopLog> loopLogs) { + void setLoopLogs(SortedSet<LoopLog> loopLogs) { this.loopLogs = loopLogs; } @@ -228,9 +237,9 @@ public class Loop implements Serializable { microServicePolicy.getUsedByLoops().add(this); } - void addLog(LoopLog log) { - loopLogs.add(log); + public void addLog(LoopLog log) { log.setLoop(this); + this.loopLogs.add(log); } public String getDcaeBlueprintId() { @@ -249,6 +258,18 @@ public class Loop implements Serializable { this.modelPropertiesJson = modelPropertiesJson; } + public Map<String, ExternalComponent> getComponents() { + return components; + } + + public ExternalComponent getComponent(String componentName) { + return this.components.get(componentName); + } + + public void addComponent(ExternalComponent component) { + this.components.put(component.getComponentName(), component); + } + /** * Generate the loop name. * @@ -269,47 +290,6 @@ public class Loop implements Serializable { return buffer.toString().replace('.', '_').replaceAll(" ", ""); } - /** - * Generates the Json that must be sent to policy to add all policies to Active - * PDP group. - * - * @return The json, payload to send - */ - public String createPoliciesPayloadPdpGroup() { - JsonObject jsonObject = new JsonObject(); - JsonArray jsonArray = new JsonArray(); - jsonObject.add("policies", jsonArray); - - for (String policyName : this.listPolicyNamesPdpGroup()) { - JsonObject policyNode = new JsonObject(); - jsonArray.add(policyNode); - policyNode.addProperty("policy-id", policyName); - } - String payload = new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject); - logger.info("PdpGroup policy payload: " + payload); - return payload; - } - - /** - * Generates the list of policy names that must be send/remove to/from active - * PDP group. - * - * @return A list of policy names - */ - public List<String> listPolicyNamesPdpGroup() { - List<String> policyNamesList = new ArrayList<>(); - for (OperationalPolicy opPolicy : this.getOperationalPolicies()) { - policyNamesList.add(opPolicy.getName()); - for (String guardName : opPolicy.createGuardPolicyPayloads().keySet()) { - policyNamesList.add(guardName); - } - } - for (MicroServicePolicy microServicePolicy : this.getMicroServicePolicies()) { - policyNamesList.add(microServicePolicy.getName()); - } - return policyNamesList; - } - @Override public int hashCode() { final int prime = 31; diff --git a/src/main/java/org/onap/clamp/loop/LoopOperation.java b/src/main/java/org/onap/clamp/loop/LoopOperation.java deleted file mode 100644 index 87effa5f..00000000 --- a/src/main/java/org/onap/clamp/loop/LoopOperation.java +++ /dev/null @@ -1,265 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END============================================ - * =================================================================== - * - */ - -package org.onap.clamp.loop; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.util.Iterator; -import java.util.Set; -import java.util.UUID; - -import org.apache.camel.Exchange; -import org.apache.camel.Message; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; -import org.onap.clamp.policy.operational.OperationalPolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -/** - * Closed loop operations. - */ -@Component -public class LoopOperation { - - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopOperation.class); - protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); - private static final String DCAE_LINK_FIELD = "links"; - private static final String DCAE_STATUS_FIELD = "status"; - private static final String DCAE_SERVICETYPE_ID = "serviceTypeId"; - private static final String DCAE_INPUTS = "inputs"; - private static final String DCAE_DEPLOYMENT_PREFIX = "CLAMP_"; - private static final String DEPLOYMENT_PARA = "dcaeDeployParameters"; - private final LoopService loopService; - - public enum TempLoopState { - NOT_SUBMITTED, SUBMITTED, DEPLOYED, NOT_DEPLOYED, PROCESSING, IN_ERROR; - } - - /** - * The constructor. - * - * @param loopService - * The loop service - * @param refProp - * The clamp properties - */ - @Autowired - public LoopOperation(LoopService loopService) { - this.loopService = loopService; - } - - /** - * Get the payload used to send the deploy closed loop request. - * - * @param loop - * The loop - * @return The payload used to send deploy closed loop request - * @throws IOException - * IOException - */ - public String getDeployPayload(Loop loop) throws IOException { - JsonObject globalProp = loop.getGlobalPropertiesJson(); - JsonObject deploymentProp = globalProp.getAsJsonObject(DEPLOYMENT_PARA); - - String serviceTypeId = loop.getDcaeBlueprintId(); - - JsonObject rootObject = new JsonObject(); - rootObject.addProperty(DCAE_SERVICETYPE_ID, serviceTypeId); - if (deploymentProp != null) { - rootObject.add(DCAE_INPUTS, deploymentProp); - } - String apiBodyString = rootObject.toString(); - logger.info("Dcae api Body String - " + apiBodyString); - - return apiBodyString; - } - - /** - * Get the deployment id. - * - * @param loop - * The loop - * @return The deployment id - * @throws IOException - * IOException - */ - public String getDeploymentId(Loop loop) { - // Set the deploymentId if not present yet - String deploymentId = ""; - // If model is already deployed then pass same deployment id - if (loop.getDcaeDeploymentId() != null && !loop.getDcaeDeploymentId().isEmpty()) { - deploymentId = loop.getDcaeDeploymentId(); - } else { - deploymentId = DCAE_DEPLOYMENT_PREFIX + UUID.randomUUID(); - } - return deploymentId; - } - - /** - * Update the loop info. - * - * @param camelExchange - * The camel exchange - * @param loop - * The loop - * @param deploymentId - * The deployment id - * @throws ParseException - * The parse exception - */ - public void updateLoopInfo(Exchange camelExchange, Loop loop, String deploymentId) throws ParseException { - Message in = camelExchange.getIn(); - String msg = in.getBody(String.class); - - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(msg); - JSONObject jsonObj = (JSONObject) obj0; - - JSONObject linksObj = (JSONObject) jsonObj.get(DCAE_LINK_FIELD); - String statusUrl = (String) linksObj.get(DCAE_STATUS_FIELD); - - if (deploymentId == null) { - loop.setDcaeDeploymentId(null); - loop.setDcaeDeploymentStatusUrl(null); - } else { - loop.setDcaeDeploymentId(deploymentId); - loop.setDcaeDeploymentStatusUrl(statusUrl.replaceAll("http:", "http4:").replaceAll("https:", "https4:")); - } - loopService.saveOrUpdateLoop(loop); - } - - /** - * Get the Closed Loop status based on the reply from Policy. - * - * @param statusCode - * The status code - * @return The state based on policy response - * @throws ParseException - * The parse exception - */ - public String analysePolicyResponse(int statusCode) { - if (statusCode == 200) { - return TempLoopState.SUBMITTED.toString(); - } else if (statusCode == 404) { - return TempLoopState.NOT_SUBMITTED.toString(); - } - return TempLoopState.IN_ERROR.toString(); - } - - /** - * Get the name of the first Operational policy. - * - * @param loop - * The closed loop - * @return The name of the first operational policy - */ - public String getOperationalPolicyName(Loop loop) { - Set<OperationalPolicy> opSet = loop.getOperationalPolicies(); - Iterator<OperationalPolicy> iterator = opSet.iterator(); - while (iterator.hasNext()) { - OperationalPolicy policy = iterator.next(); - return policy.getName(); - } - return null; - } - - /** - * Get the Closed Loop status based on the reply from DCAE. - * - * @param camelExchange - * The camel exchange - * @return The state based on DCAE response - * @throws ParseException - * The parse exception - */ - public String analyseDcaeResponse(Exchange camelExchange, Integer statusCode) throws ParseException { - if (statusCode == null) { - return TempLoopState.NOT_DEPLOYED.toString(); - } - if (statusCode == 200) { - Message in = camelExchange.getIn(); - String msg = in.getBody(String.class); - - JSONParser parser = new JSONParser(); - Object obj0 = parser.parse(msg); - JSONObject jsonObj = (JSONObject) obj0; - - String opType = (String) jsonObj.get("operationType"); - String status = (String) jsonObj.get("status"); - - // status = processing/successded/failed - if (status.equals("succeeded")) { - if (opType.equals("install")) { - return TempLoopState.DEPLOYED.toString(); - } else if (opType.equals("uninstall")) { - return TempLoopState.NOT_DEPLOYED.toString(); - } - } else if (status.equals("processing")) { - return TempLoopState.PROCESSING.toString(); - } - } else if (statusCode == 404) { - return TempLoopState.NOT_DEPLOYED.toString(); - } - return TempLoopState.IN_ERROR.toString(); - } - - /** - * Update the status of the closed loop based on the response from Policy and - * DCAE. - * - * @param loop - * The closed loop - * @param policyState - * The state get from Policy - * @param dcaeState - * The state get from DCAE - * @throws ParseException - * The parse exception - */ - public LoopState updateLoopStatus(Loop loop, TempLoopState policyState, TempLoopState dcaeState) { - LoopState clState = LoopState.IN_ERROR; - if (policyState == TempLoopState.SUBMITTED) { - if (dcaeState == TempLoopState.DEPLOYED) { - clState = LoopState.DEPLOYED; - } else if (dcaeState == TempLoopState.PROCESSING) { - clState = LoopState.WAITING; - } else if (dcaeState == TempLoopState.NOT_DEPLOYED) { - clState = LoopState.SUBMITTED; - } - } else if (policyState == TempLoopState.NOT_SUBMITTED) { - if (dcaeState == TempLoopState.NOT_DEPLOYED) { - clState = LoopState.DESIGN; - } - } - loop.setLastComputedState(clState); - loopService.saveOrUpdateLoop(loop); - return clState; - } - -} diff --git a/src/main/java/org/onap/clamp/loop/LoopService.java b/src/main/java/org/onap/clamp/loop/LoopService.java index 4c139225..d1ab0e39 100644 --- a/src/main/java/org/onap/clamp/loop/LoopService.java +++ b/src/main/java/org/onap/clamp/loop/LoopService.java @@ -71,6 +71,17 @@ public class LoopService { loopsRepository.deleteById(loopName); } + public void updateDcaeDeploymentFields(Loop loop, String deploymentId, String deploymentUrl) { + loop.setDcaeDeploymentId(deploymentId); + loop.setDcaeDeploymentStatusUrl(deploymentUrl); + loopsRepository.save(loop); + } + + public void updateLoopState(Loop loop, String newState) { + loop.setLastComputedState(LoopState.valueOf(newState)); + loopsRepository.save(loop); + } + Loop updateAndSaveOperationalPolicies(String loopName, List<OperationalPolicy> newOperationalPolicies) { Loop loop = findClosedLoopByName(loopName); Set<OperationalPolicy> newPolicies = operationalPolicyService.updatePolicies(loop, newOperationalPolicies); @@ -93,9 +104,7 @@ public class LoopService { MicroServicePolicy updateMicroservicePolicy(String loopName, MicroServicePolicy newMicroservicePolicy) { Loop loop = findClosedLoopByName(loopName); - MicroServicePolicy newPolicies = microservicePolicyService.getAndUpdateMicroServicePolicy(loop, - newMicroservicePolicy); - return newPolicies; + return microservicePolicyService.getAndUpdateMicroServicePolicy(loop, newMicroservicePolicy); } private Loop findClosedLoopByName(String loopName) { diff --git a/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java b/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java new file mode 100644 index 00000000..35b3a454 --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/components/external/DcaeComponent.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.loop.components.external; + +import com.google.gson.JsonObject; + +import java.util.UUID; + +import org.apache.camel.Exchange; +import org.onap.clamp.clds.model.dcae.DcaeOperationStatusResponse; +import org.onap.clamp.clds.util.JsonUtils; +import org.onap.clamp.loop.Loop; + +public class DcaeComponent extends ExternalComponent { + + private static final String DCAE_DEPLOYMENT_PREFIX = "CLAMP_"; + private static final String DEPLOYMENT_PARAMETER = "dcaeDeployParameters"; + private static final String DCAE_SERVICETYPE_ID = "serviceTypeId"; + private static final String DCAE_INPUTS = "inputs"; + + public static final ExternalComponentState BLUEPRINT_DEPLOYED = new ExternalComponentState("BLUEPRINT_DEPLOYED", + "The DCAE blueprint has been found in the DCAE inventory but not yet instancianted for this loop"); + public static final ExternalComponentState PROCESSING_MICROSERVICE_INSTALLATION = new ExternalComponentState( + "PROCESSING_MICROSERVICE_INSTALLATION", + "Clamp has requested DCAE to install the microservices defined in the DCAE blueprint and it's currently processing the request"); + public static final ExternalComponentState MICROSERVICE_INSTALLATION_FAILED = new ExternalComponentState( + "MICROSERVICE_INSTALLATION_FAILED", + "Clamp has requested DCAE to install the microservices defined in the DCAE blueprint and it failed"); + public static final ExternalComponentState MICROSERVICE_INSTALLED_SUCCESSFULLY = new ExternalComponentState( + "MICROSERVICE_INSTALLED_SUCCESSFULLY", + "Clamp has requested DCAE to install the DCAE blueprint and it has been installed successfully"); + public static final ExternalComponentState PROCESSING_MICROSERVICE_UNINSTALLATION = new ExternalComponentState( + "PROCESSING_MICROSERVICE_UNINSTALLATION", + "Clamp has requested DCAE to uninstall the microservices defined in the DCAE blueprint and it's currently processing the request"); + public static final ExternalComponentState MICROSERVICE_UNINSTALLATION_FAILED = new ExternalComponentState( + "MICROSERVICE_UNINSTALLATION_FAILED", + "Clamp has requested DCAE to uninstall the microservices defined in the DCAE blueprint and it failed"); + public static final ExternalComponentState MICROSERVICE_UNINSTALLED_SUCCESSFULLY = new ExternalComponentState( + "MICROSERVICE_UNINSTALLED_SUCCESSFULLY", + "Clamp has requested DCAE to uninstall the DCAE blueprint and it has been uninstalled successfully"); + public static final ExternalComponentState IN_ERROR = new ExternalComponentState("IN_ERROR", + "There was an error during the request done to DCAE, look at the logs or try again"); + + public DcaeComponent() { + super(BLUEPRINT_DEPLOYED); + } + + @Override + public String getComponentName() { + return "DCAE"; + } + + public static DcaeOperationStatusResponse convertDcaeResponse(String responseBody) { + if (responseBody != null && !responseBody.isEmpty()) { + return JsonUtils.GSON_JPA_MODEL.fromJson(responseBody, DcaeOperationStatusResponse.class); + } else { + return null; + } + } + + /** + * Generate the deployment id, it's random + * + * @return The deployment id + */ + public static String generateDeploymentId() { + return DCAE_DEPLOYMENT_PREFIX + UUID.randomUUID(); + } + + /** + * This method prepare the url returned by DCAE to check the status if fine. + * + * @param statusUrl + * @return the Right Url modified if needed + */ + public static String getStatusUrl(DcaeOperationStatusResponse dcaeResponse) { + return dcaeResponse.getLinks().getStatus().replaceAll("http:", "http4:").replaceAll("https:", "https4:"); + } + + /** + * Return the deploy payload for DCAE. + * + * @param loop + * The loop object + * @return The payload used to send deploy closed loop request + */ + public static String getDeployPayload(Loop loop) { + JsonObject globalProp = loop.getGlobalPropertiesJson(); + JsonObject deploymentProp = globalProp.getAsJsonObject(DEPLOYMENT_PARAMETER); + + String serviceTypeId = loop.getDcaeBlueprintId(); + + JsonObject rootObject = new JsonObject(); + rootObject.addProperty(DCAE_SERVICETYPE_ID, serviceTypeId); + if (deploymentProp != null) { + rootObject.add(DCAE_INPUTS, deploymentProp); + } + return rootObject.toString(); + } + + /** + * Return the uninstallation payload for DCAE. + * + * @param loop + * The loop object + * @return The payload in string (json) + */ + public static String getUndeployPayload(Loop loop) { + JsonObject rootObject = new JsonObject(); + rootObject.addProperty(DCAE_SERVICETYPE_ID, loop.getDcaeBlueprintId()); + return rootObject.toString(); + } + + @Override + public ExternalComponentState computeState(Exchange camelExchange) { + + DcaeOperationStatusResponse dcaeResponse = (DcaeOperationStatusResponse) camelExchange.getIn().getExchange() + .getProperty("dcaeResponse"); + + if (dcaeResponse == null) { + setState(BLUEPRINT_DEPLOYED); + } else if (dcaeResponse.getOperationType().equals("install") && dcaeResponse.getStatus().equals("succeeded")) { + setState(MICROSERVICE_INSTALLED_SUCCESSFULLY); + } else if (dcaeResponse.getOperationType().equals("install") && dcaeResponse.getStatus().equals("processing")) { + setState(PROCESSING_MICROSERVICE_INSTALLATION); + } else if (dcaeResponse.getOperationType().equals("install") && dcaeResponse.getStatus().equals("failed")) { + setState(MICROSERVICE_INSTALLATION_FAILED); + } else if (dcaeResponse.getOperationType().equals("uninstall") + && dcaeResponse.getStatus().equals("succeeded")) { + setState(MICROSERVICE_UNINSTALLED_SUCCESSFULLY); + } else if (dcaeResponse.getOperationType().equals("uninstall") + && dcaeResponse.getStatus().equals("processing")) { + setState(PROCESSING_MICROSERVICE_UNINSTALLATION); + } else if (dcaeResponse.getOperationType().equals("uninstall") && dcaeResponse.getStatus().equals("failed")) { + setState(MICROSERVICE_UNINSTALLATION_FAILED); + } else { + setState(IN_ERROR); + } + return this.getState(); + } +} diff --git a/src/main/java/org/onap/clamp/loop/components/external/ExternalComponent.java b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponent.java new file mode 100644 index 00000000..a8aae203 --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponent.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.loop.components.external; + +import com.google.gson.annotations.Expose; + +import org.apache.camel.Exchange; + +/** + * + * SHould be abstract but Gson can't instantiate it if it's an abstract + * + */ +public class ExternalComponent { + @Expose + private ExternalComponentState componentState; + + public void setState(ExternalComponentState newState) { + this.componentState = newState; + } + + public ExternalComponentState getState() { + return this.componentState; + } + + public String getComponentName() { + return null; + } + + public ExternalComponentState computeState(Exchange camelExchange) { + return new ExternalComponentState("INIT", "no desc"); + } + + public ExternalComponent(ExternalComponentState initialState) { + setState(initialState); + } + + public ExternalComponent() { + } +} diff --git a/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java new file mode 100644 index 00000000..6a723c24 --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/components/external/ExternalComponentState.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.loop.components.external; + +import com.google.gson.annotations.Expose; + +/** + * This is a transient state reflecting the deployment status of a component. It + * can be Policy, DCAE, or whatever... This is object is generic. Clamp is now + * stateless, so it triggers the different components at runtime, the status per + * component is stored here. + * + */ +public class ExternalComponentState { + @Expose + private String stateName; + @Expose + private String description; + + public ExternalComponentState(String stateName, String description) { + this.stateName = stateName; + this.description = description; + } + + public ExternalComponentState() { + } + + public String getStateName() { + return stateName; + } + + public String getDescription() { + return description; + } + + @Override + public String toString() { + return stateName; + } +} diff --git a/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java b/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java new file mode 100644 index 00000000..acd6115f --- /dev/null +++ b/src/main/java/org/onap/clamp/loop/components/external/PolicyComponent.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.loop.components.external; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Transient; + +import org.apache.camel.Exchange; +import org.onap.clamp.loop.Loop; +import org.onap.clamp.policy.microservice.MicroServicePolicy; +import org.onap.clamp.policy.operational.OperationalPolicy; + +public class PolicyComponent extends ExternalComponent { + + @Transient + private static final EELFLogger logger = EELFManager.getInstance().getLogger(PolicyComponent.class); + + public static final ExternalComponentState NOT_SENT = new ExternalComponentState("NOT_SENT", + "The policies defined have NOT yet been created on the policy engine"); + public static final ExternalComponentState SENT = new ExternalComponentState("SENT", + "The policies defined have been created but NOT deployed on the policy engine"); + public static final ExternalComponentState SENT_AND_DEPLOYED = new ExternalComponentState("SENT_AND_DEPLOYED", + "The policies defined have been created and deployed on the policy engine"); + public static final ExternalComponentState IN_ERROR = new ExternalComponentState("IN_ERROR", + "There was an error during the sending to policy, the policy engine may be corrupted or inconsistent"); + + public PolicyComponent() { + super(NOT_SENT); + } + + @Override + public String getComponentName() { + return "POLICY"; + } + + /** + * Generates the Json that must be sent to policy to add all policies to Active + * PDP group. + * + * @return The json, payload to send + */ + public static String createPoliciesPayloadPdpGroup(Loop loop) { + JsonObject jsonObject = new JsonObject(); + JsonArray jsonArray = new JsonArray(); + jsonObject.add("policies", jsonArray); + + for (String policyName : PolicyComponent.listPolicyNamesPdpGroup(loop)) { + JsonObject policyNode = new JsonObject(); + jsonArray.add(policyNode); + policyNode.addProperty("policy-id", policyName); + } + String payload = new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject); + logger.info("PdpGroup policy payload: " + payload); + return new GsonBuilder().setPrettyPrinting().create().toJson(jsonObject); + } + + /** + * Generates the list of policy names that must be send/remove to/from active + * PDP group. + * + * @return A list of policy names + */ + public static List<String> listPolicyNamesPdpGroup(Loop loop) { + List<String> policyNamesList = new ArrayList<>(); + for (OperationalPolicy opPolicy : loop.getOperationalPolicies()) { + policyNamesList.add(opPolicy.getName()); + for (String guardName : opPolicy.createGuardPolicyPayloads().keySet()) { + policyNamesList.add(guardName); + } + } + for (MicroServicePolicy microServicePolicy : loop.getMicroServicePolicies()) { + policyNamesList.add(microServicePolicy.getName()); + } + return policyNamesList; + } + + @Override + public ExternalComponentState computeState(Exchange camelExchange) { + boolean oneNotFound = (boolean) camelExchange.getIn().getExchange().getProperty("atLeastOnePolicyNotFound"); + boolean oneNotDeployed = (boolean) camelExchange.getIn().getExchange() + .getProperty("atLeastOnePolicyNotDeployed"); + + if (oneNotFound && oneNotDeployed) { + this.setState(NOT_SENT); + } else if (!oneNotFound && oneNotDeployed) { + this.setState(SENT); + } else if (!oneNotFound && !oneNotDeployed) { + this.setState(SENT_AND_DEPLOYED); + } else { + this.setState(IN_ERROR); + } + return this.getState(); + } +} diff --git a/src/main/java/org/onap/clamp/loop/log/LoopLog.java b/src/main/java/org/onap/clamp/loop/log/LoopLog.java index cea49571..3feff254 100644 --- a/src/main/java/org/onap/clamp/loop/log/LoopLog.java +++ b/src/main/java/org/onap/clamp/loop/log/LoopLog.java @@ -52,7 +52,7 @@ import org.onap.clamp.loop.Loop; */ @Entity @Table(name = "loop_logs") -public class LoopLog implements Serializable { +public class LoopLog implements Serializable, Comparable<LoopLog> { /** * The serial version ID. */ @@ -69,6 +69,10 @@ public class LoopLog implements Serializable { private LogType logType; @Expose + @Column(name = "log_component", nullable = false) + private String logComponent; + + @Expose @Column(name = "message", columnDefinition = "MEDIUMTEXT", nullable = false) private String message; @@ -83,10 +87,11 @@ public class LoopLog implements Serializable { public LoopLog() { } - public LoopLog(String message, LogType logType, Loop loop) { + public LoopLog(String message, LogType logType, String logComponent, Loop loop) { this.message = message; this.logType = logType; this.loop = loop; + this.logComponent = logComponent; } public Long getId() { @@ -129,6 +134,14 @@ public class LoopLog implements Serializable { this.logInstant = logInstant.truncatedTo(ChronoUnit.SECONDS); } + public String getLogComponent() { + return logComponent; + } + + public void setLogComponent(String logComponent) { + this.logComponent = logComponent; + } + @Override public int hashCode() { final int prime = 31; @@ -159,4 +172,18 @@ public class LoopLog implements Serializable { return true; } + @Override + public int compareTo(LoopLog arg0) { + // Reverse it, so that by default we have the latest + if (getId() == null) { + return 1; + } + if (arg0.getId() == null) { + return -1; + } + + return arg0.getId().compareTo(this.getId()); + + } + } diff --git a/src/main/java/org/onap/clamp/loop/log/LoopLogService.java b/src/main/java/org/onap/clamp/loop/log/LoopLogService.java index b02bc11c..d02d0b27 100644 --- a/src/main/java/org/onap/clamp/loop/log/LoopLogService.java +++ b/src/main/java/org/onap/clamp/loop/log/LoopLogService.java @@ -38,7 +38,11 @@ public class LoopLogService { } public void addLog(String message, String logType, Loop loop) { - repository.save(new LoopLog(message, LogType.valueOf(logType), loop)); + this.addLogForComponent(message, logType, "CLAMP", loop); + } + + public void addLogForComponent(String message, String logType, String component, Loop loop) { + loop.addLog(repository.save(new LoopLog(message, LogType.valueOf(logType), component, loop))); } public boolean isExisting(Long logId) { diff --git a/src/main/java/org/onap/clamp/util/PrincipalUtils.java b/src/main/java/org/onap/clamp/util/PrincipalUtils.java index d6b20f30..d6dfacbd 100644 --- a/src/main/java/org/onap/clamp/util/PrincipalUtils.java +++ b/src/main/java/org/onap/clamp/util/PrincipalUtils.java @@ -38,6 +38,12 @@ public class PrincipalUtils { private static SecurityContext securityContext = SecurityContextHolder.getContext(); /** + * Private constructor to avoid creating instances of util class. + */ + private PrincipalUtils(){ + } + + /** * Get the Full name. * * @return The user name diff --git a/src/main/resources/META-INF/resources/designer/modeler/dist/index.html b/src/main/resources/META-INF/resources/designer/modeler/dist/index.html index ab337de8..cd7d6668 100644 --- a/src/main/resources/META-INF/resources/designer/modeler/dist/index.html +++ b/src/main/resources/META-INF/resources/designer/modeler/dist/index.html @@ -59,15 +59,17 @@ <thead> <tr> <th><span align="left" class="text">Date</span></th> - <th><span align="center" class="text">Type</span></th> + <th><span align="left" class="text">Type</span></th> + <th><span align="left" class="text">Component</span></th> <th><span align="right" class="text">Log</span></th> </tr> </thead> <tbody> <tr ng-repeat="log in loop_logs" ng-class="{reverse: reverse}"> - <td width="20%">{{log.logInstant}}</td> + <td width="10%">{{log.logInstant}}</td> <td width="10%" ng-class="log.logType">{{log.logType}}</td> - <td width="70">{{log.message}}</td> + <td width="10%">{{log.logComponent}}</td> + <td width="70%">{{log.message}}</td> </tr> </tbody> </table> diff --git a/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js b/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js index 0cc5c38f..2b27a7fd 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js +++ b/src/main/resources/META-INF/resources/designer/scripts/CldsModelService.js @@ -41,32 +41,8 @@ app ToscaModelWindow(); } } - this.toggleDeploy = function(uiAction, modelName) { - var svcAction = uiAction.toLowerCase(); - var deployUrl = "/restservices/clds/v2/loop/" + svcAction + "Loop/" + modelName; - var def = $q.defer(); - var sets = []; - $http.put(deployUrl).success( - function(data) { - def.resolve(data); - alertService.alertMessage("Action Successful: " + svcAction, 1) - // update deploymentID, lastUpdatedStatus - setLastComputedState(data.lastComputedState); - setDeploymentStatusURL(data.dcaeDeploymentStatusUrl); - setDeploymentID(data.dcaeDeploymentId); - setStatus(data.lastComputedState); - enableDisableMenuOptions(); - }).error( - function(data) { - def.resolve(data); - alertService.alertMessage("Action Failure: " + svcAction, 2); - def.reject(svcAction + " not successful"); - }); - return def.promise; - } this.getModel = function(modelName) { var def = $q.defer(); - var sets = []; var svcUrl = "/restservices/clds/v2/loop/" + modelName; $http.get(svcUrl).success(function(data) { cl_props = data; @@ -79,7 +55,6 @@ app }; this.getSavedModel = function() { var def = $q.defer(); - var sets = []; var svcUrl = "/restservices/clds/v2/loop/getAllNames"; $http.get(svcUrl).success(function(data) { @@ -92,7 +67,6 @@ app }; this.processAction = function(uiAction, modelName) { var def = $q.defer(); - var sets = []; var svcAction = uiAction.toLowerCase(); var svcUrl = "/restservices/clds/v2/loop/" + svcAction + "/" + modelName; @@ -100,10 +74,6 @@ app function(data) { def.resolve(data); alertService.alertMessage("Action Successful: " + svcAction, 1) - // update deploymentID, lastUpdatedStatus - setLastComputedState(data.lastComputedState); - setDeploymentStatusURL(data.dcaeDeploymentStatusUrl); - setDeploymentID(data.dcaeDeploymentId); }).error( function(data) { def.resolve(data); @@ -116,7 +86,6 @@ app this.manageAction = function(modelName, typeId, typeName) { var def = $q.defer(); - var sets = []; var config = { url : "/restservices/clds/v1/clds/getDispatcherInfo", method : "GET", @@ -143,37 +112,34 @@ app }; this.refreshStatus = function(modelName) { var def = $q.defer(); - var sets = []; var svcUrl = "/restservices/clds/v2/loop/getstatus/" + modelName; $http.get(svcUrl).success(function(data) { + cl_props = data; setStatus(data.lastComputedState); def.resolve(data); }).error(function(data) { def.reject("Refresh Status not successful"); }); return def.promise; - enableDisableMenuOptions(); } function setStatus(status) { // apply color to status var statusColor = 'white'; if (status.trim() === "DESIGN") { statusColor = 'gray' - } else if (status.trim() === "DISTRIBUTED") { - statusColor = 'blue' } else if (status.trim() === "SUBMITTED") { + statusColor = 'blue' + } else if (status.trim() === "DEPLOYED") { + statusColor = 'blue' + } else if (status.trim() === "RUNNING") { statusColor = 'green' } else if (status.trim() === "STOPPED") { - statusColor = 'red' - } else if (status.trim() === "DELETING") { - statusColor = 'pink' - } else if (status.trim() === "ERROR") { statusColor = 'orange' - } else if (status.trim() === "UNKNOWN") { - statusColor = 'blue' - } else { - statusColor = null; - } + } else if (status.trim() === "IN_ERROR") { + statusColor = 'red' + } else if (status.trim() === "WAITING") { + statusColor = 'greenyellow' + } var statusMsg = '<span style="background-color:' + statusColor + ';-moz-border-radius: 50px; -webkit-border-radius: 50px; border-radius: 50px;"> ' @@ -185,6 +151,22 @@ app .append( '<span id="status_clds" style="position: absolute; left: 61%;top: 151px; font-size:20px;">Status: ' + statusMsg + '</span>'); + + var statusTable = '<table id="status_components_table" style="width:100%"><tr><th><span align="left" class="text">Component</span></th><th><span align="center" class="text">State</span></th><th><span align="right" class="text">Description</span></th></tr>'; + + $.each(cl_props['components'], function(componentIndex, componentValue) { + statusTable+='<tr><td>'+componentIndex+'</td>'; + statusTable+='<td>'+componentValue['componentState']['stateName']+'</td>'; + statusTable+='<td>'+componentValue['componentState']['description']+'</td></tr>'; + }); + statusTable+= '</table>'; + if ($("#status_components").length >= 1) + $("#status_components").remove(); + $("#activity_modeler") + .append( + '<span id="status_components" style="position: absolute; left: 61%;top: 191px; font-size:10px;">' + + statusTable + '</span>'); + } function manageCLImage(modelName) { getModelImage(modelName).then(function(pars) { @@ -203,13 +185,12 @@ app }, function(data) { }); } - enableDisableMenuOptions = function() { + function enableDisableMenuOptions () { enableDefaultMenu(); enableAllActionMenu(); } - getModelImage = function(modelName) { + function getModelImage(modelName) { var def = $q.defer(); - var sets = []; var svcUrl = "/restservices/clds/v2/loop/svgRepresentation/" + modelName; $http.get(svcUrl).success(function(data) { def.resolve(data); diff --git a/src/main/resources/META-INF/resources/designer/scripts/app.js b/src/main/resources/META-INF/resources/designer/scripts/app.js index 5597bd99..7dda8479 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/app.js +++ b/src/main/resources/META-INF/resources/designer/scripts/app.js @@ -388,7 +388,7 @@ function($scope, $rootScope, $timeout, dialogs) { }; $scope.propertyExplorerErrorMessage = function(msg) { - var dlg = dialogs.notify('Error', msg); + dialogs.notify('Error', msg); } $scope.activityModelling = function() { @@ -505,7 +505,8 @@ function($scope, $rootScope, $timeout, dialogs) { cldsModelService.processAction(uiAction, modelName).then(function(pars) { console.log("cldsPerformAction: pars=" + pars); - cldsModelService.getModel(modelName).then(function(pars) { + cldsModelService.refreshStatus(modelName).then(function(pars) { + console.log("refreshStatus: pars=" + pars); $rootScope.refreshLoopLog(); }, function(data) { }); @@ -514,9 +515,10 @@ function($scope, $rootScope, $timeout, dialogs) { }; $scope.refreshStatus = function() { var modelName = selected_model; - console.log("refreStatus modelName=" + modelName); + console.log("refreshStatus modelName=" + modelName); cldsModelService.refreshStatus(modelName).then(function(pars) { - console.log("refreStatus: pars=" + pars); + console.log("refreshStatus: pars=" + pars); + $rootScope.refreshLoopLog(); }, function(data) { }); @@ -547,7 +549,7 @@ function($scope, $rootScope, $timeout, dialogs) { 'Are you sure you want to deploy the closed loop?'); confirm.result.then(function() { - cldsToggleDeploy("deploy"); + $scope.cldsPerformAction("deploy"); }); }); }; @@ -557,24 +559,12 @@ function($scope, $rootScope, $timeout, dialogs) { + uiAction.toLowerCase() + ' the closed loop?'); dlg.result.then(function(btn) { - cldsToggleDeploy(uiAction.toLowerCase()); + $scope.cldsPerformAction(uiAction.toLowerCase()); }, function(btn) { }); }; - function cldsToggleDeploy(uiAction) { - console.log("cldsPerformAction: " + uiAction + " modelName=" - + selected_model); - cldsModelService.toggleDeploy(uiAction, selected_model).then( - function(pars) { - cldsModelService.getModel(selected_model).then(function(pars) { - $rootScope.refreshLoopLog(); - }, function(data) { - }); - }, function(data) { - }); - - } + $scope.ToscaModelWindow = function (tosca_model) { var dlg = dialogs.create('partials/portfolios/tosca_model_properties.html','ToscaModelCtrl',{closable:true,draggable:true},{size:'lg',keyboard: true,backdrop: 'static',windowClass: 'my-class'}); diff --git a/src/main/resources/META-INF/resources/designer/scripts/propertyController.js b/src/main/resources/META-INF/resources/designer/scripts/propertyController.js index a8aa83c0..0323529e 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/propertyController.js +++ b/src/main/resources/META-INF/resources/designer/scripts/propertyController.js @@ -91,30 +91,6 @@ function getMsUI(type) { return null; } -function getLastUpdatedStatus() { - return cl_props["lastComputedState"]; -} - -function setLastComputedState(status) { - cl_props["lastComputedState"] = status; -} - -function getDeploymentID() { - return cl_props["dcaeDeploymentId"]; -} - -function setDeploymentID(deploymentId) { - cl_props["dcaeDeploymentId"] = deploymentId; -} - -function getDeploymentStatusURL() { - return cl_props["dcaeDeploymentStatusUrl"]; -} - -function setDeploymentStatusURL(deploymentStatusURL) { - cl_props["dcaeDeploymentStatusUrl"] = deploymentStatusURL; -} - function getResourceDetailsVfProperty() { return cl_props["modelPropertiesJson"]["resourceDetails"]["VF"]; } @@ -127,4 +103,8 @@ function getLoopLogsArray() { return cl_props.loopLogs; } -module.exports = { getOperationalPolicyProperty,getGlobalProperty,getMsProperty,getMsUI,getLastUpdatedStatus,getDeploymentID,getDeploymentStatusURL,getResourceDetailsVfProperty,getResourceDetailsVfModuleProperty }; +function getComponentStates() { + return cl_props.components; +} + +module.exports = { getOperationalPolicyProperty,getGlobalProperty,getMsProperty,getMsUI,getResourceDetailsVfProperty,getResourceDetailsVfModuleProperty }; diff --git a/src/main/resources/clds/camel/rest/clamp-api-v2.xml b/src/main/resources/clds/camel/rest/clamp-api-v2.xml index da856e94..10144949 100644 --- a/src/main/resources/clds/camel/rest/clamp-api-v2.xml +++ b/src/main/resources/clds/camel/rest/clamp-api-v2.xml @@ -193,7 +193,7 @@ </route> </post> <put - uri="/v2/loop/deployLoop/{loopName}" + uri="/v2/loop/deploy/{loopName}" outType="org.onap.clamp.loop.Loop" produces="application/json"> <route> @@ -212,27 +212,8 @@ <to uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('DCAE DEPLOY request','INFO',${exchangeProperty[loopObject]})" /> - <to uri="direct:get-status-from-policy" /> - <to uri="direct:get-status-from-dcae" /> - <log - loggingLevel="INFO" - message="Policy deployment status: ${exchangeProperty[policyStatus]}"></log> - <choice> - <when> - <simple> ${exchangeProperty[policyStatus]} == 'SUBMITTED' and - ${exchangeProperty[dcaeStatus]} == 'NOT_DEPLOYED' - </simple> - <to uri="direct:deploy-loop" /> - </when> - <otherwise> - <log - loggingLevel="INFO" - message="POLICY status ${exchangeProperty[policyStatus]}/DCAE status ${exchangeProperty[dcaeStatus]}, DCAE deployment will be started anyway" /> - <to - uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('POLICY status ${exchangeProperty[policyStatus]}/DCAE status ${exchangeProperty[dcaeStatus]}, DCAE deployment will be started anyway','ERROR',${exchangeProperty[loopObject]})" /> - <to uri="direct:deploy-loop" /> - </otherwise> - </choice> + <to uri="direct:deploy-loop" /> + <log loggingLevel="INFO" message="DEPLOY request successfully executed for loop: ${header.loopName}" /> @@ -257,7 +238,7 @@ </route> </put> <put - uri="/v2/loop/undeployLoop/{loopName}" + uri="/v2/loop/undeploy/{loopName}" outType="org.onap.clamp.loop.Loop" produces="application/json"> <route> @@ -275,21 +256,8 @@ <to uri="direct:load-loop" /> <to uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('DCAE UNDEPLOY request','INFO',${exchangeProperty[loopObject]})" /> - <to uri="direct:get-status-from-dcae" /> - <choice> - <when> - <simple> ${exchangeProperty[dcaeStatus]} == 'DEPLOYED' or ${exchangeProperty[dcaeStatus]} == 'IN_ERROR' or ${exchangeProperty[dcaeStatus]} == 'PROCESSING' - </simple> <to uri="direct:undeploy-loop" /> - </when> - <otherwise> - <log - loggingLevel="INFO" - message="Loop is in state ${exchangeProperty[dcaeStatus]}, it can only be undeployed when in state DEPLOYED/IN_ERROR/PROCESSING" /> - <to - uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('Loop is in state ${exchangeProperty[dcaeStatus]}, it can only be deployed when in state DEPLOYED','ERROR',${exchangeProperty[loopObject]})" /> - </otherwise> - </choice> + <log loggingLevel="INFO" message="UNDEPLOY request successfully executed for loop: ${header.loopName}" /> @@ -524,6 +492,7 @@ <to uri="direct:load-loop" /> <to uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('DELETE request','INFO',${exchangeProperty[loopObject]})" /> + <to uri="direct:undeploy-loop" /> <to uri="direct:remove-all-policy-from-active-pdp-group" /> <split> <simple>${exchangeProperty[loopObject].getMicroServicePolicies()} @@ -609,20 +578,16 @@ <to uri="direct:load-loop" /> <to uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('GET STATUS request','INFO',${exchangeProperty[loopObject]})" /> - <setProperty propertyName="raiseHttpExceptionFlag"> - <simple resultType="java.lang.Boolean">false</simple> - </setProperty> - <to uri="direct:get-status-from-policy" /> - <to uri="direct:get-status-from-dcae" /> - <to - uri="bean:org.onap.clamp.loop.LoopOperation?method=updateLoopStatus(${exchangeProperty[loopObject]},${exchangeProperty[policyStatus]}, ${exchangeProperty[dcaeStatus]})" /> - <log - loggingLevel="INFO" - message="Get Status request successfully executed. The new state is: ${body}" /> + <doTry> + <to uri="direct:update-policy-status-for-loop" /> + <to uri="direct:update-dcae-status-for-loop" /> + <to uri="direct:update-loop-state" /> + <to uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('Get Status request successfully executed','INFO',${exchangeProperty[loopObject]})" /> <to uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=endLog()" /> + </doTry> <doCatch> <exception>java.lang.Exception</exception> <handled> @@ -637,8 +602,9 @@ uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('Get Status request failed, Error reported: ${exception}','ERROR',${exchangeProperty[loopObject]})" /> </doCatch> <doFinally> - <to - uri="bean:org.onap.clamp.loop.LoopController?method=getLoop(${header.loopName})" /> + <setBody> + <simple>${exchangeProperty[loopObject]}</simple> + </setBody> </doFinally> </doTry> </route> diff --git a/src/main/resources/clds/camel/routes/dcae-flows.xml b/src/main/resources/clds/camel/routes/dcae-flows.xml new file mode 100644 index 00000000..b69c4fb8 --- /dev/null +++ b/src/main/resources/clds/camel/routes/dcae-flows.xml @@ -0,0 +1,187 @@ +<routes xmlns="http://camel.apache.org/schema/spring"> + <route id="deploy-loop"> + <from uri="direct:deploy-loop" /> + <doTry> + <log + loggingLevel="INFO" + message="Deploying the loop: ${exchangeProperty[loopObject].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('DCAE', 'Deploying the loop')" /> + <setBody> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="getDeployPayload(${exchangeProperty[loopObject]})" /> + </setBody> + <setProperty propertyName="dcaeDeploymentId"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="generateDeploymentId()" /> + </setProperty> + <setHeader headerName="CamelHttpMethod"> + <constant>PUT</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to deploy loop: {{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[dcaeDeploymentId]}"></log> + <toD + uri="{{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[dcaeDeploymentId]}?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}&connectionsPerRoute=3" /> + <convertBodyTo type="java.lang.String" /> + <setProperty propertyName="dcaeResponse"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="convertDcaeResponse(${body})" /> + </setProperty> + <setProperty propertyName="dcaeStatusUrl"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="getStatusUrl(${exchangeProperty[dcaeResponse]})" /> + </setProperty> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateDcaeDeploymentFields(${exchangeProperty[loopObject]},${exchangeProperty[dcaeDeploymentId]},${exchangeProperty[dcaeStatusUrl]})" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>DEPLOY loop status + (Dep-id:${exchangeProperty[dcaeDeploymentId]}, + StatusUrl:${exchangeProperty[dcaeStatusUrl]}) + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="undeploy-loop"> + <from uri="direct:undeploy-loop" /> + <log + loggingLevel="INFO" + message="Undeploying the loop: ${exchangeProperty[loopObject].getName()} : ${exchangeProperty[loopObject].getDcaeDeploymentId()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('DCAE', 'Undeploying the loop')" /> + <choice> + <when> + <simple>${exchangeProperty[loopObject].getDcaeDeploymentId()} + != null + </simple> + <doTry> + <setBody> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="getUndeployPayload(${exchangeProperty[loopObject]})" /> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>DELETE</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to undeploy loop: {{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[loopObject].getDcaeDeploymentId()}"></log> + <toD + uri="{{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[loopObject].getDcaeDeploymentId()}?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}&connectionsPerRoute=3" /> + <convertBodyTo type="java.lang.String" /> + <setProperty propertyName="dcaeResponse"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="convertDcaeResponse(${body})" /> + </setProperty> + <setProperty propertyName="dcaeStatusUrl"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="getStatusUrl(${exchangeProperty[dcaeResponse]})" /> + </setProperty> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateDcaeDeploymentFields(${exchangeProperty[loopObject]},${exchangeProperty[loopObject].getDcaeDeploymentId()},${exchangeProperty[dcaeStatusUrl]})" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>UNDEPLOY loop status</simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </when> + <otherwise> + <log + loggingLevel="WARNING" + message="Cannot Undeploy for the loop: ${exchangeProperty[loopObject].getName()}, the Deployment ID does not exist !" /> + <to + uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('Cannot Undeploy for the loop: ${exchangeProperty[loopObject].getName()}, the Deployment ID does not exist !','WARNING',${exchangeProperty[loopObject]})" /> + + </otherwise> + </choice> + </route> + <route id="get-dcae-deployment-status"> + <from uri="direct:get-dcae-deployment-status" /> + <log + loggingLevel="INFO" + message="Getting DCAE deployment status for loop: ${exchangeProperty[loopObject].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('DCAE', 'Getting Deployment status')" /> + <doTry> + <setHeader headerName="CamelHttpMethod"> + <constant>GET</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to query Closed Loop status: ${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()}"></log> + <toD + uri="${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()}?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authMethod=Basic&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>DCAE deployment status</simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + + </route> +</routes>
\ No newline at end of file diff --git a/src/main/resources/clds/camel/routes/flexible-flow.xml b/src/main/resources/clds/camel/routes/flexible-flow.xml index 1bad5fbb..bc79fc21 100644 --- a/src/main/resources/clds/camel/routes/flexible-flow.xml +++ b/src/main/resources/clds/camel/routes/flexible-flow.xml @@ -75,642 +75,4 @@ </when> </choice> </route> - - <route id="load-loop"> - <from uri="direct:load-loop" /> - <setBody> - <simple>${header.loopName}</simple> - </setBody> - <setProperty propertyName="loopObject"> - <method - ref="org.onap.clamp.loop.LoopService" - method="getLoop" /> - </setProperty> - - <when> - <simple>${exchangeProperty[loopObject]} == null</simple> - <setHeader headerName="CamelHttpResponseCode"> - <constant>404</constant> - </setHeader> - <log - loggingLevel="WARNING" - message="Loop not found in database: ${body}" /> - <stop /> - </when> - </route> - - <route id="create-micro-service-policy"> - <from uri="direct:create-micro-service-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Creating Micro Service Policy: ${exchangeProperty[microServicePolicy].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Micro Service Policy')" /> - <setBody> - <simple>${exchangeProperty[microServicePolicy].createPolicyPayload()} - </simple> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>POST</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to create microservice policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[microServicePolicy].getName()} creation - status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="delete-micro-service-policy"> - <from uri="direct:delete-micro-service-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Deleting Micro Service Policy: ${exchangeProperty[microServicePolicy].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Micro Service Policy')" /> - <setBody> - <constant>null</constant> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>DELETE</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to delete microservice policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies/${exchangeProperty[microServicePolicy].getName()}/versions/1.0.0"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies/${exchangeProperty[microServicePolicy].getName()}/versions/1.0.0?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[microServicePolicy].getName()} removal - status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="create-operational-policy"> - <from uri="direct:create-operational-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Creating Operational Policy: ${exchangeProperty[operationalPolicy].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Operational Policy')" /> - <setBody> - <simple>${exchangeProperty[operationalPolicy].createPolicyPayload()} - </simple> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>POST</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to create operational policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[operationalPolicy].getName()} creation - status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="delete-operational-policy"> - <from uri="direct:delete-operational-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Deleting Operational Policy: ${exchangeProperty[operationalPolicy].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Operational Policy')" /> - <setBody> - <constant>null</constant> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>DELETE</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to delete operational policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicy].getName()}/versions/1"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicy].getName()}/versions/1?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[operationalPolicy].getName()} removal - status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="create-guard-policy"> - <from uri="direct:create-guard-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Creating Guard Policy: ${exchangeProperty[guardPolicy].getKey()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Guard Policy')" /> - <setBody> - <simple>${exchangeProperty[guardPolicy].getValue()} - </simple> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>POST</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to create guard policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[guardPolicy].getKey()} creation status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="delete-guard-policy"> - <from uri="direct:delete-guard-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Deleting Guard Policy: ${exchangeProperty[guardPolicy].getKey()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Guard Policy')" /> - <setBody> - <constant>null</constant> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>DELETE</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to delete guard policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/${exchangeProperty[guardPolicy].getKey()}/versions/1"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/${exchangeProperty[guardPolicy].getKey()}/versions/1?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}" /> - - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[guardPolicy].getKey()} removal status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="add-all-to-active-pdp-group"> - <from uri="direct:add-all-to-active-pdp-group" /> - <doTry> - <log - loggingLevel="INFO" - message="Adding loop policies to PDP Group: ${exchangeProperty[loopObject].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Add policies to PDP group')" /> - <setBody> - <simple>${exchangeProperty[loopObject].createPoliciesPayloadPdpGroup()} - </simple> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>POST</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to add policies to PDP Group: {{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies"></log> - <toD - uri="{{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies?bridgeEndpoint=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&useSystemProperties=true&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}" /> - - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>PDP Group push ALL status</simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="remove-all-policy-from-active-pdp-group"> - <from uri="direct:remove-all-policy-from-active-pdp-group" /> - <doTry> - <log - loggingLevel="INFO" - message="Removing policies from active PDP group for loop: ${exchangeProperty[loopObject].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Removing policies PDP group')" /> - <split> - <simple>${exchangeProperty[loopObject].listPolicyNamesPdpGroup()} - </simple> - <setProperty propertyName="policyName"> - <simple>${body}</simple> - </setProperty> - <setBody> - <constant>null</constant> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>DELETE</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to delete policy from PDP Group: {{clamp.config.policy.pap.url}}/pdps/policies/${exchangeProperty[policyName]}/versions/1.0.0"></log> - <toD - uri="{{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies/${exchangeProperty[policyName]}/versions/1.0.0?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}" /> - <setProperty propertyName="logMessage"> - <simple>${exchangeProperty[policyName]} PDP Group removal status - </simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </split> - <doCatch> - <exception>java.lang.Exception</exception> - <handled> - <constant>false</constant> - </handled> - <setProperty propertyName="logMessage"> - <simple>PDP Group removal, Error reported: ${exception}</simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doCatch> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - </doFinally> - </doTry> - </route> - <route id="deploy-loop"> - <from uri="direct:deploy-loop" /> - <doTry> - <log - loggingLevel="INFO" - message="Deploying the loop: ${exchangeProperty[loopObject].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('DCAE', 'Deploying the loop')" /> - <setBody> - <method ref="org.onap.clamp.loop.LoopOperation" - method="getDeployPayload(${exchangeProperty[loopObject]})" /> - </setBody> - <setProperty propertyName="deploymentId"> - <method ref="org.onap.clamp.loop.LoopOperation" - method="getDeploymentId(${exchangeProperty[loopObject]})" /> - </setProperty> - <setHeader headerName="CamelHttpMethod"> - <constant>PUT</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to deploy loop: {{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[deploymentId]}"></log> - <toD - uri="{{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[deploymentId]}?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}" /> - <to - uri="bean:org.onap.clamp.loop.LoopOperation?method=updateLoopInfo(*,${exchangeProperty[loopObject]},${exchangeProperty[deploymentId]})" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>DEPLOY loop status (id:${exchangeProperty[deploymentId]})</simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - - <route id="undeploy-loop"> - <from uri="direct:undeploy-loop" /> - <doTry> - <log - loggingLevel="INFO" - message="Undeploying the loop: ${exchangeProperty[loopObject].getName()} : ${exchangeProperty[loopObject].getDcaeDeploymentId()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('DCAE', 'Undeploying the loop')" /> - - <setBody> - <simple>{\"serviceTypeId\": \"${exchangeProperty[loopObject].getDcaeBlueprintId()}\"} - </simple> - </setBody> - <setHeader headerName="CamelHttpMethod"> - <constant>DELETE</constant> - </setHeader> - <setHeader headerName="Content-Type"> - <constant>application/json</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to undeploy loop: {{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[loopObject].getDcaeDeploymentId()}"></log> - <toD - uri="{{clamp.config.dcae.deployment.url}}/dcae-deployments/${exchangeProperty[loopObject].getDcaeDeploymentId()}?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}" /> - <to - uri="bean:org.onap.clamp.loop.LoopOperation?method=updateLoopInfo(*,${exchangeProperty[loopObject]},null)" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>UNDEPLOY loop status</simple> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - <route id="get-status-from-policy"> - <from uri="direct:get-status-from-policy" /> - <doTry> - <log - loggingLevel="INFO" - message="Query Closed Loop status from policy PDP: ${exchangeProperty[loopObject].getName()}" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Query operational policies to PDP group')" /> - <setProperty propertyName="operationalPolicyName"> - <method ref="org.onap.clamp.loop.LoopOperation" - method="getOperationalPolicyName(${exchangeProperty[loopObject]})" /> - </setProperty> - <setHeader headerName="CamelHttpMethod"> - <constant>GET</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to query from Policy PDP: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicyName]}/versions/deployed"></log> - <toD - uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicyName]}/versions/deployed?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authMethod=Basic&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>Policy deployment status</simple> - </setProperty> - <setProperty propertyName="policyStatus"> - <method ref="org.onap.clamp.loop.LoopOperation" - method="analysePolicyResponse(${header.CamelHttpResponseCode})" /> - </setProperty> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </route> - <route id="get-status-from-dcae"> - <from uri="direct:get-status-from-dcae" /> - <log - loggingLevel="INFO" - message="Query Closed Loop status from DCAE ${exchangeProperty[loopObject].getName()}" /> - <choice> - <when> - <simple>${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()} == null - </simple> - <setProperty propertyName="dcaeStatus"> - <method ref="org.onap.clamp.loop.LoopOperation" - method="analyseDcaeResponse(*,null)" /> - </setProperty> - <log - loggingLevel="INFO" - message="dcae status: ${exchangeProperty[dcaeStatus]}"></log> - </when> - <otherwise> - <doTry> - <log - loggingLevel="INFO" - message="Query Closed Loop status from Dcae" /> - <setHeader headerName="CamelHttpMethod"> - <constant>GET</constant> - </setHeader> - <setHeader headerName="X-ONAP-RequestID"> - <simple>${exchangeProperty[X-ONAP-RequestID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-InvocationID"> - <simple>${exchangeProperty[X-ONAP-InvocationID]} - </simple> - </setHeader> - <setHeader headerName="X-ONAP-PartnerName"> - <simple>${exchangeProperty[X-ONAP-PartnerName]} - </simple> - </setHeader> - <log - loggingLevel="INFO" - message="Endpoint to query Closed Loop status: ${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()}"></log> - <toD - uri="${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()}?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=20000&httpClient.socketTimeout=20000&authMethod=Basic&authUsername={{clamp.config.dcae.deployment.userName}}&authPassword={{clamp.config.dcae.deployment.password}}" /> - <doFinally> - <to uri="direct:reset-raise-http-exception-flag" /> - <to - uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> - <setProperty propertyName="logMessage"> - <simple>DCAE deployment status</simple> - </setProperty> - <setProperty propertyName="dcaeStatus"> - <method ref="org.onap.clamp.loop.LoopOperation" - method="analyseDcaeResponse(*,${header.CamelHttpResponseCode})" /> - </setProperty> - <log - loggingLevel="INFO" - message="dcae status: ${exchangeProperty[dcaeStatus]}"></log> - <to uri="direct:dump-loop-log-http-response" /> - </doFinally> - </doTry> - </otherwise> - </choice> - </route> - <route id="reset-raise-http-exception-flag"> - <from uri="direct:reset-raise-http-exception-flag" /> - <setProperty propertyName="raiseHttpExceptionFlag"> - <simple resultType="java.lang.Boolean">true</simple> - </setProperty> - </route> - - <route id="dump-loop-log-http-response"> - <from uri="direct:dump-loop-log-http-response" /> - <log loggingLevel="INFO" message="${exchangeProperty[logMessage]} - ${header.CamelHttpResponseCode} : ${header.CamelHttpResponseText}" /> - <to - uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('${exchangeProperty[logMessage]} - ${header.CamelHttpResponseCode} : ${header.CamelHttpResponseText}','INFO',${exchangeProperty[loopObject]})" /> - </route> </routes>
\ No newline at end of file diff --git a/src/main/resources/clds/camel/routes/loop-flows.xml b/src/main/resources/clds/camel/routes/loop-flows.xml new file mode 100644 index 00000000..ede899e7 --- /dev/null +++ b/src/main/resources/clds/camel/routes/loop-flows.xml @@ -0,0 +1,250 @@ +<routes xmlns="http://camel.apache.org/schema/spring"> + <route id="load-loop"> + <from uri="direct:load-loop" /> + <setBody> + <simple>${header.loopName}</simple> + </setBody> + <setProperty propertyName="loopObject"> + <method + ref="org.onap.clamp.loop.LoopService" + method="getLoop" /> + </setProperty> + + <when> + <simple>${exchangeProperty[loopObject]} == null</simple> + <setHeader headerName="CamelHttpResponseCode"> + <constant>404</constant> + </setHeader> + <log + loggingLevel="WARNING" + message="Loop not found in database: ${body}" /> + <stop /> + </when> + </route> + <route id="update-policy-status-for-loop"> + <from uri="direct:update-policy-status-for-loop" /> + <setProperty propertyName="atLeastOnePolicyNotFound"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <setProperty propertyName="atLeastOnePolicyNotDeployed"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <setProperty propertyName="policyComponent"> + <simple>${exchangeProperty[loopObject].getComponent('POLICY')} + </simple> + </setProperty> + <log + loggingLevel="INFO" + message="Processing all MICRO-SERVICES policies defined in loop ${exchangeProperty[loopObject].getName()}" /> + <split> + <simple>${exchangeProperty[loopObject].getMicroServicePolicies()} + </simple> + <setProperty propertyName="policyName"> + <simple>${body.getName()}</simple> + </setProperty> + <setProperty propertyName="policyType"> + <simple>${body.getModelType()}</simple> + </setProperty> + <setBody> + <constant>null</constant> + </setBody> + <log + loggingLevel="INFO" + message="Processing Micro Service Policy: ${exchangeProperty[policyName]} of type ${exchangeProperty[policyType]}" /> + <setProperty propertyName="raiseHttpExceptionFlag"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <to uri="direct:get-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotFound"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + <to uri="direct:get-deployment-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotDeployed"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + </split> + <log + loggingLevel="INFO" + message="Processing all OPERATIONAL policies defined in loop ${exchangeProperty[loopObject].getName()}" /> + <split> + <simple>${exchangeProperty[loopObject].getOperationalPolicies()} + </simple> + <setProperty propertyName="policyName"> + <simple>${body.getName()}</simple> + </setProperty> + <setProperty propertyName="policyType"> + <simple>onap.policies.controlloop.Operational</simple> + </setProperty> + <setProperty propertyName="operationalPolicy"> + <simple>${body}</simple> + </setProperty> + <setBody> + <constant>null</constant> + </setBody> + <log + loggingLevel="INFO" + message="Processing Micro Service Policy: ${exchangeProperty[policyName]} of type ${exchangeProperty[policyType]}" /> + <setProperty propertyName="raiseHttpExceptionFlag"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <to uri="direct:get-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotFound"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + <to uri="direct:get-deployment-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotDeployed"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + + <log + loggingLevel="INFO" + message="Processing all GUARD policies defined in loop ${exchangeProperty[loopObject].getName()}" /> + <split> + <simple>${exchangeProperty[operationalPolicy].createGuardPolicyPayloads().entrySet()} + </simple> + <setProperty propertyName="policyName"> + <simple>${body.getKey()}</simple> + </setProperty> + <setProperty propertyName="policyType"> + <simple>onap.policies.controlloop.Guard</simple> + </setProperty> + <setBody> + <constant>null</constant> + </setBody> + <log + loggingLevel="INFO" + message="Processing Guard Policy: ${exchangeProperty[policyName]} of type ${exchangeProperty[policyType]}" /> + <setProperty propertyName="raiseHttpExceptionFlag"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <to uri="direct:get-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotFound"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + <to uri="direct:get-deployment-policy" /> + <when> + <simple> ${header.CamelHttpResponseCode} != 200 </simple> + <setProperty propertyName="atLeastOnePolicyNotDeployed"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </when> + </split> + </split> + <setProperty propertyName="policyState"> + <simple> ${exchangeProperty[policyComponent].computeState(*)} + </simple> + </setProperty> + <log + loggingLevel="INFO" + message="Policy state set to: ${exchangeProperty[policyState].getStateName()}" /> + <to + uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLogForComponent('Policy state set to: ${exchangeProperty[policyState].getStateName()}','INFO','POLICY',${exchangeProperty[loopObject]})" /> + </route> + <route id="update-dcae-status-for-loop"> + <from uri="direct:update-dcae-status-for-loop" /> + <log + loggingLevel="INFO" + message="Updating DCAE status for loop: ${exchangeProperty[loopObject].getName()}" /> + <setProperty propertyName="dcaeComponent"> + <simple>${exchangeProperty[loopObject].getComponent('DCAE')}</simple> + </setProperty> + <when> + <simple>${exchangeProperty[loopObject].getDcaeDeploymentStatusUrl()} + != null + </simple> + <setProperty propertyName="raiseHttpExceptionFlag"> + <simple resultType="java.lang.Boolean">false</simple> + </setProperty> + <to uri="direct:get-dcae-deployment-status" /> + <when> + <simple> ${header.CamelHttpResponseCode} == 200 </simple> + <convertBodyTo type="java.lang.String" /> + <setProperty propertyName="dcaeResponse"> + <method + ref="org.onap.clamp.loop.components.external.DcaeComponent" + method="convertDcaeResponse(${body})" /> + </setProperty> + </when> + </when> + + <setProperty propertyName="dcaeState"> + <simple> ${exchangeProperty[dcaeComponent].computeState(*)} + </simple> + </setProperty> + <log + loggingLevel="INFO" + message="DCAE state set to: ${exchangeProperty[dcaeState].getStateName()} - DCAE message: ${exchangeProperty[dcaeResponse].getError()}" /> + <to + uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLogForComponent('DCAE state set to: ${exchangeProperty[dcaeState].getStateName()} - message: ${exchangeProperty[dcaeResponse].getError()}','INFO','DCAE',${exchangeProperty[loopObject]})" /> + + </route> + <route id="direct:update-loop-state"> + <from uri="direct:update-loop-state" /> + <log + loggingLevel="INFO" + message="Updating status for loop: ${exchangeProperty[loopObject].getName()}" /> + <choice> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'BLUEPRINT_DEPLOYED' and ${exchangeProperty['policyState'].getStateName()} == 'NOT_SENT'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'DESIGN')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'IN_ERROR' or ${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_INSTALLATION_FAILED'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'IN_ERROR')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_UNINSTALLATION_FAILED' or ${exchangeProperty['policyState'].getStateName()} == 'IN_ERROR'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'IN_ERROR')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_INSTALLED_SUCCESSFULLY' and ${exchangeProperty['policyState'].getStateName()} == 'SENT_AND_DEPLOYED'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'RUNNING')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_INSTALLED_SUCCESSFULLY' and ${exchangeProperty['policyState'].getStateName()} == 'SENT'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'STOPPED')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'BLUEPRINT_DEPLOYED' or ${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_UNINSTALLED_SUCCESSFULLY' and ${exchangeProperty['policyState'].getStateName()} == 'SENT_AND_DEPLOYED'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'SUBMITTED')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'PROCESSING_MICROSERVICE_INSTALLATION' or ${exchangeProperty['dcaeState'].getStateName()} == 'PROCESSING_MICROSERVICE_UNINSTALLATION' and ${exchangeProperty['policyState'].getStateName()} == 'SENT_AND_DEPLOYED'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'WAITING')" /> + </when> + <when> + <simple>${exchangeProperty['dcaeState'].getStateName()} == 'MICROSERVICE_INSTALLED_SUCCESSFULLY' and ${exchangeProperty['policyState'].getStateName()} != 'NOT_SENT'</simple> + <to + uri="bean:org.onap.clamp.loop.LoopService?method=updateLoopState(${exchangeProperty[loopObject]},'DEPLOYED')" /> + </when> + </choice> + <log + loggingLevel="INFO" + message="New loop state is: ${exchangeProperty[loopObject].getLastComputedState().toString()}" /> + <to + uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('New loop state is: ${exchangeProperty[loopObject].getLastComputedState().toString()}','INFO',${exchangeProperty[loopObject]})" /> + + </route> +</routes>
\ No newline at end of file diff --git a/src/main/resources/clds/camel/routes/policy-flows.xml b/src/main/resources/clds/camel/routes/policy-flows.xml new file mode 100644 index 00000000..8cc594d2 --- /dev/null +++ b/src/main/resources/clds/camel/routes/policy-flows.xml @@ -0,0 +1,476 @@ + +<routes xmlns="http://camel.apache.org/schema/spring"> + <route id="get-policy"> + <from uri="direct:get-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Getting Policy: ${exchangeProperty[policyName]}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Get Policy')" /> + <setHeader headerName="CamelHttpMethod"> + <constant>GET</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to get policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[policyType]}/versions/1.0.0/policies/${exchangeProperty[policyName]}/versions/1.0.0"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[policyType]}/versions/1.0.0/policies/${exchangeProperty[policyName]}/versions/1.0.0?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[policyName]} GET + Policy status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="get-deployment-policy"> + <from uri="direct:get-deployment-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Getting the policy deployment in PDP: ${exchangeProperty[policyName]}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Getting the policy deployment in PDP')" /> + <setHeader headerName="CamelHttpMethod"> + <constant>GET</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to get policy deployment status: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[policyType]}/versions/1.0.0/policies/${exchangeProperty[policyName]}/versions/deployed"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[policyType]}/versions/1.0.0/policies/${exchangeProperty[policyName]}/versions/deployed?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authMethod=Basic&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[policyName]} GET Policy deployment + status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + <route id="create-micro-service-policy"> + <from uri="direct:create-micro-service-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Creating Micro Service Policy: ${exchangeProperty[microServicePolicy].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Micro Service Policy')" /> + <setBody> + <simple>${exchangeProperty[microServicePolicy].createPolicyPayload()} + </simple> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>POST</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to create microservice policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[microServicePolicy].getName()} creation + status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="delete-micro-service-policy"> + <from uri="direct:delete-micro-service-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Deleting Micro Service Policy: ${exchangeProperty[microServicePolicy].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Micro Service Policy')" /> + <setBody> + <constant>null</constant> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>DELETE</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to delete microservice policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies/${exchangeProperty[microServicePolicy].getName()}/versions/1.0.0"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/${exchangeProperty[microServicePolicy].getModelType()}/versions/1.0.0/policies/${exchangeProperty[microServicePolicy].getName()}/versions/1.0.0?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[microServicePolicy].getName()} removal + status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="create-operational-policy"> + <from uri="direct:create-operational-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Creating Operational Policy: ${exchangeProperty[operationalPolicy].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Operational Policy')" /> + <setBody> + <simple>${exchangeProperty[operationalPolicy].createPolicyPayload()} + </simple> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>POST</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to create operational policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[operationalPolicy].getName()} creation + status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="delete-operational-policy"> + <from uri="direct:delete-operational-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Deleting Operational Policy: ${exchangeProperty[operationalPolicy].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Operational Policy')" /> + <setBody> + <constant>null</constant> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>DELETE</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to delete operational policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicy].getName()}/versions/1"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/${exchangeProperty[operationalPolicy].getName()}/versions/1?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[operationalPolicy].getName()} removal + status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="create-guard-policy"> + <from uri="direct:create-guard-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Creating Guard Policy: ${exchangeProperty[guardPolicy].getKey()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Create Guard Policy')" /> + <setBody> + <simple>${exchangeProperty[guardPolicy].getValue()} + </simple> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>POST</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to create guard policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[guardPolicy].getKey()} creation status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="delete-guard-policy"> + <from uri="direct:delete-guard-policy" /> + <doTry> + <log + loggingLevel="INFO" + message="Deleting Guard Policy: ${exchangeProperty[guardPolicy].getKey()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Delete Guard Policy')" /> + <setBody> + <constant>null</constant> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>DELETE</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to delete guard policy: {{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/${exchangeProperty[guardPolicy].getKey()}/versions/1"></log> + <toD + uri="{{clamp.config.policy.api.url}}/policy/api/v1/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/${exchangeProperty[guardPolicy].getKey()}/versions/1?bridgeEndpoint=true&useSystemProperties=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&deleteWithBody=false&mapHttpMessageBody=false&mapHttpMessageFormUrlEncodedBody=false&authUsername={{clamp.config.policy.api.userName}}&authPassword={{clamp.config.policy.api.password}}&connectionsPerRoute=3" /> + + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[guardPolicy].getKey()} removal status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="add-all-to-active-pdp-group"> + <from uri="direct:add-all-to-active-pdp-group" /> + <doTry> + <log + loggingLevel="INFO" + message="Adding loop policies to PDP Group: ${exchangeProperty[loopObject].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Add policies to PDP group')" /> + <setBody> + <simple>${exchangeProperty[loopObject].getComponent("POLICY").createPoliciesPayloadPdpGroup(exchangeProperty[loopObject])} + </simple> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>POST</constant> + </setHeader> + <setHeader headerName="Content-Type"> + <constant>application/json</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to add policies to PDP Group: {{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies"></log> + <toD + uri="{{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies?bridgeEndpoint=true&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&useSystemProperties=true&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}&connectionsPerRoute=3" /> + + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + <setProperty propertyName="logMessage"> + <simple>PDP Group push ALL status</simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doFinally> + </doTry> + </route> + + <route id="remove-all-policy-from-active-pdp-group"> + <from uri="direct:remove-all-policy-from-active-pdp-group" /> + <doTry> + <log + loggingLevel="INFO" + message="Removing policies from active PDP group for loop: ${exchangeProperty[loopObject].getName()}" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeLog('Policy', 'Removing policies PDP group')" /> + <split> + <simple>${exchangeProperty[loopObject].getComponent("POLICY").listPolicyNamesPdpGroup(exchangeProperty[loopObject])} + </simple> + <setProperty propertyName="policyName"> + <simple>${body}</simple> + </setProperty> + <setBody> + <constant>null</constant> + </setBody> + <setHeader headerName="CamelHttpMethod"> + <constant>DELETE</constant> + </setHeader> + <setHeader headerName="X-ONAP-RequestID"> + <simple>${exchangeProperty[X-ONAP-RequestID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-InvocationID"> + <simple>${exchangeProperty[X-ONAP-InvocationID]} + </simple> + </setHeader> + <setHeader headerName="X-ONAP-PartnerName"> + <simple>${exchangeProperty[X-ONAP-PartnerName]} + </simple> + </setHeader> + <log + loggingLevel="INFO" + message="Endpoint to delete policy from PDP Group: {{clamp.config.policy.pap.url}}/pdps/policies/${exchangeProperty[policyName]}/versions/1.0.0"></log> + <toD + uri="{{clamp.config.policy.pap.url}}/policy/pap/v1/pdps/policies/${exchangeProperty[policyName]}/versions/1.0.0?bridgeEndpoint=true&useSystemProperties=true&mapHttpMessageHeaders=false&throwExceptionOnFailure=${exchangeProperty[raiseHttpExceptionFlag]}&httpClient.connectTimeout=10000&authUsername={{clamp.config.policy.pap.userName}}&authPassword={{clamp.config.policy.pap.password}}&connectionsPerRoute=3" /> + <setProperty propertyName="logMessage"> + <simple>${exchangeProperty[policyName]} PDP Group removal status + </simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </split> + <doCatch> + <exception>java.lang.Exception</exception> + <handled> + <constant>false</constant> + </handled> + <setProperty propertyName="logMessage"> + <simple>PDP Group removal, Error reported: ${exception}</simple> + </setProperty> + <to uri="direct:dump-loop-log-http-response" /> + </doCatch> + <doFinally> + <to uri="direct:reset-raise-http-exception-flag" /> + <to + uri="bean:org.onap.clamp.flow.log.FlowLogOperation?method=invokeReturnLog()" /> + </doFinally> + </doTry> + </route> +</routes>
\ No newline at end of file diff --git a/src/main/resources/clds/camel/routes/utils-flows.xml b/src/main/resources/clds/camel/routes/utils-flows.xml new file mode 100644 index 00000000..adf843ff --- /dev/null +++ b/src/main/resources/clds/camel/routes/utils-flows.xml @@ -0,0 +1,17 @@ +<routes xmlns="http://camel.apache.org/schema/spring"> + <route id="reset-raise-http-exception-flag"> + <from uri="direct:reset-raise-http-exception-flag" /> + <setProperty propertyName="raiseHttpExceptionFlag"> + <simple resultType="java.lang.Boolean">true</simple> + </setProperty> + </route> + + <route id="dump-loop-log-http-response"> + <from uri="direct:dump-loop-log-http-response" /> + <log + loggingLevel="INFO" + message="${exchangeProperty[logMessage]} - ${header.CamelHttpResponseCode} : ${header.CamelHttpResponseText}" /> + <to + uri="bean:org.onap.clamp.loop.log.LoopLogService?method=addLog('${exchangeProperty[logMessage]} - ${header.CamelHttpResponseCode} : ${header.CamelHttpResponseText}','INFO',${exchangeProperty[loopObject]})" /> + </route> +</routes>
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/client/CldsEventDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/CldsEventDelegateTest.java new file mode 100644 index 00000000..3b5a9ee0 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/CldsEventDelegateTest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.dao.CldsDao; + +@RunWith(MockitoJUnitRunner.class) +public class CldsEventDelegateTest { + + private static final String CONTROL_NAME_KEY = "controlName"; + private static final String TEST_KEY = "isTest"; + private static final String INSERT_TEST_EVENT_KEY = "isInsertTestEvent"; + private static final String PREFIX = "abcdef-"; + private static final String UUID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-123456789"; + + @Mock + private Exchange exchange; + + @Mock + private CldsDao cldsDao; + + @InjectMocks + private CldsEventDelegate cldsEventDelegate; + + @Test + public void shouldExecuteSuccessfully() { + // given + when(exchange.getProperty(eq(CONTROL_NAME_KEY))).thenReturn(PREFIX + UUID); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(INSERT_TEST_EVENT_KEY))).thenReturn(false); + + // when + cldsEventDelegate.addEvent(exchange, null); + + // then + verify(cldsDao).insEvent(eq(null), eq(PREFIX), eq(UUID), any()); + } + + @Test + public void shouldExecuteWithoutInsertingEventIntoDatabase() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true); + when(exchange.getProperty(eq(INSERT_TEST_EVENT_KEY))).thenReturn(false); + + // when + cldsEventDelegate.addEvent(exchange, null); + + // then + verify(cldsDao, never()).insEvent(any(), any(), any(), any()); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/clds/client/GuardPolicyDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/GuardPolicyDelegateTest.java new file mode 100644 index 00000000..4b21d6f8 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/GuardPolicyDelegateTest.java @@ -0,0 +1,108 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.exception.ModelBpmnException; + +@RunWith(MockitoJUnitRunner.class) +public class GuardPolicyDelegateTest { + + private static final String TEST_KEY = "isTest"; + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String POLICY_ID_FROM_JSON = "{policy:[{id:guard,from:''}]}"; + private static final String ID_WITH_CHAIN_JSON = "{guard:{q:[" + + "{name:timeout,value:200}," + + "{policyConfigurations:[" + + "[{name:maxRetries,value:3}," + + "{name:retryTimeLimit,value:800}," + + "{name:enableGuardPolicy,value:on}]]}]}}"; + private static final String SIMPLE_JSON = "{}"; + private static final String NOT_JSON = "not json"; + + @Mock + private Exchange exchange; + + @Mock + private PolicyClient policyClient; + + @InjectMocks + private GuardPolicyDelegate guardPolicyDelegate; + + @Test + public void shouldExecuteSuccessfully() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(POLICY_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_WITH_CHAIN_JSON); + + // when + guardPolicyDelegate.execute(exchange); + + // then + verify(policyClient).sendGuardPolicy(any(), any(), any(), any()); + } + + @Test + public void shouldExecutePolicyNotFound() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(SIMPLE_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(SIMPLE_JSON); + + // when + guardPolicyDelegate.execute(exchange); + + // then + verify(policyClient, never()).sendGuardPolicy(any(), any(), any(), any()); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() { + // given + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(true); + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + + // when + guardPolicyDelegate.execute(exchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() { + // when + guardPolicyDelegate.execute(exchange); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDelegateTest.java new file mode 100644 index 00000000..1d3f1ce6 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDelegateTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.io.IOException; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +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.exception.ModelBpmnException; +import org.onap.clamp.clds.model.CldsModel; +import org.onap.clamp.clds.model.properties.Holmes; +import org.onap.clamp.clds.model.properties.ModelProperties; +import org.onap.clamp.clds.util.JsonUtils; + +@RunWith(MockitoJUnitRunner.class) +public class HolmesPolicyDelegateTest { + + private static final String ID_JSON = "{\"id\":{\"r\":[{},{\"serviceConfigurations\":" + + "[[\"x\",\"+\",\"2\",\"y\"]]}]}}"; + private static final String METRICS_JSON = "{\"metricsPerEventName\":[{\"thresholds\":[]}]}"; + private static final String CONTENT_JSON = "{\"content\":{}}"; + private static final String NULL_JSON = "{}"; + private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"id\",\"from\":\"\"}]}"; + private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"\",\"from\":\"\"}]}"; + private static final String CORRELATION_LOGIC_JSON = "{\"name\":\"correlationalLogic\"}"; + private static final String NOT_JSON = "not json"; + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String MODEL_NAME_KEY = "modelName"; + private static final String TEST_KEY = "isTest"; + private static final String USERID_KEY = "userid"; + private static final String TCA_TEMPLATE_KEY = "tca.template"; + private static final String TCA_POLICY_TEMPLATE_KEY = "tca.policy.template"; + private static final String TCA_THRESHOLDS_TEMPLATE_KEY = "tca.thresholds.template"; + private static final String HOLMES_POLICY_RESPONSE_MESSAGE_KEY = "holmesPolicyResponseMessage"; + private static final String RESPONSE_MESSAGE_VALUE = "responseMessage"; + private static final String MODEL_NAME_VALUE = "model.name"; + private static final String CONTROL_NAME_VALUE = "control.name"; + private static final String USERID_VALUE = "user"; + private static final String CLDS_MODEL_ID = "id"; + private static final String CLDS_MODEL_PROP_TEXT = "propText"; + + @Mock + private Exchange exchange; + + @Mock + private PolicyClient policyClient; + + @Mock + private ClampProperties clampProperties; + + @Mock + private CldsDao cldsDao; + + @InjectMocks + private HolmesPolicyDelegate holmesPolicyDelegateTest; + + @Test + public void shouldExecuteSuccessfully() throws IOException { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(exchange.getProperty(eq(MODEL_NAME_KEY))).thenReturn(MODEL_NAME_VALUE); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(exchange.getProperty(eq(USERID_KEY))).thenReturn(USERID_VALUE); + + JsonElement jsonTemplateA = mock(JsonElement.class); + when(clampProperties.getJsonTemplate(eq(TCA_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateA); + when(jsonTemplateA.getAsJsonObject()).thenReturn(getJsonObject(METRICS_JSON)); + + JsonElement jsonTemplateB = mock(JsonElement.class); + when(clampProperties.getJsonTemplate(eq(TCA_POLICY_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateB); + when(jsonTemplateB.getAsJsonObject()).thenReturn(getJsonObject(CONTENT_JSON)); + + JsonElement jsonTemplateC = mock(JsonElement.class); + when(clampProperties.getJsonTemplate(eq(TCA_THRESHOLDS_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplateC); + when(jsonTemplateC.getAsJsonObject()).thenReturn(getJsonObject(NULL_JSON)); + + when(policyClient.sendBasePolicyInOther(anyString(), anyString(), any(), anyString())) + .thenReturn(RESPONSE_MESSAGE_VALUE); + + CldsModel cldsModel = new CldsModel(); + cldsModel.setId(CLDS_MODEL_ID); + cldsModel.setPropText(CLDS_MODEL_PROP_TEXT); + when(cldsDao.getModelTemplate(eq(MODEL_NAME_VALUE))).thenReturn(cldsModel); + + // when + holmesPolicyDelegateTest.execute(exchange); + + // then + verify(exchange).setProperty(eq(HOLMES_POLICY_RESPONSE_MESSAGE_KEY), eq(RESPONSE_MESSAGE_VALUE.getBytes())); + verify(cldsDao).setModel(eq(cldsModel), eq(USERID_VALUE)); + } + + @Test + public void shouldExecuteHolmesNotFound() { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + // when + holmesPolicyDelegateTest.execute(exchange); + + // then + verify(policyClient, never()).sendBasePolicyInOther(anyString(), anyString(), any(), anyString()); + verify(exchange, never()).setProperty(eq(HOLMES_POLICY_RESPONSE_MESSAGE_KEY), any()); + verify(cldsDao, never()).setModel(any(), anyString()); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + // when + holmesPolicyDelegateTest.execute(exchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() { + // when + holmesPolicyDelegateTest.execute(exchange); + } + + @Test + public void shouldDoFormatHolmesConfigBodySuccessfully() { + // given + ModelProperties prop = new ModelProperties(null, CONTROL_NAME_VALUE, null, false, + HOLMES_ID_FROM_JSON, "{\"id\":" + CORRELATION_LOGIC_JSON + "}"); + Holmes holmes = prop.getType(Holmes.class); + + // when + String result = HolmesPolicyDelegate.formatHolmesConfigBody(prop, holmes); + + // then + assertEquals(CONTROL_NAME_VALUE + "$$$" + CORRELATION_LOGIC_JSON, result); + } + + private static JsonObject getJsonObject(String jsonText) { + return JsonUtils.GSON.fromJson(jsonText, JsonObject.class); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDeleteDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDeleteDelegateTest.java new file mode 100644 index 00000000..ccebbfbe --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/HolmesPolicyDeleteDelegateTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.client.req.policy.PolicyClient; +import org.onap.clamp.clds.exception.ModelBpmnException; + +@RunWith(MockitoJUnitRunner.class) +public class HolmesPolicyDeleteDelegateTest { + + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String TEST_KEY = "isTest"; + + private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"\",\"from\":\"\"}]}"; + private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"\",\"from\":\"\"}]}"; + private static final String ID_JSON = "{\"id\":\"\"}"; + private static final String NOT_JSON = "not json"; + + @Mock + private Exchange exchange; + + @Mock + private PolicyClient policyClient; + + @InjectMocks + private HolmesPolicyDeleteDelegate holmesPolicyDeleteDelegate; + + @Test + public void shouldExecuteSuccessfully() { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + // when + holmesPolicyDeleteDelegate.execute(exchange); + + // then + verify(policyClient).deleteBasePolicy(any()); + } + + @Test + public void shouldExecuteHolmesNotFound() { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON); + when(exchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + // when + holmesPolicyDeleteDelegate.execute(exchange); + + // then + verify(policyClient, never()).deleteBasePolicy(any()); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() { + // given + when(exchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + when(exchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + // when + holmesPolicyDeleteDelegate.execute(exchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() { + // when + holmesPolicyDeleteDelegate.execute(exchange); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/ModelDeleteDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/ModelDeleteDelegateTest.java new file mode 100644 index 00000000..06b94225 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/ModelDeleteDelegateTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.clamp.clds.dao.CldsDao; + +@RunWith(MockitoJUnitRunner.class) +public class ModelDeleteDelegateTest { + + private static final String NAME_KEY = "modelName"; + private static final String NAME_VALUE = "model.name"; + + @Mock + private Exchange exchange; + + @Mock + private CldsDao cldsDao; + + @InjectMocks + private ModelDeleteDelegate modelDeleteDelegate; + + @Test + public void shouldExecuteSuccessfully() { + // given + when(exchange.getProperty(eq(NAME_KEY))).thenReturn(NAME_VALUE); + + // when + modelDeleteDelegate.execute(exchange); + + // then + verify(cldsDao).deleteModel(eq(NAME_VALUE)); + } +} diff --git a/src/test/java/org/onap/clamp/clds/client/TcaPolicyDelegateTest.java b/src/test/java/org/onap/clamp/clds/client/TcaPolicyDelegateTest.java new file mode 100644 index 00000000..a8851992 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/client/TcaPolicyDelegateTest.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.client; + +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.io.IOException; + +import org.apache.camel.Exchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +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.exception.ModelBpmnException; +import org.onap.clamp.clds.model.CldsModel; +import org.onap.clamp.clds.util.JsonUtils; + +@RunWith(MockitoJUnitRunner.class) +public class TcaPolicyDelegateTest { + + private static final String MODEL_BPMN_KEY = "modelBpmnProp"; + private static final String MODEL_PROP_KEY = "modelProp"; + private static final String MODEL_NAME_KEY = "modelName"; + private static final String TEST_KEY = "isTest"; + private static final String USERID_KEY = "userid"; + private static final String TCA_TEMPLATE_KEY = "tca.template"; + private static final String TCA_POLICY_TEMPLATE_KEY = "tca.policy.template"; + private static final String TCA_THRESHOLDS_TEMPLATE_KEY = "tca.thresholds.template"; + private static final String TCA_POLICY_RESPONSE_MESSAGE_KEY = "tcaPolicyResponseMessage"; + + private static final String TCA_ID_FROM_JSON = "{\"tca\":[{\"id\":\"id\",\"from\":\"\"}]}"; + private static final String ID_JSON = "{\"id\":{\"r\":[{},{\"serviceConfigurations\":" + + "[[\"x\",\"+\",\"2\",\"y\"]]}]}}"; + private static final String TCA_TEMPLATE_JSON = "{\"metricsPerEventName\":[{\"thresholds\":[]}]}"; + private static final String TCA_POLICY_TEMPLATE_JSON = "{\"content\":{}}"; + private static final String TCA_THRESHOLDS_TEMPLATE_JSON = "{}"; + private static final String HOLMES_ID_FROM_JSON = "{\"holmes\":[{\"id\":\"\",\"from\":\"\"}]}"; + private static final String NOT_JSON = "not json"; + + private static final String RESPONSE_MESSAGE_VALUE = "responseMessage"; + private static final String MODEL_NAME_VALUE = "ModelName"; + private static final String USERID_VALUE = "user"; + + private static final String CLDS_MODEL_ID = "id"; + private static final String CLDS_MODEL_PROP_TEXT = "propText"; + + @Mock + private Exchange camelExchange; + + @Mock + private ClampProperties refProp; + + @Mock + private PolicyClient policyClient; + + @Mock + private CldsDao cldsDao; + + @InjectMocks + private TcaPolicyDelegate tcaPolicyDelegate; + + @Test + public void shouldExecuteSuccessfully() throws IOException { + //given + when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(TCA_ID_FROM_JSON); + when(camelExchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(camelExchange.getProperty(eq(MODEL_NAME_KEY))).thenReturn(MODEL_NAME_VALUE); + when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false); + when(camelExchange.getProperty(eq(USERID_KEY))).thenReturn(USERID_VALUE); + + JsonElement jsonTemplate; + JsonObject jsonObject; + + jsonTemplate = mock(JsonElement.class); + when(refProp.getJsonTemplate(eq(TCA_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate); + jsonObject = JsonUtils.GSON.fromJson(TCA_TEMPLATE_JSON, JsonObject.class); + when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject); + + jsonTemplate = mock(JsonElement.class); + when(refProp.getJsonTemplate(eq(TCA_POLICY_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate); + jsonObject = JsonUtils.GSON.fromJson(TCA_POLICY_TEMPLATE_JSON, JsonObject.class); + when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject); + + jsonTemplate = mock(JsonElement.class); + when(refProp.getJsonTemplate(eq(TCA_THRESHOLDS_TEMPLATE_KEY), anyString())).thenReturn(jsonTemplate); + jsonObject = JsonUtils.GSON.fromJson(TCA_THRESHOLDS_TEMPLATE_JSON, JsonObject.class); + when(jsonTemplate.getAsJsonObject()).thenReturn(jsonObject); + + when(policyClient.sendMicroServiceInOther(anyString(), any())).thenReturn(RESPONSE_MESSAGE_VALUE); + + CldsModel cldsModel = new CldsModel(); + cldsModel.setId(CLDS_MODEL_ID); + cldsModel.setPropText(CLDS_MODEL_PROP_TEXT); + when(cldsDao.getModelTemplate(eq(MODEL_NAME_VALUE))).thenReturn(cldsModel); + + //when + tcaPolicyDelegate.execute(camelExchange); + + //then + verify(camelExchange).setProperty(eq(TCA_POLICY_RESPONSE_MESSAGE_KEY), eq(RESPONSE_MESSAGE_VALUE.getBytes())); + verify(cldsDao).setModel(eq(cldsModel), eq(USERID_VALUE)); + } + + @Test + public void shouldExecuteTcaNotFound() { + //given + when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(HOLMES_ID_FROM_JSON); + when(camelExchange.getProperty(eq(MODEL_PROP_KEY))).thenReturn(ID_JSON); + when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + //when + tcaPolicyDelegate.execute(camelExchange); + + //then + verify(policyClient, never()).sendMicroServiceInOther(any(), any()); + } + + @Test(expected = ModelBpmnException.class) + public void shouldThrowModelBpmnException() { + //given + when(camelExchange.getProperty(eq(MODEL_BPMN_KEY))).thenReturn(NOT_JSON); + when(camelExchange.getProperty(eq(TEST_KEY))).thenReturn(false); + + //when + tcaPolicyDelegate.execute(camelExchange); + } + + @Test(expected = NullPointerException.class) + public void shouldThrowNullPointerException() { + //when + tcaPolicyDelegate.execute(camelExchange); + } +} diff --git a/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java b/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java index 58d94685..ab4421fc 100644 --- a/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java @@ -5,6 +5,8 @@ * Copyright (C) 2019 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -25,26 +27,26 @@ package org.onap.clamp.clds.it; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -import java.io.IOException; -import java.util.LinkedList; import java.util.List; +import org.apache.camel.Exchange; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; import org.mockito.Mockito; +import org.mockito.Spy; import org.onap.clamp.authorization.AuthorizationController; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.exception.NotAuthorizedException; import org.onap.clamp.clds.service.SecureServicePermission; import org.onap.clamp.util.PrincipalUtils; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.mock.env.MockEnvironment; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.userdetails.User; import org.springframework.test.context.junit4.SpringRunner; @@ -57,39 +59,59 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest public class AuthorizationControllerItCase { - protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AuthorizationControllerItCase.class); - private Authentication authentication; - private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); + private PermissionTestDefaultHelper permissionTestHelper = new PermissionTestDefaultHelper(); + + @Spy + MockEnvironment env; + + @Spy + @InjectMocks + private ClampProperties clampProp = new ClampProperties(); + + @InjectMocks + private AuthorizationController auth; /** * Setup the variable before the tests execution. - * - * @throws IOException - * In case of issues when opening the files */ @Before - public void setupBefore() throws IOException { - authList.add(new SimpleGrantedAuthority("permission-type-cl-manage|dev|*")); - authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read")); - authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update")); - authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read")); - authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); - authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); - authList.add(new SimpleGrantedAuthority("permission-type-cl-event|dev|*")); - - authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); - } + public void setupBefore() { + permissionTestHelper.setupMockEnv(env); + List<GrantedAuthority> authList = permissionTestHelper.getAuthList(); - @Test - public void testIsUserPermittedNoException() { SecurityContext securityContext = Mockito.mock(SecurityContext.class); - Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + Mockito.when(securityContext.getAuthentication()).thenReturn( + new UsernamePasswordAuthenticationToken(new User("admin", "", authList), + "", authList) + ); PrincipalUtils.setSecurityContext(securityContext); + } - AuthorizationController auth = new AuthorizationController(); + @Test + public void testIsUserPermitted() { assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-cl","dev","read"))); assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-cl-manage","dev","DEPLOY"))); - assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-filter-vf","dev","12345-55555-55555-5555"))); + assertTrue(auth.isUserPermitted(new SecureServicePermission("permission-type-filter-vf","dev", + "12345-55555-55555-5555"))); assertFalse(auth.isUserPermitted(new SecureServicePermission("permission-type-cl","test","read"))); } + + @Test + public void testIfUserAuthorize() { + Exchange ex = Mockito.mock(Exchange.class); + try { + permissionTestHelper.doActionOnAllPermissions(((type, instance, action) -> + auth.authorize(ex, type, instance, action) + ) + ); + } catch (NotAuthorizedException e) { + fail(e.getMessage()); + } + } + + @Test(expected = NotAuthorizedException.class) + public void testIfAuthorizeThrowException() { + Exchange ex = Mockito.mock(Exchange.class); + auth.authorize(ex,"permission-type-cl","test","read"); + } } diff --git a/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java index 5d891035..1dbea376 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsHealthcheckServiceItCase.java @@ -25,8 +25,6 @@ package org.onap.clamp.clds.it; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import javax.ws.rs.core.Response; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.clamp.clds.model.CldsHealthCheck; diff --git a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java index 347de4a7..faeb0418 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsServiceItCase.java @@ -149,6 +149,7 @@ public class CldsServiceItCase { Properties prop = new Properties(); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("clds-version.properties"); prop.load(in); + assertNotNull(in); in.close(); assertEquals(cldsInfo.getCldsVersion(), prop.getProperty("clds.version")); assertEquals(cldsInfo.getUserName(), "admin"); diff --git a/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java b/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java index 7d48086c..992c06e8 100644 --- a/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/CldsToscaServiceItCase.java @@ -69,7 +69,7 @@ public class CldsToscaServiceItCase { private String toscaModelYaml; private Authentication authentication; private CldsToscaModel cldsToscaModel; - private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); + private List<GrantedAuthority> authList = new LinkedList<>(); private LoggingUtils util; /** diff --git a/src/test/java/org/onap/clamp/clds/it/PermissionTestDefaultHelper.java b/src/test/java/org/onap/clamp/clds/it/PermissionTestDefaultHelper.java new file mode 100644 index 00000000..fa22b02b --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/it/PermissionTestDefaultHelper.java @@ -0,0 +1,61 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.it; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class PermissionTestDefaultHelper extends PermissionTestHelper { + + private static final String[] ALL_ACTION = new String[] {"*"}; + private static final String[] READ_UPDATE_ACTION = new String[] {"read", "update"}; + + private static final String DEV_INSTANCE = "dev"; + private static final String TEST_INSTANCE = "test"; + + private static final Map<String, Map> defaultPermission = ImmutableMap.of( + "permission-type-cl", ImmutableMap.of( + DEV_INSTANCE, ALL_ACTION), + "permission-type-cl-event", ImmutableMap.of( + DEV_INSTANCE, ALL_ACTION, + TEST_INSTANCE, READ_UPDATE_ACTION), + "permission-type-cl-manage", ImmutableMap.of( + DEV_INSTANCE, ALL_ACTION, + TEST_INSTANCE, READ_UPDATE_ACTION), + "permission-type-filter-vf", ImmutableMap.of( + DEV_INSTANCE, ALL_ACTION, + TEST_INSTANCE, READ_UPDATE_ACTION), + "permission-type-template", ImmutableMap.of( + DEV_INSTANCE, ALL_ACTION, + TEST_INSTANCE, READ_UPDATE_ACTION) + ); + + /** + * Permission test default helper constructor. + * This class setup the default permission in the parent PermissionTestHelper class. + */ + public PermissionTestDefaultHelper() { + super(defaultPermission); + } +} diff --git a/src/test/java/org/onap/clamp/clds/it/PermissionTestHelper.java b/src/test/java/org/onap/clamp/clds/it/PermissionTestHelper.java new file mode 100644 index 00000000..ee073b01 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/it/PermissionTestHelper.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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.it; + +import static org.onap.clamp.authorization.AuthorizationController.PERM_PREFIX; +import static org.onap.clamp.clds.config.ClampProperties.CONFIG_PREFIX; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.springframework.mock.env.MockEnvironment; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; + +public class PermissionTestHelper { + + private static final String securityPrefix = CONFIG_PREFIX + PERM_PREFIX; + private final Map<String, Map> permission; + private static final List<GrantedAuthority> authList = new LinkedList<>(); + + /** + * Permission Test Helper constructor + * Generate authList base on general permission collection + */ + public PermissionTestHelper(Map<String, Map> permission) { + this.permission = permission; + this.createAuthList(); + } + + private void createAuthList() { + permission.forEach((type, instanceMap) -> instanceMap.forEach((instance, actionList) -> { + for (String action : (String[]) actionList) { + authList.add(new SimpleGrantedAuthority(type + "|" + instance + "|" + action)); + } + })); + } + + List<GrantedAuthority> getAuthList() { + return authList; + } + + void setupMockEnv(MockEnvironment env) { + permission.forEach((type, instanceMap) -> env.withProperty(securityPrefix + type, type)); + } + + void doActionOnAllPermissions(PermissionAction action) { + permission.forEach((type, instanceMap) -> instanceMap.forEach((instance, actionList) -> { + for (String actionName : (String[]) actionList) { + action.doAction(type, (String) instance, actionName); + } + })); + } + + @FunctionalInterface + public interface PermissionAction { + void doAction(String type, String instance, String action); + } +} diff --git a/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java b/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java index 55657c97..0f0ecaed 100644 --- a/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,9 +25,13 @@ package org.onap.clamp.clds.it.sdc.controller; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; - import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; @@ -33,12 +39,16 @@ import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.clamp.clds.config.ClampProperties; import org.onap.clamp.clds.config.sdc.SdcSingleControllerConfigurationTest; +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.CsarHandler; import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.api.notification.INotificationData; import org.onap.sdc.api.notification.IResourceInstance; +import org.slf4j.MDC; +import org.slf4j.spi.MDCAdapter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @@ -59,24 +69,26 @@ public class SdcSingleControllerItCase { private SdcSingleController sdcSingleController; + private CsarInstaller csarInstaller = mock(CsarInstaller.class); + private INotificationData buildFakeSdcNotification() { // BUild what is needed for CSAR - IArtifactInfo serviceArtifact = Mockito.mock(IArtifactInfo.class); + IArtifactInfo serviceArtifact = mock(IArtifactInfo.class); Mockito.when(serviceArtifact.getArtifactType()).thenReturn(CsarHandler.CSAR_TYPE); Mockito.when(serviceArtifact.getArtifactName()).thenReturn(CSAR_ARTIFACT_NAME); List<IArtifactInfo> servicesList = new ArrayList<>(); servicesList.add(serviceArtifact); - INotificationData notifData = Mockito.mock(INotificationData.class); + INotificationData notifData = mock(INotificationData.class); Mockito.when(notifData.getServiceArtifacts()).thenReturn(servicesList); // Build what is needed for UUID Mockito.when(notifData.getServiceInvariantUUID()).thenReturn(SERVICE_UUID); // Build fake resource with one artifact BLUEPRINT - IResourceInstance resource1 = Mockito.mock(IResourceInstance.class); + IResourceInstance resource1 = mock(IResourceInstance.class); Mockito.when(resource1.getResourceType()).thenReturn("VF"); Mockito.when(resource1.getResourceInvariantUUID()).thenReturn(RESOURCE1_UUID); Mockito.when(resource1.getResourceInstanceName()).thenReturn(RESOURCE1_INSTANCE_NAME); // Create a fake artifact for resource - IArtifactInfo blueprintArtifact = Mockito.mock(IArtifactInfo.class); + IArtifactInfo blueprintArtifact = mock(IArtifactInfo.class); Mockito.when(blueprintArtifact.getArtifactType()).thenReturn(CsarHandler.BLUEPRINT_TYPE); List<IArtifactInfo> artifactsListForResource = new ArrayList<>(); artifactsListForResource.add(blueprintArtifact); @@ -92,7 +104,7 @@ public class SdcSingleControllerItCase { */ @Before public void init() { - sdcSingleController = new SdcSingleController(clampProp, Mockito.mock(CsarInstaller.class), + sdcSingleController = new SdcSingleController(clampProp, csarInstaller, SdcSingleControllerConfigurationTest.loadControllerConfiguration("clds/sdc-controller-config-TLS.json", "sdc-controller1"), null) { @@ -101,9 +113,36 @@ public class SdcSingleControllerItCase { @Test public void testTreatNotification() { + //when sdcSingleController.treatNotification(buildFakeSdcNotification()); + //then Assertions.assertThat(sdcSingleController.getNbOfNotificationsOngoing()).isEqualTo(0); + } + @Test + public void testCloseSdc() throws SdcControllerException { + //when + sdcSingleController.closeSdc(); + //then + assertThat(sdcSingleController.getControllerStatus()).isEqualTo(SdcSingleControllerStatus.STOPPED); } + @Test + public void testActivateCallback() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException, ClassNotFoundException { + //given + MDCAdapter mdcAdapter = MDC.getMDCAdapter(); + Class<?> innerClass = Class.forName("org.onap.clamp.clds.sdc.controller.SdcSingleController$SdcNotificationCallBack"); + Constructor<?> constructor = innerClass.getDeclaredConstructor(SdcSingleController.class, SdcSingleController.class); + constructor.setAccessible(true); + Object child = constructor.newInstance(sdcSingleController,sdcSingleController); + Method method = child.getClass().getDeclaredMethod("activateCallback",INotificationData.class); + method.setAccessible(true); + //when + method.invoke(child,buildFakeSdcNotification()); + //then + assertThat(mdcAdapter.get("ResponseCode")).isEqualTo("0"); + assertThat(mdcAdapter.get("StatusCode")).isEqualTo("COMPLETE"); + assertThat(mdcAdapter.get("ResponseDescription")).isEqualTo("SDC Notification received and processed successfully"); + assertThat(mdcAdapter.get("ClassName")).isEqualTo(child.getClass().getName()); + } } diff --git a/src/test/java/org/onap/clamp/clds/model/DcaeEventTest.java b/src/test/java/org/onap/clamp/clds/model/DcaeEventTest.java new file mode 100644 index 00000000..315e656d --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/model/DcaeEventTest.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. 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; + +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import javax.ws.rs.BadRequestException; +import java.util.Arrays; + +public class DcaeEventTest { + + @Test + public void testGetCldsActionId() { + //given + DcaeEvent dcaeEvent = new DcaeEvent(); + dcaeEvent.setEvent(DcaeEvent.EVENT_CREATED); + dcaeEvent.setResourceUUID("1"); + dcaeEvent.setServiceUUID("2"); + + //when + String cldsAction = dcaeEvent.getCldsActionCd(); + dcaeEvent.setInstances(Arrays.asList(new CldsModelInstance())); + //then + assertEquals(CldsEvent.ACTION_CREATE, cldsAction); + + //when + dcaeEvent.setEvent(DcaeEvent.EVENT_DEPLOYMENT); + //then + assertEquals(CldsEvent.ACTION_DEPLOY, dcaeEvent.getCldsActionCd()); + + //when + dcaeEvent.setInstances(null); + //then + assertEquals(CldsEvent.ACTION_DEPLOY, dcaeEvent.getCldsActionCd()); + + //when + dcaeEvent.setEvent(DcaeEvent.EVENT_UNDEPLOYMENT); + //then + assertEquals(CldsEvent.ACTION_UNDEPLOY, dcaeEvent.getCldsActionCd()); + + } + + @Test(expected = BadRequestException.class) + public void shouldReturnBadRequestException() { + //given + DcaeEvent dcaeEvent = new DcaeEvent(); + dcaeEvent.setResourceUUID("1"); + dcaeEvent.setServiceUUID("2"); + //when + dcaeEvent.setEvent("BadEvent"); + //then + dcaeEvent.getCldsActionCd(); + } +} diff --git a/src/test/java/org/onap/clamp/clds/util/CryptoUtilsTest.java b/src/test/java/org/onap/clamp/clds/util/CryptoUtilsTest.java index 603d2d28..1e6742c9 100644 --- a/src/test/java/org/onap/clamp/clds/util/CryptoUtilsTest.java +++ b/src/test/java/org/onap/clamp/clds/util/CryptoUtilsTest.java @@ -5,7 +5,9 @@ * Copyright (C) 2017 AT&T Intellectual Property. All rights * reserved. * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -26,17 +28,30 @@ package org.onap.clamp.clds.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.eq; + +import java.security.InvalidKeyException; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; - +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"javax.crypto.*"}) public class CryptoUtilsTest { private final String data = "This is a test string"; @Test + @PrepareForTest({CryptoUtils.class}) public final void testEncryption() throws Exception { String encodedString = CryptoUtils.encrypt(data); assertNotNull(encodedString); @@ -44,6 +59,7 @@ public class CryptoUtilsTest { } @Test + @PrepareForTest({CryptoUtils.class}) public final void testEncryptedStringIsDifferent() throws Exception { String encodedString1 = CryptoUtils.encrypt(data); String encodedString2 = CryptoUtils.encrypt(data); @@ -56,4 +72,30 @@ public class CryptoUtilsTest { byte[] subData2 = ArrayUtils.subarray(encryptedMessage2, 16, encryptedMessage2.length); assertNotEquals(subData1, subData2); } -}
\ No newline at end of file + + @Test + @PrepareForTest({CryptoUtils.class}) + public final void testEncryptionBaseOnRandomKey() throws Exception { + SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); + final String encryptionKey = String.valueOf(Hex.encodeHex(secretKey.getEncoded())); + setAesEncryptionKeyEnv(encryptionKey); + + String encodedString = CryptoUtils.encrypt(data); + String decodedString = CryptoUtils.decrypt(encodedString); + assertEquals(data, decodedString); + } + + @Test(expected = InvalidKeyException.class) + @PrepareForTest({CryptoUtils.class}) + public final void testEncryptionBadKey() throws Exception { + final String badEncryptionKey = "93210sd"; + setAesEncryptionKeyEnv(badEncryptionKey); + + CryptoUtils.encrypt(data); + } + + private static void setAesEncryptionKeyEnv(String value) { + PowerMockito.mockStatic(System.class); + PowerMockito.when(System.getenv(eq("AES_ENCRYPTION_KEY"))).thenReturn(value); + } +} diff --git a/src/test/java/org/onap/clamp/clds/util/JsonUtilsTest.java b/src/test/java/org/onap/clamp/clds/util/JsonUtilsTest.java index 82c2162a..d1adc166 100644 --- a/src/test/java/org/onap/clamp/clds/util/JsonUtilsTest.java +++ b/src/test/java/org/onap/clamp/clds/util/JsonUtilsTest.java @@ -5,6 +5,8 @@ * Copyright (C) 2018 AT&T Intellectual Property. All rights * reserved. * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -155,4 +157,9 @@ public class JsonUtilsTest { // then assertThat(timeoutValue).isEqualTo(500); } + + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionFileNotExists() throws IOException { + ResourceFileUtil.getResourceAsString("example/notExist.json"); + } } diff --git a/src/test/java/org/onap/clamp/clds/util/drawing/DocumentBuilderTest.java b/src/test/java/org/onap/clamp/clds/util/drawing/DocumentBuilderTest.java index 6546553c..63a1fa3e 100644 --- a/src/test/java/org/onap/clamp/clds/util/drawing/DocumentBuilderTest.java +++ b/src/test/java/org/onap/clamp/clds/util/drawing/DocumentBuilderTest.java @@ -47,9 +47,6 @@ public class DocumentBuilderTest { @Mock private SVGGraphics2D mockG2d; - @Mock - private Document mockDomImpl; - @Test public void pushChangestoDocumentTest() throws IOException, ParserConfigurationException, SAXException { String dataElementId = "someId"; diff --git a/src/test/java/org/onap/clamp/flow/FlowLogOperationTest.java b/src/test/java/org/onap/clamp/flow/FlowLogOperationTest.java new file mode 100644 index 00000000..16136ae2 --- /dev/null +++ b/src/test/java/org/onap/clamp/flow/FlowLogOperationTest.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 Samsung. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.flow; + +import static junit.framework.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.clds.util.ONAPLogConstants; +import org.onap.clamp.flow.log.FlowLogOperation; +import org.slf4j.MDC; +import org.slf4j.spi.MDCAdapter; +import org.springframework.test.util.ReflectionTestUtils; + +public class FlowLogOperationTest { + + private FlowLogOperation flowLogOperation = new FlowLogOperation(); + + @Test + public void testStratLog() { + //given + Exchange exchange = new DefaultExchange(mock(CamelContext.class)); + LoggingUtils loggingUtils = mock(LoggingUtils.class); + ReflectionTestUtils.setField(flowLogOperation, "util", loggingUtils); + + //when + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)).thenReturn("MockRequestId"); + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)).thenReturn("MockInvocationId"); + Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)).thenReturn("MockPartnerName"); + flowLogOperation.startLog(exchange, "serviceName"); + + //then + assertThat(exchange.getProperty(ONAPLogConstants.Headers.REQUEST_ID)).isEqualTo("MockRequestId"); + assertThat(exchange.getProperty(ONAPLogConstants.Headers.INVOCATION_ID)).isEqualTo("MockInvocationId"); + assertThat(exchange.getProperty(ONAPLogConstants.Headers.PARTNER_NAME)).isEqualTo("MockPartnerName"); + } + + @Test + public void testInvokeLog() { + //given + final String mockEntity = "mockEntity"; + final String mockServiceName = "mockSerivceName"; + MDCAdapter mdcAdapter = MDC.getMDCAdapter(); + //when + flowLogOperation.invokeLog(mockEntity, mockServiceName); + //then + String entity = mdcAdapter.get(ONAPLogConstants.MDCs.TARGET_ENTITY); + String serviceName = mdcAdapter.get(ONAPLogConstants.MDCs.TARGET_SERVICE_NAME); + assertEquals(entity,mockEntity); + assertEquals(serviceName,mockServiceName); + } + + @Test + public void testEndLog() { + //given + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-05-19T00:00:00.007Z"); + MDCAdapter mdcAdapter = MDC.getMDCAdapter(); + ///when + flowLogOperation.endLog(); + //then + assertThat(mdcAdapter.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)).isNull(); + } + + @Test + public void testErrorLog() { + //given + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-05-19T00:00:00.007Z"); + MDCAdapter mdcAdapter = MDC.getMDCAdapter(); + //when + flowLogOperation.errorLog(); + //then + assertThat(mdcAdapter.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)).isNull(); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java b/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java deleted file mode 100644 index 1abeb104..00000000 --- a/src/test/java/org/onap/clamp/flow/FlowLogOperationTestItCase.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.onap.clamp.flow; - -import org.apache.camel.CamelContext; -import org.apache.camel.Exchange; -import org.apache.camel.impl.DefaultExchange; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.clamp.clds.util.LoggingUtils; -import org.onap.clamp.clds.util.ONAPLogConstants; -import org.onap.clamp.flow.log.FlowLogOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.util.ReflectionTestUtils; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - - -public class FlowLogOperationTestItCase { - - @Autowired - CamelContext camelContext; - - @Test - public void testStratLog() { - //given - FlowLogOperation flowLogOperation = new FlowLogOperation(); - Exchange exchange = new DefaultExchange(camelContext); - LoggingUtils loggingUtils = mock(LoggingUtils.class); - ReflectionTestUtils.setField(flowLogOperation, "util", loggingUtils); - - //when - Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.REQUEST_ID)).thenReturn("MockRequestId"); - Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.INVOCATION_ID)).thenReturn("MockInvocationId"); - Mockito.when(loggingUtils.getProperties(ONAPLogConstants.MDCs.PARTNER_NAME)).thenReturn("MockPartnerName"); - flowLogOperation.startLog(exchange, "serviceName"); - - //then - assertThat(exchange.getProperty(ONAPLogConstants.Headers.REQUEST_ID)).isEqualTo("MockRequestId"); - assertThat(exchange.getProperty(ONAPLogConstants.Headers.INVOCATION_ID)).isEqualTo("MockInvocationId"); - assertThat(exchange.getProperty(ONAPLogConstants.Headers.PARTNER_NAME)).isEqualTo("MockPartnerName"); - } -}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java index cd6db68d..773332dd 100644 --- a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java @@ -6,7 +6,8 @@ * reserved. * ================================================================================ * Modifications copyright (c) 2019 Nokia - * =================================================================== + * 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 @@ -220,4 +221,13 @@ public class CsarInstallerItCase { assertThat(((MicroServicePolicy) (loop.getMicroServicePolicies().toArray()[0])).getModelType()).isNotEmpty(); } + @Test(expected = SdcArtifactInstallerException.class) + @Transactional + public void shouldThrowSdcArtifactInstallerException() throws SdcArtifactInstallerException, + SdcToscaParserException, IOException, InterruptedException, PolicyModelException { + String generatedName = RandomStringUtils.randomAlphanumeric(5); + CsarHandler csarHandler = buildFakeCsarHandler(generatedName); + Mockito.when(csarHandler.getMapOfBlueprints()).thenThrow(IOException.class); + csarInstaller.installTheCsar(csarHandler); + } } diff --git a/src/test/java/org/onap/clamp/loop/DcaeComponentTest.java b/src/test/java/org/onap/clamp/loop/DcaeComponentTest.java new file mode 100644 index 00000000..0a3c1e16 --- /dev/null +++ b/src/test/java/org/onap/clamp/loop/DcaeComponentTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights + * reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END============================================ + * =================================================================== + * + */ + +package org.onap.clamp.loop; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.util.HashSet; + +import org.junit.Test; +import org.onap.clamp.clds.model.dcae.DcaeOperationStatusResponse; +import org.onap.clamp.loop.components.external.DcaeComponent; +import org.onap.clamp.policy.microservice.MicroServicePolicy; + +public class DcaeComponentTest { + + private Loop createTestLoop() { + String yaml = "imports:\n" + " - \"http://www.getcloudify.org/spec/cloudify/3.4/types.yaml\"\n" + + "node_templates:\n" + " docker_service_host:\n" + " type: dcae.nodes.SelectedDockerHost"; + + Loop loopTest = new Loop("ControlLoopTest", yaml, "<xml></xml>"); + loopTest.setGlobalPropertiesJson( + new Gson().fromJson("{\"dcaeDeployParameters\":" + "{\"policy_id\": \"name\"}}", JsonObject.class)); + loopTest.setLastComputedState(LoopState.DESIGN); + loopTest.setDcaeDeploymentId("123456789"); + loopTest.setDcaeDeploymentStatusUrl("http4://localhost:8085"); + loopTest.setDcaeBlueprintId("UUID-blueprint"); + + MicroServicePolicy microServicePolicy = new MicroServicePolicy("configPolicyTest", "", + "tosca_definitions_version: tosca_simple_yaml_1_0_0", true, + new Gson().fromJson("{\"configtype\":\"json\"}", JsonObject.class), new HashSet<>()); + microServicePolicy.setProperties(new Gson().fromJson("{\"param1\":\"value1\"}", JsonObject.class)); + + loopTest.addMicroServicePolicy(microServicePolicy); + return loopTest; + } + + @Test + public void convertDcaeResponseTest() throws IOException { + String dcaeFakeResponse = "{'requestId':'testId','operationType':'install','status':'state','error':'errorMessage', 'links':{'self':'selfUrl','uninstall':'uninstallUrl'}}"; + DcaeOperationStatusResponse responseObject = DcaeComponent.convertDcaeResponse(dcaeFakeResponse); + assertThat(responseObject.getRequestId()).isEqualTo("testId"); + assertThat(responseObject.getOperationType()).isEqualTo("install"); + assertThat(responseObject.getStatus()).isEqualTo("state"); + assertThat(responseObject.getError()).isEqualTo("errorMessage"); + assertThat(responseObject.getLinks()).isNotNull(); + assertThat(responseObject.getLinks().getSelf()).isEqualTo("selfUrl"); + assertThat(responseObject.getLinks().getUninstall()).isEqualTo("uninstallUrl"); + + assertThat(responseObject.getLinks().getStatus()).isNull(); + } + + @Test + public void testGetDeployPayload() throws IOException { + Loop loop = this.createTestLoop(); + String deploymentPayload = DcaeComponent.getDeployPayload(loop); + String expectedPayload = "{\"serviceTypeId\":\"UUID-blueprint\",\"inputs\":{\"policy_id\":\"name\"}}"; + assertThat(deploymentPayload).isEqualTo(expectedPayload); + } + + @Test + public void testGetUndeployPayload() throws IOException { + Loop loop = this.createTestLoop(); + String unDeploymentPayload = DcaeComponent.getUndeployPayload(loop); + String expectedPayload = "{\"serviceTypeId\":\"UUID-blueprint\"}"; + assertThat(unDeploymentPayload).isEqualTo(expectedPayload); + } + +} diff --git a/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java b/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java deleted file mode 100644 index a2c97e0c..00000000 --- a/src/test/java/org/onap/clamp/loop/LoopOperationTestItCase.java +++ /dev/null @@ -1,244 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2019 Nokia 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.loop; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.util.HashSet; - -import org.apache.camel.Exchange; -import org.apache.camel.Message; -import org.json.simple.parser.ParseException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.onap.clamp.clds.Application; -import org.onap.clamp.loop.LoopOperation.TempLoopState; -import org.onap.clamp.policy.microservice.MicroServicePolicy; -import org.onap.clamp.policy.operational.OperationalPolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) -public class LoopOperationTestItCase { - - private Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create(); - @Autowired - LoopService loopService; - - private Loop createTestLoop() { - String yaml = "imports:\n" + " - \"http://www.getcloudify.org/spec/cloudify/3.4/types.yaml\"\n" - + "node_templates:\n" + " docker_service_host:\n" + " type: dcae.nodes.SelectedDockerHost"; - - Loop loopTest = new Loop("ControlLoopTest", yaml, "<xml></xml>"); - loopTest.setGlobalPropertiesJson( - new Gson().fromJson("{\"dcaeDeployParameters\":" + "{\"policy_id\": \"name\"}}", JsonObject.class)); - loopTest.setLastComputedState(LoopState.DESIGN); - loopTest.setDcaeDeploymentId("123456789"); - loopTest.setDcaeDeploymentStatusUrl("http4://localhost:8085"); - loopTest.setDcaeBlueprintId("UUID-blueprint"); - - MicroServicePolicy microServicePolicy = new MicroServicePolicy("configPolicyTest", "", - "tosca_definitions_version: tosca_simple_yaml_1_0_0", true, - gson.fromJson("{\"configtype\":\"json\"}", JsonObject.class), new HashSet<>()); - microServicePolicy.setProperties(new Gson().fromJson("{\"param1\":\"value1\"}", JsonObject.class)); - - loopTest.addMicroServicePolicy(microServicePolicy); - return loopTest; - } - - @Test - public void testAnalysePolicyResponse() { - LoopOperation loopOp = new LoopOperation(loopService); - String status1 = loopOp.analysePolicyResponse(200); - String status2 = loopOp.analysePolicyResponse(404); - String status3 = loopOp.analysePolicyResponse(500); - String status4 = loopOp.analysePolicyResponse(503); - - // then - assertThat(status1).isEqualTo("SUBMITTED"); - assertThat(status2).isEqualTo("NOT_SUBMITTED"); - assertThat(status3).isEqualTo("IN_ERROR"); - assertThat(status4).isEqualTo("IN_ERROR"); - } - - @Test - public void testGetOperationalPolicyName() { - LoopOperation loopOp = new LoopOperation(loopService); - Loop loop = this.createTestLoop(); - String opName1 = loopOp.getOperationalPolicyName(loop); - assertThat(opName1).isNull(); - - OperationalPolicy opPolicy1 = new OperationalPolicy("OperationalPolicyTest1", null, - gson.fromJson("{\"type\":\"Operational\"}", JsonObject.class)); - loop.addOperationalPolicy(opPolicy1); - String opName2 = loopOp.getOperationalPolicyName(loop); - assertThat(opName2).isEqualTo("OperationalPolicyTest1"); - } - - @Test - public void testAnalyseDcaeResponse() throws ParseException { - LoopOperation loopOp = new LoopOperation(loopService); - String dcaeStatus1 = loopOp.analyseDcaeResponse(null, null); - assertThat(dcaeStatus1).isEqualTo("NOT_DEPLOYED"); - - String dcaeStatus2 = loopOp.analyseDcaeResponse(null, 500); - assertThat(dcaeStatus2).isEqualTo("IN_ERROR"); - - String dcaeStatus3 = loopOp.analyseDcaeResponse(null, 404); - assertThat(dcaeStatus3).isEqualTo("NOT_DEPLOYED"); - - Exchange camelExchange = Mockito.mock(Exchange.class); - Message mockMessage = Mockito.mock(Message.class); - Mockito.when(camelExchange.getIn()).thenReturn(mockMessage); - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"install\",\"status\":\"succeeded\"}"); - String dcaeStatus4 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus4).isEqualTo("DEPLOYED"); - - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"install\",\"status\":\"processing\"}"); - String dcaeStatus5 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus5).isEqualTo("PROCESSING"); - - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"install\",\"status\":\"failed\"}"); - String dcaeStatus6 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus6).isEqualTo("IN_ERROR"); - - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"succeeded\"}"); - String dcaeStatus7 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus7).isEqualTo("NOT_DEPLOYED"); - - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"processing\"}"); - String dcaeStatus8 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus8).isEqualTo("PROCESSING"); - - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"operationType\":\"uninstall\",\"status\":\"failed\"}"); - String dcaeStatus9 = loopOp.analyseDcaeResponse(camelExchange, 200); - assertThat(dcaeStatus9).isEqualTo("IN_ERROR"); - } - - @Test - public void testUpdateLoopStatus() { - LoopOperation loopOp = new LoopOperation(loopService); - Loop loop = this.createTestLoop(); - loopService.saveOrUpdateLoop(loop); - LoopState newState1 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.DEPLOYED); - LoopState dbState1 = loopService.getLoop(loop.getName()).getLastComputedState(); - assertThat(newState1).isEqualTo(LoopState.DEPLOYED); - assertThat(dbState1).isEqualTo(LoopState.DEPLOYED); - - LoopState newState2 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.NOT_DEPLOYED); - LoopState dbState2 = loopService.getLoop(loop.getName()).getLastComputedState(); - assertThat(newState2).isEqualTo(LoopState.SUBMITTED); - assertThat(dbState2).isEqualTo(LoopState.SUBMITTED); - - LoopState newState3 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.PROCESSING); - assertThat(newState3).isEqualTo(LoopState.WAITING); - - LoopState newState4 = loopOp.updateLoopStatus(loop, TempLoopState.SUBMITTED, TempLoopState.IN_ERROR); - assertThat(newState4).isEqualTo(LoopState.IN_ERROR); - - LoopState newState5 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.DEPLOYED); - assertThat(newState5).isEqualTo(LoopState.IN_ERROR); - - LoopState newState6 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.PROCESSING); - assertThat(newState6).isEqualTo(LoopState.IN_ERROR); - - LoopState newState7 = loopOp.updateLoopStatus(loop, TempLoopState.NOT_SUBMITTED, TempLoopState.NOT_DEPLOYED); - assertThat(newState7).isEqualTo(LoopState.DESIGN); - - LoopState newState8 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.DEPLOYED); - assertThat(newState8).isEqualTo(LoopState.IN_ERROR); - - LoopState newState9 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.NOT_DEPLOYED); - assertThat(newState9).isEqualTo(LoopState.IN_ERROR); - - LoopState newState10 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.PROCESSING); - assertThat(newState10).isEqualTo(LoopState.IN_ERROR); - - LoopState newState11 = loopOp.updateLoopStatus(loop, TempLoopState.IN_ERROR, TempLoopState.IN_ERROR); - assertThat(newState11).isEqualTo(LoopState.IN_ERROR); - } - - @Test - public void testUpdateLoopInfo() throws ParseException { - Loop loop = this.createTestLoop(); - loopService.saveOrUpdateLoop(loop); - - Exchange camelExchange = Mockito.mock(Exchange.class); - Message mockMessage = Mockito.mock(Message.class); - Mockito.when(camelExchange.getIn()).thenReturn(mockMessage); - Mockito.when(mockMessage.getBody(String.class)) - .thenReturn("{\"links\":{\"status\":\"http://testhost/dcae-operationstatus\",\"test2\":\"test2\"}}"); - - LoopOperation loopOp = new LoopOperation(loopService); - loopOp.updateLoopInfo(camelExchange, loop, "testNewId"); - - Loop newLoop = loopService.getLoop(loop.getName()); - String newDeployId = newLoop.getDcaeDeploymentId(); - String newDeploymentStatusUrl = newLoop.getDcaeDeploymentStatusUrl(); - - assertThat(newDeployId).isEqualTo("testNewId"); - assertThat(newDeploymentStatusUrl).isEqualTo("http4://testhost/dcae-operationstatus"); - } - - @Test - public void testGetDeploymentId() { - Loop loop = this.createTestLoop(); - LoopOperation loopOp = new LoopOperation(loopService); - String deploymentId1 = loopOp.getDeploymentId(loop); - assertThat(deploymentId1).isEqualTo("123456789"); - - loop.setDcaeDeploymentId(null); - String deploymentId2 = loopOp.getDeploymentId(loop); - assertThat(deploymentId2).startsWith("CLAMP_"); - - loop.setDcaeDeploymentId(""); - String deploymentId3 = loopOp.getDeploymentId(loop); - assertThat(deploymentId3).startsWith("CLAMP_"); - assertThat(deploymentId3).isNotEqualTo(deploymentId2); - } - - @Test - public void testGetDeployPayload() throws IOException { - Loop loop = this.createTestLoop(); - LoopOperation loopOp = new LoopOperation(loopService); - String deploymentPayload = loopOp.getDeployPayload(loop); - - String expectedPayload = "{\"serviceTypeId\":\"UUID-blueprint\",\"inputs\":{\"policy_id\":\"name\"}}"; - assertThat(deploymentPayload).isEqualTo(expectedPayload); - } -}
\ No newline at end of file diff --git a/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java b/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java index a935808a..9a82ec09 100644 --- a/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java +++ b/src/test/java/org/onap/clamp/loop/LoopRepositoriesItCase.java @@ -92,7 +92,7 @@ public class LoopRepositoriesItCase { } private LoopLog getLoopLog(LogType type, String message, Loop loop) { - return new LoopLog(message, type, loop); + return new LoopLog(message, type, "CLAMP", loop); } @Test @@ -116,7 +116,7 @@ public class LoopRepositoriesItCase { // Now set the ID in the previous model so that we can compare the objects loopLog.setId(((LoopLog) loopInDb.getLoopLogs().toArray()[0]).getId()); - assertThat(loopInDb).isEqualToComparingFieldByField(loopTest); + assertThat(loopInDb).isEqualToIgnoringGivenFields(loopTest, "components"); assertThat(loopRepository.existsById(loopTest.getName())).isEqualTo(true); assertThat(operationalPolicyService.isExisting(opPolicy.getName())).isEqualTo(true); assertThat(microServicePolicyService.isExisting(microServicePolicy.getName())).isEqualTo(true); @@ -124,7 +124,7 @@ public class LoopRepositoriesItCase { // Now attempt to read from database Loop loopInDbRetrieved = loopRepository.findById(loopTest.getName()).get(); - assertThat(loopInDbRetrieved).isEqualToComparingFieldByField(loopTest); + assertThat(loopInDbRetrieved).isEqualToIgnoringGivenFields(loopTest, "components"); assertThat((LoopLog) loopInDbRetrieved.getLoopLogs().toArray()[0]).isEqualToComparingFieldByField(loopLog); assertThat((OperationalPolicy) loopInDbRetrieved.getOperationalPolicies().toArray()[0]) .isEqualToComparingFieldByField(opPolicy); diff --git a/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java b/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java index c4254ec8..8add1a7b 100644 --- a/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java +++ b/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java @@ -296,7 +296,7 @@ public class LoopServiceTestItCase { saveTestLoopToDb(); // Add log Loop loop = loopsRepository.findById(EXAMPLE_LOOP_NAME).orElse(null); - loop.addLog(new LoopLog("test", LogType.INFO, loop)); + loop.addLog(new LoopLog("test", LogType.INFO, "CLAMP", loop)); loop = loopService.saveOrUpdateLoop(loop); // Add op policy OperationalPolicy operationalPolicy = new OperationalPolicy("opPolicy", null, diff --git a/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java b/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java index dcad1a51..8899a36c 100644 --- a/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java +++ b/src/test/java/org/onap/clamp/loop/LoopToJsonTest.java @@ -36,6 +36,7 @@ import java.util.Random; import org.junit.Test; import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.clds.util.ResourceFileUtil; +import org.onap.clamp.loop.components.external.PolicyComponent; import org.onap.clamp.loop.log.LogType; import org.onap.clamp.loop.log.LoopLog; import org.onap.clamp.policy.microservice.MicroServicePolicy; @@ -71,7 +72,7 @@ public class LoopToJsonTest { } private LoopLog getLoopLog(LogType type, String message, Loop loop) { - LoopLog log = new LoopLog(message, type, loop); + LoopLog log = new LoopLog(message, type, "CLAMP", loop); log.setId(Long.valueOf(new Random().nextInt())); return log; } @@ -95,8 +96,12 @@ public class LoopToJsonTest { System.out.println(jsonSerialized); Loop loopTestDeserialized = JsonUtils.GSON_JPA_MODEL.fromJson(jsonSerialized, Loop.class); assertNotNull(loopTestDeserialized); - assertThat(loopTestDeserialized).isEqualToIgnoringGivenFields(loopTest, "svgRepresentation", "blueprint"); - + assertThat(loopTestDeserialized).isEqualToIgnoringGivenFields(loopTest, "svgRepresentation", "blueprint", + "components"); + assertThat(loopTestDeserialized.getComponent("DCAE").getState()) + .isEqualToComparingFieldByField(loopTest.getComponent("DCAE").getState()); + assertThat(loopTestDeserialized.getComponent("POLICY").getState()) + .isEqualToComparingFieldByField(loopTest.getComponent("POLICY").getState()); // svg and blueprint not exposed so wont be deserialized assertThat(loopTestDeserialized.getBlueprint()).isEqualTo(null); assertThat(loopTestDeserialized.getSvgRepresentation()).isEqualTo(null); @@ -121,6 +126,6 @@ public class LoopToJsonTest { loopTest.addMicroServicePolicy(microServicePolicy); JSONAssert.assertEquals(ResourceFileUtil.getResourceAsString("tosca/pdp-group-policy-payload.json"), - loopTest.createPoliciesPayloadPdpGroup(), false); + PolicyComponent.createPoliciesPayloadPdpGroup(loopTest), false); } } diff --git a/src/test/javascript/propertyController.test.js b/src/test/javascript/propertyController.test.js index fbbc6bec..e7199966 100644 --- a/src/test/javascript/propertyController.test.js +++ b/src/test/javascript/propertyController.test.js @@ -30,16 +30,4 @@ describe('Property controller tests', function() { test('getMsUINotExist', () => { expect(propertyController.getMsUI("test")).toEqual(null); }); - - test('getLastUpdatedStatus', () => { - expect(propertyController.getLastUpdatedStatus()).toEqual('DESIGN'); - }); - - test('getDeploymentID', () => { - expect(propertyController.getDeploymentID()).toEqual('testId'); - }); - - test('getDeploymentStatusURL', () => { - expect(propertyController.getDeploymentStatusURL()).toEqual('testUrl'); - }); });
\ No newline at end of file diff --git a/src/test/resources/http-cache/third_party_proxy.py b/src/test/resources/http-cache/third_party_proxy.py index 0db977bb..ce61ea06 100755 --- a/src/test/resources/http-cache/third_party_proxy.py +++ b/src/test/resources/http-cache/third_party_proxy.py @@ -127,10 +127,10 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w') as f: f.write(jsonGenerated) return True - elif self.path.startswith("/dcae-operationstatus") and http_type == "GET": + elif self.path.startswith("/dcae-operationstatus/install") and http_type == "GET": if not _file_available: - print "self.path start with /dcae-operationstatus, generating response json..." - jsonGenerated = "{\"operationType\": \"operationType1\", \"status\": \"succeeded\"}" + print "self.path start with /dcae-operationstatus/install, generating response json..." + jsonGenerated = "{\"operationType\": \"install\", \"status\": \"succeeded\"}" print "jsonGenerated: " + jsonGenerated try: @@ -145,24 +145,29 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w') as f: f.write(jsonGenerated) return True - elif self.path.startswith("/sdc/v1/catalog/services/") and http_type == "POST": + elif self.path.startswith("/dcae-operationstatus/uninstall") and http_type == "GET": if not _file_available: - print "self.path start with /sdc/v1/catalog/services/, generating response json..." - jsondata = json.loads(self.data_string) - jsonGenerated = "{\"artifactName\":\"" + jsondata['artifactName'] + "\",\"artifactType\":\"" + jsondata['artifactType'] + "\",\"artifactURL\":\"" + self.path + "\",\"artifactDescription\":\"" + jsondata['description'] + "\",\"artifactChecksum\":\"ZjJlMjVmMWE2M2M1OTM2MDZlODlmNTVmZmYzNjViYzM=\",\"artifactUUID\":\"" + str(uuid.uuid4()) + "\",\"artifactVersion\":\"1\"}" + print "self.path start with /dcae-operationstatus/uninstall, generating response json..." + jsonGenerated = "{\"operationType\": \"uninstall\", \"status\": \"succeeded\"}" print "jsonGenerated: " + jsonGenerated - os.makedirs(cached_file_folder, 0777) + try: + os.makedirs(cached_file_folder, 0777) + except OSError as e: + if e.errno != errno.EEXIST: + raise + print(cached_file_folder+" already exists") + with open(cached_file_header, 'w') as f: f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") with open(cached_file_content, 'w') as f: f.write(jsonGenerated) - return True; - elif self.path.startswith("/dcae-deployments/") and (http_type == "PUT" or http_type == "DELETE"): + return True + elif self.path.startswith("/sdc/v1/catalog/services/") and http_type == "POST": if not _file_available: - print "self.path start with /dcae-deployments/, generating response json..." - #jsondata = json.loads(self.data_string) - jsonGenerated = "{\"links\":{\"status\":\"http:\/\/" + PROXY_ADDRESS + "\/dcae-operationstatus\",\"test2\":\"test2\"}}" + print "self.path start with /sdc/v1/catalog/services/, generating response json..." + jsondata = json.loads(self.data_string) + jsonGenerated = "{\"artifactName\":\"" + jsondata['artifactName'] + "\",\"artifactType\":\"" + jsondata['artifactType'] + "\",\"artifactURL\":\"" + self.path + "\",\"artifactDescription\":\"" + jsondata['description'] + "\",\"artifactChecksum\":\"ZjJlMjVmMWE2M2M1OTM2MDZlODlmNTVmZmYzNjViYzM=\",\"artifactUUID\":\"" + str(uuid.uuid4()) + "\",\"artifactVersion\":\"1\"}" print "jsonGenerated: " + jsonGenerated os.makedirs(cached_file_folder, 0777) @@ -171,6 +176,30 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w') as f: f.write(jsonGenerated) return True + elif self.path.startswith("/dcae-deployments/") and http_type == "PUT": + print "self.path start with /dcae-deployments/ DEPLOY, generating response json..." + #jsondata = json.loads(self.data_string) + jsonGenerated = "{\"operationType\":\"install\",\"status\":\"processing\",\"links\":{\"status\":\"http:\/\/" + PROXY_ADDRESS + "\/dcae-operationstatus/install\"}}" + print "jsonGenerated: " + jsonGenerated + if not os.path.exists(cached_file_folder): + os.makedirs(cached_file_folder, 0777) + with open(cached_file_header, 'w+') as f: + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") + with open(cached_file_content, 'w+') as f: + f.write(jsonGenerated) + return True + elif self.path.startswith("/dcae-deployments/") and http_type == "DELETE": + print "self.path start with /dcae-deployments/ UNDEPLOY, generating response json..." + #jsondata = json.loads(self.data_string) + jsonGenerated = "{\"operationType\":\"uninstall\",\"status\":\"processing\",\"links\":{\"status\":\"http:\/\/" + PROXY_ADDRESS + "\/dcae-operationstatus/uninstall\"}}" + print "jsonGenerated: " + jsonGenerated + if not os.path.exists(cached_file_folder): + os.makedirs(cached_file_folder, 0777) + with open(cached_file_header, 'w+') as f: + f.write("{\"Content-Length\": \"" + str(len(jsonGenerated)) + "\", \"Content-Type\": \"application/json\"}") + with open(cached_file_content, 'w+') as f: + f.write(jsonGenerated) + return True elif (self.path.startswith("/pdp/api/") and (http_type == "PUT" or http_type == "DELETE")) or (self.path.startswith("/pdp/api/policyEngineImport") and http_type == "POST"): print "self.path start with /pdp/api/, copying body to response ..." if not os.path.exists(cached_file_folder): @@ -180,7 +209,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w+') as f: f.write(self.data_string) return True - elif self.path.startswith("/policy/api/v1/policyTypes/") and http_type == "POST": + elif self.path.startswith("/policy/api/v1/policytypes/") and http_type == "POST": print "self.path start with POST new policy API /pdp/api/, copying body to response ..." if not os.path.exists(cached_file_folder): os.makedirs(cached_file_folder, 0777) @@ -189,7 +218,7 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w+') as f: f.write(self.data_string) return True - elif self.path.startswith("/policy/api/v1/policyTypes/") and http_type == "DELETE": + elif self.path.startswith("/policy/api/v1/policytypes/") and http_type == "DELETE": print "self.path start with DELETE new policy API /policy/api/v1/policyTypes/ ..." if not os.path.exists(cached_file_folder): os.makedirs(cached_file_folder, 0777) @@ -199,6 +228,16 @@ class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): with open(cached_file_content, 'w+') as f: f.write(self.data_string) return True + elif self.path.startswith("/policy/pap/v1/pdps/policies") and http_type == "POST": + print "self.path start with POST new policy API /policy/pap/v1/pdps/ ..." + if not os.path.exists(cached_file_folder): + os.makedirs(cached_file_folder, 0777) + + with open(cached_file_header, 'w+') as f: + f.write("{\"Content-Length\": \"" + str(len("")) + "\", \"Content-Type\": \""+str("")+"\"}") + with open(cached_file_content, 'w+') as f: + f.write(self.data_string) + return True elif self.path.startswith("/policy/api/v1/policytypes/") and http_type == "GET": print "self.path start with /policy/api/v1/policytypes/, generating response json..." jsonGenerated = "{\"policyTypeId\": \"onap.policies.controlloop.operational\",\"policyTypeVersion\": \"1.0.0\",\"policyId\": \"OPERATIONAL_z711F_v1_0_ResourceInstanceName1_tca\"}" diff --git a/src/test/resources/https/https-test.properties b/src/test/resources/https/https-test.properties index 7614e177..0be9e298 100644 --- a/src/test/resources/https/https-test.properties +++ b/src/test/resources/https/https-test.properties @@ -30,6 +30,7 @@ server.port=${clamp.it.tests.https} server.ssl.key-store=classpath:https/keystore-test.jks server.ssl.key-store-password=testpass server.ssl.key-password=testpass +server.ssl.key-store-type=JKS ### In order to be user friendly when HTTPS is enabled, ### you can add another HTTP port that will be automatically redirected to HTTPS |