Merge "Add Junit to policy/engine LogParser package"
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / controller / MicroServiceDictionaryController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.onap.policy.pap.xacml.rest.controller;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30
31 import javax.servlet.http.HttpServletRequest;
32 import javax.servlet.http.HttpServletResponse;
33
34 import org.apache.commons.lang.StringUtils;
35 import org.json.JSONObject;
36 import org.onap.policy.common.logging.flexlogger.FlexLogger;
37 import org.onap.policy.common.logging.flexlogger.Logger;
38 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
39 import org.onap.policy.pap.xacml.rest.util.DictionaryUtils;
40 import org.onap.policy.pap.xacml.rest.util.JsonMessage;
41 import org.onap.policy.rest.dao.CommonClassDao;
42 import org.onap.policy.rest.jpa.DCAEuuid;
43 import org.onap.policy.rest.jpa.MicroServiceAttribute;
44 import org.onap.policy.rest.jpa.MicroServiceConfigName;
45 import org.onap.policy.rest.jpa.MicroServiceLocation;
46 import org.onap.policy.rest.jpa.MicroServiceModels;
47 import org.onap.policy.rest.jpa.PrefixList;
48 import org.onap.policy.rest.jpa.UserInfo;
49 import org.onap.policy.rest.util.MSAttributeObject;
50 import org.onap.policy.rest.util.MSModelUtils;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.http.MediaType;
53 import org.springframework.stereotype.Controller;
54 import org.springframework.web.bind.annotation.RequestMapping;
55 import org.springframework.web.bind.annotation.RequestMethod;
56 import org.springframework.web.servlet.ModelAndView;
57
58 import com.fasterxml.jackson.databind.DeserializationFeature;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.google.gson.Gson;
62
63 @Controller
64 public class MicroServiceDictionaryController {
65         private static final Logger LOGGER  = FlexLogger.getLogger(MicroServiceDictionaryController.class);
66
67         private static CommonClassDao commonClassDao;
68         
69     private static String successMapKey= "successMapKey";
70     private static String successMsg = "success";
71     private static String operation = "operation";
72     private static String getDictionary = "getDictionary";
73     private static String errorMsg = "error";
74     private static String dictionaryDBQuery = "dictionaryDBQuery";
75     private HashMap<String,MSAttributeObject > classMap;
76     private List<String> modelList = new ArrayList<>();
77         private static String dictionaryFields ="dictionaryFields";
78         private static String duplicateResponseString = "Duplicate";
79         private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas";
80         private static String modelName = "modelName";
81         private static String microServiceModelsDictionaryData = "microServiceModelsDictionaryData";
82         private static String description = "description";
83         private static String version = "version";
84         private static String classMapData = "classMap";
85         private static String dcaeUUIDDatas = "dcaeUUIDDictionaryDatas";
86         private static String microServiceConfigNameDatas = "microServiceConfigNameDictionaryDatas";
87         private static String microServiceLocationDatas = "microServiceLocationDictionaryDatas";
88         private static String microServiceAttributeDatas = "microServiceAttributeDictionaryDatas";
89
90     public MicroServiceDictionaryController(){
91         super();
92     }   
93         
94     private DictionaryUtils getDictionaryUtilsInstance(){
95                 return DictionaryUtils.dictionaryUtils != null ? DictionaryUtils.getDictionaryUtils() : new DictionaryUtils();
96         }
97     
98         @Autowired
99         public MicroServiceDictionaryController(CommonClassDao commonClassDao){
100                 MicroServiceDictionaryController.commonClassDao = commonClassDao;
101         }
102         public static void setCommonClassDao(CommonClassDao commonClassDao) {
103                 MicroServiceDictionaryController.commonClassDao = commonClassDao;
104         }
105
106         MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
107         
108         private MicroServiceModels newModel;
109         
110         @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
111         public void getDCAEUUIDDictionaryByNameEntityData(HttpServletResponse response){
112                 DictionaryUtils utils = getDictionaryUtilsInstance();
113                 utils.getDataByEntity(response, dcaeUUIDDatas, "name", DCAEuuid.class);
114         }
115
116         @RequestMapping(value={"/get_DCAEUUIDData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
117         public void getDCAEUUIDDictionaryEntityData(HttpServletResponse response){
118                 DictionaryUtils utils = getDictionaryUtilsInstance();
119                 utils.getData(response, dcaeUUIDDatas, DCAEuuid.class);
120         }
121         
122         @RequestMapping(value={"/ms_dictionary/save_dcaeUUID"}, method={RequestMethod.POST})
123         public ModelAndView saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
124                 DictionaryUtils utils = getDictionaryUtilsInstance();
125                 try {
126                         boolean fromAPI = utils.isRequestFromAPI(request);
127                         ObjectMapper mapper = new ObjectMapper();
128                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
129                         JsonNode root = mapper.readTree(request.getReader());
130             DCAEuuid dCAEuuid;
131             if(fromAPI){
132                 dCAEuuid = mapper.readValue(root.get(dictionaryFields).toString(), DCAEuuid.class);
133             }else{
134                 dCAEuuid = mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class);
135             }
136             
137             List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class);
138                         boolean duplicateflag = false;
139                         if(!duplicateData.isEmpty()){
140                                 DCAEuuid data = (DCAEuuid) duplicateData.get(0);
141                                 if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
142                                         dCAEuuid.setId(data.getId());
143                                 }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || 
144                                                 (request.getParameter(operation) == null && (data.getId() != dCAEuuid.getId()))){
145                                         duplicateflag = true;
146                                 }
147                         }
148                         String responseString = null;
149                         if(!duplicateflag){
150                                 if(dCAEuuid.getId() == 0){
151                                         commonClassDao.save(dCAEuuid);
152                                 }else{
153                                         commonClassDao.update(dCAEuuid); 
154                                 } 
155                                 responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class));
156                         }else{
157                                 responseString = duplicateResponseString;
158                         }
159                         if(fromAPI){
160                                 return utils.getResultForApi(responseString);
161                         }else{
162                                 utils.setResponseData(response, dcaeUUIDDatas, responseString);
163                         }
164         }catch (Exception e){
165                 utils.setErrorResponseData(response, e);
166                 }
167                 return null;
168         }
169
170         @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid"}, method={RequestMethod.POST})
171         public void removeDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
172                 DictionaryUtils utils = getDictionaryUtilsInstance();
173                 utils.removeData(request, response, dcaeUUIDDatas, DCAEuuid.class);
174         }
175         
176         @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
177         public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletResponse response){
178                 DictionaryUtils utils = getDictionaryUtilsInstance();
179                 utils.getDataByEntity(response, microServiceConfigNameDatas, "name", MicroServiceConfigName.class);
180         }
181         
182         @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
183         public void getMicroServiceConfigNameDictionaryEntityData(HttpServletResponse response){
184                 DictionaryUtils utils = getDictionaryUtilsInstance();
185                 utils.getData(response, microServiceConfigNameDatas, MicroServiceConfigName.class);
186         }
187         
188         @RequestMapping(value={"/ms_dictionary/save_configName"}, method={RequestMethod.POST})
189         public ModelAndView saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
190                 DictionaryUtils utils = getDictionaryUtilsInstance();
191                 try {
192                         boolean fromAPI = utils.isRequestFromAPI(request);
193                         ObjectMapper mapper = new ObjectMapper();
194                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
195                         JsonNode root = mapper.readTree(request.getReader());
196             MicroServiceConfigName microServiceConfigName;
197             if(fromAPI){
198                 microServiceConfigName = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceConfigName.class);
199             }else{
200                 microServiceConfigName = mapper.readValue(root.get("microServiceConfigNameDictionaryData").toString(), MicroServiceConfigName.class);
201             }
202             List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class);
203                         boolean duplicateflag = false;
204                         if(!duplicateData.isEmpty()){
205                                 MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0);
206                                 if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
207                                         microServiceConfigName.setId(data.getId());
208                                 }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || 
209                                                 (request.getParameter(operation) == null && (data.getId() != microServiceConfigName.getId()))){
210                                         duplicateflag = true;
211                                 }
212                         }
213                         String responseString = null;
214                         if(!duplicateflag){
215                                 if(microServiceConfigName.getId() == 0){
216                                         commonClassDao.save(microServiceConfigName);
217                                 }else{
218                                         commonClassDao.update(microServiceConfigName); 
219                                 } 
220                                 responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class));
221                         }else{
222                                 responseString = duplicateResponseString;
223                         }
224                         if(fromAPI){
225                                 return utils.getResultForApi(responseString);
226                         }else{
227                                 utils.setResponseData(response, microServiceConfigNameDatas, responseString);
228                         }
229         }catch (Exception e){
230                 utils.setErrorResponseData(response, e);
231                 }
232                 return null;
233         }
234
235         @RequestMapping(value={"/ms_dictionary/remove_msConfigName"}, method={RequestMethod.POST})
236         public void removeMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
237                 DictionaryUtils utils = getDictionaryUtilsInstance();
238                 utils.removeData(request, response, microServiceConfigNameDatas, MicroServiceConfigName.class);
239         }
240         
241         @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
242         public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletResponse response){
243                 DictionaryUtils utils = getDictionaryUtilsInstance();
244                 utils.getDataByEntity(response, microServiceLocationDatas, "name", MicroServiceLocation.class);
245         }
246         
247         @RequestMapping(value={"/get_MicroServiceLocationData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
248         public void getMicroServiceLocationDictionaryEntityData(HttpServletResponse response){
249                 DictionaryUtils utils = getDictionaryUtilsInstance();
250                 utils.getData(response, microServiceLocationDatas, MicroServiceLocation.class);
251         }
252         
253         @RequestMapping(value={"/ms_dictionary/save_location"}, method={RequestMethod.POST})
254         public ModelAndView saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException{
255                 DictionaryUtils utils = getDictionaryUtilsInstance();
256                 try {
257                         boolean fromAPI = utils.isRequestFromAPI(request);
258                         ObjectMapper mapper = new ObjectMapper();
259                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
260                         JsonNode root = mapper.readTree(request.getReader());
261             MicroServiceLocation microServiceLocation;
262             if(fromAPI){
263                 microServiceLocation = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceLocation.class);
264             }else{
265                 microServiceLocation = mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class);
266             }
267             
268             List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class);
269                         boolean duplicateflag = false;
270                         if(!duplicateData.isEmpty()){
271                                 MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0);
272                                 if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
273                                         microServiceLocation.setId(data.getId());
274                                 }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || 
275                                                 (request.getParameter(operation) == null && (data.getId() != microServiceLocation.getId()))){
276                                         duplicateflag = true;
277                                 }
278                         }
279                         String responseString = null;
280                         if(!duplicateflag){
281                                 if(microServiceLocation.getId() == 0){
282                                         commonClassDao.save(microServiceLocation);
283                                 }else{
284                                         commonClassDao.update(microServiceLocation); 
285                                 } 
286                                 responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class));
287                         }else{
288                                 responseString = duplicateResponseString;
289                         }
290                         if(fromAPI){
291                                 return utils.getResultForApi(responseString);
292                         }else{
293                                 utils.setResponseData(response, microServiceLocationDatas, responseString);
294                         }
295                 }catch (Exception e){
296                         utils.setErrorResponseData(response, e);
297                 }
298                 return null;
299         }
300
301         @RequestMapping(value={"/ms_dictionary/remove_msLocation"}, method={RequestMethod.POST})
302         public void removeMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
303                 DictionaryUtils utils = getDictionaryUtilsInstance();
304                 utils.removeData(request, response, microServiceLocationDatas, MicroServiceLocation.class);
305         }
306         
307     @RequestMapping(value={"/get_MicroServiceAttributeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
308     public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletResponse response){
309         DictionaryUtils utils = getDictionaryUtilsInstance();
310                 utils.getDataByEntity(response, microServiceAttributeDatas, "name", MicroServiceAttribute.class);
311     }
312     
313     @RequestMapping(value={"/get_MicroServiceAttributeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
314     public void getMicroServiceAttributeDictionaryEntityData(HttpServletResponse response){
315         DictionaryUtils utils = getDictionaryUtilsInstance();
316                 utils.getData(response, microServiceAttributeDatas, MicroServiceAttribute.class);
317     }
318     
319     @RequestMapping(value={"/ms_dictionary/save_modelAttribute"}, method={RequestMethod.POST})
320     public ModelAndView saveMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
321         DictionaryUtils utils = getDictionaryUtilsInstance();
322         try {
323                         boolean fromAPI = utils.isRequestFromAPI(request);
324             ObjectMapper mapper = new ObjectMapper();
325             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
326             JsonNode root = mapper.readTree(request.getReader());
327             
328             MicroServiceAttribute microServiceAttribute;
329             String checkValue;
330             if (fromAPI) {
331                 microServiceAttribute = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceAttribute.class);
332                 MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class);
333                 checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName();
334             } else {
335                 microServiceAttribute = mapper.readValue(root.get("modelAttributeDictionaryData").toString(), MicroServiceAttribute.class);
336                 checkValue = microServiceAttribute.getName() + ":" + microServiceAttribute.getValue() + ":" + microServiceAttribute.getModelName();
337             }
338       
339             List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class);
340                         boolean duplicateflag = false;
341                         if(!duplicateData.isEmpty()){
342                                 MicroServiceAttribute data = (MicroServiceAttribute) duplicateData.get(0);
343                                 if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
344                                         microServiceAttribute.setId(data.getId());
345                                 }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || 
346                                                 (request.getParameter(operation) == null && (data.getId() != microServiceAttribute.getId()))){
347                                         duplicateflag = true;
348                                 }
349                         }
350                         String responseString = null;
351                         if(!duplicateflag){
352                                 if(microServiceAttribute.getId() == 0){
353                                         commonClassDao.save(microServiceAttribute);
354                                 }else{
355                                         commonClassDao.update(microServiceAttribute); 
356                                 } 
357                                 responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class));
358                         }else{
359                                 responseString = duplicateResponseString;
360                         }
361                         if(fromAPI){
362                                 return utils.getResultForApi(responseString);
363                         }else{
364                                 utils.setResponseData(response, microServiceAttributeDatas, responseString);
365                         }
366         }
367         catch (Exception e){
368                 utils.setErrorResponseData(response, e);
369         }
370         return null;
371     }
372  
373     @RequestMapping(value={"/ms_dictionary/remove_modelAttribute"}, method={RequestMethod.POST})
374     public void removeMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
375         DictionaryUtils utils = getDictionaryUtilsInstance();
376                 utils.removeData(request, response, microServiceAttributeDatas, MicroServiceAttribute.class);
377     }
378  
379         
380         @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
381         public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletResponse response){
382                 DictionaryUtils utils = getDictionaryUtilsInstance();
383                 utils.getDataByEntity(response, microServiceModelsDictionaryDatas, modelName, MicroServiceModels.class);
384         }
385         
386     @RequestMapping(value={"/get_MicroServiceModelsDataByVersion"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
387     public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response){
388         try{
389             Map<String, Object> model = new HashMap<>();
390             ObjectMapper mapper = new ObjectMapper();
391             JsonNode root = mapper.readTree(request.getReader());
392             String modelName = null;
393             if (root.get(microServiceModelsDictionaryData).has(modelName)){
394                 modelName = root.get(microServiceModelsDictionaryData).get(modelName).asText().replace("\"", "");
395             }
396              if (modelName!=null){
397                     model.put(microServiceModelsDictionaryDatas, mapper.writeValueAsString(commonClassDao.getDataById(MicroServiceModels.class, modelName, modelName)));
398              } else{
399                  model.put(errorMsg, "No model name given");
400              }
401             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
402             JSONObject j = new JSONObject(msg);
403             response.getWriter().write(j.toString());
404         }
405         catch (Exception e){
406             LOGGER.error(e);
407         }
408     }
409     
410         @RequestMapping(value={"/get_MicroServiceModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
411         public void getMicroServiceModelsDictionaryEntityData(HttpServletResponse response){
412                 DictionaryUtils utils = getDictionaryUtilsInstance();
413                 utils.getData(response, microServiceModelsDictionaryDatas, MicroServiceModels.class);
414         }
415         
416     @RequestMapping(value={"/get_MicroServiceModelsDataServiceVersion"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
417     public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletResponse response){
418         try{
419             Map<String, Object> model = new HashMap<>();
420             ObjectMapper mapper = new ObjectMapper();
421             List<String> data = new ArrayList<>();
422             List<Object> datas = commonClassDao.getData(MicroServiceModels.class);
423             for(int i = 0; i < datas.size(); i++){
424                 MicroServiceModels msmodel = (MicroServiceModels) datas.get(i);
425                 if (!data.contains(msmodel.getModelName())){
426                         data.add(msmodel.getModelName() + "-v" + msmodel.getVersion());
427                 }
428             }
429             model.put(microServiceModelsDictionaryDatas, mapper.writeValueAsString(data));
430             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
431             JSONObject j = new JSONObject(msg);
432             response.addHeader("successMapKey", "success"); 
433             response.addHeader("operation", "getDictionary");
434             response.getWriter().write(j.toString());
435  
436         }
437         catch (Exception e){
438             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
439             response.addHeader("error", "dictionaryDBQuery");
440             LOGGER.error(e);
441         }
442     }
443     
444     @RequestMapping(value={"/get_MicroServiceModelsDataByClass"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
445     public void getMicroServiceModelsDictionaryClassEntityData(HttpServletResponse response){
446         try{
447             Map<String, Object> model = new HashMap<>();
448             ObjectMapper mapper = new ObjectMapper();
449             model.put("microServiceModelsDictionaryClassDatas", mapper.writeValueAsString(modelList));
450             JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
451             JSONObject j = new JSONObject(msg);
452             response.addHeader(successMapKey, successMsg);    
453             response.addHeader(operation, getDictionary);
454             response.getWriter().write(j.toString());
455  
456         }
457         catch (Exception e){
458             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                             
459             response.addHeader(errorMsg, dictionaryDBQuery);
460             LOGGER.error(e);
461         }
462     }
463     
464         @RequestMapping(value={"/ms_dictionary/save_model"}, method={RequestMethod.POST})
465         public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{
466                 DictionaryUtils utils = getDictionaryUtilsInstance();
467                 try {
468                         this.newModel = new MicroServiceModels();
469                         boolean fromAPI = utils.isRequestFromAPI(request);
470                         ObjectMapper mapper = new ObjectMapper();
471                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
472                         JsonNode root = mapper.readTree(request.getReader());
473                         MicroServiceModels microServiceModels = new MicroServiceModels();
474                         String userId = null;
475
476                         if(root.has("modelType")){
477                                 JsonNode dataType = root.get("modelType");
478                                 String modelType= dataType.toString();
479                                 if(modelType.contains("yml")){
480                                         if (root.has(microServiceModelsDictionaryData)){
481                                                 if (root.get(microServiceModelsDictionaryData).has(description)){
482                                                         microServiceModels.setDescription(root.get(microServiceModelsDictionaryData).get(description).asText().replace("\"", ""));
483                                                 }
484                                                 if (root.get(microServiceModelsDictionaryData).has(modelName)){
485                                                         microServiceModels.setModelName(root.get(microServiceModelsDictionaryData).get(modelName).asText().replace("\"", ""));
486                                                         this.newModel.setModelName(microServiceModels.getModelName());
487                                                 }
488                                                 if (root.get(microServiceModelsDictionaryData).has(version)){
489                                                         microServiceModels.setVersion(root.get(microServiceModelsDictionaryData).get(version).asText().replace("\"", ""));
490                                                         this.newModel.setVersion(microServiceModels.getVersion());
491                                                 }
492                                         }
493
494                                         classMap = new HashMap<>();
495                                         JsonNode data = root.get(classMapData);
496                                         ObjectMapper mapper1 = new ObjectMapper();
497                                         String data1 = data.toString().substring(1, data.toString().length()-1);
498                                         data1 = data1.replace("\\", "");
499                                         data1=data1.replace("\"{","{");
500                                         data1=data1.replace("}\"","}");
501                                         JSONObject jsonObject = new JSONObject(data1);
502                                         Set<String> keys = jsonObject.keySet();
503                                         for(String key : keys){
504                                                 String value = jsonObject.get(key).toString();
505                                                 MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
506                                                 classMap.put(key, msAttributeObject);
507                                         }
508
509                                         userId = root.get("userid").textValue();
510                                         MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
511                                         this.newModel.setDependency("[]");
512                                         String value = new Gson().toJson(mainClass.getSubClass());
513                                         this.newModel.setSub_attributes(value);
514                                         String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
515                                         int equalsIndexForAttributes= attributes.indexOf('=');
516                                         String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1);
517                                         this.newModel.setAttributes(atttributesAfterFirstEquals);
518                                         String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
519                                         int equalsIndex= refAttributes.indexOf('=');
520                                         String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1);
521                                         this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
522                                         this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
523                                         this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
524
525                                 }else{
526                                         if (fromAPI) {
527                                                 microServiceModels = mapper.readValue(root.get(dictionaryFields).toString(), MicroServiceModels.class);
528                                                 userId = "API";
529                                         } else {
530                                                 if (root.has(microServiceModelsDictionaryData)){
531                                                         if (root.get(microServiceModelsDictionaryData).has(description)){
532                                                                 microServiceModels.setDescription(root.get(microServiceModelsDictionaryData).get(description).asText().replace("\"", ""));
533                                                         }
534                                                         if (root.get(microServiceModelsDictionaryData).has(modelName)){
535                                                                 microServiceModels.setModelName(root.get(microServiceModelsDictionaryData).get(modelName).asText().replace("\"", ""));
536                                                                 this.newModel.setModelName(microServiceModels.getModelName());
537                                                         }
538                                                         if (root.get(microServiceModelsDictionaryData).has(version)){
539                                                                 microServiceModels.setVersion(root.get(microServiceModelsDictionaryData).get(version).asText().replace("\"", ""));
540                                                                 this.newModel.setVersion(microServiceModels.getVersion());
541                                                         }
542                                                 }
543                                                 if(root.has(classMapData)){
544                                                         classMap = new HashMap<>();
545                                                         JsonNode data = root.get(classMapData);
546                                                         ObjectMapper mapper1 = new ObjectMapper();
547                                                         String data1 = data.toString().substring(1, data.toString().length()-1);
548                                                         data1 = data1.replace("\\", "");
549                                                         JSONObject jsonObject = new JSONObject(data1);
550                                                         Set<String> keys = jsonObject.keySet();
551                                                         for(String key : keys){
552                                                                 String value = jsonObject.get(key).toString();
553                                                                 MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class);
554                                                                 classMap.put(key, msAttributeObject);
555                                                         }
556                                                 }
557                                                 userId = root.get("userid").textValue();
558                                                 addValuesToNewModel(classMap);
559                                         }
560                                 }               
561                         }
562                         microServiceModels.setAttributes(this.newModel.getAttributes());
563                         microServiceModels.setRef_attributes(this.newModel.getRef_attributes());
564                         microServiceModels.setDependency(this.newModel.getDependency());
565                         microServiceModels.setModelName(this.newModel.getModelName());
566                         microServiceModels.setSub_attributes(this.newModel.getSub_attributes());
567                         microServiceModels.setVersion(this.newModel.getVersion());
568                         microServiceModels.setEnumValues(this.newModel.getEnumValues());
569                         microServiceModels.setAnnotation(this.newModel.getAnnotation());
570                         
571                         String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion();
572                         List<Object> duplicateData =  commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class);
573                         boolean duplicateflag = false;
574                         if(!duplicateData.isEmpty()){
575                                 MicroServiceModels data = (MicroServiceModels) duplicateData.get(0);
576                                 if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){
577                                         microServiceModels.setId(data.getId());
578                                 }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || 
579                                                 (request.getParameter(operation) == null && (data.getId() != microServiceModels.getId()))){
580                                         duplicateflag = true;
581                                 }
582                         }
583                         UserInfo userInfo = utils.getUserInfo(userId);
584                         
585                         String responseString = null;
586                         if(!duplicateflag){
587                                 microServiceModels.setUserCreatedBy(userInfo);
588                                 if(microServiceModels.getId() == 0){
589                                         commonClassDao.save(microServiceModels);
590                                 }else{
591                                         commonClassDao.update(microServiceModels); 
592                                 } 
593                                 responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class));
594                         }else{
595                                 responseString = duplicateResponseString;
596                         }
597                         if(fromAPI){
598                                 return utils.getResultForApi(responseString);
599                         }else{
600                                 utils.setResponseData(response, microServiceModelsDictionaryDatas, responseString);
601                         }
602                 }catch (Exception e){
603                         utils.setErrorResponseData(response, e);
604                 }
605                 return null;
606         }
607
608         @RequestMapping(value={"/ms_dictionary/remove_msModel"}, method={RequestMethod.POST})
609         public void removeMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException {
610                 DictionaryUtils utils = getDictionaryUtilsInstance();
611                 utils.removeData(request, response, microServiceModelsDictionaryDatas, MicroServiceModels.class);
612         }
613                 
614         private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) {
615                 //Loop  through the classmap and pull out the required info for the new file.
616                 String subAttribute = null;
617                 
618                 MSAttributeObject mainClass = classMap.get(this.newModel.getModelName());
619                 
620                 if (mainClass !=null){
621                         String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
622                         ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(",")));   
623                         dependency = getFullDependencyList(dependency);
624                         for (String element : dependency){
625                                 MSAttributeObject temp = classMap.get(element);
626                                 if (temp!=null){
627                                         mainClass.addAllRefAttribute(temp.getRefAttribute());
628                                         mainClass.addAllAttribute(temp.getAttribute());
629                                 }
630                         }
631                         subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
632                 }else{
633                         subAttribute = "{}";
634                         this.newModel.setDependency("");
635                 }
636
637                 if (mainClass != null && mainClass.getDependency()==null){
638                         mainClass.setDependency("");
639                 }
640                 if(mainClass != null){
641                         this.newModel.setDependency(mainClass.getDependency());
642                         this.newModel.setSub_attributes(subAttribute);
643                         this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
644                         this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
645                         this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
646                         this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
647                 }
648         } 
649         
650         private ArrayList<String> getFullDependencyList(ArrayList<String> dependency) {
651                 ArrayList<String> returnList = new ArrayList<>();
652                 ArrayList<String> workingList = new ArrayList<>();
653                 returnList.addAll(dependency);
654                 for (String element : dependency ){
655                         if (classMap.containsKey(element)){
656                                 MSAttributeObject value = classMap.get(element);                        
657                                 String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""});
658                                 workingList = new ArrayList<>(Arrays.asList(rawValue.split(",")));      
659                                 for(String depend : workingList){
660                                         if (!returnList.contains(depend) && !depend.isEmpty()){
661                                                 returnList.add(depend.trim());
662                                                 //getFullDepedency(workingList)
663                                         }
664                                 }
665                         }
666                 }
667                 
668                 return returnList;
669         }
670
671 }