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