2 * ============LICENSE_START=======================================================
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
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 com.google.gson.Gson;
25 import java.io.BufferedInputStream;
26 import java.io.BufferedOutputStream;
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;
36 import java.util.zip.ZipEntry;
37 import java.util.zip.ZipFile;
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;
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";
60 MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
62 public CreateNewOptimizationModel() {
66 public CreateNewOptimizationModel(String importFile, String modelName, String description, String version,
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("=");
142 if (strArr.length > 1) {
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())) {
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");
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);
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);
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);
250 if (mainClass.getEnumType() != null) {
251 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
254 if (mainClass.getMatchingSet() != null) {
255 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
258 successMap.put(SUCCESS, SUCCESS);
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);
290 successMap.put("DBError", "EXISTS");
291 logger.error("Import new service failed. Service already exists");