87c9f91080297d622baadd39b2df97e2986ef42e
[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 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.Enumeration;
30 import java.util.HashMap;
31 import java.util.LinkedHashMap;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipFile;
36
37 import org.apache.commons.io.FileUtils;
38 import org.onap.policy.common.logging.eelf.MessageCodes;
39 import org.onap.policy.common.logging.eelf.PolicyLogger;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
43 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
44 import org.onap.policy.rest.jpa.OptimizationModels;
45 import org.onap.policy.rest.jpa.UserInfo;
46 import org.onap.policy.rest.util.MSAttributeObject;
47 import org.onap.policy.rest.util.MSModelUtils;
48 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
49
50 import com.google.gson.Gson;
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
61     MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
62
63     public CreateNewOptimizationModel() {
64         super();
65     }
66
67     public CreateNewOptimizationModel(String importFile, String  modelName, String description, String version, 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("Model Provided does not contain the service name provided in request. Unable to import new model");
223             PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
224             successMap.put("error", "MISSING");
225             return successMap;
226         }
227         mainClass = classMap.get(this.newModel.getModelName());
228         newModel.setDependency("[]");
229         if(mainClass.getSubClass() != null){
230            String value = new Gson().toJson(mainClass.getSubClass());
231            newModel.setSubattributes(value);
232         }
233
234         if(mainClass.getAttribute() != null){
235             String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
236             int equalsIndexForAttributes= attributes.indexOf('=');
237             String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
238             this.newModel.setAttributes(atttributesAfterFirstEquals);
239         }
240
241         if(mainClass.getRefAttribute() != null){
242             String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
243             int equalsIndex= refAttributes.indexOf('=');
244             String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
245             this.newModel.setRefattributes(refAttributesAfterFirstEquals);
246         }
247
248         if(mainClass.getEnumType() != null){
249             this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
250         }
251
252         if(mainClass.getMatchingSet() != null){
253             this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
254         }
255
256         successMap.put(SUCCESS, SUCCESS);
257         return successMap;
258
259     }
260
261     public Map<String, String> saveImportService(){
262         String modelName = this.newModel.getModelName();
263         String importedBy = "API";
264         String version = this.newModel.getVersion();
265         Map<String, String> successMap = new HashMap<>();
266         CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
267         List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version);
268         if(result.isEmpty()){
269             OptimizationModels model = new OptimizationModels();
270             model.setModelName(modelName);
271             model.setVersion(version);
272             model.setAttributes(this.newModel.getAttributes());
273             model.setAnnotation(this.newModel.getAnnotation());
274             model.setDependency(this.newModel.getDependency());
275             model.setDescription(this.newModel.getDescription());
276             model.setEnumValues(this.newModel.getEnumValues());
277             model.setRefattributes(this.newModel.getRefattributes());
278             model.setSubattributes(this.newModel.getSubattributes());
279             model.setDataOrderInfo(this.newModel.getDataOrderInfo());
280             UserInfo userInfo = new UserInfo();
281             userInfo.setUserLoginId(importedBy);
282             userInfo.setUserName(importedBy);
283             model.setUserCreatedBy(userInfo);
284             dbConnection.save(model);
285             successMap.put(SUCCESS, SUCCESS);
286         }else{
287             successMap.put("DBError", "EXISTS");
288             logger.error("Import new service failed.  Service already exists");
289         }
290         return successMap;
291     }
292 }