Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / controller / DictionaryController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.controller;
22
23 import java.io.PrintWriter;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.servlet.http.HttpServletRequest;
31 import javax.servlet.http.HttpServletResponse;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.json.JSONObject;
36 import org.openecomp.policy.pap.xacml.rest.util.JsonMessage;
37 import org.openecomp.policy.rest.dao.CommonClassDao;
38 import org.openecomp.policy.rest.jpa.Attribute;
39 import org.openecomp.policy.rest.jpa.Category;
40 import org.openecomp.policy.rest.jpa.Datatype;
41 import org.openecomp.policy.rest.jpa.EcompName;
42 import org.openecomp.policy.rest.jpa.UserInfo;
43 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.http.MediaType;
46 import org.springframework.stereotype.Controller;
47 import org.springframework.web.bind.annotation.RequestMapping;
48 import org.springframework.web.bind.annotation.RequestMethod;
49 import org.springframework.web.servlet.ModelAndView;
50
51 import com.fasterxml.jackson.databind.DeserializationFeature;
52 import com.fasterxml.jackson.databind.JsonNode;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54
55 @Controller
56 public class DictionaryController {
57         
58         private static final Log LOGGER = LogFactory.getLog(DictionaryController.class);
59
60         private static CommonClassDao commonClassDao;
61         
62         @Autowired
63         public DictionaryController(CommonClassDao commonClassDao){
64                 DictionaryController.commonClassDao = commonClassDao;
65         }
66         
67         public DictionaryController(){}
68         
69         public UserInfo getUserInfo(String loginId){
70                 UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId);
71                 return name;    
72         }
73         
74         
75         public Category getCategory(){
76                 List<Object> list = commonClassDao.getData(Category.class);
77                 for (int i = 0; i < list.size() ; i++) {
78                         Category value = (Category) list.get(i);
79                         if (value.getShortName().equals("resource")) {
80                                 return value;
81                         }
82                 }
83                 return null;    
84         }
85
86         @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
87         public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletRequest request, HttpServletResponse response){
88                 try{
89                         System.out.println();
90                         Map<String, Object> model = new HashMap<>();
91                         ObjectMapper mapper = new ObjectMapper();
92                         model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")));
93                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
94                         JSONObject j = new JSONObject(msg);
95                         response.getWriter().write(j.toString());
96                 }
97                 catch (Exception e){
98                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
99                 }
100         }
101         
102         //Attribute Dictionary
103         @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE)
104         public void getAttributeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
105                 try{
106                         System.out.println();
107                         Map<String, Object> model = new HashMap<>();
108                         ObjectMapper mapper = new ObjectMapper();
109                         model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Attribute.class)));
110                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
111                         JSONObject j = new JSONObject(msg);
112             response.addHeader("successMapKey", "success"); 
113             response.addHeader("operation", "getDictionary");
114                         response.getWriter().write(j.toString());
115                 }
116                 catch (Exception e){
117             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
118             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
119             response.addHeader("error", "dictionaryDBQuery");
120                 }
121         }
122         
123         @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
124         public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
125                 try {
126                         boolean duplicateflag = false;
127             boolean isFakeUpdate = false;
128             boolean fromAPI = false;
129             if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
130                 fromAPI = true;
131             }
132                         ObjectMapper mapper = new ObjectMapper();
133                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
134                         JsonNode root = mapper.readTree(request.getReader());
135             Attribute attributeData = null;
136             AttributeValues attributeValueData = null;
137             String userId = null;
138             if (fromAPI) {
139                 //JsonNode json = root.get("dictionaryFields");
140                 attributeData = (Attribute)mapper.readValue(root.get("dictionaryFields").toString(), Attribute.class);
141                 attributeValueData = (AttributeValues)mapper.readValue(root.get("dictionaryFields").toString(), AttributeValues.class);
142                 userId = "API";
143                 
144                 //check if update operation or create, get id for data to be updated and update attributeData
145                 if (request.getParameter("operation").equals("update")) {
146                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class);
147                         int id = 0;
148                         Attribute data = (Attribute) duplicateData.get(0);
149                         id = data.getId();
150                         if(id==0){
151                                 isFakeUpdate=true;
152                                 attributeData.setId(1);
153                         } else {
154                                 attributeData.setId(id);
155                         }
156                         attributeData.setUserCreatedBy(this.getUserInfo(userId));
157                 }
158             } else {
159                 attributeData = (Attribute)mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class);
160                 attributeValueData = (AttributeValues)mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class);
161                 userId = root.get("userid").textValue();
162             }
163                         String userValue = "";
164                         int counter = 0;
165                         if(attributeValueData.getUserDataTypeValues().size() > 0){
166                                 for(Object attribute : attributeValueData.getUserDataTypeValues()){
167                                         if(attribute instanceof LinkedHashMap<?, ?>){
168                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("attributeValues").toString();
169                                                 if(counter>0){
170                                                         userValue = userValue + ",";
171                                                 }
172                                                 userValue = userValue + key ;
173                                                 counter ++;
174                                         }
175                                 }
176                         }
177                         attributeData.setAttributeValue(userValue);
178                         if(attributeData.getDatatypeBean().getShortName() != null){
179                                 String datatype = attributeData.getDatatypeBean().getShortName();
180                                 Datatype a = new Datatype();
181                                 if(datatype.equalsIgnoreCase("string")){
182                                         a.setId(26);    
183                                 }else if(datatype.equalsIgnoreCase("integer")){
184                                         a.setId(12);    
185                                 }else if(datatype.equalsIgnoreCase("boolean")){
186                                         a.setId(18);    
187                                 }else if(datatype.equalsIgnoreCase("double")){
188                                         a.setId(25);    
189                                 }else if(datatype.equalsIgnoreCase("user")){
190                                         a.setId(29);    
191                                 }
192                                 attributeData.setDatatypeBean(a);
193                         }
194                         if(attributeData.getId() == 0){
195                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class);
196                                 if(!duplicateData.isEmpty()){
197                                         duplicateflag = true;
198                                 }else{
199                                         attributeData.setCategoryBean(this.getCategory());
200                                         attributeData.setUserCreatedBy(this.getUserInfo(userId));
201                                         attributeData.setUserModifiedBy(this.getUserInfo(userId));
202                                         commonClassDao.save(attributeData);
203                                 }
204                         }else{
205                                 if(!isFakeUpdate) {
206                                         attributeData.setUserModifiedBy(this.getUserInfo(userId));
207                                         commonClassDao.update(attributeData); 
208                                 }
209                         } 
210             String responseString = null;
211             if(duplicateflag) {
212                 responseString = "Duplicate";
213             } else {
214                 responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class));
215             }
216             
217             if (fromAPI) {
218                 if (responseString!=null && !responseString.equals("Duplicate")) {
219                     if(isFakeUpdate) {
220                         responseString = "Exists";
221                     } else {
222                         responseString = "Success";
223                     }
224                 }
225                 ModelAndView result = new ModelAndView();
226                 result.setViewName(responseString);
227                 return result;
228             } else {
229                 response.setCharacterEncoding("UTF-8");
230                 response.setContentType("application / json");
231                 request.setCharacterEncoding("UTF-8");
232  
233                 PrintWriter out = response.getWriter();
234                 JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}");
235                 out.write(j.toString());
236                 return null;
237             }
238         }catch (Exception e){
239                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
240                         response.setCharacterEncoding("UTF-8");
241                         request.setCharacterEncoding("UTF-8");
242                         PrintWriter out = response.getWriter();
243                         out.write(e.getMessage());
244                 }
245                 return null;
246         }
247
248         @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
249         public ModelAndView removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
250                 try{
251                         ObjectMapper mapper = new ObjectMapper();
252                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
253                         JsonNode root = mapper.readTree(request.getReader());
254                         Attribute attributeData = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class);
255                         commonClassDao.delete(attributeData);
256                         response.setCharacterEncoding("UTF-8");
257                         response.setContentType("application / json");
258                         request.setCharacterEncoding("UTF-8");
259
260                         PrintWriter out = response.getWriter();
261                         String responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class));
262                         JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}");
263                         out.write(j.toString());
264                         return null;
265                 }
266                 catch (Exception e){
267                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
268                         response.setCharacterEncoding("UTF-8");
269                         request.setCharacterEncoding("UTF-8");
270                         PrintWriter out = response.getWriter();
271                         out.write(e.getMessage());
272                 }
273                 return null;
274         }
275         
276         //EcompName Dictionary
277         @RequestMapping(value={"/get_EcompNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
278         public void getEcompNameDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
279                 LOGGER.info("get_EcompNameDataByName is called");
280                 try{
281                         Map<String, Object> model = new HashMap<>();
282                         ObjectMapper mapper = new ObjectMapper();
283                         model.put("ecompNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(EcompName.class, "ecompName")));
284                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
285                         JSONObject j = new JSONObject(msg);
286                         response.getWriter().write(j.toString());
287                 }
288                 catch (Exception e){
289                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
290                 }
291         }
292         
293         @RequestMapping(value={"/get_EcompNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
294         public void getEcompNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
295                 try{
296                         Map<String, Object> model = new HashMap<>();
297                         ObjectMapper mapper = new ObjectMapper();
298                         model.put("ecompNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(EcompName.class)));
299                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
300                         JSONObject j = new JSONObject(msg);
301             response.addHeader("successMapKey", "success"); 
302             response.addHeader("operation", "getDictionary");
303                         response.getWriter().write(j.toString());
304                 }
305                 catch (Exception e){
306             LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
307             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
308             response.addHeader("error", "dictionaryDBQuery");
309                 }
310         }
311
312         @RequestMapping(value={"/ecomp_dictionary/save_ecompName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
313         public ModelAndView saveEcompDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
314                 try {
315                         boolean duplicateflag = false;
316                         boolean isFakeUpdate = false;
317                         boolean fromAPI = false;
318                         if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) {
319                                 fromAPI = true;
320                         }
321                         ObjectMapper mapper = new ObjectMapper();
322                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
323                         JsonNode root = mapper.readTree(request.getReader());
324                         EcompName ecompData;
325                         String userId = null;
326                         if (fromAPI) {
327                                 ecompData = (EcompName)mapper.readValue(root.get("dictionaryFields").toString(), EcompName.class);
328                                 userId = "API";
329
330                                 //check if update operation or create, get id for data to be updated
331                                 if (request.getParameter("operation").equals("update")) {
332                                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(ecompData.getEcompName(), "ecompName", EcompName.class);
333                                         int id = 0;
334                                         EcompName data = (EcompName) duplicateData.get(0);
335                                         id = data.getId();
336                                         if(id==0){
337                                                 isFakeUpdate=true;
338                                                 ecompData.setId(1);
339                                         } else {
340                                                 ecompData.setId(id);
341                                         }
342                                         ecompData.setUserCreatedBy(this.getUserInfo(userId));
343                                 }
344                         } else {
345                                 ecompData = (EcompName)mapper.readValue(root.get("ecompNameDictionaryData").toString(), EcompName.class);
346                                 userId = root.get("userid").textValue();
347                         }
348                         if(ecompData.getId() == 0){
349                                 List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(ecompData.getEcompName(), "ecompName", EcompName.class);
350                                 if(!duplicateData.isEmpty()){
351                                         duplicateflag = true;
352                                 }else{
353                                         ecompData.setUserCreatedBy(getUserInfo(userId));
354                                         ecompData.setUserModifiedBy(getUserInfo(userId));
355                                         commonClassDao.save(ecompData);
356                                 }
357                         }else{
358                                 if(!isFakeUpdate){
359                                         ecompData.setUserModifiedBy(this.getUserInfo(userId));
360                                         commonClassDao.update(ecompData);
361                                 }
362                         } 
363                         String responseString = null;
364                         if(duplicateflag) {
365                                 responseString = "Duplicate";
366                         } else {
367                                 responseString = mapper.writeValueAsString(commonClassDao.getData(EcompName.class));
368                         }
369                         if (fromAPI) {
370                                 if (responseString!=null && !responseString.equals("Duplicate")) {
371                                         if(isFakeUpdate){
372                                                 responseString = "Exists";
373                                         } else {
374                                                 responseString = "Success";
375                                         }
376                                 }
377
378                                 ModelAndView result = new ModelAndView();
379                                 result.setViewName(responseString);
380                                 return result;
381                         } else {
382                                 response.setCharacterEncoding("UTF-8");
383                                 response.setContentType("application / json");
384                                 request.setCharacterEncoding("UTF-8");
385
386                                 PrintWriter out = response.getWriter();
387                                 JSONObject j = new JSONObject("{ecompNameDictionaryDatas: " + responseString + "}");
388                                 out.write(j.toString());
389                                 return null;
390                         }
391                 }catch (Exception e){
392                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
393                         response.setCharacterEncoding("UTF-8");
394                         request.setCharacterEncoding("UTF-8");
395                         PrintWriter out = response.getWriter();
396                         out.write(e.getMessage());
397                 }
398                 return null;
399         }
400
401         @RequestMapping(value={"/ecomp_dictionary/remove_ecomp"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
402         public ModelAndView removeEcompDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
403                 try{
404                         ObjectMapper mapper = new ObjectMapper();
405                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
406                         JsonNode root = mapper.readTree(request.getReader());
407                         EcompName ecompData = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class);
408                         commonClassDao.delete(ecompData);
409                         response.setCharacterEncoding("UTF-8");
410                         response.setContentType("application / json");
411                         request.setCharacterEncoding("UTF-8");
412
413                         PrintWriter out = response.getWriter();
414
415                         String responseString = mapper.writeValueAsString(commonClassDao.getData(EcompName.class));
416                         JSONObject j = new JSONObject("{ecompNameDictionaryDatas: " + responseString + "}");
417                         out.write(j.toString());
418
419                         return null;
420                 }
421                 catch (Exception e){
422                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
423                         response.setCharacterEncoding("UTF-8");
424                         request.setCharacterEncoding("UTF-8");
425                         PrintWriter out = response.getWriter();
426                         out.write(e.getMessage());
427                 }
428                 return null;
429         }
430
431 }
432
433 class AttributeValues{
434         private ArrayList<Object> userDataTypeValues;
435
436         public ArrayList<Object> getUserDataTypeValues() {
437                 return userDataTypeValues;
438         }
439
440         public void setUserDataTypeValues(ArrayList<Object> userDataTypeValues) {
441                 this.userDataTypeValues = userDataTypeValues;
442         }
443 }
444