2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.pap.xacml.rest.components;
23 import java.io.BufferedInputStream;
24 import java.io.BufferedOutputStream;
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;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipFile;
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;
50 import com.google.gson.Gson;
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<>();
57 private static final String EXTRACTDIR = "ExtractDir";
58 private static final String SUCCESS = "success";
61 MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
63 public CreateNewOptimizationModel() {
67 public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) {
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;
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){
87 processYmlModel(file.toString(), modelName);
90 cleanUpFile = EXTRACTDIR + File.separator + randomID + ".zip";
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);
100 if(importFile.contains(".yml")){
102 processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName);
103 cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml";
106 tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
107 classMap.putAll(tempMap);
108 cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi";
110 File deleteFile = new File(cleanUpFile);
115 private void processYmlModel(String fileName, String modelName){
119 utils.parseTosca(fileName);
121 MSAttributeObject msAttributes= new MSAttributeObject();
122 msAttributes.setClassName(modelName);
124 LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
125 returnAttributeList.put(modelName, utils.getAttributeString());
126 msAttributes.setAttribute(returnAttributeList);
128 msAttributes.setSubClass(utils.getRetmap());
130 msAttributes.setMatchingSet(utils.getMatchableValues());
132 LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
134 returnReferenceList.put(modelName, utils.getReferenceAttributes());
135 msAttributes.setRefAttribute(returnReferenceList);
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("=");
143 enumList.put(strArr[0], strArr[1]);
146 msAttributes.setEnumType(enumList);
149 classMap=new LinkedHashMap<>();
150 classMap.put(modelName, msAttributes);
152 } catch (Exception e) {
153 logger.error("Failed to process yml model" + e);
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) {
164 resultList.add(file);
165 } else if (file.isDirectory()) {
166 resultList.addAll(listModelFiles(file.getAbsolutePath()));
172 @SuppressWarnings("rawtypes")
173 private void extractFolder(String zipFile) {
175 File file = new File(zipFile);
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();
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();
190 destinationParent.mkdirs();
192 if (!entry.isDirectory()){
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)) {
200 while ((currentByte = is.read(data, 0, buffer)) != -1) {
201 dest.write(data, 0, currentByte);
207 if (currentEntry.endsWith(".zip")){
208 extractFolder(destFile.getAbsolutePath());
211 } catch (IOException e) {
212 logger.error("Failed to unzip model file " + zipFile + e);
216 public Map<String, String> addValuesToNewModel() {
218 Map<String, String> successMap = new HashMap<>();
219 MSAttributeObject mainClass;
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");
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);
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);
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);
248 if(mainClass.getEnumType() != null){
249 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
252 if(mainClass.getMatchingSet() != null){
253 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
256 successMap.put(SUCCESS, SUCCESS);
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);
287 successMap.put("DBError", "EXISTS");
288 logger.error("Import new service failed. Service already exists");