0f52b9bae11f4d9b4b4de252f824aa861403abe8
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / CreateNewOptimizationModel.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2018-2019 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 com.google.gson.Gson;
24
25 import java.io.BufferedInputStream;
26 import java.io.BufferedOutputStream;
27 import java.io.File;
28 import java.io.FileOutputStream;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.Enumeration;
32 import java.util.HashMap;
33 import java.util.LinkedHashMap;
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 org.apache.commons.io.FileUtils;
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.OptimizationModels;
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 public class CreateNewOptimizationModel {
53     private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class);
54     private OptimizationModels newModel = null;
55     private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
56
57     private static final String EXTRACTDIR = "ExtractDir";
58     private static final String SUCCESS = "success";
59
60     MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
61
62     public CreateNewOptimizationModel() {
63         super();
64     }
65
66     public CreateNewOptimizationModel(String importFile, String modelName, String description, String version,
67             String randomID) {
68
69         this.newModel = new OptimizationModels();
70         this.newModel.setVersion(version);
71         this.newModel.setModelName(modelName);
72         this.newModel.setDescription(description);
73         UserInfo userInfo = new UserInfo();
74         userInfo.setUserLoginId("API");
75         this.newModel.setUserCreatedBy(userInfo);
76         String cleanUpFile = null;
77
78         Map<String, MSAttributeObject> tempMap = new HashMap<>();
79         // Need to delete the file
80         if (importFile.contains(".zip")) {
81             extractFolder(randomID + ".zip");
82             File directory = new File(EXTRACTDIR + File.separator + randomID);
83             List<File> fileList = listModelFiles(directory.toString());
84             // get all the files from a director
85             for (File file : fileList) {
86                 if (file.isFile()) {
87                     processYmlModel(file.toString(), modelName);
88                 }
89             }
90             cleanUpFile = EXTRACTDIR + File.separator + randomID + ".zip";
91             try {
92                 FileUtils.deleteDirectory(new File(EXTRACTDIR + File.separator + randomID));
93                 FileUtils.deleteDirectory(new File(randomID));
94                 File deleteFile = new File(cleanUpFile);
95                 FileUtils.forceDelete(deleteFile);
96             } catch (IOException e) {
97                 logger.error("Failed to unzip model file " + randomID, e);
98             }
99         } else {
100             if (importFile.contains(".yml")) {
101
102                 processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName);
103                 cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml";
104
105             } else {
106                 tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", MODEL_TYPE.XMI);
107                 classMap.putAll(tempMap);
108                 cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi";
109             }
110             File deleteFile = new File(cleanUpFile);
111             deleteFile.delete();
112         }
113     }
114
115     private void processYmlModel(String fileName, String modelName) {
116
117         try {
118
119             utils.parseTosca(fileName);
120
121             MSAttributeObject msAttributes = new MSAttributeObject();
122             msAttributes.setClassName(modelName);
123
124             LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
125             returnAttributeList.put(modelName, utils.getAttributeString());
126             msAttributes.setAttribute(returnAttributeList);
127
128             msAttributes.setSubClass(utils.getRetmap());
129
130             msAttributes.setMatchingSet(utils.getMatchableValues());
131
132             LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
133
134             returnReferenceList.put(modelName, utils.getReferenceAttributes());
135             msAttributes.setRefAttribute(returnReferenceList);
136
137             if (!"".equals(utils.getListConstraints())) {
138                 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
139                 String[] listArray = utils.getListConstraints().split("#");
140                 for (String str : listArray) {
141                     String[] strArr = str.split("=");
142                     if (strArr.length > 1) {
143                         enumList.put(strArr[0], strArr[1]);
144                     }
145                 }
146                 msAttributes.setEnumType(enumList);
147             }
148
149             classMap = new LinkedHashMap<>();
150             classMap.put(modelName, msAttributes);
151
152         } catch (Exception e) {
153             logger.error("Failed to process yml model" + e);
154         }
155
156     }
157
158     private List<File> listModelFiles(String directoryName) {
159         File directory = new File(directoryName);
160         List<File> resultList = new ArrayList<>();
161         File[] fList = directory.listFiles();
162         for (File file : fList) {
163             if (file.isFile()) {
164                 resultList.add(file);
165             } else if (file.isDirectory()) {
166                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
167             }
168         }
169         return resultList;
170     }
171
172     @SuppressWarnings("rawtypes")
173     private void extractFolder(String zipFile) {
174         int buffer = 2048;
175         File file = new File(zipFile);
176
177         try (ZipFile zip = new ZipFile(EXTRACTDIR + File.separator + file);) {
178             String newPath = zipFile.substring(0, zipFile.length() - 4);
179             new File(newPath).mkdir();
180             Enumeration zipFileEntries = zip.entries();
181
182             // Process each entry
183             while (zipFileEntries.hasMoreElements()) {
184                 // grab a zip file entry
185                 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
186                 String currentEntry = entry.getName();
187                 File destFile = new File(EXTRACTDIR + File.separator + newPath + File.separator + currentEntry);
188                 File destinationParent = destFile.getParentFile();
189
190                 destinationParent.mkdirs();
191
192                 if (!entry.isDirectory()) {
193                     int currentByte;
194
195                     byte[] data = new byte[buffer];
196                     try (FileOutputStream fos = new FileOutputStream(destFile);
197                             BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
198                             BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
199
200                         while ((currentByte = is.read(data, 0, buffer)) != -1) {
201                             dest.write(data, 0, currentByte);
202                         }
203                         dest.flush();
204                     }
205                 }
206
207                 if (currentEntry.endsWith(".zip")) {
208                     extractFolder(destFile.getAbsolutePath());
209                 }
210             }
211         } catch (IOException e) {
212             logger.error("Failed to unzip model file " + zipFile + e);
213         }
214     }
215
216     public Map<String, String> addValuesToNewModel() {
217
218         Map<String, String> successMap = new HashMap<>();
219         MSAttributeObject mainClass;
220
221         if (!classMap.containsKey(this.newModel.getModelName())) {
222             logger.error(
223                     "Model Provided does not contain the service name provided in request. Unable to import new model");
224             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel",
225                     "Unable to pull out required values, file missing service name provided in request");
226             successMap.put("error", "MISSING");
227             return successMap;
228         }
229         mainClass = classMap.get(this.newModel.getModelName());
230         newModel.setDependency("[]");
231         if (mainClass.getSubClass() != null) {
232             String value = new Gson().toJson(mainClass.getSubClass());
233             newModel.setSubattributes(value);
234         }
235
236         if (mainClass.getAttribute() != null) {
237             String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
238             int equalsIndexForAttributes = attributes.indexOf('=');
239             String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1);
240             this.newModel.setAttributes(atttributesAfterFirstEquals);
241         }
242
243         if (mainClass.getRefAttribute() != null) {
244             String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
245             int equalsIndex = refAttributes.indexOf('=');
246             String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
247             this.newModel.setRefattributes(refAttributesAfterFirstEquals);
248         }
249
250         if (mainClass.getEnumType() != null) {
251             this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
252         }
253
254         if (mainClass.getMatchingSet() != null) {
255             this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
256         }
257
258         successMap.put(SUCCESS, SUCCESS);
259         return successMap;
260
261     }
262
263     public Map<String, String> saveImportService() {
264         String modelName = this.newModel.getModelName();
265         String importedBy = "API";
266         String version = this.newModel.getVersion();
267         Map<String, String> successMap = new HashMap<>();
268         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
269         List<Object> result =
270                 dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version);
271         if (result.isEmpty()) {
272             OptimizationModels model = new OptimizationModels();
273             model.setModelName(modelName);
274             model.setVersion(version);
275             model.setAttributes(this.newModel.getAttributes());
276             model.setAnnotation(this.newModel.getAnnotation());
277             model.setDependency(this.newModel.getDependency());
278             model.setDescription(this.newModel.getDescription());
279             model.setEnumValues(this.newModel.getEnumValues());
280             model.setRefattributes(this.newModel.getRefattributes());
281             model.setSubattributes(this.newModel.getSubattributes());
282             model.setDataOrderInfo(this.newModel.getDataOrderInfo());
283             UserInfo userInfo = new UserInfo();
284             userInfo.setUserLoginId(importedBy);
285             userInfo.setUserName(importedBy);
286             model.setUserCreatedBy(userInfo);
287             dbConnection.save(model);
288             successMap.put(SUCCESS, SUCCESS);
289         } else {
290             successMap.put("DBError", "EXISTS");
291             logger.error("Import new service failed.  Service already exists");
292         }
293         return successMap;
294     }
295 }