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