FIX SONAR ISSUE NESTED TRY BLOCKS
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateNewMicroServiceModel.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-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.onap.policy.pap.xacml.rest.components;
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.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Enumeration;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.zip.ZipEntry;
36 import java.util.zip.ZipFile;
37
38 import org.apache.commons.io.FileUtils;
39 import org.apache.commons.lang.StringUtils;
40 import org.onap.policy.common.logging.eelf.MessageCodes;
41 import org.onap.policy.common.logging.eelf.PolicyLogger;
42 import org.onap.policy.common.logging.flexlogger.FlexLogger;
43 import org.onap.policy.common.logging.flexlogger.Logger;
44 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
45 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
46 import org.onap.policy.rest.jpa.MicroServiceModels;
47 import org.onap.policy.rest.jpa.UserInfo;
48 import org.onap.policy.rest.util.MSAttributeObject;
49 import org.onap.policy.rest.util.MSModelUtils;
50 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
51
52 import com.google.gson.Gson;
53
54 public class CreateNewMicroServiceModel {
55     private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
56     private MicroServiceModels newModel = null;
57     private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
58
59
60     private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
61
62     public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
63         super();
64     }
65
66     public CreateNewMicroServiceModel(String importFile, String  modelName, String description, String version, String randomID) {
67
68         this.newModel = new MicroServiceModels();
69         this.newModel.setVersion(version);
70         this.newModel.setModelName(modelName);
71         UserInfo userInfo = new UserInfo();
72         userInfo.setUserLoginId("API");
73         this.newModel.setUserCreatedBy(userInfo);
74         String cleanUpFile = null;
75
76         Map<String, MSAttributeObject> tempMap = new HashMap<>();
77         //Need to delete the file
78         if (importFile.contains(".zip")){
79             extractFolder(randomID + ".zip");
80             File directory = new File("ExtractDir" + File.separator + randomID);
81             List<File> fileList = listModelFiles(directory.toString());
82             //get all the files from a director
83             processFiles(modelName, fileList);
84             doCleanUpFiles(randomID);
85         }else {
86             if(importFile.contains(".yml")){
87
88                 processYmlModel("ExtractDir" + File.separator + randomID+".yml", modelName);
89                 cleanUpFile = "ExtractDir" + File.separator + randomID+".yml";
90
91             }else{
92                 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
93                 classMap.putAll(tempMap);
94                 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
95             }
96
97             File deleteFile = new File(cleanUpFile);
98             deleteFile.delete();
99         }
100     }
101
102     private void processFiles(String modelName, List<File> fileList) {
103         Map<String, MSAttributeObject> tempMap;
104         for (File file : fileList){
105             if (file.isFile()){
106                 int i = file.getName().lastIndexOf('.');
107                 String type = file.getName().substring(i+1);
108
109                 if("yml".equalsIgnoreCase(type)){
110
111                     processYmlModel(file.toString(), modelName);
112
113                 }else{
114
115                     tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
116                     classMap.putAll(tempMap);
117                 }
118             }
119         }
120     }
121
122     private void doCleanUpFiles(String randomID) {
123         String cleanUpFile;
124         cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
125         try {
126             FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
127             FileUtils.deleteDirectory(new File(randomID));
128             File deleteFile = new File(cleanUpFile);
129             FileUtils.forceDelete(deleteFile);
130         } catch (IOException e) {
131             logger.error("Failed to unzip model file " + randomID, e);
132         }
133     }
134
135     private void processYmlModel(String fileName, String  modelName){
136
137         try {
138
139
140             utils.parseTosca(fileName);
141
142             MSAttributeObject msAttributes= new MSAttributeObject();
143             msAttributes.setClassName(modelName);
144
145             LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
146             returnAttributeList.put(modelName, utils.getAttributeString());
147             msAttributes.setAttribute(returnAttributeList);
148
149             msAttributes.setSubClass(utils.getRetmap());
150
151             msAttributes.setMatchingSet(utils.getMatchableValues());
152
153             LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
154
155             returnReferenceList.put(modelName, utils.getReferenceAttributes());
156             msAttributes.setRefAttribute(returnReferenceList);
157
158             if(!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())){
159                 LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
160                 String[] listArray=utils.getListConstraints().split("#");
161                 for(String str:listArray){
162                     String[] strArr= str.split("=");
163                     if(strArr.length>1){
164                         enumList.put(strArr[0], strArr[1]);
165                     }
166                 }
167                 msAttributes.setEnumType(enumList);
168             }
169
170             classMap=new LinkedHashMap<>();
171             classMap.put(modelName, msAttributes);
172
173         } catch (Exception e) {
174             logger.error("Failed to process yml model" + e);
175         }
176
177     }
178
179     private List<File> listModelFiles(String directoryName) {
180         File directory = new File(directoryName);
181         List<File> resultList = new ArrayList<>();
182         File[] fList = directory.listFiles();
183         for (File file : fList) {
184             if (file.isFile()) {
185                 resultList.add(file);
186             } else if (file.isDirectory()) {
187                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
188             }
189         }
190         return resultList;
191     }
192
193     @SuppressWarnings("rawtypes")
194     private void extractFolder(String zipFile) {
195         int BUFFER = 2048;
196         File file = new File(zipFile);
197
198         try(ZipFile zip = new ZipFile("ExtractDir" + File.separator +file)) {
199
200             String newPath =  zipFile.substring(0, zipFile.length() - 4);
201             new File(newPath).mkdir();
202             Enumeration zipFileEntries = zip.entries();
203
204             // Process each entry
205             while (zipFileEntries.hasMoreElements()){
206                 // grab a zip file entry
207                 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
208                 String currentEntry = entry.getName();
209                 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
210                 File destinationParent = destFile.getParentFile();
211
212                 destinationParent.mkdirs();
213
214                 if (!entry.isDirectory()){
215                     BufferedInputStream is = new BufferedInputStream(zip
216                     .getInputStream(entry));
217                     int currentByte;
218
219                     byte data[] = new byte[BUFFER];
220                     try(FileOutputStream fos = new FileOutputStream(destFile);
221                         BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
222
223                         while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
224                             dest.write(data, 0, currentByte);
225                         }
226                         dest.flush();
227                     }
228                     is.close();
229                 }
230
231                 if (currentEntry.endsWith(".zip")){
232                     extractFolder(destFile.getAbsolutePath());
233                 }
234             }
235         } catch (IOException e) {
236             logger.error("Failed to unzip model file " + zipFile + e);
237         }
238     }
239
240     public Map<String, String> addValuesToNewModel(String type) {
241
242         Map<String, String> successMap = new HashMap<>();
243         MSAttributeObject mainClass  = null;
244         List<String> dependency = null;
245         String subAttribute = null;
246
247         if (!classMap.containsKey(this.newModel.getModelName())){
248             logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
249             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
250             successMap.put("error", "MISSING");
251             return successMap;
252         }
253         mainClass = classMap.get(this.newModel.getModelName());
254
255
256         if(".yml".equalsIgnoreCase(type)){
257
258             newModel.setDependency("[]");
259             if(mainClass.getSubClass() != null){
260                String value = new Gson().toJson(mainClass.getSubClass());
261                newModel.setSub_attributes(value);
262             }
263
264             if(mainClass.getAttribute() != null){
265                 String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
266                 int equalsIndexForAttributes= attributes.indexOf("=");
267                 String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
268                 this.newModel.setAttributes(atttributesAfterFirstEquals);
269             }
270
271             if(mainClass.getRefAttribute() != null){
272                 String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
273                 int equalsIndex= refAttributes.indexOf("=");
274                 String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
275                 this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
276             }
277
278             if(mainClass.getEnumType() != null){
279                 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
280             }
281
282             if(mainClass.getMatchingSet() != null){
283                 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
284             }
285
286         }else{
287
288             String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
289             this.newModel.setDependency(dependTemp);
290             if (this.newModel.getDependency() != null && !this.newModel.getDependency().isEmpty()){
291                 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
292                 dependency = utils.getFullDependencyList(dependency, classMap);
293                 if (!dependency.isEmpty()){
294                     for (String element : dependency){
295                         MSAttributeObject temp = new MSAttributeObject();
296                         if (classMap.containsKey(element)){
297                             temp = classMap.get(element);
298                             mainClass.addAllRefAttribute(temp.getRefAttribute());
299                             mainClass.addAllAttribute(temp.getAttribute());
300                         }
301                     }
302                 }
303             }
304             subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
305
306             this.newModel.setSub_attributes(subAttribute);
307             if(mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()){
308                 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
309             }
310
311             if(mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()){
312                this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
313             }
314
315             if(mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()){
316                 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
317             }
318
319             if(mainClass.getMatchingSet() != null && !mainClass.getMatchingSet().isEmpty()){
320                 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
321             }
322         }
323         successMap.put("success", "success");
324         return successMap;
325
326     }
327
328     public Map<String, String> saveImportService(){
329         String modelName = this.newModel.getModelName();
330         String imported_by = "API";
331         String version = this.newModel.getVersion();
332         Map<String, String> successMap = new HashMap<>();
333         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
334         List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
335         if(result.isEmpty()){
336             MicroServiceModels model = new MicroServiceModels();
337             model.setModelName(modelName);
338             model.setVersion(version);
339             model.setAttributes(this.newModel.getAttributes());
340             model.setAnnotation(this.newModel.getAnnotation());
341             model.setDependency(this.newModel.getDependency());
342             model.setDescription(this.newModel.getDescription());
343             model.setEnumValues(this.newModel.getEnumValues());
344             model.setRef_attributes(this.newModel.getRef_attributes());
345             model.setSub_attributes(this.newModel.getSub_attributes());
346             model.setDataOrderInfo(this.newModel.getDataOrderInfo());
347             UserInfo userInfo = new UserInfo();
348             userInfo.setUserLoginId(imported_by);
349             userInfo.setUserName(imported_by);
350             model.setUserCreatedBy(userInfo);
351             dbConnection.save(model);
352             successMap.put("success", "success");
353         }else{
354             successMap.put("DBError", "EXISTS");
355             logger.error("Import new service failed.  Service already exists");
356         }
357         return successMap;
358     }
359 }