Rework the CldsService (rest apis)
[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 java.io.IOException;
27 import java.util.Date;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33
34 import javax.annotation.PostConstruct;
35 import javax.ws.rs.Consumes;
36 import javax.ws.rs.GET;
37 import javax.ws.rs.PUT;
38 import javax.ws.rs.Path;
39 import javax.ws.rs.PathParam;
40 import javax.ws.rs.Produces;
41 import javax.ws.rs.core.MediaType;
42 import javax.xml.transform.TransformerException;
43
44 import org.camunda.bpm.engine.RuntimeService;
45 import org.onap.clamp.clds.dao.CldsDao;
46 import org.onap.clamp.clds.model.CldsTemplate;
47 import org.onap.clamp.clds.model.ValueItem;
48 import org.onap.clamp.clds.model.prop.ModelBpmn;
49 import org.onap.clamp.clds.transform.XslTransformer;
50 import org.onap.clamp.clds.util.LoggingUtils;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Value;
53
54 import com.att.ajsc.common.AjscService;
55 import com.att.eelf.configuration.EELFLogger;
56 import com.att.eelf.configuration.EELFManager;
57 import com.fasterxml.jackson.core.JsonParseException;
58 import com.fasterxml.jackson.databind.JsonMappingException;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.fasterxml.jackson.databind.node.ArrayNode;
62 import com.fasterxml.jackson.databind.node.ObjectNode;
63
64 /**
65  * Service to save and retrieve the CLDS model attributes.
66  */
67 @AjscService
68 @Path("/cldsTempate")
69 public class CldsTemplateService extends SecureServiceBase {
70
71     protected static final EELFLogger logger         = EELFManager.getInstance().getLogger(CldsTemplateService.class);
72     protected static final EELFLogger auditLogger    = EELFManager.getInstance().getAuditLogger();
73
74     private static final String     collectorKey   = "Collector";
75     private static final String     stringMatchKey = "StringMatch";
76     private static final String     policyKey      = "Policy";
77
78     @Value("${CLDS_PERMISSION_TYPE_TEMPLATE:permission-type-template}")
79     private String                  cldsPermissionTypeTemplate;
80
81     @Value("${CLDS_PERMISSION_INSTANCE:dev}")
82     private String                  cldsPermissionInstance;
83
84     private SecureServicePermission permissionReadTemplate;
85
86     private SecureServicePermission permissionUpdateTemplate;
87
88     @PostConstruct
89     private final void afterConstruction() {
90         permissionReadTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
91                 "read");
92         permissionUpdateTemplate = SecureServicePermission.create(cldsPermissionTypeTemplate, cldsPermissionInstance,
93                 "update");
94     }
95
96     @Autowired
97     private CldsDao        cldsDao;
98     @Autowired
99     private RuntimeService runtimeService;
100     @Autowired
101     private XslTransformer cldsBpmnTransformer;
102
103     private static String  userid;
104
105     /**
106      * REST service that retrieves BPMN for a CLDS template name from the
107      * database. This is subset of the json getModel. This is only expected to
108      * be used for testing purposes, not by the UI.
109      *
110      * @param templateName
111      * @return bpmn xml text - content of bpmn given name
112      */
113     @GET
114     @Path("/template/bpmn/{templateName}")
115     @Produces(MediaType.TEXT_XML)
116     public String getBpmnTemplate(@PathParam("templateName") String templateName) {
117         Date startTime = new Date();
118         LoggingUtils.setRequestContext("CldsTemplateService: GET template bpmn", getPrincipalName());
119         isAuthorized(permissionReadTemplate);
120         logger.info("GET bpmnText for templateName=" + templateName);
121         CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
122         // audit log
123         LoggingUtils.setTimeContext(startTime, new Date());
124         LoggingUtils.setResponseContext("0", "Get template bpmn success", this.getClass().getName());
125         auditLogger.info("GET template bpmn completed");
126         return template.getBpmnText();
127     }
128
129     /**
130      * REST service that saves BPMN for a CLDS template by name in the database.
131      * This is subset of the json putModel. This is only expected to be used for
132      * testing purposes, not by the UI.
133      *
134      * @param templateName
135      * @param bpmnText
136      */
137     @PUT
138     @Path("/template/bpmn/{templateName}")
139     @Consumes(MediaType.TEXT_XML)
140     public String putBpmnTemplateXml(@PathParam("templateName") String templateName, String bpmnText) {
141         Date startTime = new Date();
142         LoggingUtils.setRequestContext("CldsTemplateService: PUT template bpmn", getPrincipalName());
143         isAuthorized(permissionUpdateTemplate);
144         logger.info("PUT bpmnText for templateName=" + templateName);
145         logger.info("PUT bpmnText=" + bpmnText);
146         CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
147         cldsTemplate.setBpmnText(bpmnText);
148         cldsTemplate.save(cldsDao, userid);
149         // audit log
150         LoggingUtils.setTimeContext(startTime, new Date());
151         LoggingUtils.setResponseContext("0", "Put template bpmn success", this.getClass().getName());
152         auditLogger.info("PUT template bpm completed");
153         return "wrote bpmnText for templateName=" + templateName;
154     }
155
156     /**
157      * REST service that retrieves image for a CLDS template name from the
158      * database. This is subset of the json getModel. This is only expected to
159      * be used for testing purposes, not by the UI.
160      *
161      * @param templateName
162      * @return image xml text - content of image given name
163      */
164     @GET
165     @Path("/template/image/{templateName}")
166     @Produces(MediaType.TEXT_XML)
167     public String getImageXml(@PathParam("templateName") String templateName) {
168         Date startTime = new Date();
169         LoggingUtils.setRequestContext("CldsTemplateService: GET template image", getPrincipalName());
170         isAuthorized(permissionReadTemplate);
171         logger.info("GET imageText for templateName=" + templateName);
172         CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
173         // audit log
174         LoggingUtils.setTimeContext(startTime, new Date());
175         LoggingUtils.setResponseContext("0", "Get template image success", this.getClass().getName());
176         auditLogger.info("GET template image completed");
177         return template.getImageText();
178     }
179
180     /**
181      * REST service that saves image for a CLDS template by name in the
182      * database. This is subset of the json putModel. This is only expected to
183      * be used for testing purposes, not by the UI.
184      *
185      * @param templateName
186      * @param imageText
187      */
188     @PUT
189     @Path("/template/image/{templateName}")
190     @Consumes(MediaType.TEXT_XML)
191     public String putImageXml(@PathParam("templateName") String templateName, String imageText) {
192         Date startTime = new Date();
193         LoggingUtils.setRequestContext("CldsTemplateService: PUT template image", getPrincipalName());
194         isAuthorized(permissionUpdateTemplate);
195         logger.info("PUT iamgeText for modelName=" + templateName);
196         logger.info("PUT imageText=" + imageText);
197         CldsTemplate cldsTemplate = CldsTemplate.retrieve(cldsDao, templateName, true);
198         cldsTemplate.setImageText(imageText);
199         cldsTemplate.save(cldsDao, userid);
200         // audit log
201         LoggingUtils.setTimeContext(startTime, new Date());
202         LoggingUtils.setResponseContext("0", "Put template image success", this.getClass().getName());
203         auditLogger.info("PUT template image completed");
204         return "wrote imageText for modelName=" + templateName;
205     }
206
207     /**
208      * REST service that retrieves a CLDS template by name from the database.
209      *
210      * @param templateName
211      * @return clds template - clds template for the given template name
212      */
213     @GET
214     @Path("/template/{templateName}")
215     @Produces(MediaType.APPLICATION_JSON)
216     public CldsTemplate getTemplate(@PathParam("templateName") String templateName) {
217         Date startTime = new Date();
218         LoggingUtils.setRequestContext("CldsTemplateService: GET template", getPrincipalName());
219         isAuthorized(permissionReadTemplate);
220         logger.info("GET model for  templateName=" + templateName);
221         CldsTemplate template = CldsTemplate.retrieve(cldsDao, templateName, false);
222         template.setUserAuthorizedToUpdate(isAuthorizedNoException(permissionUpdateTemplate));
223         // audit log
224         LoggingUtils.setTimeContext(startTime, new Date());
225         LoggingUtils.setResponseContext("0", "Get template success", this.getClass().getName());
226         auditLogger.info("GET template completed");
227         return template;
228     }
229
230     /**
231      * REST service that saves a CLDS template by name in the database.
232      *
233      * @param templateName
234      * @throws IOException
235      * @throws JsonMappingException
236      * @throws JsonParseException
237      */
238     @PUT
239     @Path("/template/{templateName}")
240     @Consumes(MediaType.APPLICATION_JSON)
241     @Produces(MediaType.APPLICATION_JSON)
242     public CldsTemplate putTemplate(@PathParam("templateName") String templateName, CldsTemplate cldsTemplate)
243             throws TransformerException, IOException {
244         Date startTime = new Date();
245         LoggingUtils.setRequestContext("CldsTemplateService: PUT template", getPrincipalName());
246         isAuthorized(permissionUpdateTemplate);
247
248         logger.info("PUT Template for  templateName=" + templateName);
249         logger.info("PUT bpmnText=" + cldsTemplate.getBpmnText());
250         logger.info("PUT propText=" + cldsTemplate.getPropText());
251         logger.info("PUT imageText=" + cldsTemplate.getImageText());
252         cldsTemplate.setName(templateName);
253         String bpmnText = cldsTemplate.getBpmnText();
254         String imageText = cldsTemplate.getImageText();
255         String propText = cldsTemplate.getPropText();
256         Map<String, String> newBpmnIdsMap = getNewBpmnIdsMap(bpmnText, cldsTemplate.getPropText());
257         for (String currBpmnId : newBpmnIdsMap.keySet()) {
258             if (currBpmnId != null && newBpmnIdsMap.get(currBpmnId) != null) {
259                 bpmnText = bpmnText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
260                 imageText = imageText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
261                 propText = propText.replace(currBpmnId, newBpmnIdsMap.get(currBpmnId));
262             }
263         }
264         cldsTemplate.setBpmnText(bpmnText);
265         cldsTemplate.setImageText(imageText);
266         cldsTemplate.setPropText(propText);
267         logger.info(" bpmnText : " + cldsTemplate.getBpmnText());
268         logger.info(" Image Text : " + cldsTemplate.getImageText());
269         logger.info(" Prop Text : " + cldsTemplate.getPropText());
270         cldsTemplate.save(cldsDao, userid);
271
272         // audit log
273         LoggingUtils.setTimeContext(startTime, new Date());
274         LoggingUtils.setResponseContext("0", "Put template success", this.getClass().getName());
275         auditLogger.info("PUT template completed");
276
277         return cldsTemplate;
278     }
279
280     /**
281      * REST service that retrieves a list of CLDS template names.
282      *
283      * @return template names in JSON
284      */
285     @GET
286     @Path("/template-names")
287     @Produces(MediaType.APPLICATION_JSON)
288     public List<ValueItem> getTemplateNames() {
289         Date startTime = new Date();
290         LoggingUtils.setRequestContext("CldsTemplateService: GET template names", getPrincipalName());
291         isAuthorized(permissionReadTemplate);
292         logger.info("GET list of template names");
293         List<ValueItem> names = cldsDao.getTemplateNames();
294         // audit log
295         LoggingUtils.setTimeContext(startTime, new Date());
296         LoggingUtils.setResponseContext("0", "Get template names success", this.getClass().getName());
297         auditLogger.info("GET template names completed");
298         return names;
299     }
300
301     private Map<String, String> getNewBpmnIdsMap(String bpmnText, String propText)
302             throws TransformerException, IOException {
303         /**
304          * Test sample code start
305          */
306         String bpmnJson = cldsBpmnTransformer.doXslTransformToString(bpmnText);
307         ModelBpmn templateBpmn = ModelBpmn.create(bpmnJson);
308         List<String> bpmnElementIds = templateBpmn.getBpmnElementIds();
309         logger.info("value of elementIds:" + bpmnElementIds);
310         logger.info("value of prop text:" + propText);
311         Map<String, String> bpmnIoIdsMap = new HashMap<>();
312         if (bpmnElementIds != null && bpmnElementIds.size() > 0) {
313             ObjectMapper objectMapper = new ObjectMapper();
314             ObjectNode root = objectMapper.readValue(propText, ObjectNode.class);
315             Iterator<Entry<String, JsonNode>> entryItr = root.fields();
316             while (entryItr.hasNext()) {
317                 // process the entry
318                 Entry<String, JsonNode> entry = entryItr.next();
319                 String keyPropName = entry.getKey();
320                 for (String currElementId : bpmnElementIds) {
321                     if (keyPropName != null && keyPropName.equalsIgnoreCase(currElementId)) {
322                         ArrayNode arrayNode = (ArrayNode) entry.getValue();
323                         // process each id/from object, like:
324                         // {"id":"Collector_11r50j1", "from":"StartEvent_1"}
325                         for (JsonNode anArrayNode : arrayNode) {
326                             ObjectNode node = (ObjectNode) anArrayNode;
327                             String valueNode = node.get("value").asText();
328                             logger.info("value of node:" + valueNode);
329                             if (keyPropName.startsWith(collectorKey)) {
330                                 valueNode = collectorKey + "_" + valueNode;
331                             } else if (keyPropName.startsWith(stringMatchKey)) {
332                                 valueNode = stringMatchKey + "_" + valueNode;
333                             } else if (keyPropName.startsWith(policyKey)) {
334                                 valueNode = policyKey + "_" + valueNode;
335                             }
336                             bpmnIoIdsMap.put(keyPropName, valueNode);
337                         }
338                         break;
339                     }
340                 }
341             }
342         }
343         logger.info("value of hashmap:" + bpmnIoIdsMap);
344         /**
345          * Test sample code end
346          */
347         return bpmnIoIdsMap;
348     }
349 }