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