2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pap.xacml.rest.components;
24 import com.google.gson.Gson;
26 import java.io.BufferedInputStream;
27 import java.io.BufferedOutputStream;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Enumeration;
34 import java.util.HashMap;
35 import java.util.LinkedHashMap;
36 import java.util.List;
38 import java.util.zip.ZipEntry;
39 import java.util.zip.ZipFile;
41 import org.apache.commons.io.FileUtils;
42 import org.apache.commons.lang.StringUtils;
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
48 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
49 import org.onap.policy.rest.jpa.MicroServiceModels;
50 import org.onap.policy.rest.jpa.UserInfo;
51 import org.onap.policy.rest.util.MSAttributeObject;
52 import org.onap.policy.rest.util.MSModelUtils;
53 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
55 public class CreateNewMicroServiceModel {
56 private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
57 private MicroServiceModels newModel = null;
58 private HashMap<String, MSAttributeObject> classMap = new HashMap<>();
60 private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
62 public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
67 * Instantiates a new creates the new micro service model.
69 * @param importFile the import file
70 * @param modelName the model name
71 * @param description the description
72 * @param version the version
73 * @param randomID the random ID
75 public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version,
78 this.newModel = new MicroServiceModels();
79 this.newModel.setVersion(version);
80 this.newModel.setModelName(modelName);
81 UserInfo userInfo = new UserInfo();
82 userInfo.setUserLoginId("API");
83 this.newModel.setUserCreatedBy(userInfo);
84 String cleanUpFile = null;
86 Map<String, MSAttributeObject> tempMap = new HashMap<>();
87 // Need to delete the file
88 if (importFile.contains(".zip")) {
89 extractFolder(randomID + ".zip");
90 File directory = new File("ExtractDir" + File.separator + randomID);
91 List<File> fileList = listModelFiles(directory.toString());
92 // get all the files from a director
93 processFiles(modelName, fileList);
94 doCleanUpFiles(randomID);
96 if (importFile.contains(".yml")) {
98 processYmlModel("ExtractDir" + File.separator + randomID + ".yml", modelName);
99 cleanUpFile = "ExtractDir" + File.separator + randomID + ".yml";
102 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID + ".xmi", MODEL_TYPE.XMI);
103 classMap.putAll(tempMap);
104 cleanUpFile = "ExtractDir" + File.separator + randomID + ".xmi";
107 File deleteFile = new File(cleanUpFile);
112 private void processFiles(String modelName, List<File> fileList) {
113 Map<String, MSAttributeObject> tempMap;
114 for (File file : fileList) {
116 int indx = file.getName().lastIndexOf('.');
117 String type = file.getName().substring(indx + 1);
119 if ("yml".equalsIgnoreCase(type)) {
121 processYmlModel(file.toString(), modelName);
125 tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
126 classMap.putAll(tempMap);
132 private void doCleanUpFiles(String randomID) {
134 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
136 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
137 FileUtils.deleteDirectory(new File(randomID));
138 File deleteFile = new File(cleanUpFile);
139 FileUtils.forceDelete(deleteFile);
140 } catch (IOException e) {
141 logger.error("Failed to unzip model file " + randomID, e);
145 private void processYmlModel(String fileName, String modelName) {
149 utils.parseTosca(fileName);
151 MSAttributeObject msAttributes = new MSAttributeObject();
152 msAttributes.setClassName(modelName);
154 LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
155 returnAttributeList.put(modelName, utils.getAttributeString());
156 msAttributes.setAttribute(returnAttributeList);
158 msAttributes.setSubClass(utils.getRetmap());
160 msAttributes.setMatchingSet(utils.getMatchableValues());
162 LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
164 returnReferenceList.put(modelName, utils.getReferenceAttributes());
165 msAttributes.setRefAttribute(returnReferenceList);
167 if (!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())) {
168 LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
169 String[] listArray = utils.getListConstraints().split("#");
170 for (String str : listArray) {
171 String[] strArr = str.split("=");
172 if (strArr.length > 1) {
173 enumList.put(strArr[0], strArr[1]);
176 msAttributes.setEnumType(enumList);
178 if (utils.getJsonRuleFormation() != null) {
179 msAttributes.setRuleFormation(utils.getJsonRuleFormation());
182 if (utils.getDataOrderInfo() != null) {
183 msAttributes.setDataOrderInfo(utils.getDataOrderInfo());
186 classMap = new LinkedHashMap<>();
187 classMap.put(modelName, msAttributes);
189 } catch (Exception e) {
190 logger.error("Failed to process yml model" + e);
195 private List<File> listModelFiles(String directoryName) {
196 File directory = new File(directoryName);
197 List<File> resultList = new ArrayList<>();
198 File[] fList = directory.listFiles();
199 for (File file : fList) {
201 resultList.add(file);
202 } else if (file.isDirectory()) {
203 resultList.addAll(listModelFiles(file.getAbsolutePath()));
209 @SuppressWarnings("rawtypes")
210 private void extractFolder(String zipFile) {
212 File file = new File(zipFile);
214 try (ZipFile zip = new ZipFile("ExtractDir" + File.separator + file)) {
216 String newPath = zipFile.substring(0, zipFile.length() - 4);
217 new File(newPath).mkdir();
218 Enumeration zipFileEntries = zip.entries();
220 // Process each entry
221 while (zipFileEntries.hasMoreElements()) {
222 // grab a zip file entry
223 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
224 String currentEntry = entry.getName();
225 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
226 File destinationParent = destFile.getParentFile();
228 destinationParent.mkdirs();
230 if (!entry.isDirectory()) {
231 BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
234 byte data[] = new byte[BUFFER];
235 try (FileOutputStream fos = new FileOutputStream(destFile);
236 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
238 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
239 dest.write(data, 0, currentByte);
246 if (currentEntry.endsWith(".zip")) {
247 extractFolder(destFile.getAbsolutePath());
250 } catch (IOException e) {
251 logger.error("Failed to unzip model file " + zipFile + e);
255 public Map<String, String> addValuesToNewModel(String type) {
257 Map<String, String> successMap = new HashMap<>();
258 MSAttributeObject mainClass = null;
259 List<String> dependency = null;
260 String subAttribute = null;
262 if (!classMap.containsKey(this.newModel.getModelName())) {
264 "Model Provided does not contain the service name provided in request. Unable to import new model");
265 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel",
266 "Unable to pull out required values, file missing service name provided in request");
267 successMap.put("error", "MISSING");
270 mainClass = classMap.get(this.newModel.getModelName());
272 if (".yml".equalsIgnoreCase(type)) {
274 newModel.setDependency("[]");
275 if (mainClass.getSubClass() != null) {
276 String value = new Gson().toJson(mainClass.getSubClass());
277 newModel.setSub_attributes(value);
280 if (mainClass.getAttribute() != null) {
281 String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", "");
282 int equalsIndexForAttributes = attributes.indexOf("=");
283 String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1);
284 this.newModel.setAttributes(atttributesAfterFirstEquals);
287 if (mainClass.getRefAttribute() != null) {
288 String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
289 int equalsIndex = refAttributes.indexOf("=");
290 String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1);
291 this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
294 if (mainClass.getEnumType() != null) {
295 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
298 if (mainClass.getMatchingSet() != null) {
299 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
301 if (mainClass.getRuleFormation() != null) {
302 this.newModel.setRuleFormation(mainClass.getRuleFormation());
305 if (mainClass.getDataOrderInfo() != null) {
306 this.newModel.setDataOrderInfo(mainClass.getDataOrderInfo());
311 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "},
312 new String[] {"", "", ""});
313 this.newModel.setDependency(dependTemp);
314 if (this.newModel.getDependency() != null && !this.newModel.getDependency().isEmpty()) {
315 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
316 dependency = utils.getFullDependencyList(dependency, classMap);
317 if (!dependency.isEmpty()) {
318 for (String element : dependency) {
319 MSAttributeObject temp = new MSAttributeObject();
320 if (classMap.containsKey(element)) {
321 temp = classMap.get(element);
322 mainClass.addAllRefAttribute(temp.getRefAttribute());
323 mainClass.addAllAttribute(temp.getAttribute());
328 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
330 this.newModel.setSub_attributes(subAttribute);
331 if (mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()) {
332 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
335 if (mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()) {
337 .setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
340 if (mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()) {
341 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
344 if (mainClass.getMatchingSet() != null && !mainClass.getMatchingSet().isEmpty()) {
345 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
348 successMap.put("success", "success");
353 public Map<String, String> saveImportService() {
354 String modelName = this.newModel.getModelName();
355 String imported_by = "API";
356 String version = this.newModel.getVersion();
357 Map<String, String> successMap = new HashMap<>();
358 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
359 List<Object> result =
360 dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + version);
361 if (result == null || result.isEmpty()) {
362 MicroServiceModels model = new MicroServiceModels();
363 model.setModelName(modelName);
364 model.setVersion(version);
365 model.setAttributes(this.newModel.getAttributes());
366 model.setAnnotation(this.newModel.getAnnotation());
367 model.setDependency(this.newModel.getDependency());
368 model.setDescription(this.newModel.getDescription());
369 model.setEnumValues(this.newModel.getEnumValues());
370 model.setRef_attributes(this.newModel.getRef_attributes());
371 model.setSub_attributes(this.newModel.getSub_attributes());
372 model.setDataOrderInfo(this.newModel.getDataOrderInfo());
373 model.setDecisionModel(this.newModel.isDecisionModel());
374 model.setRuleFormation(this.newModel.getRuleFormation());
375 UserInfo userInfo = new UserInfo();
376 userInfo.setUserLoginId(imported_by);
377 userInfo.setUserName(imported_by);
378 model.setUserCreatedBy(userInfo);
379 dbConnection.save(model);
380 successMap.put("success", "success");
382 successMap.put("DBError", "EXISTS");
383 logger.error("Import new service failed. Service already exists");