2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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 java.io.BufferedInputStream;
25 import java.io.BufferedOutputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
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.apache.commons.lang.StringUtils;
41 import org.onap.policy.common.logging.eelf.MessageCodes;
42 import org.onap.policy.common.logging.eelf.PolicyLogger;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
46 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
47 import org.onap.policy.rest.jpa.MicroServiceModels;
48 import org.onap.policy.rest.jpa.UserInfo;
49 import org.onap.policy.rest.util.MSAttributeObject;
50 import org.onap.policy.rest.util.MSModelUtils;
51 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
53 import com.google.gson.Gson;
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<>();
61 private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
63 public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
67 public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) {
69 this.newModel = new MicroServiceModels();
70 this.newModel.setVersion(version);
71 this.newModel.setModelName(modelName);
72 UserInfo userInfo = new UserInfo();
73 userInfo.setUserLoginId("API");
74 this.newModel.setUserCreatedBy(userInfo);
75 String cleanUpFile = null;
77 Map<String, MSAttributeObject> tempMap = new HashMap<>();
78 //Need to delete the file
79 if (importFile.contains(".zip")){
80 extractFolder(randomID + ".zip");
81 File directory = new File("ExtractDir" + File.separator + randomID);
82 List<File> fileList = listModelFiles(directory.toString());
83 //get all the files from a director
84 processFiles(modelName, fileList);
85 doCleanUpFiles(randomID);
87 if(importFile.contains(".yml")){
89 processYmlModel("ExtractDir" + File.separator + randomID+".yml", modelName);
90 cleanUpFile = "ExtractDir" + File.separator + randomID+".yml";
93 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
94 classMap.putAll(tempMap);
95 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
98 File deleteFile = new File(cleanUpFile);
103 private void processFiles(String modelName, List<File> fileList) {
104 Map<String, MSAttributeObject> tempMap;
105 for (File file : fileList){
107 int i = file.getName().lastIndexOf('.');
108 String type = file.getName().substring(i+1);
110 if("yml".equalsIgnoreCase(type)){
112 processYmlModel(file.toString(), modelName);
116 tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
117 classMap.putAll(tempMap);
123 private void doCleanUpFiles(String randomID) {
125 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
127 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
128 FileUtils.deleteDirectory(new File(randomID));
129 File deleteFile = new File(cleanUpFile);
130 FileUtils.forceDelete(deleteFile);
131 } catch (IOException e) {
132 logger.error("Failed to unzip model file " + randomID, e);
136 private void processYmlModel(String fileName, String modelName){
141 utils.parseTosca(fileName);
143 MSAttributeObject msAttributes= new MSAttributeObject();
144 msAttributes.setClassName(modelName);
146 LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
147 returnAttributeList.put(modelName, utils.getAttributeString());
148 msAttributes.setAttribute(returnAttributeList);
150 msAttributes.setSubClass(utils.getRetmap());
152 msAttributes.setMatchingSet(utils.getMatchableValues());
154 LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
156 returnReferenceList.put(modelName, utils.getReferenceAttributes());
157 msAttributes.setRefAttribute(returnReferenceList);
159 if(!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())){
160 LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
161 String[] listArray=utils.getListConstraints().split("#");
162 for(String str:listArray){
163 String[] strArr= str.split("=");
165 enumList.put(strArr[0], strArr[1]);
168 msAttributes.setEnumType(enumList);
171 classMap=new LinkedHashMap<>();
172 classMap.put(modelName, msAttributes);
174 } catch (Exception e) {
175 logger.error("Failed to process yml model" + e);
180 private List<File> listModelFiles(String directoryName) {
181 File directory = new File(directoryName);
182 List<File> resultList = new ArrayList<>();
183 File[] fList = directory.listFiles();
184 for (File file : fList) {
186 resultList.add(file);
187 } else if (file.isDirectory()) {
188 resultList.addAll(listModelFiles(file.getAbsolutePath()));
194 @SuppressWarnings("rawtypes")
195 private void extractFolder(String zipFile) {
197 File file = new File(zipFile);
199 try(ZipFile zip = new ZipFile("ExtractDir" + File.separator +file)) {
201 String newPath = zipFile.substring(0, zipFile.length() - 4);
202 new File(newPath).mkdir();
203 Enumeration zipFileEntries = zip.entries();
205 // Process each entry
206 while (zipFileEntries.hasMoreElements()){
207 // grab a zip file entry
208 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
209 String currentEntry = entry.getName();
210 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
211 File destinationParent = destFile.getParentFile();
213 destinationParent.mkdirs();
215 if (!entry.isDirectory()){
216 BufferedInputStream is = new BufferedInputStream(zip
217 .getInputStream(entry));
220 byte data[] = new byte[BUFFER];
221 try(FileOutputStream fos = new FileOutputStream(destFile);
222 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
224 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
225 dest.write(data, 0, currentByte);
232 if (currentEntry.endsWith(".zip")){
233 extractFolder(destFile.getAbsolutePath());
236 } catch (IOException e) {
237 logger.error("Failed to unzip model file " + zipFile + e);
241 public Map<String, String> addValuesToNewModel(String type) {
243 Map<String, String> successMap = new HashMap<>();
244 MSAttributeObject mainClass = null;
245 List<String> dependency = null;
246 String subAttribute = null;
248 if (!classMap.containsKey(this.newModel.getModelName())){
249 logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
250 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
251 successMap.put("error", "MISSING");
254 mainClass = classMap.get(this.newModel.getModelName());
257 if(".yml".equalsIgnoreCase(type)){
259 newModel.setDependency("[]");
260 if(mainClass.getSubClass() != null){
261 String value = new Gson().toJson(mainClass.getSubClass());
262 newModel.setSub_attributes(value);
265 if(mainClass.getAttribute() != null){
266 String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
267 int equalsIndexForAttributes= attributes.indexOf("=");
268 String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
269 this.newModel.setAttributes(atttributesAfterFirstEquals);
272 if(mainClass.getRefAttribute() != null){
273 String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
274 int equalsIndex= refAttributes.indexOf("=");
275 String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
276 this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
279 if(mainClass.getEnumType() != null){
280 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
283 if(mainClass.getMatchingSet() != null){
284 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
289 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
290 this.newModel.setDependency(dependTemp);
291 if (this.newModel.getDependency() != null && !this.newModel.getDependency().isEmpty()){
292 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
293 dependency = utils.getFullDependencyList(dependency, classMap);
294 if (!dependency.isEmpty()){
295 for (String element : dependency){
296 MSAttributeObject temp = new MSAttributeObject();
297 if (classMap.containsKey(element)){
298 temp = classMap.get(element);
299 mainClass.addAllRefAttribute(temp.getRefAttribute());
300 mainClass.addAllAttribute(temp.getAttribute());
305 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
307 this.newModel.setSub_attributes(subAttribute);
308 if(mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()){
309 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
312 if(mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()){
313 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
316 if(mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()){
317 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
320 if(mainClass.getMatchingSet() != null && !mainClass.getMatchingSet().isEmpty()){
321 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
324 successMap.put("success", "success");
329 public Map<String, String> saveImportService(){
330 String modelName = this.newModel.getModelName();
331 String imported_by = "API";
332 String version = this.newModel.getVersion();
333 Map<String, String> successMap = new HashMap<>();
334 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
335 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
336 if(result.isEmpty()){
337 MicroServiceModels model = new MicroServiceModels();
338 model.setModelName(modelName);
339 model.setVersion(version);
340 model.setAttributes(this.newModel.getAttributes());
341 model.setAnnotation(this.newModel.getAnnotation());
342 model.setDependency(this.newModel.getDependency());
343 model.setDescription(this.newModel.getDescription());
344 model.setEnumValues(this.newModel.getEnumValues());
345 model.setRef_attributes(this.newModel.getRef_attributes());
346 model.setSub_attributes(this.newModel.getSub_attributes());
347 model.setDataOrderInfo(this.newModel.getDataOrderInfo());
348 UserInfo userInfo = new UserInfo();
349 userInfo.setUserLoginId(imported_by);
350 userInfo.setUserName(imported_by);
351 model.setUserCreatedBy(userInfo);
352 dbConnection.save(model);
353 successMap.put("success", "success");
355 successMap.put("DBError", "EXISTS");
356 logger.error("Import new service failed. Service already exists");