[CLAMP-1] Initial ONAP CLAMP seed code commit
[clamp.git] / src / main / java / org / onap / clamp / clds / service / CldsTemplateService.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License"); 
9  * you may not use this file except in compliance with the License. 
10  * You may obtain a copy of the License at
11  * 
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software 
15  * distributed under the License is distributed on an "AS IS" BASIS, 
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
17  * See the License for the specific language governing permissions and 
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.service;
25
26 import com.att.ajsc.common.AjscService;
27 import com.fasterxml.jackson.core.JsonParseException;
28 import com.fasterxml.jackson.databind.JsonMappingException;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.databind.node.ArrayNode;
32 import com.fasterxml.jackson.databind.node.ObjectNode;
33 import org.onap.clamp.clds.dao.CldsDao;
34 import org.onap.clamp.clds.model.CldsTemplate;
35 import org.onap.clamp.clds.model.ValueItem;
36 import org.onap.clamp.clds.model.prop.ModelBpmn;
37 import org.onap.clamp.clds.transform.XslTransformer;
38 import org.camunda.bpm.engine.RuntimeService;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42
43 import javax.ws.rs.*;
44 import javax.ws.rs.core.MediaType;
45 import javax.xml.transform.TransformerException;
46 import java.io.IOException;
47 import java.util.HashMap;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Map.Entry;
52
53 /**
54  * Service to save and retrieve the CLDS model attributes.
55  */
56 @AjscService
57 @Path("/cldsTempate")
58 public class CldsTemplateService extends SecureServiceBase {
59
60     private static final Logger logger = LoggerFactory.getLogger(CldsTemplateService.class);
61
62     private static final String collectorKey = "Collector";
63     private static final String stringMatchKey = "StringMatch";
64     private static final String policyKey = "Policy";
65
66     private static final String CLDS_PERMISSION_TYPE_TEMPLATE = System.getProperty("CLDS_PERMISSION_TYPE_TEMPLATE");
67     private static final String CLDS_PERMISSION_INSTANCE = System.getProperty("CLDS_PERMISSION_INSTANCE");
68
69     private static final SecureServicePermission PERMISSION_READ_TEMPLATE = SecureServicePermission.create(CLDS_PERMISSION_TYPE_TEMPLATE, CLDS_PERMISSION_INSTANCE, "read");
70     private static final SecureServicePermission PERMISSION_UPDATE_TEMPLATE = SecureServicePermission.create(CLDS_PERMISSION_TYPE_TEMPLATE, CLDS_PERMISSION_INSTANCE, "update");
71
72     @Autowired
73     private CldsDao cldsDao;
74     @Autowired
75     private RuntimeService runtimeService;
76     @Autowired
77     private XslTransformer cldsBpmnTransformer;
78
79     private static String userid;
80
81     /**
82      * REST service that retrieves BPMN for a CLDS template name from the database.
83      * This is subset of the json getModel.
84      * This is only expected to be used for testing purposes, not by the UI.
85      *
86      * @param templateName
87      * @return bpmn xml text - content of bpmn given name
88      */
89     @GET
90     @Path("/template/bpmn/{templateName}")
91     @Produces(MediaType.TEXT_XML)
92     public String getBpmnTemplate(@PathParam("templateName") String templateName) {
93         isAuthorized(PERMISSION_READ_TEMPLATE);
94         logger.info("GET bpmnText for templateName=" + templateName);
95         CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
96         return template.getBpmnText();
97     }
98
99     /**
100      * REST service that saves BPMN for a CLDS template by name in the database.
101      * This is subset of the json putModel.
102      * This is only expected to be used for testing purposes, not by the UI.
103      *
104      * @param templateName
105      * @param bpmnText
106      */
107     @PUT
108     @Path("/template/bpmn/{templateName}")
109     @Consumes(MediaType.TEXT_XML)
110     public String putBpmnTemplateXml(@PathParam("templateName") String templateName, String bpmnText) {
111         isAuthorized(PERMISSION_UPDATE_TEMPLATE);
112         logger.info("PUT bpmnText for templateName=" + templateName);
113         logger.info("PUT bpmnText=" + bpmnText);
114         CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
115         cldsTemplate.setBpmnText(bpmnText);
116         cldsTemplate.save(cldsDao, userid);
117         return "wrote bpmnText for templateName=" + templateName;
118     }
119
120     /**
121      * REST service that retrieves image for a CLDS template name from the database.
122      * This is subset of the json getModel.
123      * This is only expected to be used for testing purposes, not by the UI.
124      *
125      * @param templateName
126      * @return image xml text - content of image given name
127      */
128     @GET
129     @Path("/template/image/{templateName}")
130     @Produces(MediaType.TEXT_XML)
131     public String getImageXml(@PathParam("templateName") String templateName) {
132         isAuthorized(PERMISSION_READ_TEMPLATE);
133         logger.info("GET imageText for templateName=" + templateName);
134         CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
135         return template.getImageText();
136     }
137
138     /**
139      * REST service that saves image for a CLDS template by name in the database.
140      * This is subset of the json putModel.
141      * This is only expected to be used for testing purposes, not by the UI.
142      *
143      * @param templateName
144      * @param imageText
145      */
146     @PUT
147     @Path("/template/image/{templateName}")
148     @Consumes(MediaType.TEXT_XML)
149     public String putImageXml(@PathParam("templateName") String templateName, String imageText) {
150         isAuthorized(PERMISSION_UPDATE_TEMPLATE);
151         logger.info("PUT iamgeText for modelName=" + templateName);
152         logger.info("PUT imageText=" + imageText);
153         CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
154         cldsTemplate.setImageText(imageText);
155         cldsTemplate.save(cldsDao, userid);
156         return "wrote imageText for modelName=" + templateName;
157     }
158
159     /**
160      * REST service that retrieves a CLDS template by name from the database.
161      *
162      * @param templateName
163      * @return clds template - clds template for the given template name
164      */
165     @GET
166     @Path("/template/{templateName}")
167     @Produces(MediaType.APPLICATION_JSON)
168     public CldsTemplate getTemplate(@PathParam("templateName") String templateName) {
169         isAuthorized(PERMISSION_READ_TEMPLATE);
170         logger.info("GET model for  templateName=" + templateName);
171         return CldsTemplate.retrieve(cldsDao, templateName, false);
172     }
173
174     /**
175      * REST service that saves a CLDS template by name in the database.
176      *
177      * @param templateName
178      * @throws IOException
179      * @throws JsonMappingException
180      * @throws JsonParseException
181      */
182     @PUT
183     @Path("/template/{templateName}")
184     @Consumes(MediaType.APPLICATION_JSON)
185     @Produces(MediaType.APPLICATION_JSON)
186     public CldsTemplate putTemplate(@PathParam("templateName") String templateName, CldsTemplate cldsTemplate) throws TransformerException, IOException {
187         isAuthorized(PERMISSION_UPDATE_TEMPLATE);
188         logger.info("PUT Template for  templateName=" + templateName);
189         logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText());
190         logger.info("PUT propText=" + cldsTemplate.getPropText());
191         logger.info("PUT imageText=" + cldsTemplate.getImageText());
192         cldsTemplate.setName(templateName);
193         String bpmnText = cldsTemplate.getBpmnText();
194         String imageText = cldsTemplate.getImageText();
195         String propText = cldsTemplate.getPropText();
196         Map<String, String> newBpmnIdsMap = getNewBpmnIdsMap(bpmnText, cldsTemplate.getPropText());
197         for (String currBpmnId : newBpmnIdsMap.keySet()) {
198             if (currBpmnId != null && newBpmnIdsMap.get(currBpmnId) != null) {
199                 bpmnText = bpmnText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
200                 imageText = imageText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
201                 propText = propText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
202             }
203         }
204         cldsTemplate.setBpmnText(bpmnText);
205         cldsTemplate.setImageText(imageText);
206         cldsTemplate.setPropText(propText);
207         logger.info(" bpmnText : " + cldsTemplate.getBpmnText());
208         logger.info(" Image Text : " + cldsTemplate.getImageText());
209         logger.info(" Prop Text : " + cldsTemplate.getPropText());
210         cldsTemplate.save(cldsDao, userid);
211         return cldsTemplate;
212     }
213
214     /**
215      * REST service that retrieves a list of CLDS template names.
216      *
217      * @return template names in JSON
218      */
219     @GET
220     @Path("/template-names")
221     @Produces(MediaType.APPLICATION_JSON)
222     public List<ValueItem> getTemplateNames() {
223         isAuthorized(PERMISSION_READ_TEMPLATE);
224         logger.info("GET list of template names");
225         return cldsDao.getTemplateNames();
226     }
227
228
229     private Map<String, String> getNewBpmnIdsMap(String bpmnText, String propText) throws TransformerException, IOException {
230         /**
231          *  Test sample code start
232          */
233         String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmnText);
234         ModelBpmn templateBpmn = ModelBpmn.create(bpmnJson);
235         List<String> bpmnElementIds = templateBpmn.getBpmnElementIds();
236         logger.info("value of elementIds:" + bpmnElementIds);
237         logger.info("value of prop text:" + propText);
238         Map<String, String> bpmnIoIdsMap = new HashMap<>();
239         if (bpmnElementIds != null && bpmnElementIds.size() > 0) {
240             ObjectMapper objectMapper = new ObjectMapper();
241             ObjectNode root = objectMapper.readValue(propText, ObjectNode.class);
242             Iterator<Entry<String, JsonNode>> entryItr = root.fields();
243             while (entryItr.hasNext()) {
244                 // process the entry
245                 Entry<String, JsonNode> entry = entryItr.next();
246                 String keyPropName = entry.getKey();
247                 for (String currElementId : bpmnElementIds) {
248                     if (keyPropName != null && keyPropName.equalsIgnoreCase(currElementId)) {
249                         ArrayNode arrayNode = (ArrayNode) entry.getValue();
250                         // process each id/from object, like: {"id":"Collector_11r50j1", "from":"StartEvent_1"}
251                         for (JsonNode anArrayNode : arrayNode) {
252                             ObjectNode node = (ObjectNode) anArrayNode;
253                             String valueNode = node.get("value").asText();
254                             logger.info("value of node:" + valueNode);
255                             if (keyPropName.startsWith(collectorKey)) {
256                                 valueNode = collectorKey + "_" + valueNode;
257                             } else if (keyPropName.startsWith(stringMatchKey)) {
258                                 valueNode = stringMatchKey + "_" + valueNode;
259                             } else if (keyPropName.startsWith(policyKey)) {
260                                 valueNode = policyKey + "_" + valueNode;
261                             }
262                             bpmnIoIdsMap.put(keyPropName, valueNode);
263                         }
264                         break;
265                     }
266                 }
267             }
268         }
269         logger.info("value of hashmap:" + bpmnIoIdsMap);
270         /**
271          *  Test sample code end
272          */
273         return bpmnIoIdsMap;
274     }
275 }