Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / controller / MicroServiceDictionaryController.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.BufferedInputStream;
24 import java.io.BufferedOutputStream;
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.OutputStream;
29 import java.io.PrintWriter;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Enumeration;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.zip.ZipEntry;
37 import java.util.zip.ZipFile;
38
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.apache.commons.compress.utils.IOUtils;
43 import org.apache.commons.fileupload.FileItem;
44 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
45 import org.apache.commons.fileupload.servlet.ServletFileUpload;
46 import org.apache.commons.lang.StringUtils;
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49 import org.json.JSONObject;
50 import org.openecomp.policy.pap.xacml.rest.util.JsonMessage;
51 import org.openecomp.policy.rest.dao.DCAEUUIDDao;
52 import org.openecomp.policy.rest.dao.MicroServiceConfigNameDao;
53 import org.openecomp.policy.rest.dao.MicroServiceLocationDao;
54 import org.openecomp.policy.rest.dao.MicroServiceModelsDao;
55 import org.openecomp.policy.rest.dao.UserInfoDao;
56 import org.openecomp.policy.rest.jpa.DCAEuuid;
57 import org.openecomp.policy.rest.jpa.MicroServiceConfigName;
58 import org.openecomp.policy.rest.jpa.MicroServiceLocation;
59 import org.openecomp.policy.rest.jpa.MicroServiceModels;
60 import org.openecomp.policy.rest.jpa.UserInfo;
61 import org.openecomp.policy.rest.util.MSAttributeObject;
62 import org.openecomp.policy.rest.util.MSModelUtitils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.http.MediaType;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.servlet.ModelAndView;
68
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72
73 @Controller
74 public class MicroServiceDictionaryController {
75         private static final Log logger = LogFactory.getLog(MicroServiceDictionaryController.class);
76
77         @Autowired
78         MicroServiceConfigNameDao microServiceConfigNameDao;
79         
80         @Autowired
81         MicroServiceLocationDao microServiceLocationDao;
82         
83         @Autowired
84         MicroServiceModelsDao microServiceModelsDao;
85         
86         @Autowired
87         DCAEUUIDDao dcaeUUIDDao;
88         
89         @Autowired
90         UserInfoDao userInfoDao;
91         
92
93         private String newFile;
94         private String directory;
95         private List<String> dirDependencyList = new ArrayList<String>();
96         private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
97         MSModelUtitils utils = new MSModelUtitils();
98         private MicroServiceModels newModel;
99         
100         public UserInfo getUserInfo(String loginId){
101                 UserInfo name = userInfoDao.getUserInfoByLoginId(loginId);
102                 return name;    
103         }
104         
105         @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
106         public void getDCAEUUIDDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
107                 try{
108                         Map<String, Object> model = new HashMap<String, Object>();
109                         ObjectMapper mapper = new ObjectMapper();
110                         model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(dcaeUUIDDao.getDCAEuuidDataByName()));
111                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
112                         JSONObject j = new JSONObject(msg);
113                         response.getWriter().write(j.toString());
114                 }
115                 catch (Exception e){
116                         e.printStackTrace();
117                 }
118         }
119
120         @RequestMapping(value={"/get_DCAEUUIDData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
121         public void getDCAEUUIDDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
122                 try{
123                         Map<String, Object> model = new HashMap<String, Object>();
124                         ObjectMapper mapper = new ObjectMapper();
125                         model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(dcaeUUIDDao.getDCAEuuidData()));
126                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
127                         JSONObject j = new JSONObject(msg);
128                         response.getWriter().write(j.toString());
129                 }
130                 catch (Exception e){
131                         e.printStackTrace();
132                 }
133         }
134         
135         @RequestMapping(value={"/ms_dictionary/save_dcaeUUID.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
136         public ModelAndView saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
137                 try {
138                         boolean duplicateflag = false;
139                         ObjectMapper mapper = new ObjectMapper();
140                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
141                         JsonNode root = mapper.readTree(request.getReader());
142                         DCAEuuid dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class);
143                         if(dCAEuuid.getId() == 0){
144                                 CheckDictionaryDuplicateEntries entry = new CheckDictionaryDuplicateEntries();
145                                 List<Object> duplicateData =  entry.CheckDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class);
146                                 if(!duplicateData.isEmpty()){
147                                         duplicateflag = true;
148                                 }else{
149                                         dcaeUUIDDao.Save(dCAEuuid);
150                                 }
151                         }else{
152                                 dcaeUUIDDao.update(dCAEuuid); 
153                         } 
154                         response.setCharacterEncoding("UTF-8");
155                         response.setContentType("application / json");
156                         request.setCharacterEncoding("UTF-8");
157
158                         PrintWriter out = response.getWriter();
159                         String responseString = "";
160                         if(duplicateflag){
161                                 responseString = "Duplicate";
162                         }else{
163                                 responseString = mapper.writeValueAsString(this.dcaeUUIDDao.getDCAEuuidData());
164                         } 
165                         JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + responseString + "}");
166
167                         out.write(j.toString());
168
169                         return null;
170                 }
171                 catch (Exception e){
172                         response.setCharacterEncoding("UTF-8");
173                         request.setCharacterEncoding("UTF-8");
174                         PrintWriter out = response.getWriter();
175                         out.write(e.getMessage());
176                 }
177                 return null;
178         }
179
180         @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
181         public ModelAndView removeDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
182                 try{
183                         ObjectMapper mapper = new ObjectMapper();
184                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
185                         JsonNode root = mapper.readTree(request.getReader());
186                         DCAEuuid dCAEuuid = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class);
187                         dcaeUUIDDao.delete(dCAEuuid);
188                         response.setCharacterEncoding("UTF-8");
189                         response.setContentType("application / json");
190                         request.setCharacterEncoding("UTF-8");
191
192                         PrintWriter out = response.getWriter();
193
194                         String responseString = mapper.writeValueAsString(this.dcaeUUIDDao.getDCAEuuidData());
195                         JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + responseString + "}");
196                         out.write(j.toString());
197
198                         return null;
199                 }
200                 catch (Exception e){
201                         System.out.println(e);
202                         response.setCharacterEncoding("UTF-8");
203                         request.setCharacterEncoding("UTF-8");
204                         PrintWriter out = response.getWriter();
205                         out.write(e.getMessage());
206                 }
207                 return null;
208         }
209         
210         
211         @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
212         public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
213                 try{
214                         Map<String, Object> model = new HashMap<String, Object>();
215                         ObjectMapper mapper = new ObjectMapper();
216                         model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(microServiceConfigNameDao.getMSConfigDataByName()));
217                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
218                         JSONObject j = new JSONObject(msg);
219                         response.getWriter().write(j.toString());
220                 }
221                 catch (Exception e){
222                         e.printStackTrace();
223                 }
224         }
225         
226         
227         
228         @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
229         public void getMicroServiceConfigNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
230                 try{
231                         Map<String, Object> model = new HashMap<String, Object>();
232                         ObjectMapper mapper = new ObjectMapper();
233                         model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(microServiceConfigNameDao.getMicroServiceConfigNameData()));
234                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
235                         JSONObject j = new JSONObject(msg);
236                         response.getWriter().write(j.toString());
237                 }
238                 catch (Exception e){
239                         e.printStackTrace();
240                 }
241         }
242         
243         @RequestMapping(value={"/ms_dictionary/save_configName.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
244         public ModelAndView saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
245                 try {
246                         boolean duplicateflag = false;
247                         ObjectMapper mapper = new ObjectMapper();
248                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
249                         JsonNode root = mapper.readTree(request.getReader());
250                         MicroServiceConfigName microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("microServiceCongigNameDictionaryData").toString(), MicroServiceConfigName.class);
251                         if(microServiceConfigName.getId() == 0){
252                                 CheckDictionaryDuplicateEntries entry = new CheckDictionaryDuplicateEntries();
253                                 List<Object> duplicateData =  entry.CheckDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class);
254                                 if(!duplicateData.isEmpty()){
255                                         duplicateflag = true;
256                                 }else{
257                                         microServiceConfigNameDao.Save(microServiceConfigName);
258                                 }
259                         }else{
260                                 microServiceConfigNameDao.update(microServiceConfigName); 
261                         } 
262                         response.setCharacterEncoding("UTF-8");
263                         response.setContentType("application / json");
264                         request.setCharacterEncoding("UTF-8");
265
266                         PrintWriter out = response.getWriter();
267                         String responseString = "";
268                         if(duplicateflag){
269                                 responseString = "Duplicate";
270                         }else{
271                                 responseString = mapper.writeValueAsString(this.microServiceConfigNameDao.getMicroServiceConfigNameData());
272                         }
273                         JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + responseString + "}");
274
275                         out.write(j.toString());
276
277                         return null;
278                 }
279                 catch (Exception e){
280                         response.setCharacterEncoding("UTF-8");
281                         request.setCharacterEncoding("UTF-8");
282                         PrintWriter out = response.getWriter();
283                         out.write(e.getMessage());
284                 }
285                 return null;
286         }
287
288         @RequestMapping(value={"/ms_dictionary/remove_msConfigName.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
289         public ModelAndView removeMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
290                 try{
291                         ObjectMapper mapper = new ObjectMapper();
292                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
293                         JsonNode root = mapper.readTree(request.getReader());
294                         MicroServiceConfigName microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("data").toString(), MicroServiceConfigName.class);
295                         microServiceConfigNameDao.delete(microServiceConfigName);
296                         response.setCharacterEncoding("UTF-8");
297                         response.setContentType("application / json");
298                         request.setCharacterEncoding("UTF-8");
299
300                         PrintWriter out = response.getWriter();
301
302                         String responseString = mapper.writeValueAsString(this.microServiceConfigNameDao.getMicroServiceConfigNameData());
303                         JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + responseString + "}");
304                         out.write(j.toString());
305
306                         return null;
307                 }
308                 catch (Exception e){
309                         System.out.println(e);
310                         response.setCharacterEncoding("UTF-8");
311                         request.setCharacterEncoding("UTF-8");
312                         PrintWriter out = response.getWriter();
313                         out.write(e.getMessage());
314                 }
315                 return null;
316         }
317         
318         @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
319         public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
320                 try{
321                         Map<String, Object> model = new HashMap<String, Object>();
322                         ObjectMapper mapper = new ObjectMapper();
323                         model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(microServiceLocationDao.getMSLocationDataByName()));
324                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
325                         JSONObject j = new JSONObject(msg);
326                         response.getWriter().write(j.toString());
327                 }
328                 catch (Exception e){
329                         e.printStackTrace();
330                 }
331         }
332         
333         @RequestMapping(value={"/get_MicroServiceLocationData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
334         public void getMicroServiceLocationDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
335                 try{
336                         Map<String, Object> model = new HashMap<String, Object>();
337                         ObjectMapper mapper = new ObjectMapper();
338                         model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(microServiceLocationDao.getMicroServiceLocationData()));
339                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
340                         JSONObject j = new JSONObject(msg);
341                         response.getWriter().write(j.toString());
342                 }
343                 catch (Exception e){
344                         e.printStackTrace();
345                 }
346         }
347         
348         @RequestMapping(value={"/ms_dictionary/save_location.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
349         public ModelAndView saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
350                 try {
351                         boolean duplicateflag = false;
352                         ObjectMapper mapper = new ObjectMapper();
353                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
354                         JsonNode root = mapper.readTree(request.getReader());
355                         MicroServiceLocation microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class);
356                         if(microServiceLocation.getId() == 0){
357                                 CheckDictionaryDuplicateEntries entry = new CheckDictionaryDuplicateEntries();
358                                 List<Object> duplicateData =  entry.CheckDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class);
359                                 if(!duplicateData.isEmpty()){
360                                         duplicateflag = true;
361                                 }else{
362                                         microServiceLocationDao.Save(microServiceLocation);
363                                 }
364                         }else{
365                                 microServiceLocationDao.update(microServiceLocation); 
366                         } 
367                         response.setCharacterEncoding("UTF-8");
368                         response.setContentType("application / json");
369                         request.setCharacterEncoding("UTF-8");
370
371                         PrintWriter out = response.getWriter();
372                         String responseString = "";
373                         if(duplicateflag){
374                                 responseString = "Duplicate";
375                         }else{
376                                 responseString = mapper.writeValueAsString(this.microServiceLocationDao.getMicroServiceLocationData());
377                         }
378                         JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + responseString + "}");
379
380                         out.write(j.toString());
381
382                         return null;
383                 }
384                 catch (Exception e){
385                         response.setCharacterEncoding("UTF-8");
386                         request.setCharacterEncoding("UTF-8");
387                         PrintWriter out = response.getWriter();
388                         out.write(e.getMessage());
389                 }
390                 return null;
391         }
392
393         @RequestMapping(value={"/ms_dictionary/remove_msLocation.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
394         public ModelAndView removeMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
395                 try{
396                         ObjectMapper mapper = new ObjectMapper();
397                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
398                         JsonNode root = mapper.readTree(request.getReader());
399                         MicroServiceLocation microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class);
400                         microServiceLocationDao.delete(microServiceLocation);
401                         response.setCharacterEncoding("UTF-8");
402                         response.setContentType("application / json");
403                         request.setCharacterEncoding("UTF-8");
404
405                         PrintWriter out = response.getWriter();
406
407                         String responseString = mapper.writeValueAsString(this.microServiceLocationDao.getMicroServiceLocationData());
408                         JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + responseString + "}");
409                         out.write(j.toString());
410
411                         return null;
412                 }
413                 catch (Exception e){
414                         System.out.println(e);
415                         response.setCharacterEncoding("UTF-8");
416                         request.setCharacterEncoding("UTF-8");
417                         PrintWriter out = response.getWriter();
418                         out.write(e.getMessage());
419                 }
420                 return null;
421         }
422         
423         @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
424         public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){
425                 try{
426                         Map<String, Object> model = new HashMap<String, Object>();
427                         ObjectMapper mapper = new ObjectMapper();
428                         model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(microServiceModelsDao.getMSModelsDataByName()));
429                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
430                         JSONObject j = new JSONObject(msg);
431                         response.getWriter().write(j.toString());
432                 }
433                 catch (Exception e){
434                         e.printStackTrace();
435                 }
436         }
437         
438         @RequestMapping(value={"/get_MicroServiceModelsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
439         public void getMicroServiceModelsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){
440                 try{
441                         Map<String, Object> model = new HashMap<String, Object>();
442                         ObjectMapper mapper = new ObjectMapper();
443                         model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(microServiceModelsDao.getMicroServiceModelsData()));
444                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
445                         JSONObject j = new JSONObject(msg);
446                         response.getWriter().write(j.toString());
447                 }
448                 catch (Exception e){
449                         e.printStackTrace();
450                 }
451         }
452         
453         @RequestMapping(value={"/ms_dictionary/save_model.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
454         public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{
455                 try {
456                         boolean duplicateflag = false;
457                         ObjectMapper mapper = new ObjectMapper();
458                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
459                         JsonNode root = mapper.readTree(request.getReader());
460                         MicroServiceModels microServiceModels = (MicroServiceModels)mapper.readValue(root.get("microServiceModelsDictionaryData").toString(), MicroServiceModels.class);
461                         String userId = root.get("loginId").textValue();
462                         microServiceModels.setAttributes(this.newModel.getAttributes());
463                         microServiceModels.setRef_attributes(this.newModel.getRef_attributes());
464                         microServiceModels.setDependency(this.newModel.getDependency());
465                         microServiceModels.setModelName(this.newModel.getModelName());
466                         microServiceModels.setSub_attributes(this.newModel.getSub_attributes());
467                         microServiceModels.setVersion(this.newModel.getVersion());
468                         if(microServiceModels.getId() == 0){
469                                 CheckDictionaryDuplicateEntries entry = new CheckDictionaryDuplicateEntries();
470                                 List<Object> duplicateData =  entry.CheckDuplicateEntry(microServiceModels.getModelName(), "modelName", MicroServiceModels.class);
471                                 if(!duplicateData.isEmpty()){
472                                         duplicateflag = true;
473                                 }else{
474                                         microServiceModels.setUserCreatedBy(this.getUserInfo(userId));
475                                         microServiceModelsDao.Save(microServiceModels);
476                                 }
477                         }else{
478                                 microServiceModelsDao.update(microServiceModels); 
479                         } 
480                         response.setCharacterEncoding("UTF-8");
481                         response.setContentType("application / json");
482                         request.setCharacterEncoding("UTF-8");
483
484                         PrintWriter out = response.getWriter();
485                         String responseString = "";
486                         if(duplicateflag){
487                                 responseString = "Duplicate";
488                         }else{
489                                 responseString = mapper.writeValueAsString(this.microServiceModelsDao.getMicroServiceModelsData());
490                         } 
491                         JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}");
492
493                         out.write(j.toString());
494
495                         return null;
496                 }
497                 catch (Exception e){
498                         response.setCharacterEncoding("UTF-8");
499                         request.setCharacterEncoding("UTF-8");
500                         PrintWriter out = response.getWriter();
501                         out.write(e.getMessage());
502                 }
503                 return null;
504         }
505
506         @RequestMapping(value={"/ms_dictionary/remove_msModel.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
507         public ModelAndView removeMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception {
508                 try{
509                         ObjectMapper mapper = new ObjectMapper();
510                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
511                         JsonNode root = mapper.readTree(request.getReader());
512                         MicroServiceModels microServiceModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class);
513                         microServiceModelsDao.delete(microServiceModels);
514                         response.setCharacterEncoding("UTF-8");
515                         response.setContentType("application / json");
516                         request.setCharacterEncoding("UTF-8");
517
518                         PrintWriter out = response.getWriter();
519
520                         String responseString = mapper.writeValueAsString(this.microServiceModelsDao.getMicroServiceModelsData());
521                         JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}");
522                         out.write(j.toString());
523
524                         return null;
525                 }
526                 catch (Exception e){
527                         System.out.println(e);
528                         response.setCharacterEncoding("UTF-8");
529                         request.setCharacterEncoding("UTF-8");
530                         PrintWriter out = response.getWriter();
531                         out.write(e.getMessage());
532                 }
533                 return null;
534         }
535         
536         @RequestMapping(value={"/ms_dictionary/set_MSModelData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
537         public void SetRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
538                 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
539                 for (FileItem item : items) {
540                         if(item.getName().endsWith(".zip")){
541                                 this.newModel = new MicroServiceModels();
542                                 try{
543                                         File file = new File(item.getName());
544                                         OutputStream outputStream = new FileOutputStream(file);
545                                         IOUtils.copy(item.getInputStream(), outputStream);
546                                         outputStream.close();
547                                         this.newFile = file.toString();
548                                         this.newModel.setModelName(this.newFile.toString().split("-v")[0]);
549                                         if (this.newFile.toString().contains("-v")){
550                                                 this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", ""));
551                                         }
552                                 }catch(Exception e){
553                                         logger.error("Upload error : " + e);
554                                 }
555                         }
556                 }
557                 extractFolder(this.newFile);
558                 List<File> fileList = listModelFiles(this.directory);
559                 
560                 File folder = new File(this.directory);
561                 File[] test = folder.listFiles();
562                 
563                 //Process Main Model file first
564                 String ignoreFile = null;
565                 for (File file : test) {
566                         if(!file.isDirectory() && file.getName().endsWith(".xmi")){
567                 retreiveDependency(file.toString(), true);
568                 ignoreFile = file.toString();
569             }   
570                 }
571                 
572                 for(File tempFile: fileList){
573                         if (!tempFile.toString().contains(ignoreFile)){
574                                 retreiveDependency(tempFile.toString(), false);
575                         }
576                 }
577                 
578                 addValuesToNewModel();
579                 
580                 File deleteFile = new File(this.newFile);
581                 deleteFile.delete();
582         }
583         
584         private void addValuesToNewModel() {
585                 //Loop  through the classmap and pull out the required info for the new file.
586                 MSAttributeObject mainClass  = null;
587                 ArrayList<String> dependency = null;
588                 String subAttribute = null;
589                 
590                 mainClass = classMap.get(this.newModel.getModelName());
591                 
592                 if (mainClass !=null){
593                         String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
594                         dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));       
595                         dependency = getFullDependencyList(dependency);
596                         for (String element : dependency){
597                                 MSAttributeObject temp = new MSAttributeObject();
598                                 temp = classMap.get(element);
599                                 if (temp!=null){
600                                         mainClass.addAllRefAttribute(temp.getRefAttribute());
601                                         mainClass.addAllAttribute(temp.getAttribute());
602                                 }
603                         }
604                         subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
605                 }else{
606                         subAttribute = "{}";
607                         this.newModel.setDependency("");
608                 }
609
610                 if (mainClass.getDependency()==null){
611                         mainClass.setDependency("");
612                 }
613
614                 this.newModel.setDependency(mainClass.getDependency());
615                 this.newModel.setSub_attributes(subAttribute.toString());
616                 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
617                 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
618         
619         } 
620         
621         private ArrayList<String> getFullDependencyList(ArrayList<String> dependency) {
622                 ArrayList<String> returnList = new ArrayList<String>();
623                 ArrayList<String> workingList = new ArrayList<String>();
624                 returnList.addAll(dependency);
625                 for (String element : dependency ){
626                         if (classMap.containsKey(element)){
627                                 MSAttributeObject value = classMap.get(element);                        
628                                 String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""});
629                                 workingList = new ArrayList<String>(Arrays.asList(rawValue.split(",")));        
630                                 for(String depend : workingList){
631                                         if (!returnList.contains(depend) && !depend.isEmpty()){
632                                                 returnList.add(depend.trim());
633                                                 //getFullDepedency(workingList)
634                                         }
635                                 }
636                         }
637                 }
638                 
639                 return returnList;
640         }
641
642         
643         /*
644          * Unzip file and store in the model directory for processing
645          */
646         @SuppressWarnings("rawtypes")
647         private void extractFolder(String zipFile )  {
648             int BUFFER = 2048;
649             File file = new File(zipFile);
650
651             ZipFile zip;
652                 try {
653                         zip = new ZipFile(file);
654                     String newPath =  "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
655                     this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
656                     new File(newPath).mkdir();
657                     Enumeration zipFileEntries = zip.entries();
658         
659                     // Process each entry
660                     while (zipFileEntries.hasMoreElements()){
661                         // grab a zip file entry
662                         ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
663                         String currentEntry = entry.getName();
664                         File destFile = new File("model" + File.separator + currentEntry);
665                         File destinationParent = destFile.getParentFile();
666                         
667                         destinationParent.mkdirs();
668         
669                         if (!entry.isDirectory()){
670                             BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
671                             int currentByte;
672                             byte data[] = new byte[BUFFER];
673                             FileOutputStream fos = new FileOutputStream(destFile);
674                             BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
675                             while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
676                                 dest.write(data, 0, currentByte);
677                             }
678                             dest.flush();
679                             dest.close();
680                             is.close();
681                         }
682         
683                         if (currentEntry.endsWith(".zip")){
684                             extractFolder(destFile.getAbsolutePath());
685                         }
686                     }
687             } catch (IOException e) {
688                         logger.error("Failed to unzip model file " + zipFile);
689                 }
690         }
691         
692         private void retreiveDependency(String workingFile, Boolean modelClass) {
693                 
694                 MSModelUtitils utils = new MSModelUtitils();
695             HashMap<String, MSAttributeObject> tempMap = new HashMap<String, MSAttributeObject>();
696             
697             tempMap = utils.processEpackage(workingFile);
698             
699             classMap.putAll(tempMap);
700             System.out.println(tempMap);
701             
702             return;     }
703                 
704         private List<File> listModelFiles(String directoryName) {
705                 File directory = new File(directoryName);
706                 List<File> resultList = new ArrayList<File>();
707                 File[] fList = directory.listFiles();
708                 for (File file : fList) {
709                         if (file.isFile()) {
710                                 resultList.add(file);
711                         } else if (file.isDirectory()) {
712                                 dirDependencyList.add(file.getName());
713                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
714                         }
715                 }
716                 return resultList;
717         }
718 }