aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java
diff options
context:
space:
mode:
authorChrisC <cc697w@intl.att.com>2017-06-21 02:38:57 -0700
committerChrisC <cc697w@intl.att.com>2017-06-21 02:58:20 -0700
commit5e9feb2a8e360b82dc2b6e4145e0fd847d2924ce (patch)
tree0c9e78d462252e5c41c977476c9dee26b1b0069b /src/main/java
parent4d8ae6fe89a9ed6cd9a64c3276d2dc5a48bbcc34 (diff)
[CLAMP-1] Initial ONAP CLAMP seed code commit
Change-Id: I2e8070a590618a06070f393d7b2c011029af5e8a Signed-off-by: ChrisC <cc697w@intl.att.com>
Diffstat (limited to 'src/main/java')
-rw-r--r--src/main/java/org/onap/clamp/clds/Application.java83
-rw-r--r--src/main/java/org/onap/clamp/clds/Routes.java42
-rw-r--r--src/main/java/org/onap/clamp/clds/WebConfig.java45
-rw-r--r--src/main/java/org/onap/clamp/clds/client/CldsEventDelegate.java62
-rw-r--r--src/main/java/org/onap/clamp/clds/client/DcaeReqDelegate.java59
-rw-r--r--src/main/java/org/onap/clamp/clds/client/DcaeReqDeleteDelegate.java54
-rw-r--r--src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java69
-rw-r--r--src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java61
-rw-r--r--src/main/java/org/onap/clamp/clds/client/PolicyClient.java342
-rw-r--r--src/main/java/org/onap/clamp/clds/client/SdcCatalogServices.java864
-rw-r--r--src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java138
-rw-r--r--src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDelegate.java67
-rw-r--r--src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDeleteDelegate.java58
-rw-r--r--src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java53
-rw-r--r--src/main/java/org/onap/clamp/clds/client/TcaPolicyDeleteDelegate.java48
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/DcaeReq.java97
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/JsonUtil.java66
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/OperationalPolicyReq.java299
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/SdcReq.java360
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/StringMatchPolicyReq.java138
-rw-r--r--src/main/java/org/onap/clamp/clds/client/req/TcaMPolicyReq.java93
-rw-r--r--src/main/java/org/onap/clamp/clds/common/LogMessages.java37
-rw-r--r--src/main/java/org/onap/clamp/clds/config/CamundaAuthFilterInitializer.java87
-rw-r--r--src/main/java/org/onap/clamp/clds/config/CamundaEngineConfiguration.java49
-rw-r--r--src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java142
-rw-r--r--src/main/java/org/onap/clamp/clds/config/CldsSecurityConfig.java117
-rw-r--r--src/main/java/org/onap/clamp/clds/config/CsiLoggingConfiguration.java48
-rw-r--r--src/main/java/org/onap/clamp/clds/dao/CldsDao.java485
-rw-r--r--src/main/java/org/onap/clamp/clds/exception/AjscExceptionMapper.java40
-rw-r--r--src/main/java/org/onap/clamp/clds/jsf/JsfExampleBean.java61
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAlarmCondition.java59
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAsdcArtifact.java112
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAsdcResource.java131
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAsdcResourceBasicInfo.java160
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceDetail.java142
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceInfo.java148
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsDBServiceCache.java66
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsEvent.java183
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsModel.java570
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java59
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsServiceData.java112
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsTemplate.java186
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsVfData.java61
-rw-r--r--src/main/java/org/onap/clamp/clds/model/CldsVfcData.java61
-rw-r--r--src/main/java/org/onap/clamp/clds/model/DcaeEvent.java149
-rw-r--r--src/main/java/org/onap/clamp/clds/model/HelloWorld.java50
-rw-r--r--src/main/java/org/onap/clamp/clds/model/ValueItem.java58
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/Collector.java47
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/Global.java113
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/ModelBpmn.java153
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/ModelBpmnEntry.java95
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/ModelElement.java232
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/ModelProperties.java320
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/Policy.java78
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/PolicyItem.java103
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/ServiceConfiguration.java156
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/StringMatch.java70
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/Tca.java47
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/TcaItem.java128
-rw-r--r--src/main/java/org/onap/clamp/clds/model/prop/TcaThreshhold.java76
-rw-r--r--src/main/java/org/onap/clamp/clds/model/refprop/RefProp.java139
-rw-r--r--src/main/java/org/onap/clamp/clds/service/CldsService.java646
-rw-r--r--src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java275
-rw-r--r--src/main/java/org/onap/clamp/clds/service/LogService.java38
-rw-r--r--src/main/java/org/onap/clamp/clds/service/LogServiceImpl.java276
-rw-r--r--src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java105
-rw-r--r--src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java190
-rw-r--r--src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogService.java101
-rw-r--r--src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogServiceImpl.java94
-rw-r--r--src/main/java/org/onap/clamp/clds/transform/TransformUtil.java66
-rw-r--r--src/main/java/org/onap/clamp/clds/transform/XslTransformer.java59
-rw-r--r--src/main/java/org/onap/clamp/clds/workflow/LogMessageDelegate.java46
-rw-r--r--src/main/java/org/onap/clamp/clds/workflow/ProcessRequestDelegate.java57
-rw-r--r--src/main/java/org/onap/clamp/clds/workflow/RestMessageDelegate.java59
74 files changed, 10240 insertions, 0 deletions
diff --git a/src/main/java/org/onap/clamp/clds/Application.java b/src/main/java/org/onap/clamp/clds/Application.java
new file mode 100644
index 000000000..8459027f3
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/Application.java
@@ -0,0 +1,83 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds;
+
+import com.att.ajsc.common.utility.SystemPropertiesLoader;
+import org.apache.camel.component.servlet.CamelHttpTransportServlet;
+import org.camunda.bpm.spring.boot.starter.webapp.CamundaBpmWebappAutoConfiguration;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration;
+import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
+import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.web.servlet.ServletRegistrationBean;
+import org.springframework.boot.web.support.SpringBootServletInitializer;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.scheduling.annotation.EnableAsync;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import java.util.ArrayList;
+import java.util.Collection;
+
+@SpringBootApplication
+@ComponentScan(basePackages = {"org.onap.clamp.clds","com.att.ajsc"})
+@EnableAutoConfiguration(exclude = {CamundaBpmWebappAutoConfiguration.class, HibernateJpaAutoConfiguration.class, JpaRepositoriesAutoConfiguration.class, SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
+@EnableAsync
+public class Application extends SpringBootServletInitializer {
+
+ private static final String CAMEL_SERVLET_NAME = "CamelServlet";
+ private static final String CAMEL_URL_MAPPING = "/restservices/clds/v1/*";
+
+ @Override
+ protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
+ return application.sources(Application.class);
+ }
+
+ public static void main(String[] args) throws Exception {
+ SystemPropertiesLoader.addSystemProperties();
+ SpringApplication.run(Application.class, args);
+ }
+
+ @Bean
+ public ServletRegistrationBean servletRegistrationBean() {
+ ServletRegistrationBean registration = new ServletRegistrationBean();
+ registration.setName(CAMEL_SERVLET_NAME);
+ registration.setServlet(new CamelHttpTransportServlet());
+ Collection<String> urlMappings = new ArrayList<>();
+ urlMappings.add(CAMEL_URL_MAPPING);
+ registration.setUrlMappings(urlMappings);
+ return registration;
+ }
+
+ @Bean
+ public Client restClient() {
+ return ClientBuilder.newClient();
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/Routes.java b/src/main/java/org/onap/clamp/clds/Routes.java
new file mode 100644
index 000000000..6fcb93078
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/Routes.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds;
+
+import com.att.ajsc.common.camel.AjscRouteBuilder;
+import org.apache.camel.builder.RouteBuilder;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class Routes extends RouteBuilder {
+ @Autowired
+ private AjscRouteBuilder ajscRoute;
+
+ @Override
+ public void configure() throws Exception {
+ ajscRoute.initialize(this);
+ ajscRoute.setRoute(from("servlet:/?matchOnUriPrefix=true").to("cxfbean:jaxrsServices?providers=jaxrsProviders"));
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/WebConfig.java b/src/main/java/org/onap/clamp/clds/WebConfig.java
new file mode 100644
index 000000000..38bd62e97
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/WebConfig.java
@@ -0,0 +1,45 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
+import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
+
+@Configuration
+public class WebConfig {
+
+ @Bean
+ public WebMvcConfigurerAdapter forwardToIndex() {
+ return new WebMvcConfigurerAdapter() {
+ @Override
+ public void addViewControllers(ViewControllerRegistry registry) {
+ registry.addViewController("/swagger").setViewName("redirect:/icd/index.html");
+ registry.addViewController("/icd/").setViewName("redirect:/icd/index.html");
+ registry.addViewController("/login").setViewName("login.html");
+ }
+ };
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/CldsEventDelegate.java b/src/main/java/org/onap/clamp/clds/client/CldsEventDelegate.java
new file mode 100644
index 000000000..0f4d30d00
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/CldsEventDelegate.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.CldsEvent;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.logging.Logger;
+
+/**
+ * Create CLDS Event.
+ */
+public class CldsEventDelegate implements JavaDelegate {
+ private static final Logger logger = Logger.getLogger(CldsEventDelegate.class.getName());
+ @Autowired
+ private CldsDao cldsDao;
+
+ /**
+ * Insert event using process variables.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String controlName = (String) execution.getVariable("controlName");
+ String actionCd = (String) execution.getVariable("actionCd");
+ String actionStateCd = (String) execution.getVariable("actionStateCd");
+ boolean isTest = (boolean) execution.getVariable("isTest");
+ boolean isInsertTestEvent = (boolean) execution.getVariable("isInsertTestEvent");
+ String userid = (String) execution.getVariable("userid");
+
+ // do not insert events for test actions unless flag set to insert them
+ if (!isTest || isInsertTestEvent) {
+ // won't really have userid here...
+ CldsEvent.insEvent(cldsDao, controlName, userid, actionCd, actionStateCd, execution.getProcessInstanceId());
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeReqDelegate.java b/src/main/java/org/onap/clamp/clds/client/DcaeReqDelegate.java
new file mode 100644
index 000000000..5583cf936
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/DcaeReqDelegate.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.client.req.DcaeReq;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.logging.Logger;
+
+
+/**
+ * Send control loop model to dcae proxy.
+ */
+public class DcaeReqDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(DcaeReqDelegate.class.getName());
+
+ @Autowired
+ private RefProp refProp;
+
+ /**
+ * Perform activity. Send to dcae proxy.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ ModelProperties prop = ModelProperties.create(execution);
+ String dcaeReq = DcaeReq.format(refProp, prop);
+ if (dcaeReq != null) {
+ execution.setVariable("dcaeReq", dcaeReq.getBytes());
+ }
+ execution.setVariable("dcaeUrl", System.getProperty("CLDS_DCAE_URL") + "/" + prop.getControlName());
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeReqDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/DcaeReqDeleteDelegate.java
new file mode 100644
index 000000000..28dd6f1d6
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/DcaeReqDeleteDelegate.java
@@ -0,0 +1,54 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.logging.Logger;
+
+
+/**
+ * Send control loop model to dcae proxy.
+ */
+public class DcaeReqDeleteDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(DcaeReqDeleteDelegate.class.getName());
+
+ @Autowired
+ private RefProp refProp;
+
+ /**
+ * Perform activity. Send to dcae proxy.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ ModelProperties prop = ModelProperties.create(execution);
+ execution.setVariable("dcaeUrl", System.getProperty("CLDS_DCAE_URL") + "/" + prop.getControlName());
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java
new file mode 100644
index 000000000..fc3ea2ab2
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDelegate.java
@@ -0,0 +1,69 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.client.req.OperationalPolicyReq;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.openecomp.policy.api.AttributeType;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.Map;
+import java.util.UUID;
+import java.util.logging.Logger;
+
+
+/**
+ * Send Operational Policy info to policy api.
+ */
+public class OperationalPolicyDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(OperationalPolicyDelegate.class.getName());
+
+ @Autowired
+ private PolicyClient policyClient;
+
+ @Autowired
+ private RefProp refProp;
+
+ /**
+ * Perform activity. Send Operational Policy info to policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String operationalPolicyRequestUuid = UUID.randomUUID().toString();
+ execution.setVariable("operationalPolicyRequestUuid", operationalPolicyRequestUuid);
+
+ ModelProperties prop = ModelProperties.create(execution);
+ Map<AttributeType, Map<String, String>> attributes = OperationalPolicyReq.formatAttributes(refProp, prop);
+ String responseMessage = policyClient.sendBrms(attributes, prop, operationalPolicyRequestUuid);
+ if (responseMessage != null) {
+ execution.setVariable("operationalPolicyResponseMessage", responseMessage.getBytes());
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java
new file mode 100644
index 000000000..816b2142a
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/OperationalPolicyDeleteDelegate.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.Policy;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.logging.Logger;
+
+
+/**
+ * Delete Operational Policy via policy api.
+ */
+public class OperationalPolicyDeleteDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(OperationalPolicyDeleteDelegate.class.getName());
+
+ @Autowired
+ private PolicyClient policyClient;
+
+ /**
+ * Perform activity. Delete Operational Policy via policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ ModelProperties prop = ModelProperties.create(execution);
+ Policy policy = prop.getPolicy();
+ prop.setCurrentModelElementId(policy.getId());
+
+ String responseMessage = policyClient.deleteBrms(prop);
+ if (responseMessage != null) {
+ execution.setVariable("operationalPolicyDeleteResponseMessage", responseMessage.getBytes());
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/PolicyClient.java b/src/main/java/org/onap/clamp/clds/client/PolicyClient.java
new file mode 100644
index 000000000..95e60ea2e
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/PolicyClient.java
@@ -0,0 +1,342 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.openecomp.policy.api.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationContext;
+
+import java.util.*;
+import java.util.logging.Logger;
+
+
+/**
+ * Policy utility methods - specifically, send the policy.
+ */
+public class PolicyClient {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(PolicyClient.class.getName());
+
+ @Value("${org.onap.clamp.config.files.cldsPolicyConfig:'classpath:etc/clds/clds-policy-config.properties'}")
+ private String cldsPolicyConfigFile;
+
+ @Autowired
+ private ApplicationContext appContext;
+
+ @Autowired
+ private RefProp refProp;
+
+ public PolicyClient() {
+
+ }
+
+ /**
+ * Perform send of microservice policy
+ *
+ * @param attributes
+ * @param prop
+ * @param policyRequestUUID
+ * @return
+ * @throws Exception
+ */
+ public String sendBrms(Map<AttributeType, Map<String, String>> attributes, ModelProperties prop, String policyRequestUUID) throws Exception {
+
+ PolicyParameters policyParameters = new PolicyParameters();
+
+ // Set Policy Type(Mandatory)
+ policyParameters.setPolicyConfigType(PolicyConfigType.BRMS_PARAM);
+
+ // Set Policy Name(Mandatory)
+ policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+ //Set Scope folder where the policy needs to be created(Mandatory)
+ //policyParameters.setPolicyScope(policyScope);
+
+ // documentation says this is options, but when tested, got the following failure: java.lang.Exception: Policy send failed: PE300 - Data Issue: No policyDescription given.
+ policyParameters.setPolicyDescription(refProp.getStringValue("op.policyDescription"));
+
+ policyParameters.setAttributes(attributes);
+
+ //Set a random UUID(Mandatory)
+ policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
+
+ String rtnMsg = send(policyParameters, prop);
+
+ String policyType = refProp.getStringValue("policy.op.type");
+ push(policyType, prop);
+
+ return rtnMsg;
+ }
+
+ /**
+ * Perform send of microservice policy
+ *
+ * @param policyJson
+ * @param prop
+ * @param policyRequestUUID
+ * @return
+ * @throws Exception
+ */
+ public String sendMicroService(String policyJson, ModelProperties prop, String policyRequestUUID) throws Exception {
+
+ PolicyParameters policyParameters = new PolicyParameters();
+
+ // Set Policy Type
+ policyParameters.setPolicyConfigType(PolicyConfigType.MicroService);
+ policyParameters.setEcompName(refProp.getStringValue("policy.ecomp.name"));
+ policyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+
+ policyParameters.setConfigBody(policyJson);
+ policyParameters.setConfigBodyType(PolicyType.JSON);
+
+ policyParameters.setRequestID(UUID.fromString(policyRequestUUID));
+
+ String rtnMsg = send(policyParameters, prop);
+
+ String policyType = refProp.getStringValue("policy.ms.type");
+ push(policyType, prop);
+
+ return rtnMsg;
+ }
+
+ /**
+ * Perform send of policy.
+ *
+ * @param policyParameters
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ private String send(PolicyParameters policyParameters, ModelProperties prop) throws Exception {
+ PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ String responseMessage;
+ try {
+ if (prop.isCreateRequest()) {
+ logger.info("Attempting to create policy for action=" + prop.getActionCd());
+ response = policyEngine.createPolicy(policyParameters);
+ responseMessage = response.getResponseMessage();
+ } else {
+ logger.info("Attempting to update policy for action=" + prop.getActionCd());
+ response = policyEngine.updatePolicy(policyParameters);
+ responseMessage = response.getResponseMessage();
+ }
+ } catch (Exception e) {
+ responseMessage = e.toString();
+ }
+ logger.info("response is " + responseMessage);
+
+ if (response != null && response.getResponseCode() == 200) {
+ logger.info("Policy send successful");
+ } else {
+ logger.warning("Policy send failed: " + responseMessage);
+ throw new Exception("Policy send failed: " + responseMessage);
+ }
+
+ return responseMessage;
+ }
+
+ /**
+ * Format and send push of policy.
+ *
+ * @param policyType
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ private String push(String policyType, ModelProperties prop) throws Exception {
+ PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
+
+ //Parameter arguments
+ pushPolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndPolicyName());
+ pushPolicyParameters.setPolicyType(policyType);
+ //pushPolicyParameters.setPolicyScope(policyScope);
+ pushPolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
+ pushPolicyParameters.setRequestID(null);
+
+ PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ String responseMessage;
+ try {
+ logger.info("Attempting to push policy...");
+ response = policyEngine.pushPolicy(pushPolicyParameters);
+ responseMessage = response.getResponseMessage();
+ } catch (Exception e) {
+ responseMessage = e.toString();
+ }
+ logger.info("response is " + responseMessage);
+
+ if (response != null && (response.getResponseCode() == 200 || response.getResponseCode() == 204)) {
+ logger.info("Policy push successful");
+ } else {
+ logger.warning("Policy push failed: " + responseMessage);
+ throw new Exception("Policy push failed: " + responseMessage);
+ }
+
+ return responseMessage;
+ }
+
+ /**
+ * Use Get Config Policy API to retrieve the versions for a policy.
+ * Return versions in sorted order.
+ * Return empty list if none found.
+ *
+ * @param policyNamePrefix
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ private List<Integer> getVersions(String policyNamePrefix, ModelProperties prop) throws Exception {
+
+ ArrayList<Integer> versions = new ArrayList<>();
+ ConfigRequestParameters configRequestParameters = new ConfigRequestParameters();
+ String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
+ logger.info("policyName=" + policyName);
+ configRequestParameters.setPolicyName(policyName);
+
+ PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+
+ Collection<PolicyConfig> response = policyEngine.getConfig(configRequestParameters);
+
+ Iterator<PolicyConfig> itrResp = response.iterator();
+
+ while (itrResp.hasNext()) {
+ PolicyConfig policyConfig = itrResp.next();
+ try {
+ Integer version = new Integer(policyConfig.getPolicyVersion());
+ versions.add(version);
+ } catch (Exception e) {
+ // just print warning - if n;o policies, version may be null
+ logger.warning("warning: failed to parse policyConfig.getPolicyVersion()=" + policyConfig.getPolicyVersion());
+ }
+ }
+ Collections.sort(versions);
+ logger.info("versions.size()=" + versions.size());
+
+ return versions;
+ }
+
+ /**
+ * Format and send delete Micro Service requests to Policy
+ *
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ public String deleteMicrosService(ModelProperties prop) throws Exception {
+ String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
+ return deletePolicy(policyNamePrefix, prop);
+ }
+
+ /**
+ * Format and send delete BRMS requests to Policy
+ *
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ public String deleteBrms(ModelProperties prop) throws Exception {
+ String policyNamePrefix = refProp.getStringValue("policy.op.policyNamePrefix");
+ return deletePolicy(policyNamePrefix, prop);
+ }
+
+ /**
+ * Format and send delete PAP and PDP requests to Policy
+ *
+ * @param policyNamePrefix
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ private String deletePolicy(String policyNamePrefix, ModelProperties prop) throws Exception {
+ String responseMessage = null;
+
+ DeletePolicyParameters deletePolicyParameters = new DeletePolicyParameters();
+
+ List<Integer> versions = getVersions(policyNamePrefix, prop);
+ if (versions.size() > 0) {
+ int maxVersion = Collections.max(versions);
+
+ // format delete all PAP request
+ deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, maxVersion));
+ deletePolicyParameters.setPolicyComponent("PAP");
+ deletePolicyParameters.setDeleteCondition(DeletePolicyCondition.ALL);
+ String policyType = refProp.getStringValue("policy.ms.type");
+ deletePolicyParameters.setPolicyType(policyType);
+
+ //send delete request
+ responseMessage = sendDeletePolicy(deletePolicyParameters, prop);
+ }
+
+ for (Integer version : versions) {
+ // format delete all PDP request
+ deletePolicyParameters.setPolicyName(prop.getCurrentPolicyScopeAndFullPolicyNameWithVersion(policyNamePrefix, version));
+ deletePolicyParameters.setPolicyComponent("PDP");
+ deletePolicyParameters.setPdpGroup(refProp.getStringValue("policy.pdp.group"));
+ //send delete request
+ responseMessage = responseMessage + "; " + sendDeletePolicy(deletePolicyParameters, prop);
+ }
+
+ return responseMessage;
+ }
+
+ /**
+ * Send delete request to Policy
+ *
+ * @param deletePolicyParameters
+ * @param prop
+ * @return
+ * @throws Exception
+ */
+ private String sendDeletePolicy(DeletePolicyParameters deletePolicyParameters, ModelProperties prop) throws Exception {
+ PolicyEngine policyEngine = new PolicyEngine(appContext.getResource(cldsPolicyConfigFile).getFile().getAbsolutePath());
+
+ // API method to create or update Policy.
+ PolicyChangeResponse response = null;
+ String responseMessage;
+ try {
+ logger.info("Attempting to delete policy...");
+ response = policyEngine.deletePolicy(deletePolicyParameters);
+ responseMessage = response.getResponseMessage();
+ } catch (Exception e) {
+ responseMessage = e.toString();
+ }
+ logger.info("response is " + responseMessage);
+
+ if (response != null && response.getResponseCode() == 200) {
+ logger.info("Policy delete successful");
+ } else {
+ logger.warning("Policy delete failed: " + responseMessage);
+ throw new Exception("Policy delete failed: " + responseMessage);
+ }
+
+ return responseMessage;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/client/SdcCatalogServices.java b/src/main/java/org/onap/clamp/clds/client/SdcCatalogServices.java
new file mode 100644
index 000000000..58bba3c9d
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/SdcCatalogServices.java
@@ -0,0 +1,864 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.databind.node.TextNode;
+import org.onap.clamp.clds.client.req.SdcReq;
+import org.onap.clamp.clds.model.*;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.apache.commons.csv.CSVFormat;
+import org.apache.commons.csv.CSVRecord;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.io.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+
+public class SdcCatalogServices {
+ private static final Logger logger = LoggerFactory.getLogger(SdcSendReqDelegate.class);
+
+ @Autowired
+ private RefProp refProp;
+
+ public String getAsdcServicesInformation(String uuid) throws Exception {
+ String baseUrl = refProp.getStringValue("asdc.serviceUrl");
+ String basicAuth = SdcReq.getAsdcBasicAuth(refProp);
+ try {
+ String url = baseUrl;
+ if (uuid != null) {
+ url = baseUrl + "/" + uuid + "/metadata";
+ }
+ URL urlObj = new URL(url);
+
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+
+ conn.setRequestProperty("X-ONAP-InstanceID", "CLAMP-Tool");
+ conn.setRequestProperty("Authorization", basicAuth);
+ conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+ conn.setRequestMethod("GET");
+
+ String resp = getResponse(conn);
+ if (resp != null) {
+ logger.info(resp.toString());
+ return resp;
+ }
+ } catch (Exception e) {
+ logger.error("not able to ger any service information from asdc for uuid:" + uuid);
+ }
+ return "";
+ }
+
+ /**
+ * To remove duplicate serviceUUIDs from asdc services List
+ *
+ * @param rawCldsAsdcServiceList
+ * @return
+ */
+ public List<CldsAsdcServiceInfo> removeDuplicateServices(List<CldsAsdcServiceInfo> rawCldsAsdcServiceList) {
+ List<CldsAsdcServiceInfo> cldsAsdcServiceInfoList = null;
+ if (rawCldsAsdcServiceList != null && rawCldsAsdcServiceList.size() > 0) {
+ // sort list
+ Collections.sort(rawCldsAsdcServiceList);
+ // and then take only the services with the max version (last in the list with the same name)
+ cldsAsdcServiceInfoList = new ArrayList<>();
+ for (int i = 1; i < rawCldsAsdcServiceList.size(); i++) {
+ // compare name with previous - if not equal, then keep the previous (it's the last with that name)
+ CldsAsdcServiceInfo prev = rawCldsAsdcServiceList.get(i - 1);
+ if (!rawCldsAsdcServiceList.get(i).getName().equals(prev.getName())) {
+ cldsAsdcServiceInfoList.add(prev);
+ }
+ }
+ // add the last in the list
+ cldsAsdcServiceInfoList.add(rawCldsAsdcServiceList.get(rawCldsAsdcServiceList.size() - 1));
+ }
+ return cldsAsdcServiceInfoList;
+ }
+
+ /**
+ * To remove duplicate serviceUUIDs from asdc resources List
+ *
+ * @param rawCldsAsdcResourceList
+ * @return
+ */
+ public List<CldsAsdcResource> removeDuplicateAsdcResourceInstances(List<CldsAsdcResource> rawCldsAsdcResourceList) {
+ List<CldsAsdcResource> cldsAsdcResourceList = null;
+ if (rawCldsAsdcResourceList != null && rawCldsAsdcResourceList.size() > 0) {
+ // sort list
+ Collections.sort(rawCldsAsdcResourceList);
+ // and then take only the resources with the max version (last in the list with the same name)
+ cldsAsdcResourceList = new ArrayList<>();
+ for (int i = 1; i < rawCldsAsdcResourceList.size(); i++) {
+ // compare name with previous - if not equal, then keep the previous (it's the last with that name)
+ CldsAsdcResource prev = rawCldsAsdcResourceList.get(i - 1);
+ if (!rawCldsAsdcResourceList.get(i).getResourceInstanceName().equals(prev.getResourceInstanceName())) {
+ cldsAsdcResourceList.add(prev);
+ }
+ }
+ // add the last in the list
+ cldsAsdcResourceList.add(rawCldsAsdcResourceList.get(rawCldsAsdcResourceList.size() - 1));
+ }
+ return cldsAsdcResourceList;
+ }
+
+
+ /**
+ * To remove duplicate basic resources with same resourceUUIDs
+ *
+ * @param rawCldsAsdcResourceListBasicList
+ * @return
+ */
+ public List<CldsAsdcResourceBasicInfo> removeDuplicateAsdcResourceBasicInfo(List<CldsAsdcResourceBasicInfo> rawCldsAsdcResourceListBasicList) {
+ List<CldsAsdcResourceBasicInfo> cldsAsdcResourceBasicInfoList = null;
+ if (rawCldsAsdcResourceListBasicList != null && rawCldsAsdcResourceListBasicList.size() > 0) {
+ // sort list
+ Collections.sort(rawCldsAsdcResourceListBasicList);
+ // and then take only the resources with the max version (last in the list with the same name)
+ cldsAsdcResourceBasicInfoList = new ArrayList<>();
+ for (int i = 1; i < rawCldsAsdcResourceListBasicList.size(); i++) {
+ // compare name with previous - if not equal, then keep the previous (it's the last with that name)
+ CldsAsdcResourceBasicInfo prev = rawCldsAsdcResourceListBasicList.get(i - 1);
+ if (!rawCldsAsdcResourceListBasicList.get(i).getName().equals(prev.getName())) {
+ cldsAsdcResourceBasicInfoList.add(prev);
+ }
+ }
+ // add the last in the list
+ cldsAsdcResourceBasicInfoList.add(rawCldsAsdcResourceListBasicList.get(rawCldsAsdcResourceListBasicList.size() - 1));
+ }
+ return cldsAsdcResourceBasicInfoList;
+ }
+
+ /**
+ * To get ServiceUUID by using serviceInvariantUUID
+ *
+ * @param invariantID
+ * @return
+ * @throws Exception
+ */
+ public String getServiceUUIDFromServiceInvariantID(String invariantID) throws Exception {
+ String serviceUUID = "";
+ String responseStr = getAsdcServicesInformation(null);
+ List<CldsAsdcServiceInfo> rawCldsAsdcServicesList = getCldsAsdcServicesListFromJson(responseStr);
+ List<CldsAsdcServiceInfo> cldsAsdcServicesList = removeDuplicateServices(rawCldsAsdcServicesList);
+ if (cldsAsdcServicesList != null && cldsAsdcServicesList.size() > 0) {
+ for (CldsAsdcServiceInfo currCldsAsdcServiceInfo : cldsAsdcServicesList) {
+ if (currCldsAsdcServiceInfo != null && currCldsAsdcServiceInfo.getInvariantUUID() != null
+ && currCldsAsdcServiceInfo.getInvariantUUID().equalsIgnoreCase(invariantID)) {
+ serviceUUID = currCldsAsdcServiceInfo.getUuid();
+ break;
+ }
+ }
+ }
+ return serviceUUID;
+ }
+
+ /**
+ * To get CldsAsdsServiceInfo class by parsing json string
+ *
+ * @param jsonStr
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public List<CldsAsdcServiceInfo> getCldsAsdcServicesListFromJson(String jsonStr) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ if (StringUtils.isBlank(jsonStr)) {
+ return null;
+ }
+ return objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, CldsAsdcServiceInfo.class));
+ }
+
+ /**
+ * To get List<CldsAsdcResourceBasicInfo> class by parsing json string
+ *
+ * @param jsonStr
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public List<CldsAsdcResourceBasicInfo> getAllAsdcResourcesListFromJson(String jsonStr) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ if (StringUtils.isBlank(jsonStr)) {
+ return null;
+ }
+ return objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, CldsAsdcResourceBasicInfo.class));
+ }
+
+ /**
+ * To get CldsAsdsResource class by parsing json string
+ *
+ * @param jsonStr
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public CldsAsdcResource getCldsAsdcResourceFromJson(String jsonStr) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(jsonStr, CldsAsdcResource.class);
+ }
+
+ /**
+ * To get CldsAsdcServiceDetail by parsing json string
+ *
+ * @param jsonStr
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public CldsAsdcServiceDetail getCldsAsdcServiceDetailFromJson(String jsonStr) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(jsonStr, CldsAsdcServiceDetail.class);
+ }
+
+ /**
+ * To upload artifact to asdc based on serviceUUID and resourcename on url
+ * @param prop
+ * @param userid
+ * @param url
+ * @param formatttedAsdcReq
+ * @return
+ * @throws Exception
+ */
+ public String uploadArtifactToAsdc(ModelProperties prop, String userid, String url, String formatttedAsdcReq) throws Exception {
+ logger.info("userid=" + userid);
+ String md5Text = SdcReq.calculateMD5ByString(formatttedAsdcReq);
+ byte[] postData = SdcReq.stringToByteArray(formatttedAsdcReq);
+ int postDataLength = postData.length;
+ HttpURLConnection conn = getAsdcHttpUrlConnection(userid, postDataLength, url, md5Text);
+ try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
+ wr.write(postData);
+ }
+ boolean requestFailed = true;
+ int responseCode = conn.getResponseCode();
+ logger.info("responseCode=" + responseCode);
+ if (responseCode == 200) {
+ requestFailed = false;
+ }
+
+ String responseStr = getResponse(conn);
+ if (responseStr != null) {
+ if (requestFailed) {
+ logger.error("requestFailed - responseStr=" + responseStr);
+ throw new Exception(responseStr);
+ }
+ }
+ return responseStr;
+ }
+
+ private HttpURLConnection getAsdcHttpUrlConnection(String userid, int postDataLength, String url, String md5Text) throws IOException {
+ logger.info("userid=" + userid);
+ String basicAuth = SdcReq.getAsdcBasicAuth(refProp);
+ String asdcXONAPInstanceID = refProp.getStringValue("asdc.asdcX-ONAP-InstanceID");
+ URL urlObj = new URL(url);
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn.setDoOutput(true);
+ conn.setRequestProperty("X-ONAP-InstanceID", asdcXONAPInstanceID);
+ conn.setRequestProperty("Authorization", basicAuth);
+ conn.setRequestProperty("Content-Type", "application/json");
+ conn.setRequestProperty("Content-MD5", md5Text);
+ conn.setRequestProperty("HTTP_CSP_USERID", userid);
+ conn.setRequestMethod("POST");
+ conn.setRequestProperty("charset", "utf-8");
+ conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
+ conn.setUseCaches(false);
+ return conn;
+ }
+
+ private String getResponse(HttpURLConnection conn) throws IOException {
+ try (InputStream is = getInputStream(conn)) {
+ if (is != null) {
+ try (BufferedReader in = new BufferedReader(new InputStreamReader(is))) {
+ StringBuffer response = new StringBuffer();
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ }
+ return response.toString();
+ }
+ }
+ }
+ return null;
+ }
+
+ private InputStream getInputStream(HttpURLConnection conn) throws IOException {
+ InputStream inStream = conn.getErrorStream();
+ if (inStream == null) {
+ inStream = conn.getInputStream();
+ }
+ return inStream;
+ }
+
+
+ public CldsDBServiceCache getCldsDBServiceCacheUsingCldsServiceData(CldsServiceData cldsServiceData) throws IOException {
+ CldsDBServiceCache cldsDbServiceCache = new CldsDBServiceCache();
+ cldsDbServiceCache.setCldsDataInstream(cldsServiceData);
+ cldsDbServiceCache.setInvariantId(cldsServiceData.getServiceInvariantUUID());
+ cldsDbServiceCache.setServiceId(cldsServiceData.getServiceUUID());
+ return cldsDbServiceCache;
+ }
+
+ public boolean isCldsAsdcCacheDataExpired(CldsServiceData cldsServiceData) throws Exception {
+ boolean expired = false;
+ if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {
+ String cachedServiceUUID = cldsServiceData.getServiceUUID();
+ String latestServiceUUID = getServiceUUIDFromServiceInvariantID(cldsServiceData.getServiceInvariantUUID());
+ String defaultRecordAge = refProp.getStringValue("CLDS_SERVICE_CACHE_MAX_SECONDS");
+ if ((!cachedServiceUUID.equalsIgnoreCase(latestServiceUUID)) ||
+ (cldsServiceData.getAgeOfRecord() != null && cldsServiceData.getAgeOfRecord() > Long.parseLong(defaultRecordAge))) {
+ expired = true;
+ }
+ } else {
+ expired = true;
+ }
+ return expired;
+ }
+
+ public CldsServiceData getCldsServiceDataWithAlarmConditions(String invariantServiceUUID) throws Exception {
+ String url = refProp.getStringValue("asdc.serviceUrl");
+ String catalogUrl = refProp.getStringValue("asdc.catalog.url");
+ String serviceUUID = getServiceUUIDFromServiceInvariantID(invariantServiceUUID);
+ String serviceDetailUrl = url + "/" + serviceUUID + "/metadata";
+ String responseStr = getCldsServicesOrResourcesBasedOnURL(serviceDetailUrl, false);
+ ObjectMapper objectMapper = new ObjectMapper();
+ CldsServiceData cldsServiceData = new CldsServiceData();
+ if (responseStr != null) {
+ CldsAsdcServiceDetail cldsAsdcServiceDetail = objectMapper.readValue(responseStr, CldsAsdcServiceDetail.class);
+ cldsServiceData.setServiceUUID(cldsAsdcServiceDetail.getUuid());
+ cldsServiceData.setServiceInvariantUUID(cldsAsdcServiceDetail.getInvariantUUID());
+
+ // To remove duplicate resources from serviceDetail and add valid vfs to service
+ if (cldsAsdcServiceDetail != null && cldsAsdcServiceDetail.getResources() != null) {
+ List<CldsAsdcResource> cldsAsdcResourceList = removeDuplicateAsdcResourceInstances(cldsAsdcServiceDetail.getResources());
+ if (cldsAsdcResourceList != null && cldsAsdcResourceList.size() > 0) {
+ List<CldsVfData> cldsVfDataList = new ArrayList<>();
+ for (CldsAsdcResource currCldsAsdcResource : cldsAsdcResourceList) {
+ if (currCldsAsdcResource != null && currCldsAsdcResource.getResoucreType() != null && currCldsAsdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+ CldsVfData currCldsVfData = new CldsVfData();
+ currCldsVfData.setVfName(currCldsAsdcResource.getResourceInstanceName());
+ currCldsVfData.setVfInvariantResourceUUID(currCldsAsdcResource.getResourceInvariantUUID());
+ cldsVfDataList.add(currCldsVfData);
+ }
+ }
+ cldsServiceData.setCldsVfs(cldsVfDataList);
+ // For each vf in the list , add all vfc's
+ getAllVfcForVfList(cldsVfDataList, catalogUrl);
+ logger.info("value of cldsServiceData:" + cldsServiceData);
+ logger.info("value of cldsServiceData:" + cldsServiceData.getServiceInvariantUUID());
+ }
+ }
+ }
+ return cldsServiceData;
+ }
+
+ /**
+ * @param cldsVfDataList
+ * @throws IOException
+ */
+ private void getAllVfcForVfList(List<CldsVfData> cldsVfDataList, String catalogUrl) throws IOException {
+ // todo : refact this..
+ if (cldsVfDataList != null && cldsVfDataList.size() > 0) {
+ List<CldsAsdcResourceBasicInfo> allAsdcResources = getAllAsdcResources();
+ String resourceVFType = "VF";
+ List<CldsAsdcResourceBasicInfo> allVfResources = getAllAsdcVForVFCResourcesBasedOnResourceType(resourceVFType, allAsdcResources);
+ String resourceVFCType = "VFC";
+ List<CldsAsdcResourceBasicInfo> allVfcResources = getAllAsdcVForVFCResourcesBasedOnResourceType(resourceVFCType, allAsdcResources);
+ for (CldsVfData currCldsVfData : cldsVfDataList) {
+ if (currCldsVfData != null && currCldsVfData.getVfInvariantResourceUUID() != null) {
+ String resourceUUID = getResourceUUIDFromResourceInvariantUUID(currCldsVfData.getVfInvariantResourceUUID(), allVfResources);
+ if (resourceUUID != null) {
+ String vfResourceUUIDUrl = catalogUrl + "resources" + "/" + resourceUUID + "/metadata";
+ String vfResponse = getCldsServicesOrResourcesBasedOnURL(vfResourceUUIDUrl, false);
+ if (vfResponse != null) {
+ List<CldsVfcData> vfcDataListFromVfResponse = getVFCDataListFromVfResponse(vfResponse);
+ if (vfcDataListFromVfResponse != null) {
+ currCldsVfData.setCldsVfcs(vfcDataListFromVfResponse);
+ if (vfcDataListFromVfResponse.size() > 0) {
+ // To get artifacts for every VFC and get alarm conditions from artifact
+ for (CldsVfcData currCldsVfcData : vfcDataListFromVfResponse) {
+ if (currCldsVfcData != null && currCldsVfcData.getVfcInvariantResourceUUID() != null) {
+ String resourceVFCUUID = getResourceUUIDFromResourceInvariantUUID(currCldsVfcData.getVfcInvariantResourceUUID(), allVfcResources);
+ if (resourceVFCUUID != null) {
+ String vfcResourceUUIDUrl = catalogUrl + "resources" + "/" + resourceVFCUUID + "/metadata";
+ String vfcResponse = getCldsServicesOrResourcesBasedOnURL(vfcResourceUUIDUrl, false);
+ if (vfcResponse != null) {
+ List<CldsAlarmCondition> alarmCondtionsFromVfc = getAlarmCondtionsFromVfc(vfcResponse);
+ currCldsVfcData.setCldsAlarmConditions(alarmCondtionsFromVfc);
+ }
+ } else {
+ logger.info("No resourceVFC UUID found for given invariantID:" + currCldsVfcData.getVfcInvariantResourceUUID());
+ }
+ }
+ }
+ }
+ }
+ }
+ } else {
+ logger.info("No resourceUUID found for given invariantREsourceUUID:" + currCldsVfData.getVfInvariantResourceUUID());
+ }
+ }
+ }
+ }
+ }
+
+ private List<CldsVfcData> getVFCDataListFromVfResponse(String vfResponse) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode vfResponseNode = (ObjectNode) mapper.readTree(vfResponse);
+ ArrayNode vfcArrayNode = (ArrayNode) vfResponseNode.get("resources");
+ List<CldsVfcData> cldsVfcDataList = new ArrayList<>();
+ if (vfcArrayNode != null && vfcArrayNode.size() > 0) {
+ for (int index = 0; index < vfcArrayNode.size(); index++) {
+ CldsVfcData currCldsVfcData = new CldsVfcData();
+ ObjectNode currVfcNode = (ObjectNode) vfcArrayNode.get(index);
+ TextNode resourceTypeNode = (TextNode) currVfcNode.get("resoucreType");
+ if (resourceTypeNode != null && resourceTypeNode.textValue().equalsIgnoreCase("VFC")) {
+ TextNode vfcResourceName = (TextNode) currVfcNode.get("resourceInstanceName");
+ TextNode vfcInvariantResourceUUID = (TextNode) currVfcNode.get("resourceInvariantUUID");
+ currCldsVfcData.setVfcName(vfcResourceName.textValue());
+ currCldsVfcData.setVfcInvariantResourceUUID(vfcInvariantResourceUUID.textValue());
+ cldsVfcDataList.add(currCldsVfcData);
+ }
+ }
+ }
+ return cldsVfcDataList;
+ }
+
+ private String removeUnwantedBracesFromString(String id) {
+ if (id != null && id.contains("\"")) {
+ id = id.replaceAll("\"", "");
+ }
+ return id;
+ }
+
+ private List<CldsAlarmCondition> getAlarmCondtionsFromVfc(String vfcResponse) throws IOException {
+ List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode vfcResponseNode = (ObjectNode) mapper.readTree(vfcResponse);
+ ArrayNode artifactsArrayNode = (ArrayNode) vfcResponseNode.get("artifacts");
+
+ if (artifactsArrayNode != null && artifactsArrayNode.size() > 0) {
+ for (int index = 0; index < artifactsArrayNode.size(); index++) {
+ ObjectNode currArtifactNode = (ObjectNode) artifactsArrayNode.get(index);
+ TextNode artifactUrlNode = (TextNode) currArtifactNode.get("artifactURL");
+ if (artifactUrlNode != null) {
+ String responsesFromArtifactUrl = getResponsesFromArtifactUrl(artifactUrlNode.textValue());
+ cldsAlarmConditionList.addAll(parseCsvToGetAlarmConditions(responsesFromArtifactUrl));
+ logger.info(responsesFromArtifactUrl);
+ }
+ }
+ }
+ return cldsAlarmConditionList;
+ }
+
+ private List<CldsAlarmCondition> parseCsvToGetAlarmConditions(String allAlarmCondsValues) throws IOException {
+ List<CldsAlarmCondition> cldsAlarmConditionList = new ArrayList<>();
+ Reader alarmReader = new StringReader(allAlarmCondsValues);
+ Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(alarmReader);
+ if (records != null) {
+ Iterator<CSVRecord> it = records.iterator();
+ if (it.hasNext()) {
+ it.next();
+ }
+ it.forEachRemaining(record -> processRecord(cldsAlarmConditionList, record));
+ }
+ return cldsAlarmConditionList;
+ }
+
+ private void processRecord(List<CldsAlarmCondition> cldsAlarmConditionList, CSVRecord record) {
+ if (record == null) {
+ return;
+ }
+ if (record.size() < 5) {
+ logger.debug("invalid csv alarm Record,total columns less than 5: " + record);
+ return;
+ }
+ if (StringUtils.isBlank(record.get(1)) || StringUtils.isBlank(record.get(3)) || StringUtils.isBlank(record.get(4))) {
+ logger.debug("invalid csv alarm Record,one of column is having blank value : " + record);
+ return;
+ }
+ CldsAlarmCondition cldsAlarmCondition = new CldsAlarmCondition();
+ cldsAlarmCondition.setEventSourceType(record.get(1));
+ cldsAlarmCondition.setAlarmConditionKey(record.get(3));
+ cldsAlarmCondition.setSeverity(record.get(4));
+ cldsAlarmConditionList.add(cldsAlarmCondition);
+ }
+
+ private String getResponsesFromArtifactUrl(String artifactsUrl) throws IOException {
+ String hostUrl = refProp.getStringValue("asdc.hostUrl");
+ artifactsUrl = artifactsUrl.replaceAll("\"", "");
+ String artifactUrl = hostUrl + artifactsUrl;
+ logger.info("value of artifactURl:" + artifactUrl);
+ String currArtifactResponse = getCldsServicesOrResourcesBasedOnURL(artifactUrl, true);
+ logger.info("value of artifactResponse:" + currArtifactResponse);
+ return currArtifactResponse;
+ }
+
+ /**
+ * Service to services/resources/artifacts from asdc.Pass alarmConditions as true to get alarmconditons from artifact url and else it is false
+ *
+ * @param url
+ * @param alarmConditions
+ * @return
+ * @throws IOException
+ */
+ private String getCldsServicesOrResourcesBasedOnURL(String url, boolean alarmConditions) throws IOException {
+ String responseStr;
+ try {
+ url = removeUnwantedBracesFromString(url);
+ URL urlObj = new URL(url);
+
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ String basicAuth = SdcReq.getAsdcBasicAuth(refProp);
+ conn.setRequestProperty("X-ONAP-InstanceID", "CLAMP-Tool");
+ conn.setRequestProperty("Authorization", basicAuth);
+ conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+ conn.setRequestMethod("GET");
+
+ int responseCode = conn.getResponseCode();
+ logger.info("responseCode=" + responseCode);
+
+ BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
+ StringBuffer response = new StringBuffer();
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ response.append(inputLine);
+ if (alarmConditions) {
+ response.append("\n");
+ }
+ }
+ responseStr = response.toString();
+ in.close();
+ } catch (Exception e) {
+ logger.error("Exception occured :" + e.getMessage());
+ throw e;
+ }
+ return responseStr;
+ }
+
+ /**
+ * To create properties object by using cldsServicedata
+ *
+ * @param globalProps
+ * @param cldsServiceData
+ * @return
+ * @throws IOException
+ */
+ public String createPropertiesObjectByUUID(String globalProps, CldsServiceData cldsServiceData) throws IOException {
+ String totalPropsStr;
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode globalPropsJson;
+ if (cldsServiceData != null && cldsServiceData.getServiceUUID() != null) {
+
+ /**
+ * Objectnode to save all byservice, byvf , byvfc and byalarm nodes
+ */
+ ObjectNode byIdObjectNode = mapper.createObjectNode();
+ /**
+ * To create vf ResourceUUID node with serviceInvariantUUID
+ *
+ */
+ ObjectNode invariantUUIDObjectNodeWithVF = createVFObjectNodeByServiceInvariantUUID(mapper, cldsServiceData);
+ byIdObjectNode.putPOJO("byService", invariantUUIDObjectNodeWithVF);
+
+ /**
+ * To create byVf and vfcResourceNode with vfResourceUUID
+ */
+ ObjectNode vfcObjectNodeByVfUUID = createVFCObjectNodeByVfUUID(mapper, cldsServiceData.getCldsVfs());
+ byIdObjectNode.putPOJO("byVf", vfcObjectNodeByVfUUID);
+
+
+ /**
+ * To create byVfc and alarmCondition with vfcResourceUUID
+ */
+ ObjectNode vfcResourceUUIDObjectNode = mapper.createObjectNode();
+ if (cldsServiceData.getCldsVfs() != null && cldsServiceData.getCldsVfs().size() > 0) {
+ for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {
+ if (currCldsVfData != null) {
+ createAlarmCondObjectNodeByVfcUUID(mapper, vfcResourceUUIDObjectNode, currCldsVfData.getCldsVfcs());
+ }
+ }
+ }
+ byIdObjectNode.putPOJO("byVfc", vfcResourceUUIDObjectNode);
+
+ /**
+ * To create byAlarmCondition with alarmConditionKey
+ */
+ List<CldsAlarmCondition> allAlarmConditions = getAllAlarmConditionsFromCldsServiceData(cldsServiceData);
+ ObjectNode alarmCondObjectNodeByAlarmKey = createAlarmCondObjectNodeByAlarmKey(mapper, allAlarmConditions);
+
+ byIdObjectNode.putPOJO("byAlarmCondition", alarmCondObjectNodeByAlarmKey);
+
+ globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
+
+ globalPropsJson.putPOJO("shared", byIdObjectNode);
+ logger.info("valuie of objNode:" + globalPropsJson);
+ } else {
+ /**
+ * to create json with total properties when no serviceUUID passed
+ */
+ globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
+ }
+ totalPropsStr = globalPropsJson.toString();
+ return totalPropsStr;
+ }
+
+ private List<CldsAlarmCondition> getAllAlarmConditionsFromCldsServiceData(CldsServiceData cldsServiceData) {
+ List<CldsAlarmCondition> alarmCondList = new ArrayList<>();
+ if (cldsServiceData != null && cldsServiceData.getCldsVfs() != null && cldsServiceData.getCldsVfs().size() > 0) {
+ for (CldsVfData currCldsVfData : cldsServiceData.getCldsVfs()) {
+ if (currCldsVfData != null && currCldsVfData.getCldsVfcs() != null && currCldsVfData.getCldsVfcs().size() > 0) {
+ for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {
+ if (currCldsVfcData != null && currCldsVfcData.getCldsAlarmConditions() != null && currCldsVfcData.getCldsAlarmConditions().size() > 0) {
+ for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {
+ if (currCldsAlarmCondition != null) {
+ alarmCondList.add(currCldsAlarmCondition);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return alarmCondList;
+ }
+
+ private ObjectNode createAlarmCondObjectNodeByAlarmKey(ObjectMapper mapper, List<CldsAlarmCondition> cldsAlarmCondList) {
+ ObjectNode alarmCondKeyNode = mapper.createObjectNode();
+
+ if (cldsAlarmCondList != null && cldsAlarmCondList.size() > 0) {
+ for (CldsAlarmCondition currCldsAlarmCondition : cldsAlarmCondList) {
+ if (currCldsAlarmCondition != null) {
+ ObjectNode alarmCondNode = mapper.createObjectNode();
+ alarmCondNode.put("eventSourceType", currCldsAlarmCondition.getEventSourceType());
+ alarmCondNode.put("eventSeverity", currCldsAlarmCondition.getSeverity());
+ alarmCondKeyNode.putPOJO(currCldsAlarmCondition.getAlarmConditionKey(), alarmCondNode);
+ }
+ }
+ } else {
+ ObjectNode alarmCondNode = mapper.createObjectNode();
+ alarmCondNode.put("eventSourceType", "");
+ alarmCondNode.put("eventSeverity", "");
+ alarmCondKeyNode.putPOJO("", alarmCondNode);
+ }
+ return alarmCondKeyNode;
+ }
+
+ private ObjectNode createVFObjectNodeByServiceInvariantUUID(ObjectMapper mapper, CldsServiceData cldsServiceData) {
+ ObjectNode invariantUUIDObjectNode = mapper.createObjectNode();
+ ObjectNode vfObjectNode = mapper.createObjectNode();
+ ObjectNode vfUUIDNode = mapper.createObjectNode();
+ List<CldsVfData> cldsVfsList = cldsServiceData.getCldsVfs();
+ if (cldsVfsList != null && cldsVfsList.size() > 0) {
+ for (CldsVfData currCldsVfData : cldsVfsList) {
+ if (currCldsVfData != null) {
+ vfUUIDNode.put(currCldsVfData.getVfInvariantResourceUUID(), currCldsVfData.getVfName());
+ }
+ }
+ } else {
+ vfUUIDNode.put("", "");
+ }
+ vfObjectNode.putPOJO("vf", vfUUIDNode);
+ invariantUUIDObjectNode.putPOJO(cldsServiceData.getServiceInvariantUUID(), vfObjectNode);
+ return invariantUUIDObjectNode;
+ }
+
+ private void createAlarmCondObjectNodeByVfcUUID(ObjectMapper mapper, ObjectNode vfcResourceUUIDObjectNode, List<CldsVfcData> cldsVfcDataList) {
+ ObjectNode alarmCondContsObjectNode = mapper.createObjectNode();
+ ObjectNode alarmCondNode = mapper.createObjectNode();
+ // alarmCondNode.put("", "");
+ if (cldsVfcDataList != null && cldsVfcDataList.size() > 0) {
+ for (CldsVfcData currCldsVfcData : cldsVfcDataList) {
+ if (currCldsVfcData != null) {
+ if (currCldsVfcData.getCldsAlarmConditions() != null && currCldsVfcData.getCldsAlarmConditions().size() > 0) {
+ for (CldsAlarmCondition currCldsAlarmCondition : currCldsVfcData.getCldsAlarmConditions()) {
+ alarmCondNode.put(currCldsAlarmCondition.getAlarmConditionKey(), currCldsAlarmCondition.getAlarmConditionKey());
+ }
+ alarmCondContsObjectNode.putPOJO("alarmCondition", alarmCondNode);
+ }
+ alarmCondContsObjectNode.putPOJO("alarmCondition", alarmCondNode);
+ vfcResourceUUIDObjectNode.putPOJO(currCldsVfcData.getVfcInvariantResourceUUID(), alarmCondContsObjectNode);
+ }
+ }
+ } else {
+ alarmCondNode.put("", "");
+ alarmCondContsObjectNode.putPOJO("alarmCondition", alarmCondNode);
+ vfcResourceUUIDObjectNode.putPOJO("", alarmCondContsObjectNode);
+ }
+ }
+
+ private ObjectNode createVFCObjectNodeByVfUUID(ObjectMapper mapper, List<CldsVfData> cldsVfDataList) {
+ ObjectNode vfUUIDObjectNode = mapper.createObjectNode();
+
+ if (cldsVfDataList != null && cldsVfDataList.size() > 0) {
+ for (CldsVfData currCldsVfData : cldsVfDataList) {
+ if (currCldsVfData != null) {
+ ObjectNode vfcObjectNode = mapper.createObjectNode();
+ ObjectNode vfcUUIDNode = mapper.createObjectNode();
+ if (currCldsVfData.getCldsVfcs() != null && currCldsVfData.getCldsVfcs().size() > 0) {
+ for (CldsVfcData currCldsVfcData : currCldsVfData.getCldsVfcs()) {
+ vfcUUIDNode.put(currCldsVfcData.getVfcInvariantResourceUUID(), currCldsVfcData.getVfcName());
+ }
+ } else {
+ vfcUUIDNode.put("", "");
+ }
+ vfcObjectNode.putPOJO("vfc", vfcUUIDNode);
+ vfUUIDObjectNode.putPOJO(currCldsVfData.getVfInvariantResourceUUID(), vfcObjectNode);
+ }
+ }
+ } else {
+ ObjectNode vfcUUIDNode = mapper.createObjectNode();
+ vfcUUIDNode.put("", "");
+ ObjectNode vfcObjectNode = mapper.createObjectNode();
+ vfcObjectNode.putPOJO("vfc", vfcUUIDNode);
+ vfUUIDObjectNode.putPOJO("", vfcObjectNode);
+ }
+ return vfUUIDObjectNode;
+ }
+
+ public String getArtifactIdIfArtifactAlreadyExists(CldsAsdcServiceDetail cldsAsdcServiceDetail, String artifactName) {
+ String artifactUUId = null;
+ boolean artifactxists = false;
+ if (cldsAsdcServiceDetail != null && cldsAsdcServiceDetail.getResources() != null && cldsAsdcServiceDetail.getResources().size() > 0) {
+ for (CldsAsdcResource currCldsAsdcResource : cldsAsdcServiceDetail.getResources()) {
+ if (artifactxists) {
+ break;
+ }
+ if (currCldsAsdcResource != null && currCldsAsdcResource.getArtifacts() != null && currCldsAsdcResource.getArtifacts().size() > 0) {
+ for (CldsAsdcArtifact currCldsAsdcArtifact : currCldsAsdcResource.getArtifacts()) {
+ if (currCldsAsdcArtifact != null && currCldsAsdcArtifact.getArtifactName() != null) {
+ if (currCldsAsdcArtifact.getArtifactName().equalsIgnoreCase(artifactName)) {
+ artifactUUId = currCldsAsdcArtifact.getArtifactUUID();
+ artifactxists = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ return artifactUUId;
+ }
+
+ public String updateControlLoopStatusToDCAE(String dcaeUrl, String invariantResourceUUID, String invariantServiceUUID, String artifactName) {
+ String baseUrl = refProp.getStringValue("asdc.serviceUrl");
+ String basicAuth = SdcReq.getAsdcBasicAuth(refProp);
+ String postStatusData = "{ \n" +
+ "\"event\" : \"" + "Created" + "\",\n" +
+ "\"serviceUUID\" : \"" + invariantServiceUUID + "\",\n" +
+ "\"resourceUUID\" :\"" + invariantResourceUUID + "\",\n" +
+ "\"artifactName\" : \"" + artifactName + "\",\n" +
+ "} \n";
+ try {
+ String url = baseUrl;
+ if (invariantServiceUUID != null) {
+ url = dcaeUrl + "/closed-loops";
+ }
+ URL urlObj = new URL(url);
+
+ HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
+ conn.setRequestProperty("X-ONAP-InstanceID", "CLAMP-Tool");
+ conn.setRequestProperty("Authorization", basicAuth);
+ conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
+ conn.setRequestMethod("POST");
+
+ byte[] postData = SdcReq.stringToByteArray(postStatusData);
+ try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
+ wr.write(postData);
+ }
+
+ int responseCode = conn.getResponseCode();
+ logger.info("responseCode=" + responseCode);
+
+ String resp = getResponse(conn);
+ if (resp != null) {
+ return resp;
+ }
+ } catch (Exception e) {
+ logger.error("not able to ger any service information from asdc for uuid:" + invariantServiceUUID);
+ }
+ return "";
+ }
+
+ /**
+ * To get all asdc VF/VFC Resources basic info
+ *
+ * @return
+ * @throws IOException
+ */
+ private List<CldsAsdcResourceBasicInfo> getAllAsdcVForVFCResourcesBasedOnResourceType(String resourceType, List<CldsAsdcResourceBasicInfo> allAsdcResources) throws IOException {
+ List<CldsAsdcResourceBasicInfo> allAsdcVFResources = new ArrayList<>();
+ if (allAsdcResources != null && allAsdcResources.size() > 0) {
+ for (CldsAsdcResourceBasicInfo currResource : allAsdcResources) {
+ if (currResource != null && currResource.getResourceType() != null && currResource.getResourceType().equalsIgnoreCase(resourceType)) {
+ allAsdcVFResources.add(currResource);
+ }
+ }
+ }
+ return allAsdcVFResources;
+ }
+
+ private String getResourceUUIDFromResourceInvariantUUID(String resourceInvariantUUID, List<CldsAsdcResourceBasicInfo> resourceInfoList) throws IOException {
+ String resourceUUID = null;
+ if (resourceInfoList != null && resourceInfoList.size() > 0) {
+ for (CldsAsdcResourceBasicInfo currResource : resourceInfoList) {
+ if (currResource != null && currResource.getInvariantUUID() != null && currResource.getUuid() != null
+ && currResource.getInvariantUUID().equalsIgnoreCase(resourceInvariantUUID)) {
+ resourceUUID = currResource.getUuid();
+ break;
+ }
+ }
+ }
+ return resourceUUID;
+ }
+
+ /**
+ * To get all asdc Resources basic info
+ *
+ * @return
+ * @throws IOException
+ */
+ private List<CldsAsdcResourceBasicInfo> getAllAsdcResources() throws IOException {
+ String catalogUrl = refProp.getStringValue("asdc.catalog.url");
+ String resourceUrl = catalogUrl + "resources";
+ String allAsdcResources = getCldsServicesOrResourcesBasedOnURL(resourceUrl, false);
+ List<CldsAsdcResourceBasicInfo> allAsdcResourceBasicInfo = getAllAsdcResourcesListFromJson(allAsdcResources);
+ return removeDuplicateAsdcResourceBasicInfo(allAsdcResourceBasicInfo);
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java b/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java
new file mode 100644
index 000000000..93b6e954d
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/SdcSendReqDelegate.java
@@ -0,0 +1,138 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.client.req.SdcReq;
+import org.onap.clamp.clds.model.CldsAsdcServiceDetail;
+import org.onap.clamp.clds.model.DcaeEvent;
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.List;
+
+/**
+ * Send control loop model to dcae proxy.
+ */
+public class SdcSendReqDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = LoggerFactory.getLogger(SdcSendReqDelegate.class);
+
+ @Autowired
+ private RefProp refProp;
+
+ @Autowired
+ private SdcCatalogServices asdcCatalogServices;
+
+ private String baseUrl;
+ private String artifactType;
+ private String locationArtifactType;
+ private String artifactLabel;
+ private String locationArtifactLabel;
+
+ /**
+ * Perform activity. Send to asdc proxy.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String userid = (String) execution.getVariable("userid");
+ logger.info("userid=" + userid);
+ String docText = (String) execution.getVariable("docText");
+ String artifactName = execution.getVariable("controlName") + DcaeEvent.ARTIFACT_NAME_SUFFIX;
+ execution.setVariable("artifactName", artifactName);
+ getAsdcAttributes();
+ ModelProperties prop = ModelProperties.create(execution);
+ String bluprintPayload = SdcReq.formatBlueprint(refProp, prop, docText);
+ String formatttedAsdcReq = SdcReq.formatAsdcReq(bluprintPayload, artifactName, artifactLabel, artifactType);
+ if (formatttedAsdcReq != null) {
+ execution.setVariable("formattedArtifactReq", formatttedAsdcReq.getBytes());
+ }
+ List<String> asdcReqUrlsList = SdcReq.getAsdcReqUrlsList(prop, baseUrl, asdcCatalogServices, execution);
+
+ String asdcLocationsPayload = SdcReq.formatAsdcLocationsReq(prop, artifactName);
+ String locationArtifactName = execution.getVariable("controlName") + "-location.json";
+ String formattedAsdcLocationReq = SdcReq.formatAsdcReq(asdcLocationsPayload, locationArtifactName, locationArtifactLabel, locationArtifactType);
+ if (formattedAsdcLocationReq != null) {
+ execution.setVariable("formattedLocationReq", formattedAsdcLocationReq.getBytes());
+ }
+ String serviceInvariantUUID = getServiceInvariantUUIDFromProps(prop);
+ uploadToAsdc(prop, serviceInvariantUUID, userid, asdcReqUrlsList, formatttedAsdcReq, formattedAsdcLocationReq, artifactName, locationArtifactName);
+ }
+
+ private String getServiceInvariantUUIDFromProps(ModelProperties props) {
+ String invariantUUID = "";
+ Global globalProps = props.getGlobal();
+ if (globalProps != null) {
+ if (globalProps.getService() != null) {
+ invariantUUID = globalProps.getService();
+ }
+ }
+ return invariantUUID;
+ }
+
+ private void uploadToAsdc(ModelProperties prop, String serviceInvariantUUID, String userid, List<String> asdcReqUrlsList, String formatttedAsdcReq, String formattedAsdcLocationReq, String artifactName, String locationArtifactName) throws Exception {
+ logger.info("userid=" + userid);
+ if (asdcReqUrlsList != null && asdcReqUrlsList.size() > 0) {
+ for (String url : asdcReqUrlsList) {
+ if (url != null) {
+ String originalServiceUUID = asdcCatalogServices.getServiceUUIDFromServiceInvariantID(serviceInvariantUUID);
+ logger.info("ServiceUUID used before upload in url:" + originalServiceUUID);
+ String asdcServicesInformation = asdcCatalogServices.getAsdcServicesInformation(originalServiceUUID);
+ CldsAsdcServiceDetail cldsAsdcServiceDetail = asdcCatalogServices.getCldsAsdcServiceDetailFromJson(asdcServicesInformation);
+ String uploadedArtifactUUID = asdcCatalogServices.getArtifactIdIfArtifactAlreadyExists(cldsAsdcServiceDetail, artifactName);
+ // Upload artifacts to asdc
+ String updateUrl = uploadedArtifactUUID != null ? url + "/" + uploadedArtifactUUID : url;
+ String responseStr = asdcCatalogServices.uploadArtifactToAsdc(prop, userid, updateUrl, formatttedAsdcReq);
+ logger.info("value of asdc Response of uploading to asdc :" + responseStr);
+ String updatedServiceUUID = asdcCatalogServices.getServiceUUIDFromServiceInvariantID(serviceInvariantUUID);
+ if (!originalServiceUUID.equalsIgnoreCase(updatedServiceUUID)) {
+ url = url.replace(originalServiceUUID, updatedServiceUUID);
+ }
+ logger.info("ServiceUUID used after upload in ulr:" + updatedServiceUUID);
+ asdcServicesInformation = asdcCatalogServices.getAsdcServicesInformation(updatedServiceUUID);
+ cldsAsdcServiceDetail = asdcCatalogServices.getCldsAsdcServiceDetailFromJson(asdcServicesInformation);
+ uploadedArtifactUUID = asdcCatalogServices.getArtifactIdIfArtifactAlreadyExists(cldsAsdcServiceDetail, locationArtifactName);
+ // To send location information also to asdc
+ updateUrl = uploadedArtifactUUID != null ? url + "/" + uploadedArtifactUUID : url;
+ responseStr = asdcCatalogServices.uploadArtifactToAsdc(prop, userid, updateUrl, formattedAsdcLocationReq);
+ logger.info("value of asdc Response of uploading location to asdc :" + responseStr);
+ }
+ }
+ }
+ }
+
+ private void getAsdcAttributes() {
+ baseUrl = refProp.getStringValue("asdc.serviceUrl");
+ artifactLabel = refProp.getStringValue("asdc.artifactLabel");
+ locationArtifactLabel = refProp.getStringValue("asdc.locationArtifactLabel");
+ artifactType = refProp.getStringValue("asdc.artifactType");
+ locationArtifactType = refProp.getStringValue("asdc.locationArtifactType");
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDelegate.java
new file mode 100644
index 000000000..90e259f8c
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDelegate.java
@@ -0,0 +1,67 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.client.req.StringMatchPolicyReq;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.UUID;
+import java.util.logging.Logger;
+
+
+/**
+ * Send String Match info to policy api.
+ */
+public class StringMatchPolicyDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(StringMatchPolicyDelegate.class.getName());
+
+ @Autowired
+ private PolicyClient policyClient;
+
+ @Autowired
+ private RefProp refProp;
+
+ /**
+ * Perform activity. Send String Match info to policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String stringMatchPolicyRequestUuid = UUID.randomUUID().toString();
+ execution.setVariable("stringMatchPolicyRequestUuid", stringMatchPolicyRequestUuid);
+
+ ModelProperties prop = ModelProperties.create(execution);
+ String policyJson = StringMatchPolicyReq.format(refProp, prop);
+ String responseMessage = policyClient.sendMicroService(policyJson, prop, stringMatchPolicyRequestUuid);
+ if (responseMessage != null) {
+ execution.setVariable("stringMatchPolicyResponseMessage", responseMessage.getBytes());
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDeleteDelegate.java
new file mode 100644
index 000000000..9efd358d7
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/StringMatchPolicyDeleteDelegate.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client;
+
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.StringMatch;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import java.util.logging.Logger;
+
+
+/**
+ * Delete String Match Policy via policy api.
+ */
+public class StringMatchPolicyDeleteDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(StringMatchPolicyDeleteDelegate.class.getName());
+
+ @Autowired
+ private PolicyClient policyClient;
+
+ /**
+ * Perform activity. Delete String Match Policy via policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ ModelProperties prop = ModelProperties.create(execution);
+ StringMatch stringMatch = prop.getStringMatch();
+ prop.setCurrentModelElementId(stringMatch.getId());
+
+ policyClient.deleteMicrosService(prop);
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java
new file mode 100644
index 000000000..58843d9bf
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDelegate.java
@@ -0,0 +1,53 @@
+package org.onap.clamp.clds.client;
+
+import java.util.UUID;
+import java.util.logging.Logger;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import org.onap.clamp.clds.client.req.TcaMPolicyReq;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.Tca;
+import org.onap.clamp.clds.model.refprop.RefProp;
+
+
+/**
+ * Send Tca info to policy api.
+ *
+ *
+ */
+public class TcaPolicyDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(TcaPolicyDelegate.class.getName());
+
+ @Autowired
+ private RefProp refProp;
+
+ @Autowired PolicyClient policyClient;
+
+ /**
+ * Perform activity. Send Tca info to policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String tcaPolicyRequestUuid = UUID.randomUUID().toString();
+ execution.setVariable("tcaPolicyRequestUuid", tcaPolicyRequestUuid);
+
+ ModelProperties prop = ModelProperties.create(execution);
+ Tca tca = prop.getTca();
+ if(tca.isFound()){
+ String policyJson = TcaMPolicyReq.formatTca(refProp, prop);
+ String responseMessage = policyClient.sendMicroService(policyJson, prop, tcaPolicyRequestUuid);
+ if(responseMessage != null)
+ {
+ execution.setVariable("tcaPolicyResponseMessage", responseMessage.getBytes());
+ }
+ }
+ }
+
+
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/TcaPolicyDeleteDelegate.java b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDeleteDelegate.java
new file mode 100644
index 000000000..31e05d7dd
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/TcaPolicyDeleteDelegate.java
@@ -0,0 +1,48 @@
+package org.onap.clamp.clds.client;
+
+import java.util.logging.Logger;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.Tca;
+import org.onap.clamp.clds.model.refprop.RefProp;
+
+
+/**
+ * Delete Tca Policy via policy api.
+ *
+ *
+ */
+public class TcaPolicyDeleteDelegate implements JavaDelegate {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(TcaPolicyDeleteDelegate.class.getName());
+
+ @Autowired
+ private PolicyClient policyClient;
+
+ /**
+ * Perform activity. Delete Tca Policy via policy api.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+
+ ModelProperties prop = ModelProperties.create(execution);
+ Tca tca = prop.getTca();
+ if(tca.isFound()){
+ prop.setCurrentModelElementId(tca.getId());
+
+ String responseMessage = policyClient.deleteMicrosService(prop);
+ if(responseMessage != null)
+ {
+ execution.setVariable("tcaPolicyDeleteResponseMessage", responseMessage.getBytes());
+ }
+ }
+ }
+
+
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/DcaeReq.java b/src/main/java/org/onap/clamp/clds/client/req/DcaeReq.java
new file mode 100644
index 000000000..35d6c9f5f
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/DcaeReq.java
@@ -0,0 +1,97 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client.req;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.StringMatch;
+import org.onap.clamp.clds.model.refprop.RefProp;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Logger;
+
+
+/**
+ * Construct a DCAE request given CLDS objects.
+ */
+public class DcaeReq {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(DcaeReq.class.getName());
+
+ /**
+ * Format DCAE request.
+ *
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws IOException
+ * @throws JsonMappingException
+ * @throws JsonParseException
+ */
+ public static String format(RefProp refProp, ModelProperties prop) throws IOException {
+ Global globalProp = prop.getGlobal();
+ String service = globalProp.getService();
+
+ StringMatch smProp = prop.getStringMatch();
+ prop.setCurrentModelElementId(smProp.getId());
+
+ ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("dcae.template");
+
+ // "properties":{
+ ObjectNode properties = rootNode.with("properties");
+ // "service_name":
+ properties.put("service_name", globalProp.getService());
+ // "service_ids":[
+ List<String> service_ids = refProp.decodeToList("dcae.decode.service_ids", globalProp.getService());
+ JsonUtil.addArrayField(properties, "service_ids", service_ids);
+ // "vnf_ids":[
+ JsonUtil.addArrayField(properties, "vnf_ids", globalProp.getResourceVf());
+ // "location_ids":[
+ JsonUtil.addArrayField(properties, "location_ids", globalProp.getLocation());
+
+ // "template":{
+ ObjectNode template = rootNode.with("template");
+ // "string_matching":{
+ ObjectNode string_matching = template.with("string_matching");
+ // "dcae":{
+ ObjectNode dcae = string_matching.with("dcae");
+
+ dcae.put("inputTopic", smProp.getTopicSubscribes());
+ dcae.put("outputTopic", smProp.getTopicPublishes());
+ dcae.put("closedLoopControlName", prop.getControlName());
+ dcae.put("policyName", prop.getCurrentPolicyScopeAndPolicyName());
+
+ // "serviceConfigurations":[
+ StringMatchPolicyReq.appendServiceConfigurations(refProp, service, dcae, smProp);
+
+ String dcaeReq = rootNode.toString();
+ logger.info("dcaeReq=" + dcaeReq);
+ return dcaeReq;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/JsonUtil.java b/src/main/java/org/onap/clamp/clds/client/req/JsonUtil.java
new file mode 100644
index 000000000..6aba683bc
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/JsonUtil.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client.req;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Utility methods for formatting json
+ */
+public class JsonUtil {
+
+ /**
+ * Add list of values to json array node
+ *
+ * @param list
+ * @param node
+ */
+ public static void addListToArrayNode(List<String> list, ArrayNode node) {
+ for (String aList : list) {
+ node.add(aList);
+ }
+ }
+
+ /**
+ * Add list of values to json array node
+ *
+ * @param json
+ * @param name
+ * @param list
+ */
+ public static void addArrayField(JsonNode json, String name, List<String> list) {
+ if (list != null) {
+ ArrayNode node = (ArrayNode) json.withArray(name);
+ for (String aList : list) {
+ node.add(aList);
+ }
+ }
+
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/OperationalPolicyReq.java b/src/main/java/org/onap/clamp/clds/client/req/OperationalPolicyReq.java
new file mode 100644
index 000000000..90b9ff8ad
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/OperationalPolicyReq.java
@@ -0,0 +1,299 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client.req;
+
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.Policy;
+import org.onap.clamp.clds.model.prop.PolicyItem;
+import org.openecomp.policy.controlloop.policy.TargetType;
+import org.openecomp.policy.controlloop.policy.PolicyResult;
+import org.openecomp.policy.controlloop.policy.Target;
+import org.openecomp.policy.controlloop.policy.builder.BuilderException;
+import org.openecomp.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
+import org.openecomp.policy.controlloop.policy.builder.Message;
+import org.openecomp.policy.controlloop.policy.builder.Results;
+import org.openecomp.policy.api.AttributeType;
+import org.openecomp.policy.asdc.Resource;
+import org.openecomp.policy.asdc.ResourceType;
+import org.openecomp.policy.asdc.Service;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.jboss.resteasy.spi.BadRequestException;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.*;
+import java.util.logging.Logger;
+
+
+/**
+ * Construct an Operational Policy request given CLDS objects.
+ */
+public class OperationalPolicyReq {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(OperationalPolicyReq.class.getName());
+
+
+ /**
+ * Format Operational Policy attributes.
+ *
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws BuilderException
+ * @throws UnsupportedEncodingException
+ */
+ public static Map<AttributeType, Map<String, String>> formatAttributes(RefProp refProp, ModelProperties prop) throws BuilderException, UnsupportedEncodingException {
+ Global global = prop.getGlobal();
+ Policy policy = prop.getPolicy();
+ prop.setCurrentModelElementId(policy.getId());
+
+ String templateName = refProp.getStringValue("op.templateName", global.getService());
+ String recipeTopic = refProp.getStringValue("op.recipeTopic", global.getService());
+ String operationTopic = refProp.getStringValue("op.operationTopic", global.getService());
+ String notificationTopic = refProp.getStringValue("op.notificationTopic", global.getService());
+
+ // ruleAttributes
+ Map<String, String> ruleAttributes = new HashMap<>();
+
+ if (operationTopic == null || operationTopic.length() == 0) {
+ logger.info("templateName=" + templateName);
+ logger.info("recipeTopic=" + recipeTopic);
+ logger.info("notificationTopic=" + notificationTopic);
+
+ // if no operationTopic, then don't format yaml - use first policy from list
+ PolicyItem policyItem = policy.getPolicyItems().get(0);
+
+ ruleAttributes.put("templateName", templateName);
+ ruleAttributes.put("ClosedLoopControlName", prop.getControlName());
+ ruleAttributes.put("RecipeTopic", recipeTopic);
+ ruleAttributes.put("NotificationTopic", notificationTopic);
+
+ String recipe = policyItem.getRecipe();
+ String maxRetries = String.valueOf(policyItem.getMaxRetries());
+ String retryTimeLimit = String.valueOf(policyItem.getRetryTimeLimit());
+ logger.info("recipe=" + recipe);
+ logger.info("maxRetries=" + maxRetries);
+ logger.info("retryTimeLimit=" + retryTimeLimit);
+ ruleAttributes.put("Recipe", recipe);
+ ruleAttributes.put("MaxRetries", maxRetries);
+ ruleAttributes.put("RetryTimeLimit", retryTimeLimit);
+ } else {
+ logger.info("templateName=" + templateName);
+ logger.info("operationTopic=" + operationTopic);
+ logger.info("notificationTopic=" + notificationTopic);
+
+ // format yaml
+ String yaml = formatYaml(refProp, prop);
+
+ ruleAttributes.put("templateName", templateName);
+ ruleAttributes.put("ClosedLoopControlName", prop.getControlName());
+ ruleAttributes.put("OperationTopic", operationTopic);
+ ruleAttributes.put("NotificationTopic", notificationTopic);
+
+ ruleAttributes.put("ControlLoopYaml", yaml);
+ }
+
+ // matchingAttributes
+ String controller = refProp.getStringValue("op.controller", global.getService());
+
+ Map<String, String> matchingAttributes = new HashMap<>();
+ matchingAttributes.put("controller", controller);
+
+ Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
+ attributes.put(AttributeType.RULE, ruleAttributes);
+ attributes.put(AttributeType.MATCHING, matchingAttributes);
+
+
+ return attributes;
+ }
+
+
+ /**
+ * Format Operational Policy yaml.
+ *
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws BuilderException
+ * @throws UnsupportedEncodingException
+ */
+ private static String formatYaml(RefProp refProp, ModelProperties prop) throws BuilderException, UnsupportedEncodingException {
+ // get property objects
+ Global global = prop.getGlobal();
+ Policy policy = prop.getPolicy();
+ prop.setCurrentModelElementId(policy.getId());
+
+ // convert values to ASDC objects
+ Service service = new Service(global.getService());
+ Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF);
+ Resource[] vfcResources = convertToResource(global.getResourceVfc(), ResourceType.VFC);
+
+ // create builder
+ ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(), policy.getTimeout(), service, vfResources);
+ builder.addResource(vfcResources);
+
+ // process each policy
+ HashMap<String, org.openecomp.policy.controlloop.policy.Policy> policyObjMap = new HashMap<>();
+ List<PolicyItem> policyItemList = orderParentFirst(policy.getPolicyItems());
+ for (int i = 0; i < policyItemList.size(); i++) {
+ org.openecomp.policy.controlloop.policy.Policy policyObj;
+ PolicyItem policyItem = policyItemList.get(i);
+ String policyName = policyItem.getRecipe() + " Policy";
+ if (i == 0) {
+ String policyDescription = policyItem.getRecipe() + " Policy - the trigger (no parent) policy - created by CLDS";
+ policyObj = builder.setTriggerPolicy(
+ policyName,
+ policyDescription,
+ "APPC",
+ new Target(TargetType.VM),
+ policyItem.getRecipe(),
+ new HashMap<>(), //TODO To verify !
+ policyItem.getMaxRetries(),
+ policyItem.getRetryTimeLimit());
+ } else {
+ org.openecomp.policy.controlloop.policy.Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
+ String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by " + parentPolicyObj.getName() + " - created by CLDS";
+ policyObj = builder.setPolicyForPolicyResult(
+ policyName,
+ policyDescription,
+ "APPC",
+ new Target(TargetType.VM),
+ policyItem.getRecipe(),
+ new HashMap<>(), //TODO To verify !
+ policyItem.getMaxRetries(),
+ policyItem.getRetryTimeLimit(),
+ parentPolicyObj.getId(),
+ convertToPolicyResult(policyItem.getParentPolicyConditions()));
+ logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
+ }
+ policyObjMap.put(policyItem.getId(), policyObj);
+ }
+
+ //
+ // Build the specification
+ //
+ Results results = builder.buildSpecification();
+ if (results.isValid()) {
+ logger.info("results.getSpecification()=" + results.getSpecification());
+ } else {
+ // throw exception with error info
+ StringBuilder sb = new StringBuilder();
+ sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
+ for (Message message : results.getMessages()) {
+ sb.append(message.getMessage());
+ sb.append("; ");
+ }
+ throw new BadRequestException(sb.toString());
+ }
+ return URLEncoder.encode(results.getSpecification(), "UTF-8");
+ }
+
+ /**
+ * Order list of PolicyItems so that parents come before any of their children
+ *
+ * @param inOrigList
+ * @return
+ */
+ private static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
+ List<PolicyItem> inList = new ArrayList<>();
+ inList.addAll(inOrigList);
+ List<PolicyItem> outList = new ArrayList<>();
+ int prevSize = 0;
+ while (!inList.isEmpty()) {
+ // check if there's a loop in the policy chain (the inList should have been reduced by at least one)
+ if (inList.size() == prevSize) {
+ throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
+ }
+ prevSize = inList.size();
+ // the following loop should remove at least one PolicyItem from the inList
+ Iterator<PolicyItem> inListItr = inList.iterator();
+ while (inListItr.hasNext()) {
+ PolicyItem inItem = inListItr.next();
+ // check for trigger policy (no parent)
+ String parent = inItem.getParentPolicy();
+ if (parent == null || parent.length() == 0) {
+ if (outList.size() > 0) {
+ throw new BadRequestException("Operation Policy validation problem: more than one trigger policy");
+ } else {
+ outList.add(inItem);
+ inListItr.remove();
+ }
+ } else {
+ // check if this PolicyItem's parent has been processed
+ for (PolicyItem outItem : outList) {
+ if (outItem.getId().equals(parent)) {
+ // if the inItem parent is already in the outList, then add inItem to outList and remove from inList
+ outList.add(inItem);
+ inListItr.remove();
+ break;
+ }
+ }
+ }
+ }
+ }
+ return outList;
+ }
+
+
+ /**
+ * Convert a List of resource strings to an array of Resource objects.
+ *
+ * @param rList
+ * @param resourceType
+ * @return
+ */
+ private static Resource[] convertToResource(List<String> rList, ResourceType resourceType) {
+ int size = 0;
+ if (rList != null) {
+ size = rList.size();
+ }
+ Resource[] rArray = new Resource[size];
+ for (int i = 0; i < size; i++) {
+ String rString = rList.get(i);
+ rArray[i] = new Resource(rString, resourceType);
+ }
+ return rArray;
+ }
+
+ /**
+ * Convert a List of policy result strings to an array of PolicyResult objects.
+ *
+ * @param prList
+ * @return
+ */
+ private static PolicyResult[] convertToPolicyResult(List<String> prList) {
+ int size = 0;
+ if (prList != null) {
+ size = prList.size();
+ }
+ PolicyResult[] prArray = new PolicyResult[size];
+ for (int i = 0; i < size; i++) {
+ String prString = prList.get(i);
+ prArray[i] = PolicyResult.toResult(prString);
+ }
+ return prArray;
+ }
+
+} \ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/client/req/SdcReq.java b/src/main/java/org/onap/clamp/clds/client/req/SdcReq.java
new file mode 100644
index 000000000..45f17164a
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/SdcReq.java
@@ -0,0 +1,360 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client.req;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
+import org.onap.clamp.clds.client.SdcCatalogServices;
+import org.onap.clamp.clds.model.CldsAsdcResource;
+import org.onap.clamp.clds.model.CldsAsdcServiceDetail;
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.StringMatch;
+import org.onap.clamp.clds.model.prop.Tca;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.logging.Logger;
+
+/**
+ * Construct a Asdc request given CLDS objects.
+ */
+public class SdcReq {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(SdcReq.class.getName());
+
+ /**
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
+ throws JsonParseException, JsonMappingException, IOException {
+
+ Global globalProp = prop.getGlobal();
+ String service = globalProp.getService();
+
+ String yamlvalue = getYamlvalue(docText);
+
+ String updatedBlueprint = "";
+ StringMatch stringMatch = prop.getStringMatch();
+ Tca tca = prop.getTca();
+ if (stringMatch.isFound()) {
+ prop.setCurrentModelElementId(stringMatch.getId());
+ ObjectMapper objectMapper = new ObjectMapper();
+ ObjectNode serviceConfigurations = objectMapper.createObjectNode();
+
+ StringMatchPolicyReq.appendServiceConfigurations(refProp, service, serviceConfigurations, stringMatch);
+ logger.info("Value of serviceConfigurations:" + serviceConfigurations);
+ ObjectNode servConfNode = (ObjectNode) serviceConfigurations.get("serviceConfigurations");
+
+ // get updated blueprint by attaching service Conf from
+ // globalProperties
+ updatedBlueprint = getUpdatedBlueprintWithServiceConf(refProp, prop, yamlvalue, servConfNode);
+ } else if (tca.isFound()) {
+ prop.setCurrentModelElementId(tca.getId());
+ ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("tca.template", service);
+ ObjectNode content = rootNode.with("content");
+ TcaMPolicyReq.appendSignatures(refProp, service, content, tca, prop);
+ logger.info("Value of content:" + content);
+ // ObjectNode servConfNode =
+ // (ObjectNode)signatures.get("signatures");
+
+ // get updated blueprint by attaching service Conf from
+ // globalProperties
+ updatedBlueprint = getUpdatedBlueprintWithConfiguration(refProp, prop, yamlvalue, content);
+ }
+
+ logger.info("value of blueprint:" + updatedBlueprint);
+ return updatedBlueprint;
+ }
+
+ private static String getUpdatedBlueprintWithServiceConf(RefProp refProp, ModelProperties prop, String yamlValue,
+ ObjectNode serviceConf) throws IOException {
+ Yaml yaml = new Yaml();
+
+ // Serialiaze Yaml file
+ Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
+ // Get node templates information from Yaml
+ Map<String, Map> nodeTemplates = (Map<String, Map>) loadedYaml.get("node_templates");
+ logger.info("value of NodeTemplates:" + nodeTemplates);
+
+ // Get StringMatch Object information from node templates of Yaml
+ Map<String, Map> smObject = (Map<String, Map>) nodeTemplates.get("SM");
+ logger.info("value of StringMatch:" + smObject);
+
+ // Get Properties Object information from stringmatch of Yaml
+ Map<String, String> propsObject = (Map<String, String>) smObject.get("properties");
+ logger.info("value of PropsObject:" + propsObject);
+
+ String deploymentJsonObject = propsObject.get("deployment_JSON");
+ logger.info("value of deploymentJson:" + deploymentJsonObject);
+
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
+ ObjectNode configurationObjectNode = (ObjectNode) deployJsonNode.get("configuration");
+
+ // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_StringMatch_",
+ String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
+ String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
+ configurationObjectNode.put("policyName", policyName);
+
+ // "closedLoopControlName":"ClosedLoop-FRWL-SIG-0538e6f2-8c1b-4656-9999-3501b3c59ad7",
+ configurationObjectNode.put("closedLoopControlName", prop.getControlName());
+ configurationObjectNode.set("serviceConfigurations", serviceConf);
+ propsObject.put("deployment_JSON", deployJsonNode.toString());
+ String blueprint = yaml.dump(loadedYaml);
+ logger.info("value of updated Yaml File:" + blueprint);
+
+ blueprint = yaml.dump(loadedYaml);
+ logger.info("value of updated Yaml File:" + blueprint);
+
+ return blueprint;
+ }
+
+ private static String getUpdatedBlueprintWithConfiguration(RefProp refProp, ModelProperties prop, String yamlValue,
+ ObjectNode serviceConf) throws JsonProcessingException, IOException {
+ String blueprint = "";
+ Yaml yaml = new Yaml();
+ // Serialiaze Yaml file
+ Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
+ // Get node templates information from Yaml
+ Map<String, Map> nodeTemplates = (Map<String, Map>) loadedYaml.get("node_templates");
+ logger.info("value of NodeTemplates:" + nodeTemplates);
+ // Get Tca Object information from node templates of Yaml
+ Map<String, Map> tcaObject = (Map<String, Map>) nodeTemplates.get("MTCA");
+ logger.info("value of Tca:" + tcaObject);
+ // Get Properties Object information from tca of Yaml
+ Map<String, String> propsObject = (Map<String, String>) tcaObject.get("properties");
+ logger.info("value of PropsObject:" + propsObject);
+ String deploymentJsonObject = (String) propsObject.get("deployment_JSON");
+ logger.info("value of deploymentJson:" + deploymentJsonObject);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
+
+ // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_Tca_",
+ String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
+ String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
+ serviceConf.put("policyName", policyName);
+
+ deployJsonNode.set("configuration", serviceConf);
+ propsObject.put("deployment_JSON", deployJsonNode.toString());
+ blueprint = yaml.dump(loadedYaml);
+ logger.info("value of updated Yaml File:" + blueprint);
+
+ return blueprint;
+ }
+
+ public static String formatAsdcLocationsReq(ModelProperties prop, String artifactName) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ Global global = prop.getGlobal();
+ List<String> locationsList = global.getLocation();
+ ArrayNode locationsArrayNode = objectMapper.createArrayNode();
+ ObjectNode locationObject = objectMapper.createObjectNode();
+ for (String currLocation : locationsList) {
+ locationsArrayNode.add(currLocation);
+ }
+ locationObject.put("artifactName", artifactName);
+ locationObject.putPOJO("locations", locationsArrayNode);
+ String locationJsonFormat = locationObject.toString();
+ logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
+ return locationJsonFormat;
+ }
+
+ public static String formatAsdcReq(String payloadData, String artifactName, String artifactLabel,
+ String artifactType) throws IOException {
+ logger.info("artifact=" + payloadData);
+ String base64Artifact = base64Encode(payloadData);
+ return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
+ + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
+ + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
+ + "} \n";
+ }
+
+ public static String getAsdcReqUrl(ModelProperties prop, String url) {
+ Global globalProps = prop.getGlobal();
+ String serviceUUID = "";
+ String resourceInstanceName = "";
+ if (globalProps != null) {
+ List<String> resourceVf = globalProps.getResourceVf();
+ if (resourceVf != null && resourceVf.size() > 0) {
+ resourceInstanceName = resourceVf.get(0);
+ }
+ if (globalProps.getService() != null) {
+ serviceUUID = globalProps.getService();
+ }
+ }
+ String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
+ return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
+ }
+
+ /**
+ * To get List of urls for all vfresources
+ *
+ * @param prop
+ * @param baseUrl
+ * @param sdcCatalogServices
+ * @return
+ * @throws Exception
+ */
+ public static List<String> getAsdcReqUrlsList(ModelProperties prop, String baseUrl,
+ SdcCatalogServices sdcCatalogServices, DelegateExecution execution) throws Exception {
+ // TODO : refact and regroup with very similar code
+ List<String> urlList = new ArrayList<>();
+ Global globalProps = prop.getGlobal();
+ if (globalProps != null) {
+ if (globalProps.getService() != null) {
+ String serviceInvariantUUID = globalProps.getService();
+ execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
+ List<String> resourceVfList = globalProps.getResourceVf();
+ String serviceUUID = sdcCatalogServices.getServiceUUIDFromServiceInvariantID(serviceInvariantUUID);
+ String asdcServicesInformation = sdcCatalogServices.getAsdcServicesInformation(serviceUUID);
+ CldsAsdcServiceDetail cldsAsdcServiceDetail = sdcCatalogServices.getCldsAsdcServiceDetailFromJson(asdcServicesInformation);
+ if (cldsAsdcServiceDetail != null && resourceVfList != null) {
+ List<CldsAsdcResource> cldsAsdcResourcesList = cldsAsdcServiceDetail.getResources();
+ if (cldsAsdcResourcesList != null && cldsAsdcResourcesList.size() > 0) {
+ for (CldsAsdcResource cldsAsdcResource : cldsAsdcResourcesList) {
+ if (cldsAsdcResource != null && cldsAsdcResource.getResoucreType() != null
+ && cldsAsdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+ if (resourceVfList.contains(cldsAsdcResource.getResourceInvariantUUID())) {
+ String normalizedResourceInstanceName = normalizeResourceInstanceName(cldsAsdcResource.getResourceInstanceName());
+ String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
+ urlList.add(svcUrl);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return urlList;
+ }
+
+ /**
+ * "Normalize" the resource instance name: - Remove spaces, underscores,
+ * dashes, and periods. - make lower case This is required by ASDC when
+ * using the resource instance name to upload an artifact.
+ *
+ * @param inText
+ * @return
+ */
+ public static String normalizeResourceInstanceName(String inText) {
+ return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
+ }
+
+ /**
+ * from michael
+ *
+ * @param data
+ * @return
+ */
+ public static String calculateMD5ByString(String data) {
+ String calculatedMd5 = DigestUtils.md5Hex(data);
+ // encode base-64 result
+ return base64Encode(calculatedMd5.getBytes());
+ }
+
+ /**
+ * Base 64 encode a String.
+ *
+ * @param inText
+ * @return
+ */
+ public static String base64Encode(String inText) {
+ return base64Encode(stringToByteArray(inText));
+ }
+
+ /**
+ * Convert String to byte array.
+ *
+ * @param inText
+ * @return
+ */
+ public static byte[] stringToByteArray(String inText) {
+ return inText.getBytes(StandardCharsets.UTF_8);
+ }
+
+ /**
+ * Base 64 encode a byte array.
+ *
+ * @param bytes
+ * @return
+ */
+ public static String base64Encode(byte[] bytes) {
+ Base64.Encoder encoder = Base64.getEncoder();
+ return encoder.encodeToString(bytes);
+ }
+
+ /**
+ * Return ASDC id and pw as a HTTP Basic Auth string (for example: Basic
+ * dGVzdDoxMjM0NTY=).
+ *
+ * @return
+ */
+ public static String getAsdcBasicAuth(RefProp refProp) {
+ String asdcId = refProp.getStringValue("asdc.serviceUsername");
+ String asdcPw = refProp.getStringValue("asdc.servicePassword");
+ String idPw = base64Encode(asdcId + ":" + asdcPw);
+ return "Basic " + idPw;
+ }
+
+ private static String getYamlvalue(String docText) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ String yamlFileValue = "";
+ ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
+ Iterator<Entry<String, JsonNode>> entryItr = root.fields();
+ while (entryItr.hasNext()) {
+ Entry<String, JsonNode> entry = entryItr.next();
+ String key = entry.getKey();
+ if (key != null && key.equalsIgnoreCase("global")) {
+ ArrayNode arrayNode = (ArrayNode) entry.getValue();
+ for (JsonNode anArrayNode : arrayNode) {
+ ObjectNode node = (ObjectNode) anArrayNode;
+ ArrayNode arrayValueNode = (ArrayNode) node.get("value");
+ JsonNode jsonNode = arrayValueNode.get(0);
+ yamlFileValue = jsonNode.asText();
+ logger.info("value:" + yamlFileValue);
+ }
+ break;
+ }
+ }
+ return yamlFileValue;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/StringMatchPolicyReq.java b/src/main/java/org/onap/clamp/clds/client/req/StringMatchPolicyReq.java
new file mode 100644
index 000000000..0f66cd9ba
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/StringMatchPolicyReq.java
@@ -0,0 +1,138 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.client.req;
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.ServiceConfiguration;
+import org.onap.clamp.clds.model.prop.StringMatch;
+import org.onap.clamp.clds.model.refprop.RefProp;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.Map.Entry;
+import java.util.logging.Logger;
+
+
+/**
+ * Construct a Policy for String Match Micro Service request given CLDS objects.
+ */
+public class StringMatchPolicyReq {
+ // currently uses the java.util.logging.Logger like the Camunda engine
+ private static final Logger logger = Logger.getLogger(StringMatchPolicyReq.class.getName());
+
+ /**
+ * Format Policy String Match request.
+ *
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws IOException
+ */
+ public static String format(RefProp refProp, ModelProperties prop) throws IOException {
+ Global global = prop.getGlobal();
+ String service = global.getService();
+
+ StringMatch sm = prop.getStringMatch();
+ prop.setCurrentModelElementId(sm.getId());
+ ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("sm.template", service);
+
+ // "policyName":
+ rootNode.put("policyName", prop.getCurrentPolicyScopeAndPolicyName());
+
+ // "content":{
+ ObjectNode content = rootNode.with("content");
+
+ // "closedLoopControlName":
+ content.put("closedLoopControlName", prop.getControlName());
+
+ // "serviceConfigurations":[
+ appendServiceConfigurations(refProp, service, content, sm);
+
+ String stringMatchPolicyReq = rootNode.toString();
+ logger.info("stringMatchPolicyReq=" + stringMatchPolicyReq);
+ return stringMatchPolicyReq;
+ }
+
+ /**
+ * Add serviceConfigurations to json
+ *
+ * @param appendToNode
+ * @param sm
+ * @throws IOException
+ */
+ public static void appendServiceConfigurations(RefProp refProp, String service, ObjectNode appendToNode, StringMatch sm) throws IOException {
+ // "serviceConfigurations":{
+ ObjectNode scNodes = appendToNode.with("serviceConfigurations");
+
+ Iterator<ServiceConfiguration> scItr = sm.getServiceConfigurations().iterator();
+ int index = 0;
+ while (scItr.hasNext()) {
+ ServiceConfiguration sc = scItr.next();
+
+ //"ItemX":{
+ index++;
+ String keyValue = "Item" + index;
+ ObjectNode scNode = (ObjectNode) refProp.getJsonTemplate("sm.sc.template", service);
+ scNodes.set(keyValue, scNode);
+
+ // "rulegroup":"abc",
+ String rulegroupInd = refProp.getStringValue("sm.rulegroup", service);
+ String groupNumber = sc.getGroupNumber();
+ if (rulegroupInd != null && rulegroupInd.equalsIgnoreCase("true") && groupNumber != null && groupNumber.length() > 0) {
+
+ //String rulegroup = (sc.getResourceVf() == null ? "" : String.join(" ", sc.getResourceVf())) + " - " + (sc.getResourceVfc() == null ? "" : String.join(" ", sc.getResourceVfc()));
+ scNode.put("rulegroup", groupNumber);
+ }
+
+ // "aaiMatchingFields" : ["VM_NAME"],
+ JsonUtil.addArrayField(scNode, "aaiMatchingFields", sc.getaaiMatchingFields());
+ // "aaiSendFields" : ["VMID", "TenantID"],
+ JsonUtil.addArrayField(scNode, "aaiSendFields", sc.getaaiSendFields());
+
+ // "stringSet": [
+ ArrayNode ssNode = scNode.putArray("stringSet");
+ // ObjectNode ssNode = scNode.with("stringSet");
+ for (Entry<String, String> entry : sc.getStringSet().entrySet()) {
+ // exclude eventSourceType
+ if (!entry.getKey().equals("eventSourceType")) {
+ ssNode.add(entry.getKey());
+ ssNode.add(entry.getValue());
+ }
+ }
+
+ // timeWindow": "0",
+ scNode.put("timeWindow", sc.getTimeWindow());
+ // "ageLimit": "3600",
+ scNode.put("ageLimit", sc.getAgeLimit());
+ // "createClosedLoopEventId" : "Initial",
+ scNode.put("createClosedLoopEventId", sc.getCreateClosedLoopEventId());
+ // "outputEventName": "OnSet"
+ scNode.put("outputEventName", sc.getOutputEventName());
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/client/req/TcaMPolicyReq.java b/src/main/java/org/onap/clamp/clds/client/req/TcaMPolicyReq.java
new file mode 100644
index 000000000..f8acb64f6
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/client/req/TcaMPolicyReq.java
@@ -0,0 +1,93 @@
+package org.onap.clamp.clds.client.req;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+import org.onap.clamp.clds.model.prop.Global;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.prop.Tca;
+import org.onap.clamp.clds.model.prop.TcaItem;
+import org.onap.clamp.clds.model.prop.TcaThreshhold;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Construct a Policy for Tca/MTca Service request given CLDS objects.
+ *
+ *
+ */
+public class TcaMPolicyReq {
+ private static final Logger logger = Logger.getLogger(StringMatchPolicyReq.class.getName());
+
+ /**
+ * Format Tca Policy request
+ *
+ * @param refProp
+ * @param prop
+ * @return
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static String formatTca(RefProp refProp, ModelProperties prop) throws JsonParseException, JsonMappingException, IOException {
+ Global global = prop.getGlobal();
+ String service = global.getService();
+
+ Tca tca = prop.getTca();
+ prop.setCurrentModelElementId(tca.getId());
+ ObjectNode rootNode = (ObjectNode)refProp.getJsonTemplate("tca.template", service);
+ rootNode.put("policyName", prop.getCurrentPolicyScopeAndPolicyName());
+ ObjectNode content = rootNode.with("content");
+ appendSignatures(refProp, service, content, tca, prop);
+
+ String tcaPolicyReq = rootNode.toString();
+ logger.info("tcaPolicyReq=" + tcaPolicyReq);
+ return tcaPolicyReq;
+ }
+
+ /**
+ * Add appendSignatures to json
+ *
+ * @param refProp
+ * @param service
+ * @param appendToNode
+ * @param tca
+ * @param prop
+ * @throws JsonParseException
+ * @throws JsonMappingException
+ * @throws IOException
+ */
+ public static void appendSignatures(RefProp refProp, String service, ObjectNode appendToNode, Tca tca, ModelProperties prop) throws JsonParseException, JsonMappingException, IOException {
+ // "signatures":{
+ ArrayNode tcaNodes = appendToNode.withArray("signatures");
+ for(TcaItem tcaItem : tca.getTcaItems()){
+ ObjectNode tcaNode = (ObjectNode)refProp.getJsonTemplate("tca.signature.template", service);
+ tcaNode.put("useCaseName", tcaItem.getTcaName());
+ tcaNode.put("signatureName", tcaItem.getTcaName()+ "_" + tcaItem.getTcaUuId());
+ tcaNode.put("signatureUuid", tcaItem.getTcaUuId());
+ prop.setPolicyUniqueId(tcaItem.getPolicyId());
+ tcaNode.put("closedLoopControlName", prop.getControlNameAndPolicyUniqueId());
+ tcaNode.put("severity", tcaItem.getSeverity());
+ tcaNode.put("maxInterval", tcaItem.getInterval());
+ tcaNode.put("minMessageViolations", tcaItem.getViolations());
+
+ tcaNodes.add(tcaNode);
+ Iterator<TcaThreshhold> scItr = tcaItem.getTcaThreshholds().iterator();
+ while(scItr.hasNext()) {
+ TcaThreshhold tcaThreshhold = scItr.next();
+ // "thresholds": [
+ ArrayNode thNodes = tcaNode.withArray("thresholds");
+ ObjectNode thNode = thNodes.addObject();
+ thNode.put("fieldPath", tcaThreshhold.getFieldPath());
+ thNode.put("thresholdName", tcaThreshhold.getMetric());
+ thNode.put("thresholdValue", tcaThreshhold.getThreshhold());
+ thNode.put("direction", tcaThreshhold.getOperator());
+ }
+ }
+ }
+
+} \ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/common/LogMessages.java b/src/main/java/org/onap/clamp/clds/common/LogMessages.java
new file mode 100644
index 000000000..cdd479371
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/common/LogMessages.java
@@ -0,0 +1,37 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.common;
+
+import com.att.eelf.i18n.EELFResolvableErrorEnum;
+import com.att.eelf.i18n.EELFResourceManager;
+
+public enum LogMessages implements EELFResolvableErrorEnum {
+
+ LOGSERVICE_HELLO_MESSAGE, LOGSERVICE_EMAIL_ERROR, LOGSERVICE_EMAIL_CLASS, LOGSERVICE_EMAIL_CLASS_NULL, PROCESS_INSTANCE_ID;
+
+ static {
+ EELFResourceManager.loadMessageBundle("logmessages");
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/config/CamundaAuthFilterInitializer.java b/src/main/java/org/onap/clamp/clds/config/CamundaAuthFilterInitializer.java
new file mode 100644
index 000000000..244b40aa1
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/config/CamundaAuthFilterInitializer.java
@@ -0,0 +1,87 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.config;
+
+import java.util.EnumSet;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import javax.servlet.DispatcherType;
+import javax.servlet.Filter;
+import javax.servlet.FilterRegistration;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+
+import org.camunda.bpm.spring.boot.starter.CamundaBpmAutoConfiguration;
+import org.camunda.bpm.webapp.impl.security.auth.AuthenticationFilter;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.AutoConfigureAfter;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
+import org.springframework.boot.web.servlet.ServletContextInitializer;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@ConditionalOnWebApplication
+@AutoConfigureAfter(CamundaBpmAutoConfiguration.class)
+public class CamundaAuthFilterInitializer implements ServletContextInitializer {
+
+ private static final EnumSet<DispatcherType> DISPATCHER_TYPES = EnumSet.of(DispatcherType.REQUEST);
+
+ private static final String AJSC_CADI_PROPS_FILE = "cadi.properties";
+
+ private ServletContext servletContext;
+
+ @Value("${com.att.ajsc.camunda.contextPath:/camunda}")
+ private String CAMUNDA_SUFFIX;
+
+ private static final Logger log = Logger.getLogger(CamundaAuthFilterInitializer.class.getName());
+
+ @Override
+ public void onStartup(ServletContext servletContext) throws ServletException {
+ this.servletContext = servletContext;
+
+ registerFilter("Authentication Filter", AuthenticationFilter.class, CAMUNDA_SUFFIX + "/*");
+ }
+
+ private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass,
+ final String... urlPatterns) {
+ return registerFilter(filterName, filterClass, null, urlPatterns);
+ }
+
+ private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass,
+ final Map<String, String> initParameters, final String... urlPatterns) {
+ FilterRegistration filterRegistration = servletContext.getFilterRegistration(filterName);
+
+ if (filterRegistration == null) {
+ filterRegistration = servletContext.addFilter(filterName, filterClass);
+ filterRegistration.addMappingForUrlPatterns(DISPATCHER_TYPES, true, urlPatterns);
+
+ if (initParameters != null) {
+ filterRegistration.setInitParameters(initParameters);
+ }
+ }
+
+ return filterRegistration;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/config/CamundaEngineConfiguration.java b/src/main/java/org/onap/clamp/clds/config/CamundaEngineConfiguration.java
new file mode 100644
index 000000000..949f4ea62
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/config/CamundaEngineConfiguration.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.config;
+
+import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Primary;
+
+import javax.sql.DataSource;
+
+@Configuration
+public class CamundaEngineConfiguration {
+
+ /**
+ * Camunda Identity databse DataSource configuration
+ */
+ @Primary
+ @Bean(name = "camundaBpmDataSource")
+ @ConfigurationProperties(prefix = "spring.datasource")
+ public DataSource dataSource() {
+ return DataSourceBuilder
+ .create()
+ .build();
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java b/src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java
new file mode 100644
index 000000000..814d2c6ad
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/config/CldsConfiguration.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.config;
+
+import com.att.ajsc.common.AjscProvider;
+import com.att.ajsc.common.AjscService;
+import org.onap.clamp.clds.client.*;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.onap.clamp.clds.transform.XslTransformer;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+
+import javax.sql.DataSource;
+import javax.xml.transform.TransformerConfigurationException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+@Configuration
+@Profile("clamp-default")
+public class CldsConfiguration {
+
+ @Autowired
+ private ApplicationContext context;
+
+ /**
+ * Clds Identity databse DataSource configuration
+ */
+ @Bean(name = "cldsDataSource")
+ @ConfigurationProperties(prefix = "spring.cldsdatasource")
+ public DataSource cldsDataSource() {
+ return DataSourceBuilder
+ .create()
+ .build();
+ }
+
+ @Bean(name = "jaxrsProviders")
+ public List jaxrsProviders() {
+ return new ArrayList(context.getBeansWithAnnotation(AjscProvider.class).values());
+ }
+
+ @Bean(name = "jaxrsServices")
+ public List jaxrsServices() {
+ return new ArrayList(context.getBeansWithAnnotation(AjscService.class).values());
+ }
+
+ @Bean(name = "cldsDao")
+ public CldsDao getCldsDao() {
+ CldsDao cldsDao = new CldsDao();
+ cldsDao.setDataSource(cldsDataSource());
+ return cldsDao;
+ }
+
+ @Bean(name = "cldsBpmnTransformer")
+ public XslTransformer getCldsBpmnXslTransformer() throws TransformerConfigurationException {
+ XslTransformer xslTransformer = new XslTransformer();
+ xslTransformer.setXslResourceName("xsl/clds-bpmn-transformer.xsl");
+ return xslTransformer;
+ }
+
+ @Bean
+ public RefProp getRefProp() throws IOException {
+ return new RefProp();
+ }
+
+ @Bean
+ public PolicyClient getPolicyClient() {
+ return new PolicyClient();
+ }
+
+ @Bean(name = "cldsEventDelegate")
+ public CldsEventDelegate getCldsEventDelegate() {
+ return new CldsEventDelegate();
+ }
+
+ @Bean(name = "dcaeReqDelegate")
+ public DcaeReqDelegate getDcaeReqDelegate() {
+ return new DcaeReqDelegate();
+ }
+
+ @Bean(name = "sdcSendReqDelegate")
+ public SdcSendReqDelegate getSdcSendReqDelegate() {
+ return new SdcSendReqDelegate();
+ }
+
+ @Bean(name = "dcaeReqDeleteDelegate")
+ public DcaeReqDeleteDelegate getDcaeReqDeleteDelegate() {
+ return new DcaeReqDeleteDelegate();
+ }
+
+ @Bean(name = "operationalPolicyDelegate")
+ public OperationalPolicyDelegate getOperationalPolicyDelegate() {
+ return new OperationalPolicyDelegate();
+ }
+
+ @Bean(name = "operationalPolicyDeleteDelegate")
+ public OperationalPolicyDeleteDelegate getOperationalPolicyDeleteDelegate() {
+ return new OperationalPolicyDeleteDelegate();
+ }
+
+ @Bean(name = "stringMatchPolicyDelegate")
+ public StringMatchPolicyDelegate getStringMatchPolicyDelegate() {
+ return new StringMatchPolicyDelegate();
+ }
+
+ @Bean(name = "stringMatchPolicyDeleteDelegate")
+ public StringMatchPolicyDeleteDelegate getStringMatchPolicyDeleteDelegate() {
+ return new StringMatchPolicyDeleteDelegate();
+ }
+
+ @Bean(name = "sdcCatalogServices")
+ public SdcCatalogServices getAsdcCatalogServices() {
+ return new SdcCatalogServices();
+ }
+} \ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/config/CldsSecurityConfig.java b/src/main/java/org/onap/clamp/clds/config/CldsSecurityConfig.java
new file mode 100644
index 000000000..571ad4b40
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/config/CldsSecurityConfig.java
@@ -0,0 +1,117 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.io.Resource;
+import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+@Configuration
+@EnableWebSecurity
+public class CldsSecurityConfig extends WebSecurityConfigurerAdapter {
+
+ private static final Logger logger = Logger.getLogger(CldsSecurityConfig.class.getName());
+
+ @Autowired
+ private ApplicationContext appContext;
+
+ @Value("${org.onap.clamp.config.files.cldsUsers:'classpath:etc/config/clds/clds-users.properties'}")
+ private String cldsUsers;
+
+ private final static String ROLEPREFIX = "null|null|";
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .csrf().disable()
+ .authorizeRequests()
+ .anyRequest().authenticated()
+ .and()
+ .formLogin()
+ .loginPage("/login.html")
+ .permitAll()
+ .and()
+ .logout()
+ .permitAll();
+ }
+
+ @Autowired
+ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
+ List<String> userList = loadUsers();
+
+ // no users defined
+ if (null == userList || userList.isEmpty()) {
+ logger.log(Level.SEVERE, "No users defined. Users should be defined under clds/clds-users.properties.");
+ return;
+ }
+
+ for (String user : userList) {
+ String[] userInfo = user.split("[|]");
+ if (userInfo.length != 3) {
+ logger.log(Level.SEVERE, "Defined User(" + user + ") is not in good format. User format should be:<username>|<password>|<role>. Role should be eiother 'read' or 'all'.");
+ continue;
+ }
+
+ auth
+ .inMemoryAuthentication()
+ .withUser(userInfo[0]).password(userInfo[1]).roles(ROLEPREFIX + ("all".equalsIgnoreCase(userInfo[2]) ? "*" : userInfo[2]));
+
+ }
+ }
+
+ private boolean validUser(String[] userInfo) {
+ return ((userInfo != null) && (userInfo.length == 3) && (("all".equals(userInfo[2])) || ("read".equals(userInfo[2]))));
+ }
+
+ private List<String> loadUsers() throws Exception {
+ logger.info("Load from clds-users.properties");
+
+ Resource resource = appContext.getResource(cldsUsers);
+ BufferedReader input = new BufferedReader(new InputStreamReader(resource.getInputStream()));
+
+ List<String> userList = new LinkedList<>();
+
+ String line;
+ while ((line = input.readLine()) != null) {
+ if (!line.contains("#")) {
+ userList.add(line);
+ }
+ logger.info("line read:" + line);
+ }
+ return userList;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/org/onap/clamp/clds/config/CsiLoggingConfiguration.java b/src/main/java/org/onap/clamp/clds/config/CsiLoggingConfiguration.java
new file mode 100644
index 000000000..5c5ba5742
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/config/CsiLoggingConfiguration.java
@@ -0,0 +1,48 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.config;
+
+import com.att.ajsc.csilogging.common.AsyncSupport;
+import com.att.ajsc.csilogging.interceptors.CsiLoggingCamelPostInterceptor;
+import com.att.ajsc.csilogging.interceptors.CsiLoggingCamelPreInterceptor;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class CsiLoggingConfiguration {
+ @Bean
+ public CsiLoggingCamelPreInterceptor csiLoggingCamelPreInterceptor() {
+ return new CsiLoggingCamelPreInterceptor();
+ }
+
+ @Bean
+ public CsiLoggingCamelPostInterceptor csiLoggingCamelPostInterceptor() {
+ return new CsiLoggingCamelPostInterceptor();
+ }
+
+ @Bean
+ public AsyncSupport asyncsupport() {
+ return new AsyncSupport();
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/dao/CldsDao.java b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java
new file mode 100644
index 000000000..67e4d1b84
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/dao/CldsDao.java
@@ -0,0 +1,485 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.dao;
+
+import org.onap.clamp.clds.model.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.core.RowMapper;
+import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
+import org.springframework.jdbc.core.namedparam.SqlParameterSource;
+import org.springframework.jdbc.core.simple.SimpleJdbcCall;
+import org.springframework.stereotype.Repository;
+
+import javax.sql.DataSource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.sql.Blob;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Data Access for CLDS Model tables.
+ */
+@Repository("cldsDao")
+public class CldsDao {
+
+ private static final Logger logger = LoggerFactory.getLogger(CldsDao.class);
+
+ private JdbcTemplate jdbcTemplateObject;
+ private SimpleJdbcCall procGetModel;
+ private SimpleJdbcCall procGetModelTemplate;
+ private SimpleJdbcCall procSetModel;
+ private SimpleJdbcCall procInsEvent;
+ private SimpleJdbcCall procUpdEvent;
+ private SimpleJdbcCall procSetTemplate;
+ private SimpleJdbcCall procGetTemplate;
+ private SimpleJdbcCall procDelAllModelInstances;
+ private SimpleJdbcCall procInsModelInstance;
+ private SimpleJdbcCall procDelModelInstance;
+
+ /**
+ * Log message when instantiating
+ */
+ public CldsDao() {
+ logger.info("CldsDao instantiating...");
+ }
+
+ /**
+ * When dataSource is provided, instantiate spring jdbc objects.
+ *
+ * @param dataSource
+ */
+ public void setDataSource(DataSource dataSource) {
+ this.jdbcTemplateObject = new JdbcTemplate(dataSource);
+ this.procGetModel = new SimpleJdbcCall(dataSource).withProcedureName("get_model");
+ this.procGetModelTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_model_template");
+ this.procSetModel = new SimpleJdbcCall(dataSource).withProcedureName("set_model");
+ this.procInsEvent = new SimpleJdbcCall(dataSource).withProcedureName("ins_event");
+ this.procUpdEvent = new SimpleJdbcCall(dataSource).withProcedureName("upd_event");
+ this.procGetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("get_template");
+ this.procSetTemplate = new SimpleJdbcCall(dataSource).withProcedureName("set_template");
+ this.procInsModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("ins_model_instance");
+ this.procDelModelInstance = new SimpleJdbcCall(dataSource).withProcedureName("del_model_instance");
+ this.procDelAllModelInstances = new SimpleJdbcCall(dataSource).withProcedureName("del_all_model_instances");
+ }
+
+ /**
+ * Get a model from the database given the model name.
+ *
+ * @param modelName
+ * @return model
+ */
+ public CldsModel getModel(String modelName) {
+ return getModel(modelName, null);
+ }
+
+ /**
+ * Get a model from the database given the controlNameUuid.
+ *
+ * @param controlNameUuid
+ * @return model
+ */
+ public CldsModel getModelByUuid(String controlNameUuid) {
+ return getModel(null, controlNameUuid);
+ }
+
+ /**
+ * Get a model from the database given the model name or a controlNameUuid.
+ *
+ * @param modelName
+ * @return model
+ */
+ private CldsModel getModel(String modelName, String controlNameUuid) {
+ CldsModel model = new CldsModel();
+ model.setName(modelName);
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_model_name", modelName)
+ .addValue("v_control_name_uuid", controlNameUuid);
+ Map<String, Object> out = logSqlExecution(procGetModel, in);
+ model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
+ model.setControlNameUuid((String) out.get("v_control_name_uuid"));
+ model.setId((String) (out.get("v_model_id")));
+ model.setTemplateId((String) (out.get("v_template_id")));
+ model.setTemplateName((String) (out.get("v_template_name")));
+ model.setBpmnId((String) (out.get("v_template_bpmn_id")));
+ model.setBpmnUserid((String) out.get("v_template_bpmn_userid"));
+ model.setBpmnText((String) out.get("v_template_bpmn_text"));
+ model.setPropId((String) (out.get("v_model_prop_id")));
+ model.setPropUserid((String) out.get("v_model_prop_userid"));
+ model.setPropText((String) out.get("v_model_prop_text"));
+ model.setImageId((String) (out.get("v_template_image_id")));
+ model.setImageUserid((String) out.get("v_template_image_userid"));
+ model.setImageText((String) out.get("v_template_image_text"));
+ model.setDocId((String) (out.get("v_template_doc_id")));
+ model.setDocUserid((String) out.get("v_template_doc_userid"));
+ model.setDocText((String) out.get("v_template_doc_text"));
+ model.setBlueprintText((String) out.get("v_model_blueprint_text"));
+ model.getEvent().setId((String) (out.get("v_event_id")));
+ model.getEvent().setActionCd((String) out.get("v_action_cd"));
+ model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
+ model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
+ model.getEvent().setUserid((String) out.get("v_event_userid"));
+ return model;
+ }
+
+ /**
+ * Get a model and template information from the database given the model name.
+ *
+ * @param modelName
+ * @return model
+ */
+ public CldsModel getModelTemplate(String modelName) {
+ CldsModel model = new CldsModel();
+ model.setName(modelName);
+ SqlParameterSource in = new MapSqlParameterSource().addValue("v_model_name", modelName);
+ Map<String, Object> out = logSqlExecution(procGetModelTemplate, in);
+ // todo : rationalize
+ model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
+ model.setControlNameUuid((String) out.get("v_control_name_uuid"));
+ model.setId((String) (out.get("v_model_id")));
+ model.setTemplateId((String) (out.get("v_template_id")));
+ model.setTemplateName((String) (out.get("v_template_name")));
+ model.setBpmnId((String) (out.get("v_template_bpmn_id")));
+ model.setBpmnUserid((String) out.get("v_template_bpmn_userid"));
+ model.setBpmnText((String) out.get("v_template_bpmn_text"));
+ model.setPropId((String) (out.get("v_model_prop_id")));
+ model.setPropUserid((String) out.get("v_model_prop_userid"));
+ model.setPropText((String) out.get("v_model_prop_text"));
+ model.setImageId((String) (out.get("v_template_image_id")));
+ model.setImageUserid((String) out.get("v_template_image_userid"));
+ model.setImageText((String) out.get("v_template_image_text"));
+ model.setDocId((String) (out.get("v_template_doc_id")));
+ model.setDocUserid((String) out.get("v_template_doc_userid"));
+ model.setDocText((String) out.get("v_template_doc_text"));
+ model.setBlueprintText((String) out.get("v_model_blueprint_text"));
+ model.getEvent().setId((String) (out.get("v_event_id")));
+ model.getEvent().setActionCd((String) out.get("v_action_cd"));
+ model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
+ model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
+ model.getEvent().setUserid((String) out.get("v_event_userid"));
+
+ Map<String, Object> modelResults = logSqlExecution(procGetModel, in);
+ Object modelResultObject = modelResults.get("#result-set-1");
+ if (modelResultObject != null && modelResultObject instanceof ArrayList) {
+ List<Object> modelInstanceRs = (List<Object>) modelResultObject;
+ for (Object currModelInstance : modelInstanceRs) {
+ if (currModelInstance != null && currModelInstance instanceof HashMap) {
+ HashMap<String, String> modelInstanceMap = (HashMap<String, String>) currModelInstance;
+ CldsModelInstance modelInstance = new CldsModelInstance();
+ modelInstance.setModelInstanceId(modelInstanceMap.get("model_instance_id"));
+ modelInstance.setVmName(modelInstanceMap.get("vm_name"));
+ modelInstance.setLocation(modelInstanceMap.get("location"));
+ model.getCldsModelInstanceList().add(modelInstance);
+ logger.info("value of currModel: {}", currModelInstance);
+ }
+ }
+ }
+ return model;
+ }
+
+ /**
+ * Update model in the database using parameter values and return updated model object.
+ *
+ * @param model
+ * @param userid
+ * @return
+ */
+ public CldsModel setModel(CldsModel model, String userid) {
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_model_name", model.getName())
+ .addValue("v_template_id", model.getTemplateId())
+ .addValue("v_userid", userid)
+ .addValue("v_model_prop_text", model.getPropText())
+ .addValue("v_model_blueprint_text", model.getBlueprintText())
+ .addValue("v_control_name_prefix", model.getControlNamePrefix())
+ .addValue("v_control_name_uuid", model.getControlNameUuid());
+ Map<String, Object> out = logSqlExecution(procSetModel, in);
+ model.setControlNamePrefix((String) out.get("v_control_name_prefix"));
+ model.setControlNameUuid((String) out.get("v_control_name_uuid"));
+ model.setId((String) (out.get("v_model_id")));
+ model.setPropId((String) (out.get("v_model_prop_id")));
+ model.setPropUserid((String) (out.get("v_model_prop_userid")));
+ model.setBlueprintId((String) (out.get("v_model_blueprint_id")));
+ model.setBlueprintUserid((String) out.get("v_model_blueprint_userid"));
+ model.getEvent().setId((String) (out.get("v_event_id")));
+ model.getEvent().setActionCd((String) out.get("v_action_cd"));
+ model.getEvent().setActionStateCd((String) out.get("v_action_state_cd"));
+ model.getEvent().setProcessInstanceId((String) out.get("v_event_process_instance_id"));
+ model.getEvent().setUserid((String) out.get("v_event_userid"));
+ return model;
+ }
+
+ /**
+ * Inserts new modelInstance in the database using parameter values and return updated model object.
+ *
+ * @param model
+ * @param modelInstancesList
+ * @return
+ */
+ public void insModelInstance(CldsModel model, List<CldsModelInstance> modelInstancesList) {
+ // Delete all existing model instances for given controlNameUUID
+ logger.debug("deleting instances for: {}", model.getControlNameUuid());
+ delAllModelInstances(model.getControlNameUuid());
+
+ if (modelInstancesList == null) {
+ logger.debug("modelInstancesList == null");
+ } else {
+ for (CldsModelInstance currModelInstance : modelInstancesList) {
+ logger.debug("v_control_name_uuid={}", model.getControlNameUuid());
+ logger.debug("v_vm_name={}", currModelInstance.getVmName());
+ logger.debug("v_location={}", currModelInstance.getLocation());
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_control_name_uuid", model.getControlNameUuid())
+ .addValue("v_vm_name", currModelInstance.getVmName())
+ .addValue("v_location", currModelInstance.getLocation());
+ Map<String, Object> out = logSqlExecution(procInsModelInstance, in);
+ model.setId((String) (out.get("v_model_id")));
+ CldsModelInstance modelInstance = new CldsModelInstance();
+ modelInstance.setLocation(currModelInstance.getLocation());
+ modelInstance.setVmName(currModelInstance.getVmName());
+ modelInstance.setModelInstanceId((String) (out.get("v_model_instance_id")));
+ model.getCldsModelInstanceList().add(modelInstance);
+ }
+ }
+ }
+
+ /**
+ * Delete a list of modelInstance from the database using parameter values and returns updated model object.
+ * This method is defunct - DCAE Proxy will not undeploy individual instances. It will send an empty list of
+ * deployed instances to indicate all have been removed. Or it will send an updated list to indicate those that
+ * are still deployed with any not on the list considered undeployed.
+ *
+ * @param controlNameUUid
+ * @param modelInstancesList
+ * @return
+ */
+ private CldsModel delModelInstance(String controlNameUUid, List<CldsModelInstance> modelInstancesList) {
+ CldsModel model = new CldsModel();
+ for (CldsModelInstance currModelInstance : modelInstancesList) {
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_control_name_uuid", controlNameUUid)
+ .addValue("v_vm_name", currModelInstance.getVmName());
+ Map<String, Object> out = logSqlExecution(procDelModelInstance, in);
+ model.setId((String) (out.get("v_model_id")));
+ }
+ return model;
+ }
+
+ /**
+ * Insert an event in the database - require either modelName or controlNamePrefix/controlNameUuid.
+ * @param modelName
+ * @param controlNamePrefix
+ * @param controlNameUuid
+ * @param cldsEvent
+ * @return
+ */
+ public CldsEvent insEvent(String modelName, String controlNamePrefix, String controlNameUuid, CldsEvent cldsEvent) {
+ CldsEvent event = new CldsEvent();
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_model_name", modelName)
+ .addValue("v_control_name_prefix", controlNamePrefix)
+ .addValue("v_control_name_uuid", controlNameUuid)
+ .addValue("v_userid", cldsEvent.getUserid())
+ .addValue("v_action_cd", cldsEvent.getActionCd())
+ .addValue("v_action_state_cd", cldsEvent.getActionStateCd())
+ .addValue("v_process_instance_id", cldsEvent.getProcessInstanceId());
+ Map<String, Object> out = logSqlExecution(procInsEvent, in);
+ event.setId((String) (out.get("v_event_id")));
+ return event;
+ }
+
+ /**
+ * Method to delete all model instances based on controlNameUUID
+ *
+ * @param controlNameUUid
+ * @return
+ */
+ private String delAllModelInstances(String controlNameUUid) {
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_control_name_uuid", controlNameUUid);
+ Map<String, Object> out = logSqlExecution(procDelAllModelInstances, in);
+ return (String) (out.get("v_model_id"));
+ }
+
+ /**
+ * Update event with process instance id.
+ *
+ * @param eventId
+ * @param processInstanceId
+ */
+ public void updEvent(String eventId, String processInstanceId) {
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_event_id", eventId)
+ .addValue("v_process_instance_id", processInstanceId);
+ logSqlExecution(procUpdEvent, in);
+ }
+
+ /**
+ * Generic mapper for list of values
+ */
+ private static final class ValueItemMapper implements RowMapper<ValueItem> {
+ public ValueItem mapRow(ResultSet rs, int rowNum) throws SQLException {
+ ValueItem item = new ValueItem();
+ item.setValue(rs.getString(1));
+ return item;
+ }
+ }
+
+ /**
+ * Generic mapper for CldsDBServiceCache
+ */
+ private static final class CldsServiceDataMapper implements RowMapper<CldsServiceData> {
+ public CldsServiceData mapRow(ResultSet rs, int rowNum) throws SQLException {
+ CldsServiceData cldsServiceData = new CldsServiceData();
+ long age;
+ age = rs.getLong(5);
+ Blob blob = rs.getBlob(4);
+ InputStream is = blob.getBinaryStream();
+ ObjectInputStream oip;
+ try {
+ oip = new ObjectInputStream(is);
+ cldsServiceData = (CldsServiceData) oip.readObject();
+ cldsServiceData.setAgeOfRecord(age);
+ } catch (IOException | ClassNotFoundException e) {
+ logger.error("Error caught while retrieving cldsServiceData from database");
+ }
+ return cldsServiceData;
+ }
+ }
+
+ /**
+ * Return list of model names
+ *
+ * @return model names
+ */
+ public List<ValueItem> getBpmnNames() {
+ String SQL = "SELECT model_name FROM model ORDER BY 1;";
+ return jdbcTemplateObject.query(SQL, new ValueItemMapper());
+ }
+
+ /**
+ * Update template in the database using parameter values and return updated template object.
+ *
+ * @param template
+ * @param userid
+ * @return
+ */
+ public CldsTemplate setTemplate(CldsTemplate template, String userid) {
+ SqlParameterSource in = new MapSqlParameterSource()
+ .addValue("v_template_name", template.getName())
+ .addValue("v_userid", userid)
+ .addValue("v_template_bpmn_text", template.getBpmnText())
+ .addValue("v_template_image_text", template.getImageText())
+ .addValue("v_template_doc_text", template.getPropText());
+ Map<String, Object> out = logSqlExecution(procSetTemplate, in);
+ template.setId((String) (out.get("v_template_id")));
+ template.setBpmnUserid((String) (out.get("v_template_bpmn_userid")));
+ template.setBpmnId((String) (out.get("v_template_bpmn_id")));
+ template.setBpmnText((String) (out.get("v_template_bpmn_text")));
+ template.setImageId((String) (out.get("v_template_image_id")));
+ template.setImageUserid((String) out.get("v_template_image_userid"));
+ template.setImageText((String) out.get("v_template_image_text"));
+ template.setPropId((String) (out.get("v_template_doc_id")));
+ template.setPropUserid((String) out.get("v_template_doc_userid"));
+ template.setPropText((String) out.get("v_template_doc_text"));
+ return template;
+ }
+
+ /**
+ * Return list of template names
+ *
+ * @return template names
+ */
+ public List<ValueItem> getTemplateNames() {
+ String SQL = "SELECT template_name FROM template ORDER BY 1;";
+ return jdbcTemplateObject.query(SQL, new ValueItemMapper());
+ }
+
+ /**
+ * Get a template from the database given the model name.
+ *
+ * @param templateName
+ * @return model
+ */
+ public CldsTemplate getTemplate(String templateName) {
+ CldsTemplate template = new CldsTemplate();
+ template.setName(templateName);
+ SqlParameterSource in = new MapSqlParameterSource().addValue("v_template_name", templateName);
+ Map<String, Object> out = logSqlExecution(procGetTemplate, in);
+ template.setId((String) (out.get("v_template_id")));
+ template.setBpmnUserid((String) (out.get("v_template_bpmn_userid")));
+ template.setBpmnId((String) (out.get("v_template_bpmn_id")));
+ template.setBpmnText((String) (out.get("v_template_bpmn_text")));
+ template.setImageId((String) (out.get("v_template_image_id")));
+ template.setImageUserid((String) out.get("v_template_image_userid"));
+ template.setImageText((String) out.get("v_template_image_text"));
+ template.setPropId((String) (out.get("v_template_doc_id")));
+ template.setPropUserid((String) out.get("v_template_doc_userid"));
+ template.setPropText((String) out.get("v_template_doc_text"));
+ return template;
+ }
+
+ public CldsServiceData getCldsServiceCache(String invariantUUID) throws SQLException, IOException, ClassNotFoundException {
+ CldsServiceData cldsServiceData = null;
+ List<CldsServiceData> cldsServiceDataList = new ArrayList<>();
+ try {
+ String getCldsServiceSQL = "SELECT * , TIMESTAMPDIFF(SECOND, timestamp, CURRENT_TIMESTAMP()) FROM clds_service_cache where invariant_service_id = ? ";
+ cldsServiceData = jdbcTemplateObject.queryForObject(getCldsServiceSQL, new Object[]{invariantUUID}, new CldsServiceDataMapper());
+ logger.info("value of cldsServiceDataList: {}", cldsServiceDataList);
+ } catch (EmptyResultDataAccessException e) {
+ logger.info("cache row not found for invariantUUID: {}", invariantUUID);
+ }
+ return cldsServiceData;
+ }
+
+ public void setCldsServiceCache(CldsDBServiceCache cldsDBServiceCache) throws SQLException, IOException {
+ if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null && cldsDBServiceCache.getServiceId() != null) {
+ String invariantUUID = cldsDBServiceCache.getInvariantId();
+ String serviceUUID = cldsDBServiceCache.getServiceId();
+ InputStream is = cldsDBServiceCache.getCldsDataInstream();
+ String insertCldsServiceCacheSQL = "INSERT INTO clds_service_cache"
+ + "(invariant_service_id,service_id,timestamp,object_data) VALUES"
+ + "(?,?,CURRENT_TIMESTAMP,?) ON DUPLICATE KEY UPDATE invariant_service_id = VALUES(invariant_service_id) , timestamp = CURRENT_TIMESTAMP , object_data = VALUES(object_data) ";
+ jdbcTemplateObject.update(insertCldsServiceCacheSQL, invariantUUID, serviceUUID, is);
+ }
+ }
+
+ private static Map<String, Object> logSqlExecution(SimpleJdbcCall call, SqlParameterSource source) {
+ try {
+ return call.execute(source);
+ } catch (Exception e) {
+ logger.error("Exception occured in " + source.getClass().getCanonicalName() + ": " + e);
+ throw e;
+ }
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/exception/AjscExceptionMapper.java b/src/main/java/org/onap/clamp/clds/exception/AjscExceptionMapper.java
new file mode 100644
index 000000000..41023acec
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/exception/AjscExceptionMapper.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.exception;
+
+import com.att.ajsc.common.AjscProvider;
+import com.att.ajsc.common.exception.ServerErrorException;
+import com.att.ajsc.common.exception.ServiceException;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+@AjscProvider
+public class AjscExceptionMapper implements ExceptionMapper<Exception> {
+
+ @Override
+ public Response toResponse(final Exception exception) {
+ return exception instanceof ServiceException ? ((ServiceException) exception).toResponse() : new ServerErrorException(exception.getMessage()).toResponse();
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/jsf/JsfExampleBean.java b/src/main/java/org/onap/clamp/clds/jsf/JsfExampleBean.java
new file mode 100644
index 000000000..5fdcedd96
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/jsf/JsfExampleBean.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.jsf;
+
+import javax.faces.bean.ManagedBean;
+import javax.faces.bean.SessionScoped;
+import java.io.Serializable;
+import java.util.Date;
+
+@ManagedBean
+@SessionScoped
+public class JsfExampleBean implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String value;
+ private Date dateValue;
+
+ private static final java.text.SimpleDateFormat timestampFormat = new java.text.SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ public Date getDateValue() {
+ return dateValue;
+ }
+
+ public void setDateValue(Date dateValue) {
+ this.dateValue = dateValue;
+ }
+
+ public String getDateValueText() {
+ return timestampFormat.format(dateValue);
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAlarmCondition.java b/src/main/java/org/onap/clamp/clds/model/CldsAlarmCondition.java
new file mode 100644
index 000000000..032547836
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAlarmCondition.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import java.io.Serializable;
+
+public class CldsAlarmCondition implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private String eventSourceType;
+ private String alarmConditionKey;
+ private String severity;
+
+ public String getEventSourceType() {
+ return eventSourceType;
+ }
+
+ public void setEventSourceType(String eventSourceType) {
+ this.eventSourceType = eventSourceType;
+ }
+
+ public String getSeverity() {
+ return severity;
+ }
+
+ public void setSeverity(String severity) {
+ this.severity = severity;
+ }
+
+ public String getAlarmConditionKey() {
+ return alarmConditionKey;
+ }
+
+ public void setAlarmConditionKey(String alarmConditionKey) {
+ this.alarmConditionKey = alarmConditionKey;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAsdcArtifact.java b/src/main/java/org/onap/clamp/clds/model/CldsAsdcArtifact.java
new file mode 100644
index 000000000..43d5ab6ae
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAsdcArtifact.java
@@ -0,0 +1,112 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CldsAsdcArtifact {
+
+ private String artifactName;
+ private String artifactType;
+ private String artifactURL;
+ private String artifactDescription;
+ private String artifactTimeout;
+ private String artifactChecksum;
+ private String artifactUUID;
+ private String artifactVersion;
+ private String generatedFromUUID;
+
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public String getArtifactType() {
+ return artifactType;
+ }
+
+ public void setArtifactType(String artifactType) {
+ this.artifactType = artifactType;
+ }
+
+ public String getArtifactURL() {
+ return artifactURL;
+ }
+
+ public void setArtifactURL(String artifactURL) {
+ this.artifactURL = artifactURL;
+ }
+
+ public String getArtifactDescription() {
+ return artifactDescription;
+ }
+
+ public void setArtifactDescription(String artifactDescription) {
+ this.artifactDescription = artifactDescription;
+ }
+
+ public String getArtifactTimeout() {
+ return artifactTimeout;
+ }
+
+ public void setArtifactTimeout(String artifactTimeout) {
+ this.artifactTimeout = artifactTimeout;
+ }
+
+ public String getArtifactChecksum() {
+ return artifactChecksum;
+ }
+
+ public void setArtifactChecksum(String artifactChecksum) {
+ this.artifactChecksum = artifactChecksum;
+ }
+
+ public String getArtifactUUID() {
+ return artifactUUID;
+ }
+
+ public void setArtifactUUID(String artifactUUID) {
+ this.artifactUUID = artifactUUID;
+ }
+
+ public String getArtifactVersion() {
+ return artifactVersion;
+ }
+
+ public void setArtifactVersion(String artifactVersion) {
+ this.artifactVersion = artifactVersion;
+ }
+
+ public String getGeneratedFromUUID() {
+ return generatedFromUUID;
+ }
+
+ public void setGeneratedFromUUID(String generatedFromUUID) {
+ this.generatedFromUUID = generatedFromUUID;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAsdcResource.java b/src/main/java/org/onap/clamp/clds/model/CldsAsdcResource.java
new file mode 100644
index 000000000..3210b696b
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAsdcResource.java
@@ -0,0 +1,131 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+import java.math.BigDecimal;
+import java.util.List;
+import java.util.logging.Logger;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CldsAsdcResource implements Comparable<CldsAsdcResource> {
+ private static final Logger logger = Logger.getLogger(CldsAsdcServiceInfo.class.getName());
+
+ private String resourceInstanceName;
+ private String resourceName;
+ private String resourceInvariantUUID;
+ private String resourceVersion;
+ private String resoucreType;
+ private String resourceUUID;
+ private List<CldsAsdcArtifact> artifacts;
+
+ public String getResourceInstanceName() {
+ return resourceInstanceName;
+ }
+
+ public void setResourceInstanceName(String resourceInstanceName) {
+ this.resourceInstanceName = resourceInstanceName;
+ }
+
+ public String getResourceName() {
+ return resourceName;
+ }
+
+ public void setResourceName(String resourceName) {
+ this.resourceName = resourceName;
+ }
+
+ public String getResourceInvariantUUID() {
+ return resourceInvariantUUID;
+ }
+
+ public void setResourceInvariantUUID(String resourceInvariantUUID) {
+ this.resourceInvariantUUID = resourceInvariantUUID;
+ }
+
+ public String getResourceVersion() {
+ return resourceVersion;
+ }
+
+ public void setResourceVersion(String resourceVersion) {
+ this.resourceVersion = resourceVersion;
+ }
+
+ public String getResoucreType() {
+ return resoucreType;
+ }
+
+ public void setResoucreType(String resoucreType) {
+ this.resoucreType = resoucreType;
+ }
+
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ public List<CldsAsdcArtifact> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<CldsAsdcArtifact> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+ @Override
+ public int compareTo(CldsAsdcResource in) {
+ // Compares this object with the specified object for order.
+ // Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
+
+ // first compare based on name
+ int rtn = resourceInstanceName.compareToIgnoreCase(in.resourceInstanceName);
+
+ if (rtn == 0) {
+ BigDecimal myVersion = convertVersion(resourceVersion);
+ BigDecimal inVersion = convertVersion(in.resourceVersion);
+ rtn = myVersion.compareTo(inVersion);
+ }
+ return rtn;
+ }
+
+ /**
+ * Convert version String into a BigDecimal
+ *
+ * @param versionText
+ * @return
+ */
+ private BigDecimal convertVersion(String versionText) {
+ BigDecimal rtn = new BigDecimal(0.0);
+ try {
+ rtn = new BigDecimal(versionText);
+ } catch (NumberFormatException nfe) {
+ logger.warning("ASDC version=" + versionText + " is not decimal for name=" + resourceInstanceName);
+ }
+ return rtn;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAsdcResourceBasicInfo.java b/src/main/java/org/onap/clamp/clds/model/CldsAsdcResourceBasicInfo.java
new file mode 100644
index 000000000..c66428a68
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAsdcResourceBasicInfo.java
@@ -0,0 +1,160 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+import java.math.BigDecimal;
+import java.util.logging.Logger;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CldsAsdcResourceBasicInfo implements Comparable<CldsAsdcResourceBasicInfo> {
+ private static final Logger logger = Logger.getLogger(CldsAsdcServiceInfo.class.getName());
+
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
+ private String category;
+ private String subCategory;
+ private String resourceType;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+
+ @Override
+ public int compareTo(CldsAsdcResourceBasicInfo in) {
+ // Compares this object with the specified object for order.
+ // Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
+ // first compare based on name
+ int rtn = name.compareToIgnoreCase(in.name);
+
+ if (rtn == 0) {
+ BigDecimal myVersion = convertVersion(version);
+ BigDecimal inVersion = convertVersion(in.version);
+ rtn = myVersion.compareTo(inVersion);
+ }
+ return rtn;
+ }
+
+ /**
+ * Convert version String into a BigDecimal
+ *
+ * @param version
+ * @return
+ */
+ private BigDecimal convertVersion(String version) {
+ BigDecimal rtn = new BigDecimal(0.0);
+ try {
+ rtn = new BigDecimal(version);
+ } catch (NumberFormatException nfe) {
+ logger.warning("ASDC version=" + version + " is not decimal for name=" + name);
+ }
+ return rtn;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getToscaModelURL() {
+ return toscaModelURL;
+ }
+
+ public void setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getSubCategory() {
+ return subCategory;
+ }
+
+ public void setSubCategory(String subCategory) {
+ this.subCategory = subCategory;
+ }
+
+ public String getResourceType() {
+ return resourceType;
+ }
+
+ public void setResourceType(String resourceType) {
+ this.resourceType = resourceType;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public Logger getLOGGER() {
+ return logger;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceDetail.java b/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceDetail.java
new file mode 100644
index 000000000..f50e09d5f
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceDetail.java
@@ -0,0 +1,142 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+import java.util.List;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CldsAsdcServiceDetail {
+
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
+ private String category;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+ private String distributionStatus;
+ private String lastUpdaterFullName;
+ private List<CldsAsdcResource> resources;
+ private List<CldsAsdcArtifact> artifacts;
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getToscaModelURL() {
+ return toscaModelURL;
+ }
+
+ public void setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
+
+ public String getLastUpdaterFullName() {
+ return lastUpdaterFullName;
+ }
+
+ public void setLastUpdaterFullName(String lastUpdaterFullName) {
+ this.lastUpdaterFullName = lastUpdaterFullName;
+ }
+
+ public List<CldsAsdcResource> getResources() {
+ return resources;
+ }
+
+ public void setResources(List<CldsAsdcResource> resources) {
+ this.resources = resources;
+ }
+
+ public List<CldsAsdcArtifact> getArtifacts() {
+ return artifacts;
+ }
+
+ public void setArtifacts(List<CldsAsdcArtifact> artifacts) {
+ this.artifacts = artifacts;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceInfo.java b/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceInfo.java
new file mode 100644
index 000000000..3ed575345
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsAsdcServiceInfo.java
@@ -0,0 +1,148 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import java.math.BigDecimal;
+import java.util.logging.Logger;
+
+public class CldsAsdcServiceInfo implements Comparable<CldsAsdcServiceInfo> {
+ private static final Logger logger = Logger.getLogger(CldsAsdcServiceInfo.class.getName());
+
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
+ private String category;
+ private String lifecycleState;
+ private String lastUpdaterUserId;
+ private String distributionStatus;
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getInvariantUUID() {
+ return invariantUUID;
+ }
+
+ public void setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getToscaModelURL() {
+ return toscaModelURL;
+ }
+
+ public void setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ }
+
+ public String getCategory() {
+ return category;
+ }
+
+ public void setCategory(String category) {
+ this.category = category;
+ }
+
+ public String getLifecycleState() {
+ return lifecycleState;
+ }
+
+ public void setLifecycleState(String lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ }
+
+ public String getLastUpdaterUserId() {
+ return lastUpdaterUserId;
+ }
+
+ public void setLastUpdaterUserId(String lastUpdaterUserId) {
+ this.lastUpdaterUserId = lastUpdaterUserId;
+ }
+
+ public String getDistributionStatus() {
+ return distributionStatus;
+ }
+
+ public void setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ }
+
+ /**
+ * Compare using name and then version. Version is converted to a decimal.
+ */
+ @Override
+ public int compareTo(CldsAsdcServiceInfo in) {
+ // Compares this object with the specified object for order.
+ // Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
+ // first compare based on name
+ int rtn = name.compareToIgnoreCase(in.name);
+
+ if (rtn == 0) {
+ BigDecimal myVersion = convertVersion(version);
+ BigDecimal inVersion = convertVersion(in.version);
+ rtn = myVersion.compareTo(inVersion);
+ }
+
+ return rtn;
+ }
+
+ /**
+ * Convert version String into a BigDecimal
+ *
+ * @param versionText
+ * @return
+ */
+ private BigDecimal convertVersion(String versionText) {
+ try {
+ return new BigDecimal(versionText);
+ } catch (NumberFormatException nfe) {
+ logger.warning("ASDC version=" + versionText + " is not decimal for name=" + name);
+ }
+ return new BigDecimal(0.0);
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsDBServiceCache.java b/src/main/java/org/onap/clamp/clds/model/CldsDBServiceCache.java
new file mode 100644
index 000000000..658e21f96
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsDBServiceCache.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import java.io.*;
+
+public class CldsDBServiceCache {
+
+ private String invariantId;
+ private String serviceId;
+ private InputStream cldsDataInstream;
+
+ public String getInvariantId() {
+ return invariantId;
+ }
+
+ public void setInvariantId(String invariantId) {
+ this.invariantId = invariantId;
+ }
+
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public InputStream getCldsDataInstream() throws IOException {
+ return cldsDataInstream;
+ }
+
+ public void setCldsDataInstream(CldsServiceData cldsServiceData) throws IOException {
+ this.cldsDataInstream = getInstreamFromObject(cldsServiceData);
+ }
+
+ private InputStream getInstreamFromObject(CldsServiceData cldsServiceData) throws IOException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(cldsServiceData);
+ oos.flush();
+ oos.close();
+ return new ByteArrayInputStream(baos.toByteArray());
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsEvent.java b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java
new file mode 100644
index 000000000..8379e5024
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsEvent.java
@@ -0,0 +1,183 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import org.onap.clamp.clds.dao.CldsDao;
+
+/**
+ * Represent a CLDS Event.
+ */
+public class CldsEvent {
+ public static final String ACTION_CREATE = "CREATE";
+ public static final String ACTION_SUBMIT = "SUBMIT";
+ public static final String ACTION_RESUBMIT = "RESUBMIT"; // an update before model is active
+ public static final String ACTION_DISTRIBUTE = "DISTRIBUTE"; // only from dcae
+ public static final String ACTION_DEPLOY = "DEPLOY"; // only from dcae
+ public static final String ACTION_UNDEPLOY = "UNDEPLOY"; // only from dcae
+ public static final String ACTION_UPDATE = "UPDATE";
+ public static final String ACTION_DELETE = "DELETE";
+ public static final String ACTION_STOP = "STOP";
+ public static final String ACTION_RESTART = "RESTART";
+
+ public static final String ACTION_STATE_INITIATED = "INITIATED";
+ public static final String ACTION_STATE_SENT = "SENT";
+ public static final String ACTION_STATE_COMPLETED = "COMPLETED";
+ public static final String ACTION_STATE_RECEIVED = "RECEIVED";
+ public static final String ACTION_STATE_ERROR = "ERROR";
+ public static final String ACTION_STATE_ANY = null;
+
+ private String id;
+ private String actionCd;
+ private String actionStateCd;
+ private String processInstanceId;
+ private String userid;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * @param cldsDao
+ * @param controlName
+ * @param userid
+ * @param actionCd
+ * @param actionStateCd
+ * @param processInstanceId
+ * @return
+ */
+ public static CldsEvent insEvent(CldsDao cldsDao, String controlName, String userid, String actionCd, String actionStateCd, String processInstanceId) {
+ CldsModel model = CldsModel.createUsingControlName(controlName);
+ return insEvent(cldsDao, model, actionCd, actionStateCd, processInstanceId);
+ }
+
+ /**
+ * Insert event using controlNameUuid to find the model.
+ * This method meant for processing events from dcae.
+ * @param cldsDao
+ * @param model
+ * @param actionCd
+ * @param actionStateCd
+ * @param processInstanceId
+ * @return
+ */
+ public static CldsEvent insEvent(CldsDao cldsDao, CldsModel model, String actionCd, String actionStateCd, String processInstanceId) {
+ CldsEvent event = new CldsEvent();
+ event.setActionCd(actionCd);
+ event.setActionStateCd(actionStateCd);
+ event.setProcessInstanceId(processInstanceId);
+ cldsDao.insEvent(null, model.getControlNamePrefix(), model.getControlNameUuid(), event);
+ return event;
+ }
+
+ /**
+ * Check if actionCd and actionStateCd are equal to the supplied checkActionCd and checkActionStateCd.
+ * Treat checkActionStateCd == null as a wildcard
+ * checkActionCd should not be null.
+ *
+ * @param checkActionCd
+ * @param checkActionStateCd
+ * @return
+ */
+ public boolean isActionAndStateCd(String checkActionCd, String checkActionStateCd) {
+ if (actionCd == null) {
+ return false;
+ }
+ // treat checkActionStateCd == null as a wildcard (same for actionStateCd, although it shouln't be null...)
+ if (checkActionStateCd == null || actionStateCd == null) {
+ return actionCd.equals(checkActionCd);
+ }
+ return actionCd.equals(checkActionCd) && actionStateCd.equals(checkActionStateCd);
+ }
+
+ /**
+ * Check if actionStateCd is equal to the supplied checkActionStateCd.
+ * checkActionCd should not be null.
+ *
+ * @param checkActionStateCd
+ * @return
+ */
+ public boolean isActionStateCd(String checkActionStateCd) {
+ return !(checkActionStateCd == null || actionStateCd == null) && actionStateCd.equals(checkActionStateCd);
+ }
+
+ /**
+ * @return the actionCd
+ */
+ public String getActionCd() {
+ return actionCd;
+ }
+
+ /**
+ * @param actionCd the actionCd to set
+ */
+ public void setActionCd(String actionCd) {
+ this.actionCd = actionCd;
+ }
+
+ /**
+ * @return the actionStateCd
+ */
+ public String getActionStateCd() {
+ return actionStateCd;
+ }
+
+ /**
+ * @param actionStateCd the actionStateCd to set
+ */
+ public void setActionStateCd(String actionStateCd) {
+ this.actionStateCd = actionStateCd;
+ }
+
+ /**
+ * @return the processInstanceId
+ */
+ public String getProcessInstanceId() {
+ return processInstanceId;
+ }
+
+ /**
+ * @param processInstanceId the processInstanceId to set
+ */
+ public void setProcessInstanceId(String processInstanceId) {
+ this.processInstanceId = processInstanceId;
+ }
+
+ /**
+ * @return the userid
+ */
+ public String getUserid() {
+ return userid;
+ }
+
+ /**
+ * @param userid the userid to set
+ */
+ public void setUserid(String userid) {
+ this.userid = userid;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModel.java b/src/main/java/org/onap/clamp/clds/model/CldsModel.java
new file mode 100644
index 000000000..4d4f3aab3
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsModel.java
@@ -0,0 +1,570 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import org.onap.clamp.clds.dao.CldsDao;
+import org.jboss.resteasy.spi.BadRequestException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.NotFoundException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Represent a CLDS Model.
+ */
+public class CldsModel {
+ private static final Logger logger = LoggerFactory.getLogger(CldsModel.class);
+
+ private static final int UUID_LENGTH = 36;
+
+ public static final String STATUS_DESIGN = "DESIGN";
+ public static final String STATUS_DISTRIBUTED = "DISTRIBUTED";
+ public static final String STATUS_ACTIVE = "ACTIVE";
+ public static final String STATUS_STOPPED = "STOPPED";
+ public static final String STATUS_DELETING = "DELETING";
+ public static final String STATUS_ERROR = "ERROR"; // manual intervention required
+ public static final String STATUS_UNKNOWN = "UNKNOWN";
+
+ private String id;
+ private String templateId;
+ private String templateName;
+ private String name;
+ private String controlNamePrefix;
+ private String controlNameUuid;
+ private String bpmnId;
+ private String bpmnUserid;
+ private String bpmnText;
+ private String propId;
+ private String propUserid;
+ private String propText;
+ private String imageId;
+ private String imageUserid;
+ private String imageText;
+ private String docId;
+ private String docUserid;
+ private String docText;
+ private String blueprintId;
+ private String blueprintUserid;
+ private String blueprintText;
+ private CldsEvent event;
+ private String status;
+ private List<String> permittedActionCd;
+ private List<CldsModelInstance> cldsModelInstanceList;
+
+ /**
+ * Construct empty model.
+ */
+ public CldsModel() {
+ event = new CldsEvent();
+ }
+
+ /**
+ * Retrieve from DB.
+ *
+ * @param cldsDao
+ * @param name
+ * @return
+ */
+ public static CldsModel retrieve(CldsDao cldsDao, String name, boolean okIfNotFound) {
+ // get from db
+ CldsModel model = cldsDao.getModelTemplate(name);
+ if (model.getId() == null && !okIfNotFound) {
+ throw new NotFoundException();
+ }
+ model.determineStatus();
+ model.determinePermittedActionCd();
+ return model;
+ }
+
+ /**
+ * Save model to DB.
+ *
+ * @param cldsDao
+ * @param userid
+ */
+ public void save(CldsDao cldsDao, String userid) {
+ cldsDao.setModel(this, userid);
+ determineStatus();
+ determinePermittedActionCd();
+ }
+
+ /**
+ * Insert a new event for the new action.
+ * Throw IllegalArgumentException if requested actionCd is not permitted.
+ *
+ * @param cldsDao
+ * @param userid
+ * @param actionCd
+ * @param actionStateCd
+ */
+ public void insEvent(CldsDao cldsDao, String userid, String actionCd, String actionStateCd) {
+ validateAction(actionCd);
+ event = CldsEvent.insEvent(cldsDao, this, actionCd, actionStateCd, null);
+ determineStatus();
+ determinePermittedActionCd();
+ }
+
+ /**
+ * Update event with processInstanceId
+ *
+ * @param cldsDao
+ * @param processInstanceId
+ */
+ public void updEvent(CldsDao cldsDao, String processInstanceId) {
+ cldsDao.updEvent(event.getId(), processInstanceId);
+ }
+
+ /**
+ * set the status in the model
+ */
+ private void determineStatus() {
+
+ status = STATUS_UNKNOWN;
+ if (event == null || event.getActionCd() == null) {
+ status = STATUS_DESIGN;
+ } else if (event.isActionStateCd(CldsEvent.ACTION_STATE_ERROR)) {
+ status = STATUS_ERROR;
+ } else if (event.isActionAndStateCd(CldsEvent.ACTION_CREATE, CldsEvent.ACTION_STATE_ANY) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_SUBMIT, CldsEvent.ACTION_STATE_ANY) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_RESUBMIT, CldsEvent.ACTION_STATE_ANY) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_RECEIVED)) {
+ status = STATUS_DESIGN;
+ } else if (event.isActionAndStateCd(CldsEvent.ACTION_DISTRIBUTE, CldsEvent.ACTION_STATE_RECEIVED) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_UNDEPLOY, CldsEvent.ACTION_STATE_RECEIVED)) {
+ status = STATUS_DISTRIBUTED;
+ } else if (event.isActionAndStateCd(CldsEvent.ACTION_DELETE, CldsEvent.ACTION_STATE_SENT)) {
+ status = STATUS_DELETING;
+ } else if (event.isActionAndStateCd(CldsEvent.ACTION_DEPLOY, CldsEvent.ACTION_STATE_RECEIVED) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_RESTART, CldsEvent.ACTION_STATE_ANY) ||
+ event.isActionAndStateCd(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STATE_ANY)) {
+ status = STATUS_ACTIVE;
+ } else if (event.isActionAndStateCd(CldsEvent.ACTION_STOP, CldsEvent.ACTION_STATE_ANY)) {
+ status = STATUS_STOPPED;
+ }
+
+ }
+
+ /**
+ * Get the actionCd from current event. If none, default value is CldsEvent.ACTION_CREATE
+ *
+ * @return
+ */
+ private String getCurrentActionCd() {
+ // current default actionCd is CREATE
+ String actionCd = CldsEvent.ACTION_CREATE;
+ if (event != null && event.getActionCd() != null) {
+ actionCd = event.getActionCd();
+ }
+ return actionCd;
+ }
+
+ /**
+ * Get the actionStateCd from current event. If none, default value is CldsEvent.ACTION_STATE_COMPLETED
+ *
+ * @return
+ */
+ private String getCurrentActionStateCd() {
+ // current default actionStateCd is CREATE
+ String actionStateCd = CldsEvent.ACTION_STATE_COMPLETED;
+ if (event != null && event.getActionStateCd() != null) {
+ actionStateCd = event.getActionStateCd();
+ }
+ return actionStateCd;
+ }
+
+ /**
+ * Determine permittedActionCd list using the actionCd from the current event.
+ */
+ private void determinePermittedActionCd() {
+ String actionCd = getCurrentActionCd();
+ switch (actionCd) {
+ case CldsEvent.ACTION_CREATE:
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT);
+ break;
+ case CldsEvent.ACTION_SUBMIT:
+ case CldsEvent.ACTION_RESUBMIT:
+ // for 1702 delete is not currently implemented (and resubmit requires manually deleting artifact from asdc
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_RESUBMIT);
+ break;
+ case CldsEvent.ACTION_DISTRIBUTE:
+ case CldsEvent.ACTION_UNDEPLOY:
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE);
+ break;
+ case CldsEvent.ACTION_DEPLOY:
+ case CldsEvent.ACTION_RESTART:
+ case CldsEvent.ACTION_UPDATE:
+ // for 1702 delete is not currently implemented
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_STOP);
+ break;
+ case CldsEvent.ACTION_DELETE:
+ if (getCurrentActionStateCd().equals(CldsEvent.ACTION_STATE_SENT)) {
+ permittedActionCd = Arrays.asList();
+ } else {
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_SUBMIT);
+ }
+ break;
+ case CldsEvent.ACTION_STOP:
+ // for 1702 delete is not currently implemented
+ permittedActionCd = Arrays.asList(CldsEvent.ACTION_UPDATE, CldsEvent.ACTION_RESTART);
+ break;
+ default:
+ logger.warn("Invalid current actionCd: " + actionCd);
+ }
+ }
+
+ /**
+ * Validate requestedActionCd - determine permittedActionCd and then check if contained in permittedActionCd
+ * Throw IllegalArgumentException if requested actionCd is not permitted.
+ *
+ * @param requestedActionCd
+ */
+ public void validateAction(String requestedActionCd) {
+ determinePermittedActionCd();
+ if (!permittedActionCd.contains(requestedActionCd)) {
+ throw new IllegalArgumentException("Invalid requestedActionCd: " + requestedActionCd + ". Given current actionCd: " + getCurrentActionCd() + ", the permittedActionCd: " + permittedActionCd);
+ }
+ }
+
+ /**
+ * Extract the UUID portion of a given full control name (controlNamePrefix + controlNameUuid).
+ * No fields are populated other than controlNamePrefix and controlNameUuid.
+ * Throws BadRequestException if length of given control name is less than UUID_LENGTH.
+ *
+ * @param fullControlName
+ * @return
+ */
+ public static CldsModel createUsingControlName(String fullControlName) {
+
+ int len = 0;
+
+ if (fullControlName != null) {
+ len = fullControlName.length();
+ }
+ if (len < UUID_LENGTH) {
+ throw new BadRequestException("closed loop id / control name length, " + len + ", less than the minimum of: " + UUID_LENGTH);
+ }
+ CldsModel model = new CldsModel();
+ model.setControlNamePrefix(fullControlName.substring(0, len - UUID_LENGTH));
+ model.setControlNameUuid(fullControlName.substring(len - UUID_LENGTH));
+ return model;
+ }
+
+ /**
+ * @return the controlName (controlNamePrefix + controlNameUuid)
+ */
+ public String getControlName() {
+ return controlNamePrefix + controlNameUuid;
+ }
+
+ /**
+ * To insert modelInstance to the database
+ *
+ * @param cldsDao
+ * @param dcaeEvent
+ */
+ public static CldsModel insertModelInstance(CldsDao cldsDao, DcaeEvent dcaeEvent, String userid) {
+ String controlName = dcaeEvent.getControlName();
+ CldsModel cldsModel = createUsingControlName(controlName);
+ cldsModel = cldsDao.getModelByUuid(cldsModel.getControlNameUuid());
+ cldsModel.determineStatus();
+ if (dcaeEvent.getCldsActionCd().equals(CldsEvent.ACTION_UNDEPLOY) ||
+ (dcaeEvent.getCldsActionCd().equals(CldsEvent.ACTION_DEPLOY) && (cldsModel.getStatus().equals(STATUS_DISTRIBUTED) || cldsModel.getStatus().equals(STATUS_DESIGN)))) {
+ CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(), CldsEvent.ACTION_STATE_RECEIVED, null);
+ }
+ cldsDao.insModelInstance(cldsModel, dcaeEvent.getInstances());
+ return cldsModel;
+ }
+
+ /**
+ * To remove modelInstance from the database
+ * This method is defunct - DCAE Proxy will not undeploy individual instances. It will send an empty list of
+ * deployed instances to indicate all have been removed. Or it will send an updated list to indicate those that
+ * are still deployed with any not on the list considered undeployed.
+ *
+ * @param cldsDao
+ * @param dcaeEvent
+ */
+ @SuppressWarnings("unused")
+ private static CldsModel removeModelInstance(CldsDao cldsDao, DcaeEvent dcaeEvent) {
+ String controlName = dcaeEvent.getControlName();
+ //cldsModel = cldsDao.delModelInstance(cldsModel.getControlNameUuid(), dcaeEvent.getInstances() );
+ return createUsingControlName(controlName);
+ }
+
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @param name the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getTemplateId() {
+ return templateId;
+ }
+
+ public void setTemplateId(String templateId) {
+ this.templateId = templateId;
+ }
+
+ /**
+ * @return the controlNamePrefix
+ */
+ public String getControlNamePrefix() {
+ return controlNamePrefix;
+ }
+
+ /**
+ * @param controlNamePrefix the controlNamePrefix to set
+ */
+ public void setControlNamePrefix(String controlNamePrefix) {
+ this.controlNamePrefix = controlNamePrefix;
+ }
+
+ /**
+ * @return the controlNameUuid
+ */
+ public String getControlNameUuid() {
+ return controlNameUuid;
+ }
+
+ /**
+ * @param controlNameUuid the controlNameUuid to set
+ */
+ public void setControlNameUuid(String controlNameUuid) {
+ this.controlNameUuid = controlNameUuid;
+ }
+
+
+ /**
+ * @return the propUserid
+ */
+ public String getPropUserid() {
+ return propUserid;
+ }
+
+ /**
+ * @param propUserid the propUserid to set
+ */
+ public void setPropUserid(String propUserid) {
+ this.propUserid = propUserid;
+ }
+
+ /**
+ * @return the propText
+ */
+ public String getPropText() {
+ return propText;
+ }
+
+ /**
+ * @param propText the propText to set
+ */
+ public void setPropText(String propText) {
+ this.propText = propText;
+ }
+
+ /**
+ * @return the event
+ */
+ public CldsEvent getEvent() {
+ return event;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getTemplateName() {
+ return templateName;
+ }
+
+ public void setTemplateName(String templateName) {
+ this.templateName = templateName;
+ }
+
+ public String getPropId() {
+ return propId;
+ }
+
+ public void setPropId(String propId) {
+ this.propId = propId;
+ }
+
+ /**
+ * @param event the event to set
+ */
+ public void setEvent(CldsEvent event) {
+ this.event = event;
+ }
+
+ /**
+ * @return the status
+ */
+ public String getStatus() {
+ return status;
+ }
+
+ /**
+ * @param status the status to set
+ */
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ /**
+ * @return the permittedActionCd
+ */
+ public List<String> getPermittedActionCd() {
+ return permittedActionCd;
+ }
+
+ /**
+ * @param permittedActionCd the permittedActionCd to set
+ */
+ public void setPermittedActionCd(List<String> permittedActionCd) {
+ this.permittedActionCd = permittedActionCd;
+ }
+
+ public String getBlueprintId() {
+ return blueprintId;
+ }
+
+ public void setBlueprintId(String blueprintId) {
+ this.blueprintId = blueprintId;
+ }
+
+ public String getBlueprintUserid() {
+ return blueprintUserid;
+ }
+
+ public void setBlueprintUserid(String blueprintUserid) {
+ this.blueprintUserid = blueprintUserid;
+ }
+
+ public String getBlueprintText() {
+ return blueprintText;
+ }
+
+ public void setBlueprintText(String blueprintText) {
+ this.blueprintText = blueprintText;
+ }
+
+ public String getBpmnId() {
+ return bpmnId;
+ }
+
+ public void setBpmnId(String bpmnId) {
+ this.bpmnId = bpmnId;
+ }
+
+ public String getBpmnUserid() {
+ return bpmnUserid;
+ }
+
+ public void setBpmnUserid(String bpmnUserid) {
+ this.bpmnUserid = bpmnUserid;
+ }
+
+ public String getBpmnText() {
+ return bpmnText;
+ }
+
+ public void setBpmnText(String bpmnText) {
+ this.bpmnText = bpmnText;
+ }
+
+ public String getImageId() {
+ return imageId;
+ }
+
+ public void setImageId(String imageId) {
+ this.imageId = imageId;
+ }
+
+ public String getImageUserid() {
+ return imageUserid;
+ }
+
+ public void setImageUserid(String imageUserid) {
+ this.imageUserid = imageUserid;
+ }
+
+ public String getImageText() {
+ return imageText;
+ }
+
+ public void setImageText(String imageText) {
+ this.imageText = imageText;
+ }
+
+ public String getDocId() {
+ return docId;
+ }
+
+ public void setDocId(String docId) {
+ this.docId = docId;
+ }
+
+ public String getDocUserid() {
+ return docUserid;
+ }
+
+ public void setDocUserid(String docUserid) {
+ this.docUserid = docUserid;
+ }
+
+ public String getDocText() {
+ return docText;
+ }
+
+ public void setDocText(String docText) {
+ this.docText = docText;
+ }
+
+ public List<CldsModelInstance> getCldsModelInstanceList() {
+ if (cldsModelInstanceList == null) {
+ cldsModelInstanceList = new ArrayList<>();
+ }
+ return cldsModelInstanceList;
+ }
+
+ public void setCldsModelInstanceList(List<CldsModelInstance> cldsModelInstanceList) {
+ this.cldsModelInstanceList = cldsModelInstanceList;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java b/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java
new file mode 100644
index 000000000..4c16aadef
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsModelInstance.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class CldsModelInstance {
+
+ private String modelInstanceId;
+ private String location;
+ private String vmName;
+
+ public String getVmName() {
+ return vmName;
+ }
+
+ public void setVmName(String vmName) {
+ this.vmName = vmName;
+ }
+
+ public String getLocation() {
+ return location;
+ }
+
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ public String getModelInstanceId() {
+ return modelInstanceId;
+ }
+
+ public void setModelInstanceId(String modelInstanceId) {
+ this.modelInstanceId = modelInstanceId;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsServiceData.java b/src/main/java/org/onap/clamp/clds/model/CldsServiceData.java
new file mode 100644
index 000000000..89108393f
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsServiceData.java
@@ -0,0 +1,112 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.service.CldsService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.NotAuthorizedException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class CldsServiceData implements Serializable {
+ private static final Logger logger = LoggerFactory.getLogger(CldsServiceData.class);
+
+ private static final long serialVersionUID = 1L;
+
+ private String serviceInvariantUUID;
+ private String serviceUUID;
+ private Long ageOfRecord;
+ private List<CldsVfData> cldsVfs;
+
+ public String getServiceInvariantUUID() {
+ return serviceInvariantUUID;
+ }
+
+ public void setServiceInvariantUUID(String serviceInvariantUUID) {
+ this.serviceInvariantUUID = serviceInvariantUUID;
+ }
+
+ public List<CldsVfData> getCldsVfs() {
+ return cldsVfs;
+ }
+
+ public void setCldsVfs(List<CldsVfData> cldsVfs) {
+ this.cldsVfs = cldsVfs;
+ }
+
+ public String getServiceUUID() {
+ return serviceUUID;
+ }
+
+ public void setServiceUUID(String serviceUUID) {
+ this.serviceUUID = serviceUUID;
+ }
+
+ public CldsServiceData getCldsServiceCache(CldsDao cldsDao, String invariantServiceUUID) throws Exception {
+ return cldsDao.getCldsServiceCache(invariantServiceUUID);
+ }
+
+ public void setCldsServiceCache(CldsDao cldsDao, CldsDBServiceCache cldsDBServiceCache) throws Exception {
+ cldsDao.setCldsServiceCache(cldsDBServiceCache);
+ }
+
+ public Long getAgeOfRecord() {
+ return ageOfRecord;
+ }
+
+ public void setAgeOfRecord(Long ageOfRecord) {
+ this.ageOfRecord = ageOfRecord;
+ }
+
+ /**
+ * Filter out any VFs that the user is not authorized for.
+ * Use the CldsService to determine if the user is authorized for a VF.
+ *
+ * @param svc
+ */
+ public void filterVfs(CldsService svc) {
+ List<CldsVfData> filteredCldsVfs = new ArrayList<>();
+ if (cldsVfs == null) {
+ logger.debug("cldsVfs == null");
+ } else {
+ for (CldsVfData vf : cldsVfs) {
+ // if user is authorized for the VF then add it to the filtered list
+ try {
+ if (svc.isAuthorizedForVf(vf.getVfInvariantResourceUUID())) {
+ filteredCldsVfs.add(vf);
+ }
+ } catch (NotAuthorizedException e) {
+ logger.debug("user not authorized for {}", vf.getVfInvariantResourceUUID());
+ // when not NotAuthorizedException - don't add to filteredCldsVfs list
+ }
+ }
+ }
+ // new filtered list replaces the list of VFs for the user
+ cldsVfs = filteredCldsVfs;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsTemplate.java b/src/main/java/org/onap/clamp/clds/model/CldsTemplate.java
new file mode 100644
index 000000000..6e2c8d70d
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsTemplate.java
@@ -0,0 +1,186 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import org.onap.clamp.clds.dao.CldsDao;
+
+import javax.ws.rs.NotFoundException;
+
+/**
+ * Represent a CLDS Model.
+ */
+public class CldsTemplate {
+
+ public static final String STATUS_DESIGN = "DESIGN";
+ public static final String STATUS_ACTIVE = "ACTIVE";
+ public static final String STATUS_STOPPED = "STOPPED";
+ public static final String STATUS_DELETING = "DELETING";
+ public static final String STATUS_ERROR = "ERROR"; // manual intervention required
+ public static final String STATUS_UNKNOWN = "UNKNOWN";
+
+ private String id;
+ private String name;
+ private String controlNamePrefix;
+ private String controlNameUuid;
+ private String bpmnId;
+ private String bpmnUserid;
+ private String bpmnText;
+ private String imageId;
+ private String imageUserid;
+ private String imageText;
+ private String propId;
+ private String propUserid;
+ private String propText;
+
+ /**
+ * Save template to DB.
+ *
+ * @param cldsDao
+ * @param userid
+ */
+ public void save(CldsDao cldsDao, String userid) {
+ cldsDao.setTemplate(this, userid);
+ }
+
+ /**
+ * Retrieve from DB.
+ *
+ * @param cldsDao
+ * @param name
+ * @return
+ */
+ public static CldsTemplate retrieve(CldsDao cldsDao, String name, boolean okIfNotFound) {
+ // get from db
+ CldsTemplate template = cldsDao.getTemplate(name);
+ if (template.getId() == null && !okIfNotFound) {
+ throw new NotFoundException();
+ }
+ return template;
+ }
+
+ public String getBpmnUserid() {
+ return bpmnUserid;
+ }
+
+ public void setBpmnUserid(String bpmnUserid) {
+ this.bpmnUserid = bpmnUserid;
+ }
+
+ public String getBpmnText() {
+ return bpmnText;
+ }
+
+ public void setBpmnText(String bpmnText) {
+ this.bpmnText = bpmnText;
+ }
+
+ public String getImageUserid() {
+ return imageUserid;
+ }
+
+ public void setImageUserid(String imageUserid) {
+ this.imageUserid = imageUserid;
+ }
+
+ public String getImageText() {
+ return imageText;
+ }
+
+ public void setImageText(String imageText) {
+ this.imageText = imageText;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getControlNamePrefix() {
+ return controlNamePrefix;
+ }
+
+ public void setControlNamePrefix(String controlNamePrefix) {
+ this.controlNamePrefix = controlNamePrefix;
+ }
+
+ public String getControlNameUuid() {
+ return controlNameUuid;
+ }
+
+ public void setControlNameUuid(String controlNameUuid) {
+ this.controlNameUuid = controlNameUuid;
+ }
+
+ public String getPropId() {
+ return propId;
+ }
+
+ public void setPropId(String propId) {
+ this.propId = propId;
+ }
+
+ public String getPropUserid() {
+ return propUserid;
+ }
+
+ public void setPropUserid(String propUserid) {
+ this.propUserid = propUserid;
+ }
+
+ public String getPropText() {
+ return propText;
+ }
+
+ public void setPropText(String propText) {
+ this.propText = propText;
+ }
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getBpmnId() {
+ return bpmnId;
+ }
+
+ public void setBpmnId(String bpmnId) {
+ this.bpmnId = bpmnId;
+ }
+
+ public String getImageId() {
+ return imageId;
+ }
+
+ public void setImageId(String imageId) {
+ this.imageId = imageId;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsVfData.java b/src/main/java/org/onap/clamp/clds/model/CldsVfData.java
new file mode 100644
index 000000000..dbcfb3464
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsVfData.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class CldsVfData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String vfName;
+ private String vfInvariantResourceUUID;
+ private List<CldsVfcData> cldsVfcs;
+
+ public String getVfName() {
+ return vfName;
+ }
+
+ public void setVfName(String vfName) {
+ this.vfName = vfName;
+ }
+
+ public List<CldsVfcData> getCldsVfcs() {
+ return cldsVfcs;
+ }
+
+ public void setCldsVfcs(List<CldsVfcData> cldsVfcs) {
+ this.cldsVfcs = cldsVfcs;
+ }
+
+ public String getVfInvariantResourceUUID() {
+ return vfInvariantResourceUUID;
+ }
+
+ public void setVfInvariantResourceUUID(String vfInvariantResourceUUID) {
+ this.vfInvariantResourceUUID = vfInvariantResourceUUID;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/CldsVfcData.java b/src/main/java/org/onap/clamp/clds/model/CldsVfcData.java
new file mode 100644
index 000000000..2d56d01f0
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/CldsVfcData.java
@@ -0,0 +1,61 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import java.io.Serializable;
+import java.util.List;
+
+public class CldsVfcData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String vfcName;
+ private String vfcInvariantResourceUUID;
+ private List<CldsAlarmCondition> cldsAlarmConditions;
+
+ public String getVfcName() {
+ return vfcName;
+ }
+
+ public void setVfcName(String vfcName) {
+ this.vfcName = vfcName;
+ }
+
+ public List<CldsAlarmCondition> getCldsAlarmConditions() {
+ return cldsAlarmConditions;
+ }
+
+ public void setCldsAlarmConditions(List<CldsAlarmCondition> cldsAlarmConditions) {
+ this.cldsAlarmConditions = cldsAlarmConditions;
+ }
+
+ public String getVfcInvariantResourceUUID() {
+ return vfcInvariantResourceUUID;
+ }
+
+ public void setVfcInvariantResourceUUID(String vfcInvariantResourceUUID) {
+ this.vfcInvariantResourceUUID = vfcInvariantResourceUUID;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/DcaeEvent.java b/src/main/java/org/onap/clamp/clds/model/DcaeEvent.java
new file mode 100644
index 000000000..e10971e7d
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/DcaeEvent.java
@@ -0,0 +1,149 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+import org.jboss.resteasy.spi.BadRequestException;
+
+import java.util.List;
+
+/**
+ * Represent a DCAE Event.
+ */
+public class DcaeEvent {
+ public static final String EVENT_CREATED = "created"; // this is an event we (clds) sends to dcae
+ public static final String EVENT_DISTRIBUTION = "distribution";
+ public static final String EVENT_DEPLOYMENT = "deployment";
+ public static final String EVENT_UNDEPLOYMENT = "undeployment";
+ public static final String ARTIFACT_NAME_SUFFIX = ".yml";
+
+ private String event;
+ private String serviceUUID;
+ private String resourceUUID;
+ private String artifactName; // controlName.yml
+ private List<CldsModelInstance> instances;
+
+ /**
+ * Transform a DCAE Event Action to a CldsEvent.actionCd
+ *
+ * @return
+ */
+ public String getCldsActionCd() {
+ if (event == null || event.length() == 0) {
+ throw new BadRequestException("action null or empty");
+ } else if (event.equals(EVENT_CREATED)) {
+ return CldsEvent.ACTION_CREATE;
+ } else if (event.equals(EVENT_DISTRIBUTION)) {
+ return CldsEvent.ACTION_DISTRIBUTE;
+ } else if (event.equals(EVENT_DEPLOYMENT) &&
+ (instances == null || instances.size() == 0)) {
+ return CldsEvent.ACTION_UNDEPLOY;
+ } else if (event.equals(EVENT_DEPLOYMENT)) {
+ return CldsEvent.ACTION_DEPLOY;
+ // EVENT_UNDEPLOYMENT is defunct - DCAE Proxy will not undeploy individual instances. It will send an empty list of
+ // deployed instances to indicate all have been removed. Or it will send an updated list to indicate those that
+ // are still deployed with any not on the list considered undeployed.
+ //} else if ( event.equals(EVENT_UNDEPLOYMENT) ) {
+ // return CldsEvent.ACTION_UNDEPLOY;
+ }
+ throw new BadRequestException("event value not valid: " + event);
+ }
+
+ /**
+ * Derive the controlName from the artifactName.
+ *
+ * @return the controlName
+ */
+ public String getControlName() {
+ if (artifactName != null && artifactName.endsWith(ARTIFACT_NAME_SUFFIX)) {
+ return artifactName.substring(0, artifactName.length() - ARTIFACT_NAME_SUFFIX.length());
+ } else {
+ throw new BadRequestException("artifactName value not valid (expecting it to end with " + ARTIFACT_NAME_SUFFIX + "): " + artifactName);
+ }
+ }
+
+ /**
+ * @return the event
+ */
+ public String getEvent() {
+ return event;
+ }
+
+ /**
+ * @param event the event to set
+ */
+ public void setEvent(String event) {
+ this.event = event;
+ }
+
+ /**
+ * @return the serviceUUID
+ */
+ public String getServiceUUID() {
+ return serviceUUID;
+ }
+
+ /**
+ * @param serviceUUID the serviceUUID to set
+ */
+ public void setServiceUUID(String serviceUUID) {
+ this.serviceUUID = serviceUUID;
+ }
+
+ /**
+ * @return the resourceUUID
+ */
+ public String getResourceUUID() {
+ return resourceUUID;
+ }
+
+ /**
+ * @param resourceUUID the resourceUUID to set
+ */
+ public void setResourceUUID(String resourceUUID) {
+ this.resourceUUID = resourceUUID;
+ }
+
+ /**
+ * @return the artifactName
+ */
+ public String getArtifactName() {
+ return artifactName;
+ }
+
+ /**
+ * @param artifactName the artifactName to set
+ */
+ public void setArtifactName(String artifactName) {
+ this.artifactName = artifactName;
+ }
+
+ public List<CldsModelInstance> getInstances() {
+ return instances;
+ }
+
+ public void setInstances(List<CldsModelInstance> instances) {
+ this.instances = instances;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/HelloWorld.java b/src/main/java/org/onap/clamp/clds/model/HelloWorld.java
new file mode 100644
index 000000000..1165f5da4
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/HelloWorld.java
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+public class HelloWorld {
+
+ private String message;
+
+ public HelloWorld() {
+ // needed for deserializer
+ }
+
+ public HelloWorld(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ @Override
+ public String toString() {
+ return "message = " + getMessage();
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/ValueItem.java b/src/main/java/org/onap/clamp/clds/model/ValueItem.java
new file mode 100644
index 000000000..804d18546
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/ValueItem.java
@@ -0,0 +1,58 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model;
+
+/**
+ * ValueItem used for value lists.
+ */
+public class ValueItem {
+ private String value;
+
+ /**
+ * Instantiate using value.
+ *
+ * @param value
+ */
+ public ValueItem(String value) {
+ this.value = value;
+ }
+
+ public ValueItem() {
+ }
+
+ /**
+ * @return the value
+ */
+ public String getValue() {
+ return value;
+ }
+
+ /**
+ * @param value the value to set
+ */
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/Collector.java b/src/main/java/org/onap/clamp/clds/model/prop/Collector.java
new file mode 100644
index 000000000..84bc38f0c
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/Collector.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.logging.Logger;
+
+/**
+ * Parse Collector json properties.
+ */
+public class Collector extends ModelElement {
+ private static final Logger logger = Logger.getLogger(Collector.class.getName());
+
+ /**
+ * Parse Collector given json node.
+ *
+ * @param modelBpmn
+ * @param modelJson
+ */
+ public Collector(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) {
+ super(TYPE_COLLECTOR, modelProp, modelBpmn, modelJson);
+ topicPublishes = getValueByName("topicPublishes");
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/Global.java b/src/main/java/org/onap/clamp/clds/model/prop/Global.java
new file mode 100644
index 000000000..f8986b361
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/Global.java
@@ -0,0 +1,113 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Parse global json properties.
+ * <p>
+ * Example json: "global":[{"name":"service","value":["vUSP"]},{"name":"vnf","value":["vCTS","v3CDB"]},{"name":"location","value":["san_diego","san_antonio","kansas_city","kings_mountain","Secaucus","lisle","concord","houston","akron"]}]
+ */
+public class Global {
+ private static final Logger logger = Logger.getLogger(Global.class.getName());
+
+ private String service;
+ private List<String> resourceVf;
+ private List<String> resourceVfc;
+ private List<String> location;
+
+ /**
+ * Parse global given json node.
+ *
+ * @param modelJson
+ */
+ public Global(JsonNode modelJson) {
+ JsonNode globalNode = modelJson.get("global");
+ service = ModelElement.getValueByName(globalNode, "service");
+ resourceVf = ModelElement.getValuesByName(globalNode, "vf");
+ resourceVfc = ModelElement.getValuesByName(globalNode, "vfc");
+ location = ModelElement.getValuesByName(globalNode, "location");
+ }
+
+ /**
+ * @return the service
+ */
+ public String getService() {
+ return service;
+ }
+
+ /**
+ * @param service the service to set
+ */
+ public void setService(String service) {
+ this.service = service;
+ }
+
+ /**
+ * @return the resourceVf
+ */
+ public List<String> getResourceVf() {
+ return resourceVf;
+ }
+
+ /**
+ * @param resourceVf the resourceVf to set
+ */
+ public void setResourceVf(List<String> resourceVf) {
+ this.resourceVf = resourceVf;
+ }
+
+ /**
+ * @return the resourceVfc
+ */
+ public List<String> getResourceVfc() {
+ return resourceVfc;
+ }
+
+ /**
+ * @param resourceVfc the resourceVfc to set
+ */
+ public void setResourceVfc(List<String> resourceVfc) {
+ this.resourceVfc = resourceVfc;
+ }
+
+ /**
+ * @return the location
+ */
+ public List<String> getLocation() {
+ return location;
+ }
+
+ /**
+ * @param location the location to set
+ */
+ public void setLocation(List<String> location) {
+ this.location = location;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmn.java b/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmn.java
new file mode 100644
index 000000000..b4cc11dc2
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmn.java
@@ -0,0 +1,153 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.Map.Entry;
+import java.util.logging.Logger;
+
+/**
+ * Parse Model BPMN properties.
+ * <p>
+ * Example json: {"collector":[{"id":"Collector_11r50j1", "from":"StartEvent_1"}],"stringMatch":[{"id":"StringMatch_0h6cbdv"}],"policy":[{"id":"Policy_0oxeocn", "from":"StringMatch_0h6cbdv"}]}
+ */
+public class ModelBpmn {
+ private static final Logger logger = Logger.getLogger(ModelBpmn.class.getName());
+
+ // for each type, an array of entries
+ private final Map<String, List<ModelBpmnEntry>> entriesByType = new HashMap<>();
+
+ // for each id, an array of entries
+ private final Map<String, List<ModelBpmnEntry>> entriesById = new HashMap<>();
+
+ // List of all elementIds
+ private List<String> bpmnElementIds;
+
+ /**
+ * Create ModelBpmn and populate maps from json
+ *
+ * @param modelBpmnPropText
+ * @return
+ * @throws IOException
+ * @throws JsonMappingException
+ * @throws JsonParseException
+ */
+ public static ModelBpmn create(String modelBpmnPropText) throws IOException {
+ ModelBpmn modelBpmn = new ModelBpmn();
+ ObjectMapper objectMapper = new ObjectMapper();
+ ObjectNode root = objectMapper.readValue(modelBpmnPropText, ObjectNode.class);
+ // iterate over each entry like: "collector":[{"id":"Collector_11r50j1","from":"StartEvent_1"}]
+ Iterator<Entry<String, JsonNode>> entryItr = root.fields();
+ List<String> bpmnElementIdList = new ArrayList<>();
+ while (entryItr.hasNext()) {
+ // process the entry
+ Entry<String, JsonNode> entry = entryItr.next();
+ String type = entry.getKey();
+ ArrayNode arrayNode = (ArrayNode) entry.getValue();
+ // process each id/from object, like: {"id":"Collector_11r50j1","from":"StartEvent_1"}
+ for (JsonNode anArrayNode : arrayNode) {
+ ObjectNode node = (ObjectNode) anArrayNode;
+ String id = node.get("id").asText();
+ String fromId = node.get("from").asText();
+ ModelBpmnEntry modelBpmnEntry = new ModelBpmnEntry(type, id, fromId);
+ modelBpmn.addEntry(modelBpmnEntry);
+ bpmnElementIdList.add(id);
+ }
+ modelBpmn.setBpmnElementIds(bpmnElementIdList);
+ }
+ return modelBpmn;
+ }
+
+ /**
+ * Add entry to both maps.
+ *
+ * @param entry
+ */
+ private void addEntry(ModelBpmnEntry entry) {
+ addEntry(entriesByType, entry, entry.getType());
+ addEntry(entriesById, entry, entry.getId());
+ }
+
+ /**
+ * Add an entry to provided map with provided key.
+ *
+ * @param map
+ * @param entry
+ * @param key
+ */
+ private static void addEntry(Map<String, List<ModelBpmnEntry>> map, ModelBpmnEntry entry, String key) {
+ List<ModelBpmnEntry> list = map.computeIfAbsent(key, k -> new ArrayList<>());
+ list.add(entry);
+ }
+
+ /**
+ *
+ *
+ * @param type
+ * @return true if the element is found or false otherwise
+ */
+ public boolean getModelElementFound(String type) {
+ return entriesByType.get(type) != null;
+ }
+
+ /**
+ * @return the id field given the ModelElement type
+ */
+ public String getId(String type) {
+ return entriesByType.get(type).get(0).getId();
+ }
+
+ /**
+ * @return the fromId field given the ModelElement type
+ */
+ public String getFromId(String type) {
+ return entriesByType.get(type).get(0).getFromId();
+ }
+
+ /**
+ * @return the ModelElement type given the ModelElement id
+ */
+ public String getType(String id) {
+ return entriesById.get(id).get(0).getType();
+ }
+
+ /**
+ * @return list of elementIds from bpmn
+ */
+ public List<String> getBpmnElementIds() {
+ return bpmnElementIds;
+ }
+
+ public void setBpmnElementIds(List<String> bpmnElementIds) {
+ this.bpmnElementIds = bpmnElementIds;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmnEntry.java b/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmnEntry.java
new file mode 100644
index 000000000..8002f447f
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/ModelBpmnEntry.java
@@ -0,0 +1,95 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import java.util.logging.Logger;
+
+/**
+ * Model BPMN property entry
+ * <p>
+ * Example json: {"collector":[{"id":"Collector_11r50j1", "from":"StartEvent_1"}],"stringMatch":[{"id":"StringMatch_0h6cbdv"],"policy":[{"id":"Policy_0oxeocn", "from":"StringMatch_0h6cbdv"}]}
+ */
+public class ModelBpmnEntry {
+ private static final Logger logger = Logger.getLogger(ModelBpmnEntry.class.getName());
+
+ private String type;
+ private String id;
+ private String fromId;
+
+ /**
+ * Parse the json so that the "id" and "from" fields can be retrieved on demand.
+ *
+ * @param type
+ * @param id
+ * @param fromId
+ */
+ public ModelBpmnEntry(String type, String id, String fromId) {
+ this.type = type;
+ this.id = id;
+ this.fromId = fromId;
+ }
+
+ /**
+ * @return the type
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * @param type the type to set
+ */
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ /**
+ * @return the id
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * @param id the id to set
+ */
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ /**
+ * @return the fromId
+ */
+ public String getFromId() {
+ return fromId;
+ }
+
+ /**
+ * @param fromId the fromId to set
+ */
+ public void setFromId(String fromId) {
+ this.fromId = fromId;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/ModelElement.java b/src/main/java/org/onap/clamp/clds/model/prop/ModelElement.java
new file mode 100644
index 000000000..d8e903060
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/ModelElement.java
@@ -0,0 +1,232 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Provide base ModelElement functionality.
+ */
+public abstract class ModelElement {
+ private final static Logger sLOGGER = Logger.getLogger(ModelElement.class.getName());
+ private static final Logger logger = Logger.getLogger(ModelElement.class.getName());
+
+ public static final String TYPE_COLLECTOR = "collector";
+ public static final String TYPE_STRING_MATCH = "stringMatch";
+ public static final String TYPE_POLICY = "policy";
+ public static final String TYPE_TCA = "tca";
+
+ private final String type;
+ private final ModelBpmn modelBpmn;
+ private final String id;
+ protected String topicPublishes;
+ protected final JsonNode meNode;
+ private boolean isFound;
+
+ private final ModelProperties modelProp;
+
+ /**
+ * Perform base parsing of properties for a ModelElement (such as,
+ * Collector, StringMatch, Policy and Tca)
+ *
+ * @param type
+ * @param modelProp
+ * @param modelBpmn
+ * @param modelJson
+ */
+ protected ModelElement(String type, ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) {
+ this.type = type;
+ this.modelProp = modelProp;
+ this.modelBpmn = modelBpmn;
+ this.id = modelBpmn.getId(type);
+ this.meNode = modelJson.get(id);
+ this.isFound = modelBpmn.getModelElementFound(type);
+ }
+
+ /**
+ * topicSubscribes is the topicPublishes of the from Model Element
+ *
+ * @return the topicSubscribes
+ */
+ public String getTopicSubscribes() {
+ // get fromId for this type
+ String fromId = modelBpmn.getFromId(type);
+ // find the type of the from model element
+ String fromType = modelBpmn.getType(fromId);
+ // get the model element for the type
+ ModelElement me = modelProp.getModelElementByType(fromType);
+ // get the topic publishes for the model element
+ return me.topicPublishes;
+ }
+
+ /**
+ * @return the topicPublishes
+ */
+ public String getTopicPublishes() {
+ return topicPublishes;
+ }
+
+ /**
+ * Return the value field of the json node element that has a name field
+ * equals to the given name.
+ *
+ * @param nodeIn
+ * @param name
+ * @return
+ */
+ public static String getValueByName(JsonNode nodeIn, String name) {
+ String value = null;
+ if (nodeIn != null) {
+ for (JsonNode node : nodeIn) {
+ if (node.path("name").asText().equals(name)) {
+ JsonNode vnode = node.path("value");
+ if (vnode.isArray()) {
+ // if array, assume value is in first element
+ value = vnode.path(0).asText();
+ } else {
+ // otherwise, just return text
+ value = vnode.asText();
+ }
+ }
+ }
+ }
+ if (value == null || value.length() == 0) {
+ sLOGGER.warning(name + "=" + value);
+ } else {
+ sLOGGER.fine(name + "=" + value);
+ }
+ return value;
+ }
+
+ /**
+ * Return the int value field of the json node element that has a name field
+ * equals to the given name.
+ *
+ * @param nodeIn
+ * @param name
+ * @return
+ */
+ public static Integer getIntValueByName(JsonNode nodeIn, String name) {
+ String value = getValueByName(nodeIn, name);
+ return Integer.valueOf(value);
+ }
+
+ /**
+ * Return an array of values for the field of the json node element that has
+ * a name field equals to the given name.
+ *
+ * @param nodeIn
+ * @param name
+ * @return
+ */
+ public static List<String> getValuesByName(JsonNode nodeIn, String name) {
+ List<String> values = null;
+ if (nodeIn != null) {
+ Iterator<JsonNode> i = nodeIn.iterator();
+ while (i.hasNext()) {
+ JsonNode node = i.next();
+ if (node.path("name").asText().equals(name)) {
+ values = getValuesList(node);
+ }
+ }
+ }
+ if (values == null || values.size() == 0) {
+ sLOGGER.warning(name + "=" + values);
+ } else {
+ sLOGGER.fine(name + "=" + values);
+ }
+ return values;
+ }
+
+ /**
+ * Return an array of String values.
+ *
+ * @param nodeIn
+ * @return
+ */
+ public static List<String> getValuesList(JsonNode nodeIn) {
+ ArrayList<String> al = new ArrayList<>();
+ if (nodeIn != null) {
+ Iterator<JsonNode> itr = nodeIn.path("value").elements();
+ while (itr.hasNext()) {
+ JsonNode node = itr.next();
+ al.add(node.asText());
+ }
+ }
+ return al;
+ }
+
+ /**
+ * Return the value field of the json node element that has a name field
+ * equals to the given name.
+ *
+ * @param name
+ * @return
+ */
+ public String getValueByName(String name) {
+ return getValueByName(meNode, name);
+ }
+
+ /**
+ * Return the int value field of the json node element that has a name field
+ * equals to the given name.
+ *
+ * @param name
+ * @return
+ */
+ public Integer getIntValueByName(String name) {
+ return getIntValueByName(meNode, name);
+ }
+
+ /**
+ * Return an array of values for the field of the json node element that has
+ * a name field equals to the given name.
+ *
+ * @param name
+ * @return
+ */
+ public List<String> getValuesByName(String name) {
+ return getValuesByName(meNode, name);
+ }
+
+ /**
+ * @return the id
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * @return the isFound
+ */
+ public boolean isFound() {
+ return isFound;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/ModelProperties.java b/src/main/java/org/onap/clamp/clds/model/prop/ModelProperties.java
new file mode 100644
index 000000000..014b8c77e
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/ModelProperties.java
@@ -0,0 +1,320 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.onap.clamp.clds.model.CldsEvent;
+import org.onap.clamp.clds.model.CldsModel;
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Parse model properties.
+ */
+public class ModelProperties {
+ private static final Logger logger = Logger.getLogger(ModelProperties.class.getName());
+
+ private ModelBpmn modelBpmn;
+ private JsonNode modelJson;
+
+ private final String modelName;
+ private final String controlName;
+ private final String actionCd;
+
+ private Global global;
+ private Collector collector;
+ private StringMatch stringMatch;
+ private Policy policy;
+ private Tca tca;
+
+ private String currentModelElementId;
+ private String policyUniqueId;
+
+ /**
+ * Retain data required to parse the ModelElement objects. (Rather than
+ * parse them all - parse them on demand if requested.)
+ *
+ * @param modelName
+ * @param controlName
+ * @param actionCd
+ * @param modelBpmnPropText
+ * @param modelPropText
+ * @throws JsonProcessingException
+ * @throws IOException
+ */
+ public ModelProperties(String modelName, String controlName, String actionCd, String modelBpmnPropText, String modelPropText) throws IOException {
+ this.modelName = modelName;
+ this.controlName = controlName;
+ this.actionCd = actionCd;
+ modelBpmn = ModelBpmn.create(modelBpmnPropText);
+ ObjectMapper mapper = new ObjectMapper();
+ modelJson = mapper.readTree(modelPropText);
+ }
+
+ /**
+ * Get the VF for a model. If return null if there is no VF.
+ *
+ * @param model
+ * @return
+ */
+ public static String getVf(CldsModel model) {
+ List<String> vfs = null;
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode modelJson = mapper.readTree(model.getPropText());
+ Global global = new Global(modelJson);
+ vfs = global.getResourceVf();
+ } catch (IOException e) {
+ // VF is null
+ }
+ String vf = null;
+ if (vfs != null && !vfs.isEmpty()) {
+ vf = vfs.get(0);
+ }
+ return vf;
+ }
+
+ /**
+ * Create ModelProperties for Camunda Delegate.
+ *
+ * @param execution
+ * @return
+ * @throws JsonProcessingException
+ * @throws IOException
+ */
+ public static ModelProperties create(DelegateExecution execution) throws IOException {
+ String modelProp = (String) execution.getVariable("modelProp");
+ String modelBpmnProp = (String) execution.getVariable("modelBpmnProp");
+ String modelName = (String) execution.getVariable("modelName");
+ String controlName = (String) execution.getVariable("controlName");
+ String actionCd = (String) execution.getVariable("actionCd");
+
+ return new ModelProperties(modelName, controlName, actionCd, modelBpmnProp, modelProp);
+ }
+
+ /**
+ * return appropriate model element given the type
+ *
+ * @param type
+ * @return
+ */
+ public ModelElement getModelElementByType(String type) {
+ ModelElement me;
+ switch (type) {
+ case ModelElement.TYPE_COLLECTOR:
+ me = getCollector();
+ break;
+ case ModelElement.TYPE_STRING_MATCH:
+ me = getStringMatch();
+ break;
+ case ModelElement.TYPE_POLICY:
+ me = getPolicy();
+ break;
+ case ModelElement.TYPE_TCA:
+ me = getTca();
+ break;
+ default:
+ throw new IllegalArgumentException("Invalid ModelElement type: " + type);
+ }
+ return me;
+ }
+
+ /**
+ * @return the modelName
+ */
+ public String getModelName() {
+ return modelName;
+ }
+
+ /**
+ * @return the controlName
+ */
+ public String getControlName() {
+ return controlName;
+ }
+
+ /**
+ * @return the controlNameAndPolicyUniqueId
+ */
+ public String getControlNameAndPolicyUniqueId() {
+ return controlName + "_" + policyUniqueId;
+ }
+
+ /**
+ * @return the currentPolicyName
+ */
+ private String getCurrentPolicyName() {
+ return normalizePolicyScopeName(controlName + "_" + currentModelElementId);
+ }
+
+ /**
+ * @return the currentPolicyScopeAndPolicyName
+ */
+ public String getCurrentPolicyScopeAndPolicyName() {
+ return normalizePolicyScopeName(modelName + "." + getCurrentPolicyName());
+ }
+
+ /**
+ * @return the currentPolicyScopeAndFullPolicyName
+ */
+ public String getCurrentPolicyScopeAndFullPolicyName(String policyNamePrefix) {
+ return normalizePolicyScopeName(modelName + "." + policyNamePrefix + getCurrentPolicyName());
+ }
+
+ /**
+ * @return the currentPolicyScopeAndFullPolicyNameWithVersion
+ */
+ public String getCurrentPolicyScopeAndFullPolicyNameWithVersion(String policyNamePrefix, int version) {
+ return normalizePolicyScopeName(
+ modelName + "." + policyNamePrefix + getCurrentPolicyName() + "." + version + ".xml");
+ }
+
+ /**
+ * Replace all '-' with '_' within policy scope and name.
+ *
+ * @param inName
+ * @return
+ */
+ private String normalizePolicyScopeName(String inName) {
+ return inName.replaceAll("-", "_");
+ }
+
+ /**
+ * @return the currentModelElementId
+ */
+ public String getCurrentModelElementId() {
+ return currentModelElementId;
+ }
+
+ /**
+ * When generating a policy request for a model element, must set the id of
+ * that model element using this method. Used to generate the policy name.
+ *
+ * @param currentModelElementId
+ * the currentModelElementId to set
+ */
+ public void setCurrentModelElementId(String currentModelElementId) {
+ this.currentModelElementId = currentModelElementId;
+ }
+
+ /**
+ * @return the policyUniqueId
+ */
+ public String getPolicyUniqueId() {
+ return policyUniqueId;
+ }
+
+ /**
+ * When generating a policy request for a model element, must set the unique
+ * id of that policy using this method. Used to generate the policy name.
+ *
+ * @param policyUniqueId
+ * the policyUniqueId to set
+ */
+ public void setPolicyUniqueId(String policyUniqueId) {
+ this.policyUniqueId = policyUniqueId;
+ }
+
+ /**
+ * @return the collector
+ */
+ public Collector getCollector() {
+ if (collector == null) {
+ collector = new Collector(this, modelBpmn, modelJson);
+ }
+ return collector;
+ }
+
+ /**
+ * @return the actionCd
+ */
+ public String getActionCd() {
+ return actionCd;
+ }
+
+ /**
+ * @return the isCreateRequest
+ */
+ public boolean isCreateRequest() {
+ switch (actionCd) {
+ case CldsEvent.ACTION_SUBMIT:
+ case CldsEvent.ACTION_RESTART:
+ return true;
+ }
+ return false;
+ }
+
+ public boolean isStopRequest() {
+ switch (actionCd) {
+ case CldsEvent.ACTION_STOP:
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * @return the global
+ */
+ public Global getGlobal() {
+ if (global == null) {
+ global = new Global(modelJson);
+ }
+ return global;
+ }
+
+ /**
+ * @return the stringMatch
+ */
+ public StringMatch getStringMatch() {
+ if (stringMatch == null) {
+ stringMatch = new StringMatch(this, modelBpmn, modelJson);
+ }
+ return stringMatch;
+ }
+
+ /**
+ * @return the policy
+ */
+ public Policy getPolicy() {
+ if (policy == null) {
+ policy = new Policy(this, modelBpmn, modelJson);
+ }
+ return policy;
+ }
+
+ /**
+ * @return the tca
+ */
+ public Tca getTca() {
+ if (tca == null) {
+ tca = new Tca(this, modelBpmn, modelJson);
+ }
+ return tca;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/Policy.java b/src/main/java/org/onap/clamp/clds/model/prop/Policy.java
new file mode 100644
index 000000000..729eb4381
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/Policy.java
@@ -0,0 +1,78 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Parse Policy json properties.
+ * <p>
+ * Example json: "Policy_005sny1":[[{"name":"timeout","value":"5"}],{"policyConfigurations":[[{"name":"recipe","value":["restart"]},{"name":"maxRetries","value":["3"]},{"name":"retryTimeLimit","value":["180"]},{"name":"_id","value":["vf3RtPi"]},{"name":"location","value":["san_diego"]},{"name":"resource","value":["vCTS"]},{"name":"onMaxRetriesLimit","value":[""]},{"name":"onTimeLimit","value":[""]},{"name":"onOtherFailure","value":[""]},{"name":"policy_parent","value":[""]}],[{"name":"recipe","value":["rebuild"]},{"name":"maxRetries","value":["3"]},{"name":"retryTimeLimit","value":["180"]},{"name":"_id","value":["89z8Ncl"]},{"name":"location","value":["san_diego"]},{"name":"resource","value":["vCTS"]},{"name":"onMaxRetriesLimit","value":[""]},{"name":"onTimeLimit","value":[""]},{"name":"onOtherFailure","value":[""]},{"name":"policy_parent","value":["vf3RtPi"]}]]}]
+ */
+public class Policy extends ModelElement {
+ private static final Logger logger = Logger.getLogger(Policy.class.getName());
+
+ private final Integer timeout;
+ private final List<PolicyItem> policyItems;
+
+ /**
+ * Parse Policy given json node.
+ *
+ * @param modelProp
+ * @param modelBpmn
+ * @param modelJson
+ */
+ public Policy(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) {
+ super(TYPE_POLICY, modelProp, modelBpmn, modelJson);
+ timeout = getIntValueByName(meNode.get(0), "timeout");
+
+ // process policies
+ JsonNode policyNode = meNode.get(1).get("policyConfigurations");
+ Iterator<JsonNode> itr = policyNode.elements();
+ policyItems = new ArrayList<>();
+ while (itr.hasNext()) {
+ policyItems.add(new PolicyItem(itr.next()));
+ }
+ }
+
+ /**
+ * @return the timeout
+ */
+ public Integer getTimeout() {
+ return timeout;
+ }
+
+ /**
+ * @return the policyItems
+ */
+ public List<PolicyItem> getPolicyItems() {
+ return policyItems;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/PolicyItem.java b/src/main/java/org/onap/clamp/clds/model/prop/PolicyItem.java
new file mode 100644
index 000000000..a943f1840
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/PolicyItem.java
@@ -0,0 +1,103 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Parse policyConfigurations from Policy json properties.
+ * <p>
+ * Example json: "Policy_005sny1":[[{"name":"timeout","value":"5"}],{"policyConfigurations":[[{"name":"recipe","value":["restart"]},{"name":"maxRetries","value":["3"]},{"name":"retryTimeLimit","value":["180"]},{"name":"_id","value":["vf3RtPi"]},{"name":"location","value":["san_diego"]},{"name":"resource","value":["vCTS"]},{"name":"onMaxRetriesLimit","value":[""]},{"name":"onTimeLimit","value":[""]},{"name":"onOtherFailure","value":[""]},{"name":"policy_parent","value":[""]}],[{"name":"recipe","value":["rebuild"]},{"name":"maxRetries","value":["3"]},{"name":"retryTimeLimit","value":["180"]},{"name":"_id","value":["89z8Ncl"]},{"name":"location","value":["san_diego"]},{"name":"resource","value":["vCTS"]},{"name":"onMaxRetriesLimit","value":[""]},{"name":"onTimeLimit","value":[""]},{"name":"onOtherFailure","value":[""]},{"name":"policy_parent","value":["vf3RtPi"]}]]}]
+ */
+public class PolicyItem {
+ private static final Logger logger = Logger.getLogger(Policy.class.getName());
+
+ private final String id;
+ private final String recipe;
+ private final int maxRetries;
+ private final int retryTimeLimit;
+ private final String parentPolicy;
+ private final List<String> parentPolicyConditions;
+
+ /**
+ * Parse Policy given json node.
+ *
+ * @param node
+ */
+ public PolicyItem(JsonNode node) {
+ id = ModelElement.getValueByName(node, "_id");
+ recipe = ModelElement.getValueByName(node, "recipe");
+ maxRetries = ModelElement.getIntValueByName(node, "maxRetries");
+ retryTimeLimit = ModelElement.getIntValueByName(node, "retryTimeLimit");
+ parentPolicy = ModelElement.getValueByName(node, "parentPolicy");
+ parentPolicyConditions = ModelElement.getValuesByName(node, "parentPolicyConditions");
+
+ }
+
+ /**
+ * @return the id
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * @return the recipe
+ */
+ public String getRecipe() {
+ return recipe;
+ }
+
+ /**
+ * @return the maxRetries
+ */
+ public int getMaxRetries() {
+ return maxRetries;
+ }
+
+ /**
+ * @return the retryTimeLimit
+ */
+ public int getRetryTimeLimit() {
+ return retryTimeLimit;
+ }
+
+ /**
+ * @return the parentPolicy
+ */
+ public String getParentPolicy() {
+ return parentPolicy;
+ }
+
+ /**
+ * @return the parentPolicyConditions
+ */
+ public List<String> getParentPolicyConditions() {
+ return parentPolicyConditions;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/ServiceConfiguration.java b/src/main/java/org/onap/clamp/clds/model/prop/ServiceConfiguration.java
new file mode 100644
index 000000000..498f852e9
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/ServiceConfiguration.java
@@ -0,0 +1,156 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * Parse serviceConfigurations from StringMatch json properties.
+ * <p>
+ * Example json: "StringMatch_0c2cy0c":[[{"name":"topicPublishes","value":"DCAE-CL-EVENT"}],{"serviceConfigurations":[[{"name":"aaiMatchingFields","value":["VMID"]},{"name":"aaiSendFields","value":["VNFNAME","LOCID"]},{"name":"vnf","value":["aSBG"]},{"name":"timeWindow","value":["0"]},{"name":"ageLimit","value":["1600"]},{"name":"createClosedLoopEventId","value":["Initial"]},{"name":"outputEventName","value":["OnSet"]},{"stringSet":[{"name":"alarmCondition","value":["authenticationFailure"]},{"name":"eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":["f5BigIP"]}]}],[{"name":"aaiMatchingFields","value":["VMID"]},{"name":"aaiSendFields","value":["VMID","Identiy","VNFNAME"]},{"name":"vnf","value":["aSBG"]},{"name":"timeWindow","value":["0"]},{"name":"ageLimit","value":["1600"]},{"name":"createClosedLoopEventId","value":["Close"]},{"name":"outputEventName","value":["Abatement"]},{"stringSet":[{"name":"alarmCondition","value":["authenticationFailure"]},{"name":"eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":["f5BigIP"]}]}]]}]
+ */
+public class ServiceConfiguration {
+
+ private static final Logger logger = Logger.getLogger(ServiceConfiguration.class.getName());
+
+ private final List<String> aaiMatchingFields;
+ private final List<String> aaiSendFields;
+ private final String groupNumber;
+ private final List<String> resourceVf;
+ private final List<String> resourceVfc;
+ private final String timeWindow;
+ private final String ageLimit;
+ private final String createClosedLoopEventId;
+ private final String outputEventName;
+ private final Map<String, String> stringSet;
+
+ /**
+ * Parse serviceConfigurations given json node.
+ *
+ * @param node
+ */
+ public ServiceConfiguration(JsonNode node) {
+ aaiMatchingFields = ModelElement.getValuesByName(node, "aaiMatchingFields");
+ aaiSendFields = ModelElement.getValuesByName(node, "aaiSendFields");
+ groupNumber = ModelElement.getValueByName(node, "groupNumber");
+ resourceVf = ModelElement.getValuesByName(node, "vf");
+ resourceVfc = ModelElement.getValuesByName(node, "vfc");
+ timeWindow = ModelElement.getValueByName(node, "timeWindow");
+ ageLimit = ModelElement.getValueByName(node, "ageLimit");
+ createClosedLoopEventId = ModelElement.getValueByName(node, "createClosedLoopEventId");
+ outputEventName = ModelElement.getValueByName(node, "outputEventName");
+
+ // process the stringSet fields
+ JsonNode ssNodes = node.findPath("stringSet");
+ Iterator<JsonNode> itr = ssNodes.elements();
+ stringSet = new HashMap<>();
+ while (itr.hasNext()) {
+ JsonNode ssNode = itr.next();
+ String key = ssNode.path("name").asText();
+ String value = ssNode.path("value").path(0).asText();
+ if (key.length() != 0 && value.length() != 0) {
+ // only add string set field if not null
+ logger.fine("stringSet: " + key + "=" + value);
+ stringSet.put(key, value);
+ }
+ }
+ }
+
+ /**
+ * @return the aaiMatchingFields
+ */
+ public List<String> getaaiMatchingFields() {
+ return aaiMatchingFields;
+ }
+
+ /**
+ * @return the aaiSendFields
+ */
+ public List<String> getaaiSendFields() {
+ return aaiSendFields;
+ }
+
+ /**
+ * @return the groupNumber
+ */
+ public String getGroupNumber() {
+ return groupNumber;
+ }
+
+ /**
+ * @return the resourceVf
+ */
+ public List<String> getResourceVf() {
+ return resourceVf;
+ }
+
+ /**
+ * @return the resourceVfc
+ */
+ public List<String> getResourceVfc() {
+ return resourceVfc;
+ }
+
+ /**
+ * @return the timeWindow
+ */
+ public String getTimeWindow() {
+ return timeWindow;
+ }
+
+ /**
+ * @return the ageLimit
+ */
+ public String getAgeLimit() {
+ return ageLimit;
+ }
+
+ /**
+ * @return the createClosedLoopEventId
+ */
+ public String getCreateClosedLoopEventId() {
+ return createClosedLoopEventId;
+ }
+
+ /**
+ * @return the outputEventName
+ */
+ public String getOutputEventName() {
+ return outputEventName;
+ }
+
+ /**
+ * @return the stringSet
+ */
+ public Map<String, String> getStringSet() {
+ return stringSet;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/StringMatch.java b/src/main/java/org/onap/clamp/clds/model/prop/StringMatch.java
new file mode 100644
index 000000000..d7092c4e6
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/StringMatch.java
@@ -0,0 +1,70 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.prop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Parse StringMatch json properties.
+ * <p>
+ * Example json: "StringMatch_0c2cy0c":[[{"name":"topicPublishes","value":"DCAE-CL-EVENT"}],{"serviceConfigurations":[[{"name":"aaiMatchingFields","value":["VMID"]},{"name":"aaiSendFields","value":["VNFNAME","LOCID"]},{"name":"vnf","value":["aSBG"]},{"name":"timeWindow","value":["0"]},{"name":"ageLimit","value":["1600"]},{"name":"createClosedLoopEventId","value":["Initial"]},{"name":"outputEventName","value":["OnSet"]},{"stringSet":[{"name":"alarmCondition","value":["authenticationFailure"]},{"name":"eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":["f5BigIP"]}]}],[{"name":"aaiMatchingFields","value":["VMID"]},{"name":"aaiSendFields","value":["VMID","Identiy","VNFNAME"]},{"name":"vnf","value":["aSBG"]},{"name":"timeWindow","value":["0"]},{"name":"ageLimit","value":["1600"]},{"name":"createClosedLoopEventId","value":["Close"]},{"name":"outputEventName","value":["Abatement"]},{"stringSet":[{"name":"alarmCondition","value":["authenticationFailure"]},{"name":"eventSeverity","value":["NORMAL"]},{"name":"eventSourceType","value":["f5BigIP"]}]}]]}]
+ */
+public class StringMatch extends ModelElement {
+ private static final Logger logger = Logger.getLogger(StringMatch.class.getName());
+
+ private final List<ServiceConfiguration> serviceConfigurations;
+
+ /**
+ * Parse StringMatch given json node.
+ *
+ * @param modelBpmn
+ * @param modelJson
+ */
+ public StringMatch(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) {
+ super(ModelElement.TYPE_STRING_MATCH, modelProp, modelBpmn, modelJson);
+
+ topicPublishes = getValueByName(meNode.get(0), "topicPublishes");
+
+ // process Server_Configurations
+ JsonNode serviceConfigurationsNode = meNode.get(1).get("serviceConfigurations");
+ Iterator<JsonNode> itr = serviceConfigurationsNode.elements();
+ serviceConfigurations = new ArrayList<>();
+ while (itr.hasNext()) {
+ serviceConfigurations.add(new ServiceConfiguration(itr.next()));
+ }
+ }
+
+ /**
+ * @return the serviceConfigurations
+ */
+ public List<ServiceConfiguration> getServiceConfigurations() {
+ return serviceConfigurations;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/Tca.java b/src/main/java/org/onap/clamp/clds/model/prop/Tca.java
new file mode 100644
index 000000000..c7b23608a
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/Tca.java
@@ -0,0 +1,47 @@
+package org.onap.clamp.clds.model.prop;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * Parse Tca json properties.
+ *
+ * Example json: {"TCA_0lm6cix":{"Narra":[{"name":"tname","value":"Narra"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Polcicy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Critical"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_1",">","4"],["FIELDPATH_test_1","=","5"]]}],"Srini":[{"name":"tname","value":"Srini"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Policy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Major"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_2","=","3"],["FIELDPATH_test_1",">","2"]]}]}}
+ *
+ *
+ */
+public class Tca extends ModelElement {
+
+ private static final Logger logger = Logger.getLogger(StringMatch.class.getName());
+
+ private List<TcaItem> tcaItems;
+
+ /**
+ * Parse Tca given json node
+ *
+ * @param modelProp
+ * @param modelBpmn
+ * @param modelJson
+ */
+ public Tca(ModelProperties modelProp, ModelBpmn modelBpmn, JsonNode modelJson) {
+ super(ModelElement.TYPE_TCA, modelProp, modelBpmn, modelJson);
+
+ // process Server_Configurations
+ if(meNode != null){
+ Iterator<JsonNode> itr = meNode.elements();
+ tcaItems = new ArrayList<TcaItem>();
+ while(itr.hasNext()) {
+ tcaItems.add(new TcaItem(itr.next()));
+ }
+ }
+ }
+
+ public List<TcaItem> getTcaItems() {
+ return tcaItems;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/TcaItem.java b/src/main/java/org/onap/clamp/clds/model/prop/TcaItem.java
new file mode 100644
index 000000000..5792c0574
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/TcaItem.java
@@ -0,0 +1,128 @@
+package org.onap.clamp.clds.model.prop;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.logging.Logger;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * Parse Tca Item json properties.
+ *
+ * Example json: {"TCA_0lm6cix":{"Narra":[{"name":"tname","value":"Narra"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Polcicy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Critical"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_1",">","4"],["FIELDPATH_test_1","=","5"]]}],"Srini":[{"name":"tname","value":"Srini"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Policy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Major"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_2","=","3"],["FIELDPATH_test_1",">","2"]]}]}}
+ *
+ *
+ */
+public class TcaItem {
+
+ private static final Logger logger = Logger.getLogger(TcaItem.class.getName());
+
+ private String tcaName;
+ private String tcaUuId;
+ private String nfNamingCode;
+ private String tcaEnable;
+ private String policyId;
+ private Integer interval;
+ private String severity;
+ private Integer violations;
+ private List<TcaThreshhold> tcaThreshholds;
+
+ /**
+ * Parse Tca Item given json node
+ *
+ * @param node
+ */
+ public TcaItem(JsonNode node) {
+
+ tcaName = ModelElement.getValueByName(node, "tname");
+ tcaUuId = ModelElement.getValueByName(node, "tuuid");
+ nfNamingCode = ModelElement.getValueByName(node, "tnfc");
+ tcaEnable = ModelElement.getValueByName(node, "tcaEnab");
+ policyId = ModelElement.getValueByName(node, "tcaPolId");
+ if(ModelElement.getValueByName(node, "tcaInt") != null){
+ interval = Integer.valueOf(ModelElement.getValueByName(node, "tcaInt"));
+ }
+ severity = ModelElement.getValueByName(node, "tcaSev");
+ if(ModelElement.getValueByName(node, "tcaVio") != null){
+ violations = Integer.valueOf(ModelElement.getValueByName(node, "tcaVio"));
+ }
+
+ // process service Configurations
+ JsonNode serviceConfigurationsNode = node.get(node.size() - 1).get("serviceConfigurations");
+ Iterator<JsonNode> itr = serviceConfigurationsNode.elements();
+ tcaThreshholds = new ArrayList<TcaThreshhold>();
+ while(itr.hasNext()) {
+ tcaThreshholds.add(new TcaThreshhold(itr.next()));
+ }
+ }
+
+ public String getTcaName() {
+ return tcaName;
+ }
+
+ public void setTcaName(String tcaName) {
+ this.tcaName = tcaName;
+ }
+
+ public String getTcaUuId() {
+ return tcaUuId;
+ }
+
+ public void setTcaUuId(String tcaUuId) {
+ this.tcaUuId = tcaUuId;
+ }
+
+ public String getNfNamingCode() {
+ return nfNamingCode;
+ }
+
+ public void setNfNamingCode(String nfNamingCode) {
+ this.nfNamingCode = nfNamingCode;
+ }
+
+ public String getTcaEnable() {
+ return tcaEnable;
+ }
+
+ public void setTcaEnable(String tcaEnable) {
+ this.tcaEnable = tcaEnable;
+ }
+
+ public String getPolicyId() {
+ return policyId;
+ }
+
+ public void setPolicyId(String policyId) {
+ this.policyId = policyId;
+ }
+
+ public Integer getInterval() {
+ return interval;
+ }
+
+ public void setInterval(Integer interval) {
+ this.interval = interval;
+ }
+
+ public String getSeverity() {
+ return severity;
+ }
+
+ public void setSeverity(String severity) {
+ this.severity = severity;
+ }
+
+ public Integer getViolations() {
+ return violations;
+ }
+
+ public void setViolations(Integer violations) {
+ this.violations = violations;
+ }
+
+ public List<TcaThreshhold> getTcaThreshholds() {
+ return tcaThreshholds;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/prop/TcaThreshhold.java b/src/main/java/org/onap/clamp/clds/model/prop/TcaThreshhold.java
new file mode 100644
index 000000000..47f2c6fd5
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/prop/TcaThreshhold.java
@@ -0,0 +1,76 @@
+package org.onap.clamp.clds.model.prop;
+
+import java.util.logging.Logger;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * Parse Tca Threshhold json properties.
+ *
+ * Example json: {"TCA_0lm6cix":{"Narra":[{"name":"tname","value":"Narra"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Polcicy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Critical"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_1",">","4"],["FIELDPATH_test_1","=","5"]]}],"Srini":[{"name":"tname","value":"Srini"},{"name":"tcaEnab","value":"on"},{"name":"tcaPol","value":"Policy1"},{"name":"tcaPolId","value":"1"},{"name":"tcaInt","value":"1"},{"name":"tcaSev","value":"Major"},{"name":"tcaVio","value":"1"},{"serviceConfigurations":[["FIELDPATH_test_2","=","3"],["FIELDPATH_test_1",">","2"]]}]}}
+ *
+ *
+ */
+public class TcaThreshhold {
+
+ private static final Logger logger = Logger.getLogger(TcaThreshhold.class.getName());
+
+ private String metric;
+ private String fieldPath;
+ private String operator;
+ private Integer threshhold;
+
+ /**
+ * Parse Tca Threshhold given json node
+ *
+ * @param node
+ */
+ public TcaThreshhold(JsonNode node) {
+
+ if(node.get(0) != null){
+ metric = node.get(0).asText();
+ }
+ if(node.get(1) != null){
+ operator = node.get(1).asText();
+ }
+ if(node.get(2) != null){
+ threshhold = Integer.valueOf(node.get(2).asText());
+ }
+ if(node.get(3) != null){
+ fieldPath = node.get(3).asText();
+ }
+ }
+
+ public String getMetric() {
+ return metric;
+ }
+
+ public void setMetric(String metric) {
+ this.metric = metric;
+ }
+
+ public String getFieldPath() {
+ return fieldPath;
+ }
+
+ public void setFieldPath(String fieldPath) {
+ this.fieldPath = fieldPath;
+ }
+
+ public String getOperator() {
+ return operator;
+ }
+
+ public void setOperator(String operator) {
+ this.operator = operator;
+ }
+
+ public Integer getThreshhold() {
+ return threshhold;
+ }
+
+ public void setThreshhold(Integer threshhold) {
+ this.threshhold = threshhold;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/model/refprop/RefProp.java b/src/main/java/org/onap/clamp/clds/model/refprop/RefProp.java
new file mode 100644
index 000000000..c81b6a770
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/model/refprop/RefProp.java
@@ -0,0 +1,139 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.model.refprop;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationContext;
+import org.springframework.core.io.Resource;
+
+import javax.annotation.PostConstruct;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.logging.Logger;
+
+/**
+ * Holds reference properties.
+ */
+public class RefProp {
+ private static final Logger logger = Logger.getLogger(RefProp.class.getName());
+
+ @Autowired
+ private ApplicationContext appContext;
+
+ private Properties prop;
+
+ @Value("${org.onap.clamp.config.files.cldsReference:'classpath:/clds/clds-reference.properties'}")
+ private String cldsReferenceValuesFile;
+
+ /**
+ * Load reference properties via null constructor
+ *
+ * @throws IOException
+ */
+ public RefProp() throws IOException {
+ }
+
+ @PostConstruct
+ public void loadConfig () throws IOException {
+ prop = new Properties();
+ Resource resource = appContext.getResource(cldsReferenceValuesFile);
+ prop.load(resource.getInputStream());
+ }
+
+ /**
+ * get property value
+ *
+ * @param key
+ * @return
+ */
+ public String getStringValue(String key) {
+ return prop.getProperty(key);
+ }
+
+ /**
+ * get property value for a combo key (key1 + "." + key2). If not found just use key1.
+ *
+ * @param key1
+ * @param key2
+ * @return
+ */
+ public String getStringValue(String key1, String key2) {
+ String value = getStringValue(key1 + "." + key2);
+ if (value == null || value.length() == 0) {
+ value = getStringValue(key1);
+ }
+ return value;
+ }
+
+ /**
+ * Return json as objects that can be updated
+ *
+ * @param key
+ * @return
+ * @throws IOException
+ */
+ public JsonNode getJsonTemplate(String key) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(getStringValue(key), JsonNode.class);
+ }
+
+ /**
+ * Return json as objects that can be updated. First try with combo key (key1 + "." + key2), otherwise default to just key1.
+ *
+ * @param key1
+ * @param key2
+ * @return
+ * @throws IOException
+ */
+ public JsonNode getJsonTemplate(String key1, String key2) throws IOException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ return objectMapper.readValue(getStringValue(key1, key2), JsonNode.class);
+ }
+
+ /**
+ * Get list of values for a property field containing json and a field/keyword within that json.
+ *
+ * @param fieldName
+ * @param value
+ * @return
+ * @throws IOException
+ */
+ public List<String> decodeToList(String fieldName, String value) throws IOException {
+ JsonNode decode = getJsonTemplate(fieldName);
+ Iterator<JsonNode> itr = decode.path(value).elements();
+ ArrayList<String> al = new ArrayList<>();
+ while (itr.hasNext()) {
+ JsonNode node = itr.next();
+ al.add(node.asText());
+ }
+ return al;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/CldsService.java b/src/main/java/org/onap/clamp/clds/service/CldsService.java
new file mode 100644
index 000000000..a0aadccb5
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/CldsService.java
@@ -0,0 +1,646 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+import com.att.ajsc.common.AjscService;
+import com.att.ajsc.filemonitor.AJSCPropertiesMap;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onap.clamp.clds.client.SdcCatalogServices;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.prop.ModelProperties;
+import org.onap.clamp.clds.model.refprop.RefProp;
+import org.onap.clamp.clds.transform.XslTransformer;
+import org.apache.commons.lang3.StringUtils;
+import org.camunda.bpm.engine.RuntimeService;
+import org.camunda.bpm.engine.runtime.ProcessInstance;
+import org.jboss.resteasy.spi.BadRequestException;
+import org.onap.clamp.clds.model.*;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.ApplicationContext;
+import org.springframework.core.io.Resource;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Service to save and retrieve the CLDS model attributes.
+ */
+@AjscService
+@Path("/clds")
+public class CldsService extends SecureServiceBase {
+
+ @Autowired
+ private ApplicationContext appContext;
+
+ private static final Logger logger = LoggerFactory.getLogger(CldsService.class);
+
+ @Value("${CLDS_PERMISSION_TYPE_CL:org.onap.clamp.clds.cl}")
+ private static String CLDS_PERMISSION_TYPE_CL;
+
+ @Value("${CLDS_PERMISSION_TYPE_CL_MANAGE:org.onap.clamp.clds.cl.manage}")
+ private static String CLDS_PERMISSION_TYPE_CL_MANAGE;
+
+ @Value("${CLDS_PERMISSION_TYPE_CL_EVENT:/META-INF/securityFilterRules.json}")
+ private static String CLDS_PERMISSION_TYPE_CL_EVENT;
+
+ @Value("${CLDS_PERMISSION_TYPE_FILTER_VF:/META-INF/securityFilterRules.json}")
+ private static String CLDS_PERMISSION_TYPE_FILTER_VF;
+
+ @Value("${CLDS_PERMISSION_INSTANCE:/META-INF/securityFilterRules.json}")
+ private static String CLDS_PERMISSION_INSTANCE;
+
+ private static final SecureServicePermission PERMISSION_READ_CL = SecureServicePermission.create(CLDS_PERMISSION_TYPE_CL, CLDS_PERMISSION_INSTANCE, "read");
+
+ private static final SecureServicePermission PERMISSION_UPDATE_CL = SecureServicePermission.create(CLDS_PERMISSION_TYPE_CL, CLDS_PERMISSION_INSTANCE, "update");
+
+ @Value("${org.onap.clamp.config.files.globalClds:classpath:/clds/globalClds.properties}")
+ private String globalClds;
+ private Properties globalCldsProperties;
+
+ @Autowired
+ private CldsDao cldsDao;
+ @Autowired
+ private RuntimeService runtimeService;
+ @Autowired
+ private XslTransformer cldsBpmnTransformer;
+
+ @Autowired
+ private RefProp refProp;
+
+ @Autowired
+ private SdcCatalogServices asdcCatalogServices;
+ //
+
+ public CldsService() {
+ }
+
+ public CldsService(RefProp refProp) {
+ this.refProp = refProp;
+ }
+
+ /**
+ * REST service that retrieves BPMN for a CLDS model name from the database.
+ * This is subset of the json getModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param modelName
+ * @return bpmn xml text - content of bpmn given name
+ */
+ @GET
+ @Path("/model/bpmn/{modelName}")
+ @Produces(MediaType.TEXT_XML)
+ public String getBpmnXml(@PathParam("modelName") String modelName) {
+ isAuthorized(PERMISSION_READ_CL);
+ logger.info("GET bpmnText for modelName={}", modelName);
+ CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
+ return model.getBpmnText();
+ }
+
+ /**
+ * REST service that saves BPMN for a CLDS model by name in the database.
+ * This is subset of the json putModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param modelName
+ */
+ @PUT
+ @Path("/model/bpmn/{modelName}")
+ @Consumes(MediaType.TEXT_XML)
+ public String putBpmnXml(@PathParam("modelName") String modelName, String bpmnText) {
+ isAuthorized(PERMISSION_UPDATE_CL);
+ logger.info("PUT bpmnText for modelName={}", modelName);
+ logger.info("PUT bpmnText={}", bpmnText);
+ CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
+ cldsModel.setBpmnText(bpmnText);
+ cldsModel.save(cldsDao, getUserid());
+ return "wrote bpmnText for modelName=" + modelName;
+ }
+
+ /**
+ * REST service that retrieves image for a CLDS model name from the database.
+ * This is subset of the json getModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param modelName
+ * @return image xml text - content of image given name
+ */
+ @GET
+ @Path("/model/image/{modelName}")
+ @Produces(MediaType.TEXT_XML)
+ public String getImageXml(@PathParam("modelName") String modelName) {
+ isAuthorized(PERMISSION_READ_CL);
+ logger.info("GET imageText for modelName={}", modelName);
+ CldsModel model = CldsModel.retrieve(cldsDao, modelName, false);
+ return model.getImageText();
+ }
+
+ /**
+ * REST service that saves image for a CLDS model by name in the database.
+ * This is subset of the json putModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param modelName
+ */
+ @PUT
+ @Path("/model/image/{modelName}")
+ @Consumes(MediaType.TEXT_XML)
+ public String putImageXml(@PathParam("modelName") String modelName, String imageText) {
+ isAuthorized(PERMISSION_UPDATE_CL);
+ logger.info("PUT iamgeText for modelName={}", modelName);
+ logger.info("PUT imageText={}", imageText);
+ CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, true);
+ cldsModel.setImageText(imageText);
+ cldsModel.save(cldsDao, getUserid());
+ return "wrote imageText for modelName=" + modelName;
+ }
+
+ /**
+ * REST service that retrieves a CLDS model by name from the database.
+ *
+ * @param modelName
+ * @return clds model - clds model for the given model name
+ * @throws NotAuthorizedException
+ */
+ @GET
+ @Path("/model/{modelName}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public CldsModel getModel(@PathParam("modelName") String modelName) throws NotAuthorizedException {
+ isAuthorized(PERMISSION_READ_CL);
+ logger.debug("GET model for modelName={}", modelName);
+ CldsModel cldsModel = CldsModel.retrieve(cldsDao, modelName, false);
+ isAuthorizedForVf(cldsModel);
+ return cldsModel;
+ }
+
+ /**
+ * REST service that saves a CLDS model by name in the database.
+ *
+ * @param modelName
+ * @throws TransformerException
+ * @throws TransformerConfigurationException
+ */
+ @PUT
+ @Path("/model/{modelName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public CldsModel putModel(@PathParam("modelName") String modelName, CldsModel cldsModel) throws TransformerException {
+ isAuthorized(PERMISSION_UPDATE_CL);
+ isAuthorizedForVf(cldsModel);
+ logger.info("PUT model for modelName={}", modelName);
+ logger.info("PUT bpmnText={}", cldsModel.getBpmnText());
+ logger.info("PUT propText={}", cldsModel.getPropText());
+ logger.info("PUT imageText={}", cldsModel.getImageText());
+ cldsModel.setName(modelName);
+
+ if (cldsModel.getTemplateName() != null) {
+ CldsTemplate template = cldsDao.getTemplate(cldsModel.getTemplateName());
+ if (template != null) {
+ cldsModel.setTemplateId(template.getId());
+ cldsModel.setDocText(template.getPropText());
+ cldsModel.setDocId(template.getPropId());
+ }
+ }
+ cldsModel.save(cldsDao, getUserid());
+ return cldsModel;
+ }
+
+ /**
+ * REST service that retrieves a list of CLDS model names.
+ *
+ * @return model names in JSON
+ */
+ @GET
+ @Path("/model-names")
+ @Produces(MediaType.APPLICATION_JSON)
+ public List<ValueItem> getModelNames() {
+// isAuthorized(PERMISSION_READ_CL);
+ logger.info("GET list of model names");
+ return cldsDao.getBpmnNames();
+ }
+
+ /**
+ * REST service that saves and processes an action for a CLDS model by name.
+ *
+ * @param action
+ * @param modelName
+ * @param test
+ * @param model
+ * @return
+ * @throws TransformerConfigurationException
+ * @throws TransformerException
+ * @throws IOException
+ * @throws JsonProcessingException
+ * @throws NotAuthorizedException
+ */
+ @PUT
+ @Path("/action/{action}/{modelName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public CldsModel putModelAndProcessAction(@PathParam("action") String action, @PathParam("modelName") String modelName, @QueryParam("test") String test, CldsModel model) throws TransformerException, NotAuthorizedException, IOException {
+ String actionCd = action.toUpperCase();
+ SecureServicePermission permisionManage = SecureServicePermission.create(CLDS_PERMISSION_TYPE_CL_MANAGE, CLDS_PERMISSION_INSTANCE, actionCd);
+ isAuthorized(permisionManage);
+ isAuthorizedForVf(model);
+ String userid = getUserid();
+ String actionStateCd = CldsEvent.ACTION_STATE_INITIATED;
+ String processDefinitionKey = "clds-process-action-wf";
+
+ logger.info("PUT actionCd={}", actionCd);
+ logger.info("PUT actionStateCd={}", actionStateCd);
+ logger.info("PUT processDefinitionKey={}", processDefinitionKey);
+ logger.info("PUT modelName={}", modelName);
+ logger.info("PUT test={}", test);
+ logger.info("PUT bpmnText={}", model.getBpmnText());
+ logger.info("PUT propText={}", model.getPropText());
+ logger.info("PUT userid={}", userid);
+
+ if (model.getTemplateName() != null) {
+ CldsTemplate template = cldsDao.getTemplate(model.getTemplateName());
+ if (template != null) {
+ model.setTemplateId(template.getId());
+ model.setDocText(template.getPropText());
+ model.setDocId(template.getPropId());
+ }
+ }
+ // save model to db
+ model.setName(modelName);
+ 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);
+ logger.info("PUT bpmnJson={}", bpmnJson);
+
+ boolean isTest = false;
+ if (test != null && test.equalsIgnoreCase("true")) {
+ isTest = true;
+ } else {
+ // if action.test.override is true, then any action will be marked as test=true (even if incoming action request had test=false); otherwise, test flag will be unchanged on the action request
+ String actionTestOverride = refProp.getStringValue("action.test.override");
+ if (actionTestOverride != null && actionTestOverride.equalsIgnoreCase("true")) {
+ logger.info("PUT actionTestOverride={}", actionTestOverride);
+ logger.info("PUT override test indicator and setting it to true");
+ isTest = true;
+ }
+ }
+ logger.info("PUT isTest={}", isTest);
+
+
+ boolean isInsertTestEvent = false;
+ String insertTestEvent = refProp.getStringValue("action.insert.test.event");
+ if (insertTestEvent != null && insertTestEvent.equalsIgnoreCase("true")) {
+ isInsertTestEvent = true;
+ }
+ logger.info("PUT isInsertTestEvent={}", isInsertTestEvent);
+
+
+ // determine if requested action is permitted
+ model.validateAction(actionCd);
+
+ // input variables to camunda process
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("actionCd", actionCd);
+ variables.put("modelProp", prop);
+ variables.put("modelBpmnProp", bpmnJson);
+ variables.put("modelName", modelName);
+ variables.put("controlName", controlName);
+ variables.put("docText", docText);
+ variables.put("isTest", isTest);
+ variables.put("userid", userid);
+ variables.put("isInsertTestEvent", isInsertTestEvent);
+
+ // start camunda process
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);
+
+ // log process info
+ logger.info("Started processDefinitionId={}, processInstanceId={}", pi.getProcessDefinitionId(), pi.getProcessInstanceId());
+
+ // refresh model info from db (get fresh event info)
+ return CldsModel.retrieve(cldsDao, modelName, false);
+ }
+
+ /**
+ * REST service that accepts events for a model.
+ *
+ * @param test
+ * @param dcaeEvent
+ * @throws BadRequestException
+ */
+ @POST
+ @Path("/dcae/event")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public String postDcaeEvent(@QueryParam("test") String test, DcaeEvent dcaeEvent) throws BadRequestException {
+ String userid = null;
+ // TODO: allow auth checking to be turned off by removing the permission type property
+ if (CLDS_PERMISSION_TYPE_CL_EVENT != null && CLDS_PERMISSION_TYPE_CL_EVENT.length() > 0) {
+ SecureServicePermission permissionEvent = SecureServicePermission.create(CLDS_PERMISSION_TYPE_CL_EVENT, CLDS_PERMISSION_INSTANCE, dcaeEvent.getEvent());
+ isAuthorized(permissionEvent);
+ userid = getUserid();
+ }
+
+ boolean isTest = false;
+ if (test != null && test.equalsIgnoreCase("true")) {
+ isTest = true;
+ }
+
+ int instanceCount = 0;
+ if (dcaeEvent.getInstances() != null) {
+ instanceCount = dcaeEvent.getInstances().size();
+ }
+ String msgInfo = "event=" + dcaeEvent.getEvent() + " serviceUUID=" + dcaeEvent.getServiceUUID() + " resourceUUID=" + dcaeEvent.getResourceUUID() + " artifactName=" + dcaeEvent.getArtifactName() + " instance count=" + instanceCount + " isTest=" + isTest;
+ logger.info("POST dcae event {}", msgInfo);
+
+ if (isTest) {
+ logger.warn("Ignorning test event from DCAE");
+ } else {
+ if (DcaeEvent.EVENT_DEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent())) {
+ CldsModel.insertModelInstance(cldsDao, dcaeEvent, userid);
+ } else {
+ CldsEvent.insEvent(cldsDao, dcaeEvent.getControlName(), userid, dcaeEvent.getCldsActionCd(), CldsEvent.ACTION_STATE_RECEIVED, null);
+ }
+ // EVENT_UNDEPLOYMENT is defunct - DCAE Proxy will not undeploy individual instances. It will send an empty list of
+ // deployed instances to indicate all have been removed. Or it will send an updated list to indicate those that
+ // are still deployed with any not on the list considered undeployed.
+ //else if(DcaeEvent.EVENT_UNDEPLOYMENT.equalsIgnoreCase(dcaeEvent.getEvent()))
+ //{
+ // CldsModel.removeModelInstance(cldsDao, dcaeEvent);
+ //}
+ }
+
+ return msgInfo;
+ }
+
+ /**
+ * REST service that retrieves asdc services
+ *
+ * @throws Exception
+ */
+ @GET
+ @Path("/asdc/services")
+ @Produces(MediaType.APPLICATION_JSON)
+ public String getAsdcServices() throws Exception {
+ String retStr;
+ try {
+ String responseStr = asdcCatalogServices.getAsdcServicesInformation(null);
+ retStr = createUiServiceFormatJson(responseStr);
+ } catch (Exception e) {
+ logger.info("{} {}", e.getClass().getName(), e.getMessage());
+ throw e;
+ }
+ logger.info("value of asdcServices : {}", retStr);
+ return retStr;
+ }
+
+ /**
+ * REST service that retrieves total properties required by UI
+ *
+ * @throws Exception
+ */
+ @GET
+ @Path("/properties")
+ @Produces(MediaType.APPLICATION_JSON)
+ public String getAsdcProperties() throws Exception {
+ return createPropertiesObjectByUUID(getGlobalCldsString(), "{}");
+ }
+
+ /**
+ * REST service that retrieves total properties by using invariantUUID based on refresh and non refresh
+ *
+ * @throws Exception
+ */
+ @GET
+ @Path("/properties/{serviceInvariantUUID}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public String getAsdcPropertiesByServiceUUIDForRefresh(@PathParam("serviceInvariantUUID") String serviceInvariantUUID, @DefaultValue("false") @QueryParam("refresh") String refresh) throws Exception {
+ CldsServiceData cldsServiceData = new CldsServiceData();
+ cldsServiceData.setServiceInvariantUUID(serviceInvariantUUID);
+
+ boolean isCldsAsdcDataExpired = true;
+ // To getcldsService information from database cache using invariantUUID only when refresh = false
+ if (refresh != null && refresh.equalsIgnoreCase("false")) {
+ cldsServiceData = cldsServiceData.getCldsServiceCache(cldsDao, serviceInvariantUUID);
+ // If cldsService is available in database Cache , verify is data expired or not
+ if (cldsServiceData != null) {
+ isCldsAsdcDataExpired = asdcCatalogServices.isCldsAsdcCacheDataExpired(cldsServiceData);
+ }
+ }
+ // If user Requested for refresh or database cache expired , get all data from asdc api.
+ if ((refresh != null && refresh.equalsIgnoreCase("true")) || isCldsAsdcDataExpired) {
+ cldsServiceData = asdcCatalogServices.getCldsServiceDataWithAlarmConditions(serviceInvariantUUID);
+ CldsDBServiceCache cldsDBServiceCache = asdcCatalogServices.getCldsDBServiceCacheUsingCldsServiceData(cldsServiceData);
+ if (cldsDBServiceCache != null && cldsDBServiceCache.getInvariantId() != null && cldsDBServiceCache.getServiceId() != null) {
+ cldsServiceData.setCldsServiceCache(cldsDao, cldsDBServiceCache);
+ }
+ }
+
+ // filter out VFs the user is not authorized for
+ cldsServiceData.filterVfs(this);
+
+ // format retrieved data into properties json
+ return asdcCatalogServices.createPropertiesObjectByUUID(getGlobalCldsString(), cldsServiceData);
+ }
+
+ /**
+ * Determine if the user is authorized for a particular VF by its invariant UUID.
+ *
+ * @param vfInvariantUuid
+ * @throws NotAuthorizedException
+ * @return
+ */
+ public boolean isAuthorizedForVf(String vfInvariantUuid) throws NotAuthorizedException {
+ if (CLDS_PERMISSION_TYPE_FILTER_VF != null && CLDS_PERMISSION_TYPE_FILTER_VF.length() > 0) {
+ SecureServicePermission permission = SecureServicePermission.create(CLDS_PERMISSION_TYPE_FILTER_VF, CLDS_PERMISSION_INSTANCE, vfInvariantUuid);
+ return isAuthorized(permission);
+ } else {
+ // if CLDS_PERMISSION_TYPE_FILTER_VF property is not provided, then VF filtering is turned off
+ logger.warn("VF filtering turned off");
+ return true;
+ }
+ }
+
+ /**
+ * Determine if the user is authorized for a particular VF by its invariant UUID.
+ * If not authorized, then NotAuthorizedException is thrown.
+ *
+ * @param model
+ * @return
+ */
+ private boolean isAuthorizedForVf(CldsModel model) throws NotAuthorizedException {
+ String vf = ModelProperties.getVf(model);
+ if (vf == null || vf.length() == 0) {
+ logger.info("VF not found in model");
+ return true;
+ } else {
+ return isAuthorizedForVf(vf);
+ }
+ }
+
+ private String createUiServiceFormatJson(String responseStr) throws IOException {
+ if (StringUtils.isBlank(responseStr)) {
+ return "";
+ }
+ ObjectMapper objectMapper = new ObjectMapper();
+ List<CldsAsdcServiceInfo> rawList = objectMapper.readValue(responseStr, objectMapper.getTypeFactory().constructCollectionType(List.class, CldsAsdcServiceInfo.class));
+ ObjectNode invariantIdServiceNode = objectMapper.createObjectNode();
+ ObjectNode serviceNode = objectMapper.createObjectNode();
+ logger.info("value of cldsserviceiNfolist: {}", rawList);
+ if (rawList != null && rawList.size() > 0) {
+ List<CldsAsdcServiceInfo> cldsAsdcServiceInfoList = asdcCatalogServices.removeDuplicateServices(rawList);
+
+ for (CldsAsdcServiceInfo currCldsAsdcServiceInfo : cldsAsdcServiceInfoList) {
+ if (currCldsAsdcServiceInfo != null) {
+ invariantIdServiceNode.put(currCldsAsdcServiceInfo.getInvariantUUID(), currCldsAsdcServiceInfo.getName());
+ }
+ }
+ serviceNode.putPOJO("service", invariantIdServiceNode);
+ }
+ return serviceNode.toString();
+ }
+
+ private String createPropertiesObjectByUUID(String globalProps, String cldsResponseStr) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ CldsAsdcServiceDetail cldsAsdcServiceDetail = mapper.readValue(cldsResponseStr, CldsAsdcServiceDetail.class);
+ ObjectNode globalPropsJson = null;
+ if (cldsAsdcServiceDetail != null && cldsAsdcServiceDetail.getUuid() != null) {
+ /**
+ * to create json with vf, alarm and locations
+ */
+ ObjectNode serviceObjectNode = createEmptyVfAlarmObject(mapper);
+ ObjectNode vfObjectNode = mapper.createObjectNode();
+
+ /**
+ * to create json with vf and vfresourceId
+ */
+ createVfObjectNode(vfObjectNode, mapper, cldsAsdcServiceDetail.getResources());
+ serviceObjectNode.putPOJO(cldsAsdcServiceDetail.getInvariantUUID(), vfObjectNode);
+ ObjectNode byServiceBasicObjetNode = mapper.createObjectNode();
+ byServiceBasicObjetNode.putPOJO("byService", serviceObjectNode);
+
+ /**
+ * to create json with VFC Node
+ */
+ ObjectNode emptyvfcobjectNode = createByVFCObjectNode(mapper, cldsAsdcServiceDetail.getResources());
+ byServiceBasicObjetNode.putPOJO("byVf", emptyvfcobjectNode);
+ globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
+ globalPropsJson.putPOJO("shared", byServiceBasicObjetNode);
+ logger.info("valuie of objNode: {}", globalPropsJson);
+ } else {
+ /**
+ * to create json with total properties when no serviceUUID passed
+ */
+ globalPropsJson = (ObjectNode) mapper.readValue(globalProps, JsonNode.class);
+ }
+ return globalPropsJson.toString();
+ }
+
+ private ObjectNode createEmptyVfAlarmObject(ObjectMapper mapper) {
+ ObjectNode emptyObjectNode = mapper.createObjectNode();
+ emptyObjectNode.put("", "");
+ ObjectNode vfObjectNode = mapper.createObjectNode();
+ vfObjectNode.putPOJO("vf", emptyObjectNode);
+ vfObjectNode.putPOJO("location", emptyObjectNode);
+ vfObjectNode.putPOJO("alarmCondition", emptyObjectNode);
+ ObjectNode emptyServiceObjectNode = mapper.createObjectNode();
+ emptyServiceObjectNode.putPOJO("", vfObjectNode);
+ return emptyServiceObjectNode;
+ }
+
+ private void createVfObjectNode(ObjectNode vfObjectNode2, ObjectMapper mapper, List<CldsAsdcResource> rawCldsAsdcResourceList) throws IOException {
+ ObjectNode vfNode = mapper.createObjectNode();
+ vfNode.put("", "");
+
+ // To remove repeated resource instance name from resourceInstanceList
+ List<CldsAsdcResource> cldsAsdcResourceList = asdcCatalogServices.removeDuplicateAsdcResourceInstances(rawCldsAsdcResourceList);
+ /**
+ * Creating vf resource node using cldsAsdcResource Object
+ */
+ if (cldsAsdcResourceList != null && cldsAsdcResourceList.size() > 0) {
+ for (CldsAsdcResource cldsAsdcResource : cldsAsdcResourceList) {
+ if (cldsAsdcResource != null && cldsAsdcResource.getResoucreType() != null && cldsAsdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+ vfNode.put(cldsAsdcResource.getResourceUUID(), cldsAsdcResource.getResourceName());
+ }
+ }
+ }
+ vfObjectNode2.putPOJO("vf", vfNode);
+ String locationStringValue = refProp.getStringValue("ui.location.default");
+ String alarmStringValue = refProp.getStringValue("ui.alarm.default");
+
+ /**
+ * creating location json object using properties file value
+ */
+ ObjectNode locationJsonNode = (ObjectNode) mapper.readValue(locationStringValue, JsonNode.class);
+ vfObjectNode2.putPOJO("location", locationJsonNode);
+
+ /**
+ * creating alarm json object using properties file value
+ */
+ logger.info("value of alarm: {}", alarmStringValue);
+ ObjectNode alarmStringJsonNode = (ObjectNode) mapper.readValue(alarmStringValue, JsonNode.class);
+ vfObjectNode2.putPOJO("alarmCondition", alarmStringJsonNode);
+ }
+
+ private ObjectNode createByVFCObjectNode(ObjectMapper mapper, List<CldsAsdcResource> cldsAsdcResourceList) {
+ ObjectNode emptyObjectNode = mapper.createObjectNode();
+ ObjectNode emptyvfcobjectNode = mapper.createObjectNode();
+ ObjectNode vfCObjectNode = mapper.createObjectNode();
+ vfCObjectNode.putPOJO("vfC", emptyObjectNode);
+ ObjectNode subVfCObjectNode = mapper.createObjectNode();
+ subVfCObjectNode.putPOJO("vfc", emptyObjectNode);
+ if (cldsAsdcResourceList != null && cldsAsdcResourceList.size() > 0) {
+ for (CldsAsdcResource cldsAsdcResource : cldsAsdcResourceList) {
+ if (cldsAsdcResource != null && cldsAsdcResource.getResoucreType() != null && cldsAsdcResource.getResoucreType().equalsIgnoreCase("VF")) {
+ vfCObjectNode.putPOJO(cldsAsdcResource.getResourceUUID(), subVfCObjectNode);
+ }
+ }
+ }
+ emptyvfcobjectNode.putPOJO("", vfCObjectNode);
+ return emptyvfcobjectNode;
+ }
+
+ private String getGlobalCldsString() throws Exception {
+ if (null == globalCldsProperties) {
+ globalCldsProperties = new Properties();
+ globalCldsProperties.load(appContext.getResource(globalClds).getInputStream());
+ }
+ return (String) globalCldsProperties.get("globalCldsProps");
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java
new file mode 100644
index 000000000..0ffa955c4
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/CldsTemplateService.java
@@ -0,0 +1,275 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+import com.att.ajsc.common.AjscService;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onap.clamp.clds.dao.CldsDao;
+import org.onap.clamp.clds.model.CldsTemplate;
+import org.onap.clamp.clds.model.ValueItem;
+import org.onap.clamp.clds.model.prop.ModelBpmn;
+import org.onap.clamp.clds.transform.XslTransformer;
+import org.camunda.bpm.engine.RuntimeService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+import javax.xml.transform.TransformerException;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+/**
+ * Service to save and retrieve the CLDS model attributes.
+ */
+@AjscService
+@Path("/cldsTempate")
+public class CldsTemplateService extends SecureServiceBase {
+
+ private static final Logger logger = LoggerFactory.getLogger(CldsTemplateService.class);
+
+ private static final String collectorKey = "Collector";
+ private static final String stringMatchKey = "StringMatch";
+ private static final String policyKey = "Policy";
+
+ private static final String CLDS_PERMISSION_TYPE_TEMPLATE = System.getProperty("CLDS_PERMISSION_TYPE_TEMPLATE");
+ private static final String CLDS_PERMISSION_INSTANCE = System.getProperty("CLDS_PERMISSION_INSTANCE");
+
+ private static final SecureServicePermission PERMISSION_READ_TEMPLATE = SecureServicePermission.create(CLDS_PERMISSION_TYPE_TEMPLATE, CLDS_PERMISSION_INSTANCE, "read");
+ private static final SecureServicePermission PERMISSION_UPDATE_TEMPLATE = SecureServicePermission.create(CLDS_PERMISSION_TYPE_TEMPLATE, CLDS_PERMISSION_INSTANCE, "update");
+
+ @Autowired
+ private CldsDao cldsDao;
+ @Autowired
+ private RuntimeService runtimeService;
+ @Autowired
+ private XslTransformer cldsBpmnTransformer;
+
+ private static String userid;
+
+ /**
+ * REST service that retrieves BPMN for a CLDS template name from the database.
+ * This is subset of the json getModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param templateName
+ * @return bpmn xml text - content of bpmn given name
+ */
+ @GET
+ @Path("/template/bpmn/{templateName}")
+ @Produces(MediaType.TEXT_XML)
+ public String getBpmnTemplate(@PathParam("templateName") String templateName) {
+ isAuthorized(PERMISSION_READ_TEMPLATE);
+ logger.info("GET bpmnText for templateName=" + templateName);
+ CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
+ return template.getBpmnText();
+ }
+
+ /**
+ * REST service that saves BPMN for a CLDS template by name in the database.
+ * This is subset of the json putModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param templateName
+ * @param bpmnText
+ */
+ @PUT
+ @Path("/template/bpmn/{templateName}")
+ @Consumes(MediaType.TEXT_XML)
+ public String putBpmnTemplateXml(@PathParam("templateName") String templateName, String bpmnText) {
+ isAuthorized(PERMISSION_UPDATE_TEMPLATE);
+ logger.info("PUT bpmnText for templateName=" + templateName);
+ logger.info("PUT bpmnText=" + bpmnText);
+ CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
+ cldsTemplate.setBpmnText(bpmnText);
+ cldsTemplate.save(cldsDao, userid);
+ return "wrote bpmnText for templateName=" + templateName;
+ }
+
+ /**
+ * REST service that retrieves image for a CLDS template name from the database.
+ * This is subset of the json getModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param templateName
+ * @return image xml text - content of image given name
+ */
+ @GET
+ @Path("/template/image/{templateName}")
+ @Produces(MediaType.TEXT_XML)
+ public String getImageXml(@PathParam("templateName") String templateName) {
+ isAuthorized(PERMISSION_READ_TEMPLATE);
+ logger.info("GET imageText for templateName=" + templateName);
+ CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
+ return template.getImageText();
+ }
+
+ /**
+ * REST service that saves image for a CLDS template by name in the database.
+ * This is subset of the json putModel.
+ * This is only expected to be used for testing purposes, not by the UI.
+ *
+ * @param templateName
+ * @param imageText
+ */
+ @PUT
+ @Path("/template/image/{templateName}")
+ @Consumes(MediaType.TEXT_XML)
+ public String putImageXml(@PathParam("templateName") String templateName, String imageText) {
+ isAuthorized(PERMISSION_UPDATE_TEMPLATE);
+ logger.info("PUT iamgeText for modelName=" + templateName);
+ logger.info("PUT imageText=" + imageText);
+ CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
+ cldsTemplate.setImageText(imageText);
+ cldsTemplate.save(cldsDao, userid);
+ return "wrote imageText for modelName=" + templateName;
+ }
+
+ /**
+ * REST service that retrieves a CLDS template by name from the database.
+ *
+ * @param templateName
+ * @return clds template - clds template for the given template name
+ */
+ @GET
+ @Path("/template/{templateName}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public CldsTemplate getTemplate(@PathParam("templateName") String templateName) {
+ isAuthorized(PERMISSION_READ_TEMPLATE);
+ logger.info("GET model for templateName=" + templateName);
+ return CldsTemplate.retrieve(cldsDao, templateName, false);
+ }
+
+ /**
+ * REST service that saves a CLDS template by name in the database.
+ *
+ * @param templateName
+ * @throws IOException
+ * @throws JsonMappingException
+ * @throws JsonParseException
+ */
+ @PUT
+ @Path("/template/{templateName}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public CldsTemplate putTemplate(@PathParam("templateName") String templateName, CldsTemplate cldsTemplate) throws TransformerException, IOException {
+ isAuthorized(PERMISSION_UPDATE_TEMPLATE);
+ logger.info("PUT Template for templateName=" + templateName);
+ logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText());
+ logger.info("PUT propText=" + cldsTemplate.getPropText());
+ logger.info("PUT imageText=" + cldsTemplate.getImageText());
+ cldsTemplate.setName(templateName);
+ String bpmnText = cldsTemplate.getBpmnText();
+ String imageText = cldsTemplate.getImageText();
+ String propText = cldsTemplate.getPropText();
+ Map<String, String> newBpmnIdsMap = getNewBpmnIdsMap(bpmnText, cldsTemplate.getPropText());
+ for (String currBpmnId : newBpmnIdsMap.keySet()) {
+ if (currBpmnId != null && newBpmnIdsMap.get(currBpmnId) != null) {
+ bpmnText = bpmnText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
+ imageText = imageText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
+ propText = propText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
+ }
+ }
+ cldsTemplate.setBpmnText(bpmnText);
+ cldsTemplate.setImageText(imageText);
+ cldsTemplate.setPropText(propText);
+ logger.info(" bpmnText : " + cldsTemplate.getBpmnText());
+ logger.info(" Image Text : " + cldsTemplate.getImageText());
+ logger.info(" Prop Text : " + cldsTemplate.getPropText());
+ cldsTemplate.save(cldsDao, userid);
+ return cldsTemplate;
+ }
+
+ /**
+ * REST service that retrieves a list of CLDS template names.
+ *
+ * @return template names in JSON
+ */
+ @GET
+ @Path("/template-names")
+ @Produces(MediaType.APPLICATION_JSON)
+ public List<ValueItem> getTemplateNames() {
+ isAuthorized(PERMISSION_READ_TEMPLATE);
+ logger.info("GET list of template names");
+ return cldsDao.getTemplateNames();
+ }
+
+
+ private Map<String, String> getNewBpmnIdsMap(String bpmnText, String propText) throws TransformerException, IOException {
+ /**
+ * Test sample code start
+ */
+ String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmnText);
+ ModelBpmn templateBpmn = ModelBpmn.create(bpmnJson);
+ List<String> bpmnElementIds = templateBpmn.getBpmnElementIds();
+ logger.info("value of elementIds:" + bpmnElementIds);
+ logger.info("value of prop text:" + propText);
+ Map<String, String> bpmnIoIdsMap = new HashMap<>();
+ if (bpmnElementIds != null && bpmnElementIds.size() > 0) {
+ ObjectMapper objectMapper = new ObjectMapper();
+ ObjectNode root = objectMapper.readValue(propText, ObjectNode.class);
+ Iterator<Entry<String, JsonNode>> entryItr = root.fields();
+ while (entryItr.hasNext()) {
+ // process the entry
+ Entry<String, JsonNode> entry = entryItr.next();
+ String keyPropName = entry.getKey();
+ for (String currElementId : bpmnElementIds) {
+ if (keyPropName != null && keyPropName.equalsIgnoreCase(currElementId)) {
+ ArrayNode arrayNode = (ArrayNode) entry.getValue();
+ // process each id/from object, like: {"id":"Collector_11r50j1", "from":"StartEvent_1"}
+ for (JsonNode anArrayNode : arrayNode) {
+ ObjectNode node = (ObjectNode) anArrayNode;
+ String valueNode = node.get("value").asText();
+ logger.info("value of node:" + valueNode);
+ if (keyPropName.startsWith(collectorKey)) {
+ valueNode = collectorKey + "_" + valueNode;
+ } else if (keyPropName.startsWith(stringMatchKey)) {
+ valueNode = stringMatchKey + "_" + valueNode;
+ } else if (keyPropName.startsWith(policyKey)) {
+ valueNode = policyKey + "_" + valueNode;
+ }
+ bpmnIoIdsMap.put(keyPropName, valueNode);
+ }
+ break;
+ }
+ }
+ }
+ }
+ logger.info("value of hashmap:" + bpmnIoIdsMap);
+ /**
+ * Test sample code end
+ */
+ return bpmnIoIdsMap;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/LogService.java b/src/main/java/org/onap/clamp/clds/service/LogService.java
new file mode 100644
index 000000000..1c3d9dc67
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/LogService.java
@@ -0,0 +1,38 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+public interface LogService {
+
+ String logMessage(String logMessageText, String javamail, String springmail, String commonsmail);
+
+ String postLogMessage(String histEventList);
+
+ String createLogMessage(String startTime, String endTime, String serviceName);
+
+ String createLogMessageUsingHistory(String procInstId, String histEventList);
+
+ String CreateHistLog(String procInstId);
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/LogServiceImpl.java b/src/main/java/org/onap/clamp/clds/service/LogServiceImpl.java
new file mode 100644
index 000000000..e7ee93a40
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/LogServiceImpl.java
@@ -0,0 +1,276 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+import com.att.ajsc.camunda.core.AttCamundaHistoryEvent;
+import com.att.ajsc.camunda.core.AttCamundaService;
+import com.att.ajsc.logging.AjscEelfManager;
+import com.att.eelf.configuration.EELFLogger;
+import com.google.gson.Gson;
+import org.onap.clamp.clds.common.LogMessages;
+import org.apache.commons.mail.Email;
+import org.apache.commons.mail.SimpleEmail;
+import org.apache.cxf.jaxrs.ext.MessageContext;
+import org.camunda.bpm.engine.HistoryService;
+import org.camunda.bpm.engine.RuntimeService;
+import org.camunda.bpm.engine.history.HistoricActivityInstance;
+import org.camunda.bpm.engine.impl.history.event.HistoricActivityInstanceEventEntity;
+import org.camunda.bpm.engine.runtime.ProcessInstance;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.mail.MailException;
+import org.springframework.mail.SimpleMailMessage;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.stereotype.Service;
+
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import javax.ws.rs.core.Context;
+import java.util.*;
+
+@Service
+public class LogServiceImpl implements LogService {
+ private static final EELFLogger logger = AjscEelfManager.getInstance().getLogger(LogServiceImpl.class);
+
+ @Autowired
+ private RuntimeService runtimeService;
+
+ @Autowired
+ private HistoryService historyService;
+
+ @Context
+ private MessageContext context;
+
+ public void setRuntimeService(RuntimeService runtimeService) {
+ this.runtimeService = runtimeService;
+ }
+
+ public LogServiceImpl() {
+ // needed for instantiation
+ }
+
+ @Override
+ public String logMessage(String logMessageText, String javamail, String springmail, String commonsmail) {
+ logger.info("Value of contexxt : " + context);
+ String convId = null;
+ if (context != null) {
+ convId = context.getHttpServletRequest().getHeader("X-CSI-ConversationId");
+ if (convId == null) {
+ convId = (String) context.getHttpServletRequest().getAttribute("X-CSI-ConversationId");
+ }
+ context.getHttpServletRequest().setAttribute("CALL_TYPE", "Testing");
+ AttCamundaService.setHttpRequest(context.getHttpServletRequest());
+ }
+ // input variables to example camunda process
+ Map<String, Object> variables = new HashMap<>();
+ variables.put("logMessageText", logMessageText);
+ if (convId != null) {
+ variables.put("conversationId", convId);
+ }
+
+ // BEGIN - added for send mail testing
+ // also added the following to the method signature: , @QueryParam("javamail") String javamail, @QueryParam("springmail") String springmail, @QueryParam("commonsmail") String commonsmail
+ // if javamail parameter provided, assume it contains an email address.
+ // use Java Mail to send an email from that address, to that address
+ if (javamail != null && javamail.length() > 0) {
+ variables.put("javamail", javamail);
+ try {
+ Properties props = new Properties();
+ props.put("mail.smtp.host", "smtp.sbc.com"); // eMail.setHostName
+ Session session = Session.getInstance(props);
+ MimeMessage msg = new MimeMessage(session);
+
+ msg.setFrom(new InternetAddress(javamail)); //eMail.setFrom
+
+ InternetAddress[] fromAddresses = {new InternetAddress(javamail)};
+ msg.setReplyTo(fromAddresses); //eMail.addReplyTo
+ msg.setSubject("test message using javax.mail"); //eMail.setSubject
+ msg.setText(logMessageText); // eMail.setMsg
+
+ msg.addRecipient(Message.RecipientType.TO, new InternetAddress(javamail)); // eMail.addTo
+ Transport.send(msg);
+ } catch (MessagingException e) {
+ logger.error(LogMessages.LOGSERVICE_EMAIL_ERROR, e);
+ }
+ }
+
+ // if springmail parameter provided, assume it contains an email address.
+ // use Spring Mail to send an email from that address, to that address
+ if (springmail != null && springmail.length() > 0) {
+ variables.put("springmail", springmail);
+ JavaMailSenderImpl sender = new JavaMailSenderImpl();
+ SimpleMailMessage smsg = new SimpleMailMessage();
+
+ try {
+ sender.setHost("smtp.sbc.com"); // eMail.setHostName
+ smsg.setFrom(springmail); //eMail.setFrom
+ smsg.setReplyTo(springmail); //eMail.addReplyTo
+ smsg.setSubject("test message using spring mail"); //eMail.setSubject
+ smsg.setText(logMessageText); // eMail.setMsg
+ smsg.setTo(springmail); // eMail.addTo
+ sender.send(smsg);
+ } catch (MailException e) {
+ logger.error(LogMessages.LOGSERVICE_EMAIL_ERROR, e);
+ }
+ }
+
+ // if commonsmail parameter provided, assume it contains an email address.
+ // use Apache Commons Mail to send an email from that address, to that address
+ if (commonsmail != null && commonsmail.length() > 0) {
+ variables.put("commonsmail", commonsmail);
+ Email eMail = new SimpleEmail();
+ try {
+ eMail.setHostName("smtp.sbc.com");
+ eMail.setFrom(commonsmail);
+ eMail.addReplyTo(commonsmail);
+ eMail.setSubject("test message using commons mail");
+ eMail.setMsg(logMessageText);
+ eMail.addTo(commonsmail);
+ java.net.URL classUrl = this.getClass().getResource("com.sun.mail.util.TraceInputStream");
+ if (classUrl != null) {
+ logger.info(LogMessages.LOGSERVICE_EMAIL_CLASS, classUrl.getFile());
+ } else {
+ logger.info(LogMessages.LOGSERVICE_EMAIL_CLASS, classUrl.getFile());
+ logger.info(LogMessages.LOGSERVICE_EMAIL_CLASS_NULL);
+ }
+ eMail.send();
+ } catch (Exception e) {
+ logger.error(LogMessages.LOGSERVICE_EMAIL_ERROR, e);
+ }
+ }
+ // END - added for send mail testing
+
+ // execute example camunda process, log-message-wf
+ ProcessInstance pi = runtimeService.startProcessInstanceByKey("log-message-wf", variables);
+ AttCamundaService.setHttpRequest(null);
+ // return text message of what was done
+ return "Started processDefinitionId=" + pi.getProcessDefinitionId() + ", processInstanceId=" + pi.getProcessInstanceId() + ", to log message: " + logMessageText;
+ }
+
+ @Override
+ public String postLogMessage(String histEventList) {
+ String message = "no logs Created";
+ logger.info("value of history events:" + histEventList);
+ Gson gson = new Gson();
+ AttCamundaHistoryEvent attCamundaHistoryEvent = gson.fromJson(histEventList, AttCamundaHistoryEvent.class);
+ if (attCamundaHistoryEvent != null && attCamundaHistoryEvent.getProcInstId() != null) {
+ logger.info(LogMessages.PROCESS_INSTANCE_ID, attCamundaHistoryEvent.getProcInstId());
+ if (context != null && context.getHttpServletRequest() != null && context.getHttpServletRequest().getAttribute("PERFORMANCE_TRACKER_BEAN") != null) {
+ context.getHttpServletRequest().setAttribute("CALL_TYPE", "Testing");
+ List<HistoricActivityInstance> histActInstList = historyService.createHistoricActivityInstanceQuery().processInstanceId(attCamundaHistoryEvent.getProcInstId()).list();
+
+ if (histActInstList != null && histActInstList.size() > 0) {
+ for (HistoricActivityInstance currHistoricActivityInstance : histActInstList) {
+ if (currHistoricActivityInstance != null && currHistoricActivityInstance.getActivityName() != null && currHistoricActivityInstance.getStartTime() != null
+ && currHistoricActivityInstance.getEndTime() != null) {
+ logger.info("value of serviceTrack:" + currHistoricActivityInstance);
+ message = "Log Entry Created";
+ logger.info(message);
+ }
+ }
+ }
+ if (attCamundaHistoryEvent.getHistoryEventList() != null && attCamundaHistoryEvent.getHistoryEventList().size() > 0) {
+ List<HistoricActivityInstanceEventEntity> historyEventList = attCamundaHistoryEvent.getHistoryEventList();
+ for (HistoricActivityInstanceEventEntity actiEvent : historyEventList) {
+ // resolve null pointer exception if actiEvent.getActivityName()
+ message = "Log Entry Created";
+ }
+ }
+ }
+ }
+ return message;
+ }
+
+ @Override
+ public String createLogMessage(String startTime, String endTime, String serviceName) {
+ String message = "no logs Created";
+
+ if (context != null && context.getHttpServletRequest() != null && context.getHttpServletRequest().getAttribute("PERFORMANCE_TRACKER_BEAN") != null) {
+ context.getHttpServletRequest().setAttribute("X-CSI-ClientApp", "AJSC-CSI~sdsds");
+ /*PerformanceTrackingBean trackingBean =(PerformanceTrackingBean) context.getHttpServletRequest().getAttribute("PERFORMANCE_TRACKER_BEAN");
+ PerformanceTracking.addInvokeServiceTrack(trackingBean,
+ serviceName, Long.valueOf(startTime), Long.valueOf(endTime), "Completed",
+ 500, 1000) ;*/
+ message = "Log Entry Created";
+ }
+ // return text message of what was done
+ return message;
+ }
+
+ @Override
+ public String createLogMessageUsingHistory(String procInstId, String histEventList) {
+ String message = "no logs Created";
+ logger.info("value of history events:" + histEventList);
+ logger.info("value of events:" + histEventList + ":" + histEventList);
+ if (context != null && context.getHttpServletRequest() != null && context.getHttpServletRequest().getAttribute("PERFORMANCE_TRACKER_BEAN") != null) {
+ context.getHttpServletRequest().setAttribute("CALL_TYPE", "Testing");
+ List<HistoricActivityInstance> histActInstList = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInstId).list();
+
+ if (histActInstList != null && histActInstList.size() > 0) {
+ for (HistoricActivityInstance currHistoricActivityInstance : histActInstList) {
+ if (currHistoricActivityInstance != null && currHistoricActivityInstance.getActivityName() != null && currHistoricActivityInstance.getStartTime() != null
+ && currHistoricActivityInstance.getEndTime() != null) {
+ logger.info("value of serviceTrack:" + currHistoricActivityInstance);
+ message = "Log Entry Created";
+ logger.info(message);
+ }
+ }
+ }
+ }
+ return message;
+ }
+
+ @Override
+ public String CreateHistLog(String procInstId) {
+ String message = "no logs Created";
+ if (context != null && context.getHttpServletRequest() != null && context.getHttpServletRequest().getAttribute("PERFORMANCE_TRACKER_BEAN") != null) {
+ List<HistoricActivityInstance> histActInstList = historyService.createHistoricActivityInstanceQuery().processInstanceId(procInstId).list();
+
+ if (histActInstList != null && histActInstList.size() > 0) {
+ for (HistoricActivityInstance currHistoricActivityInstance : histActInstList) {
+ if (currHistoricActivityInstance != null && currHistoricActivityInstance.getActivityName() != null && currHistoricActivityInstance.getStartTime() != null
+ && currHistoricActivityInstance.getEndTime() != null) {
+ logger.info("value of serviceTrack:" + currHistoricActivityInstance);
+ context.getHttpServletRequest().setAttribute("X-CSI-ClientApp", "AJSC-CSI~sdsds");
+ message = "Log Entry Created";
+ }
+ }
+ }
+ }
+ return message;
+ }
+
+ private String getActivityInstanceState(int activityInstanceState) {
+ String activityState = "Default";
+ if (activityInstanceState == 1) {
+ activityState = "Complete";
+ } else if (activityInstanceState == 2) {
+ activityState = "Cancelled";
+ }
+ return activityState;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java
new file mode 100644
index 000000000..c17af97fa
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/SecureServiceBase.java
@@ -0,0 +1,105 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.NotAuthorizedException;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.SecurityContext;
+import java.security.Principal;
+
+/**
+ * Base/abstract Service class.
+ * Implements shared security methods.
+ */
+public abstract class SecureServiceBase {
+ private static final Logger logger = LoggerFactory.getLogger(SecureServiceBase.class);
+
+ @Context
+ private SecurityContext securityContext;
+
+ /**
+ * Get the userid
+ *
+ * @return
+ */
+ public String getUserid() {
+ return getPrincipalName();
+ }
+
+ /**
+ * Get the principal name.
+ *
+ * @return
+ */
+ public String getPrincipalName() {
+ Principal p = securityContext.getUserPrincipal();
+ String name = "Not found";
+ if (p != null) {
+ name = p.getName();
+ }
+ logger.debug("userPrincipal.getName()={}", name);
+ return name;
+ }
+
+ /**
+ * Check if user is authorized for the given the permission.
+ * Allow matches if user has a permission with an "*" in permission instance
+ * or permission action even if the permission to check has a specific value
+ * in those fields. For example:
+ * if the user has this permission: app-perm-type|*|*
+ * it will be authorized if the inPermission to check is: app-perm-type|dev|read
+ *
+ * @param inPermission
+ * @return
+ * @throws NotAuthorizedException
+ */
+ public boolean isAuthorized(SecureServicePermission inPermission) throws NotAuthorizedException {
+ boolean authorized = false;
+ logger.debug("checking if {} has permission: {}", getPrincipalName(), inPermission);
+ // check if the user has the permission key or the permission key with a combination of all instance and/or all action.
+ if (securityContext.isUserInRole(inPermission.getKey())) {
+ logger.info("{} authorized for permission: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ // the rest of these don't seem to be required - isUserInRole method appears to take * as a wildcard
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllInstance())) {
+ logger.info("{} authorized because user has permission with * for instance: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllInstanceAction())) {
+ logger.info("{} authorized because user has permission with * for instance and * for action: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else if (securityContext.isUserInRole(inPermission.getKeyAllAction())) {
+ logger.info("{} authorized because user has permission with * for action: {}", getPrincipalName(), inPermission.getKey());
+ authorized = true;
+ } else {
+ String msg = getPrincipalName() + " does not have permission: " + inPermission;
+ logger.warn(msg);
+ throw new NotAuthorizedException(msg);
+ }
+ return authorized;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java b/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java
new file mode 100644
index 000000000..a2213f91a
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/SecureServicePermission.java
@@ -0,0 +1,190 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service;
+
+/**
+ * Permission class that can be instantiated easily using constructor or factory methods.
+ */
+public class SecureServicePermission {
+ public final static String ALL = "*";
+
+ private String type;
+ private String instance;
+ private String action;
+
+ /**
+ * Factory method to create permission given type, instance, and action.
+ *
+ * @param type
+ * @param instance
+ * @param action
+ * @return
+ */
+ public static SecureServicePermission create(String type, String instance, String action) {
+ return new SecureServicePermission(type, instance, action);
+ }
+
+ /**
+ * Factory method to create permission given type and instance. Default action to ALL/*.
+ *
+ * @param type
+ * @param instance
+ * @return
+ */
+ public static SecureServicePermission create(String type, String instance) {
+ return new SecureServicePermission(type, instance);
+ }
+
+ /**
+ * Factory method to create permission given type. Default instance and action to ALL/*.
+ *
+ * @param type
+ * @return
+ */
+ public static SecureServicePermission create(String type) {
+ return new SecureServicePermission(type);
+ }
+
+ /**
+ * Instantiate permission given type, instance, and action.
+ *
+ * @param type
+ * @param instance
+ * @param action
+ */
+ public SecureServicePermission(String type, String instance, String action) {
+ this.type = type;
+ this.instance = instance;
+ this.action = action;
+ }
+
+ /**
+ * Instantiate permission given type and instance. Default action to ALL/*.
+ *
+ * @param type
+ * @param instance
+ */
+ public SecureServicePermission(String type, String instance) {
+ this.type = type;
+ this.instance = instance;
+ this.action = ALL;
+ }
+
+ /**
+ * Instantiate permission given type. Default instance and action to ALL/*.
+ *
+ * @param type
+ */
+ public SecureServicePermission(String type) {
+ this.type = type;
+ this.instance = ALL;
+ this.action = ALL;
+ }
+
+ /**
+ * Override toString - return permission in key format
+ */
+ public String toString() {
+ return getKey();
+ }
+
+ /**
+ * Return Permission in Key format = type, instance, and action separate by pipe character.
+ *
+ * @return
+ */
+ public String getKey() {
+ return type + "|" + instance + "|" + action;
+ }
+
+ /**
+ * Return Permission in Key format = type, all instance, and action separate by pipe character.
+ *
+ * @return
+ */
+ public String getKeyAllInstance() {
+ return type + "|" + ALL + "|" + action;
+ }
+
+ /**
+ * Return Permission in Key format = type, all instance, and all action separate by pipe character.
+ *
+ * @return
+ */
+ public String getKeyAllInstanceAction() {
+ return type + "|" + ALL + "|" + ALL;
+ }
+
+ /**
+ * Return Permission in Key format = type, instance, and all action separate by pipe character.
+ *
+ * @return
+ */
+ public String getKeyAllAction() {
+ return type + "|" + instance + "|" + ALL;
+ }
+
+ /**
+ * @return the type
+ */
+ public String getType() {
+ return type;
+ }
+
+ /**
+ * @param type the type to set
+ */
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ /**
+ * @return the instance
+ */
+ public String getInstance() {
+ return instance;
+ }
+
+ /**
+ * @param instance the instance to set
+ */
+ public void setInstance(String instance) {
+ this.instance = instance;
+ }
+
+ /**
+ * @return the action
+ */
+ public String getAction() {
+ return action;
+ }
+
+ /**
+ * @param action the action to set
+ */
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogService.java b/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogService.java
new file mode 100644
index 000000000..d0ef13595
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogService.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service.rs;
+
+import io.swagger.annotations.Api;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.MediaType;
+
+
+/**
+ * Service to invoke example Camunda process.
+ * <p>
+ * Try testing by using:
+ * http://[hostname]:[serverPort]/jaxrsservices/log/log-message/your-message-here
+ */
+@Api(value = "/log")
+@Path("/log")
+@Produces({MediaType.TEXT_PLAIN})
+public interface JaxrsLogService {
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param logMessageText
+ * @return output from service - comment on what was done
+ */
+ @GET
+ @Path("/log-message/{logMessageText}")
+ @Produces(MediaType.TEXT_PLAIN)
+ String logMessage(@PathParam("logMessageText") String logMessageText, @QueryParam("javamail") String javamail, @QueryParam("springmail") String springmail, @QueryParam("commonsmail") String commonsmail);
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @return output from service - comment on what was done
+ */
+ @POST
+ @Path("/postLogHist")
+ @Produces(MediaType.TEXT_PLAIN)
+ @Consumes(MediaType.APPLICATION_JSON)
+ String postLogMessage(String histEventList);
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param startTime
+ * @param endTime
+ * @param serviceName
+ * @return output from service - comment on what was done
+ */
+ @GET
+ @Path("/createLog/{startTime}/{endTime}/{serviceName}")
+ @Produces(MediaType.TEXT_PLAIN)
+ String createLogMessage(@PathParam("startTime") String startTime, @PathParam("endTime") String endTime, @PathParam("serviceName") String serviceName);
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param procInstId
+ * @param histEventList
+ * @return output from service - comment on what was done
+ */
+ @GET
+ @Path("/createLogHist/{procInstId}/{histEventList}")
+ @Produces(MediaType.TEXT_PLAIN)
+ String createLogMessageUsingHistory(@PathParam("procInstId") String procInstId, @PathParam("histEventList") String histEventList);
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param procInstId
+ * @return output from service - comment on what was done
+ */
+ @GET
+ @Path("/histLog/{procInstId}")
+ @Produces(MediaType.TEXT_PLAIN)
+ String CreateHistLog(@PathParam("procInstId") String procInstId);
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogServiceImpl.java b/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogServiceImpl.java
new file mode 100644
index 000000000..4ef7d2e9e
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/service/rs/JaxrsLogServiceImpl.java
@@ -0,0 +1,94 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.service.rs;
+
+import com.att.ajsc.common.AjscService;
+import org.onap.clamp.clds.service.LogService;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * Service to invoke example Camunda process.
+ * <p>
+ * Try testing by using:
+ * http://[hostname]:[serverPort]/services/log/log-message/your-message-here
+ */
+@AjscService
+public class JaxrsLogServiceImpl implements JaxrsLogService {
+
+ @Autowired
+ private LogService logService;
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param logMessageText
+ * @return output from service - comment on what was done
+ */
+ public String logMessage(String logMessageText, String javamail, String springmail, String commonsmail) {
+ return logService.logMessage(logMessageText, javamail, springmail, commonsmail);
+ }
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @return output from service - comment on what was done
+ */
+ public String postLogMessage(String histEventList) {
+ return logService.postLogMessage(histEventList);
+ }
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param startTime
+ * @param endTime
+ * @param serviceName
+ * @return output from service - comment on what was done
+ */
+ public String createLogMessage(String startTime, String endTime, String serviceName) {
+ return logService.createLogMessage(startTime, endTime, serviceName);
+ }
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param procInstId
+ * @param histEventList
+ * @return output from service - comment on what was done
+ */
+ public String createLogMessageUsingHistory(String procInstId, String histEventList) {
+ return logService.createLogMessageUsingHistory(procInstId, histEventList);
+ }
+
+ /**
+ * REST service that executes example camunda process to log input message.
+ *
+ * @param procInstId
+ * @return output from service - comment on what was done
+ */
+ public String CreateHistLog(String procInstId) {
+ return logService.CreateHistLog(procInstId);
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/transform/TransformUtil.java b/src/main/java/org/onap/clamp/clds/transform/TransformUtil.java
new file mode 100644
index 000000000..2c666db06
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/transform/TransformUtil.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.transform;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Utility methods supporting transforms.
+ */
+public class TransformUtil {
+
+ /**
+ * Return resource as a Stream.
+ *
+ * @param name
+ * @return resource - resource as stream
+ */
+ public static InputStream getResourceAsStream(String name) {
+ InputStream is = Thread.currentThread().getContextClassLoader()
+ .getResourceAsStream(name);
+ if (is == null) {
+ throw new IllegalArgumentException("Unable to find resource: "
+ + name);
+ }
+ return is;
+ }
+
+ /**
+ * Return resource as a Stream.
+ *
+ * @param name
+ * @throws IOException
+ */
+ public static String getResourceAsString(String name) throws IOException {
+ InputStream is = getResourceAsStream(name);
+ java.util.Scanner scanner = new java.util.Scanner(is);
+ java.util.Scanner s = scanner.useDelimiter("\\A");
+ String text = s.hasNext() ? s.next() : "";
+ s.close();
+ scanner.close();
+ is.close();
+ return text;
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/transform/XslTransformer.java b/src/main/java/org/onap/clamp/clds/transform/XslTransformer.java
new file mode 100644
index 000000000..7d0031604
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/transform/XslTransformer.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.transform;
+
+import javax.xml.transform.*;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+/**
+ * XSL Transformer.
+ */
+public class XslTransformer {
+
+ private Templates templates;
+
+ public void setXslResourceName(String xslResourceName) throws TransformerConfigurationException {
+ TransformerFactory tfactory = TransformerFactory.newInstance();
+ templates = tfactory.newTemplates(new StreamSource(TransformUtil.getResourceAsStream(xslResourceName)));
+ }
+
+ /**
+ * Given xml input, return the transformed result.
+ *
+ * @param xml
+ * @throws TransformerException
+ */
+ public String doXslTransformToString(String xml) throws TransformerException {
+ StringWriter output = new StringWriter(4000);
+
+ Transformer transformer = templates.newTransformer();
+ transformer.transform(new StreamSource(new StringReader(xml)),
+ new StreamResult(output));
+ return output.toString();
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/workflow/LogMessageDelegate.java b/src/main/java/org/onap/clamp/clds/workflow/LogMessageDelegate.java
new file mode 100644
index 000000000..693b334ee
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/workflow/LogMessageDelegate.java
@@ -0,0 +1,46 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.workflow;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+
+/**
+ * Log message.
+ * Invoked by the log-message-wf example Camunda workflow/bpmn.
+ */
+public class LogMessageDelegate implements JavaDelegate {
+
+ /**
+ * Perform activity. Log message from running process and set a variable in the running process.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String logMessageText = (String) execution.getVariable("logMessageText");
+
+ System.out.println("Invoked from processDefinitionId=" + execution.getProcessDefinitionId() + ", processInstanceId=" + execution.getProcessInstanceId() + ", activityInstanceId=" + execution.getActivityInstanceId() + ": logMessageText=" + logMessageText);
+ execution.setVariable("isMessageLogComplete", true);
+ }
+}
diff --git a/src/main/java/org/onap/clamp/clds/workflow/ProcessRequestDelegate.java b/src/main/java/org/onap/clamp/clds/workflow/ProcessRequestDelegate.java
new file mode 100644
index 000000000..324496422
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/workflow/ProcessRequestDelegate.java
@@ -0,0 +1,57 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+/* 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.
+ */
+package org.onap.clamp.clds.workflow;
+
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class ProcessRequestDelegate implements JavaDelegate {
+
+ private static final Logger logger = LoggerFactory.getLogger(ProcessRequestDelegate.class);
+
+ //@Override
+ public void execute(DelegateExecution execution) throws Exception {
+ logger.info("Processing request by '" + execution.getVariable("customerId") + "'...");
+ logger.info("Processing request by '" + execution.getVariable("amount") + "'...");
+ }
+
+}
diff --git a/src/main/java/org/onap/clamp/clds/workflow/RestMessageDelegate.java b/src/main/java/org/onap/clamp/clds/workflow/RestMessageDelegate.java
new file mode 100644
index 000000000..0eda2decc
--- /dev/null
+++ b/src/main/java/org/onap/clamp/clds/workflow/RestMessageDelegate.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP CLAMP
+ * ================================================================================
+ * Copyright (C) 2017 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============================================
+ * ===================================================================
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
+
+package org.onap.clamp.clds.workflow;
+
+import org.camunda.bpm.engine.delegate.DelegateExecution;
+import org.camunda.bpm.engine.delegate.JavaDelegate;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * Log message.
+ * Invoked by the log-message-wf example Camunda workflow/bpmn.
+ */
+public class RestMessageDelegate implements JavaDelegate {
+ private static final Logger logger = Logger.getLogger(RestMessageDelegate.class.getName());
+
+ /**
+ * Perform activity. Log message from running process and set a variable in the running process.
+ *
+ * @param execution
+ */
+ public void execute(DelegateExecution execution) throws Exception {
+ String logMessageText = (String) execution.getVariable("logMessageText");
+ RestTemplate restTemplate = new RestTemplate();
+ Map<String, String> restValues = new HashMap<>();
+ restValues.put("procInstId", execution.getProcessInstanceId());
+ logger.info("Invoked from processDefinitionId=" + execution.getProcessDefinitionId() + ", processInstanceId=" + execution.getProcessInstanceId() + ", activityInstanceId=" + execution.getActivityInstanceId() + ": logMessageText=" + logMessageText);
+ // TODO: this should be fixed - put in temporary solution with existing sysprop and vars - why are we calling our own service?
+ String port = System.getProperty("server.port");
+ ResponseEntity<String> resp = restTemplate.getForEntity("http://localhost:" + port + "/services/CamundaExample/v1/jaxrsExample/log/histLog/{procInstId}", String.class, restValues);
+ logger.info("value of resp:" + resp);
+ execution.setVariable("isMessageLogComplete", true);
+ }
+}