2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 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.Arrays;
30 import java.util.Enumeration;
31 import java.util.HashMap;
32 import java.util.LinkedHashMap;
33 import java.util.List;
35 import java.util.zip.ZipEntry;
36 import java.util.zip.ZipFile;
38 import org.apache.commons.io.FileUtils;
39 import org.apache.commons.lang.StringUtils;
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.MicroServiceModels;
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 import com.google.gson.Gson;
54 public class CreateNewMicroServiceModel {
55 private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
56 private MicroServiceModels newModel = null;
57 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) {
66 public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) {
68 this.newModel = new MicroServiceModels();
69 this.newModel.setVersion(version);
70 this.newModel.setModelName(modelName);
71 UserInfo userInfo = new UserInfo();
72 userInfo.setUserLoginId("API");
73 this.newModel.setUserCreatedBy(userInfo);
74 String cleanUpFile = null;
76 Map<String, MSAttributeObject> tempMap = new HashMap<>();
77 //Need to delete the file
78 if (importFile.contains(".zip")){
79 extractFolder(randomID + ".zip");
80 File directory = new File("ExtractDir" + File.separator + randomID);
81 List<File> fileList = listModelFiles(directory.toString());
82 //get all the files from a director
83 processFiles(modelName, fileList);
84 doCleanUpFiles(randomID);
86 if(importFile.contains(".yml")){
88 processYmlModel("ExtractDir" + File.separator + randomID+".yml", modelName);
89 cleanUpFile = "ExtractDir" + File.separator + randomID+".yml";
92 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
93 classMap.putAll(tempMap);
94 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
97 File deleteFile = new File(cleanUpFile);
102 private void processFiles(String modelName, List<File> fileList) {
103 Map<String, MSAttributeObject> tempMap;
104 for (File file : fileList){
106 int i = file.getName().lastIndexOf('.');
107 String type = file.getName().substring(i+1);
109 if("yml".equalsIgnoreCase(type)){
111 processYmlModel(file.toString(), modelName);
115 tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
116 classMap.putAll(tempMap);
122 private void doCleanUpFiles(String randomID) {
124 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
126 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
127 FileUtils.deleteDirectory(new File(randomID));
128 File deleteFile = new File(cleanUpFile);
129 FileUtils.forceDelete(deleteFile);
130 } catch (IOException e) {
131 logger.error("Failed to unzip model file " + randomID, e);
135 private void processYmlModel(String fileName, String modelName){
140 utils.parseTosca(fileName);
142 MSAttributeObject msAttributes= new MSAttributeObject();
143 msAttributes.setClassName(modelName);
145 LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
146 returnAttributeList.put(modelName, utils.getAttributeString());
147 msAttributes.setAttribute(returnAttributeList);
149 msAttributes.setSubClass(utils.getRetmap());
151 msAttributes.setMatchingSet(utils.getMatchableValues());
153 LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
155 returnReferenceList.put(modelName, utils.getReferenceAttributes());
156 msAttributes.setRefAttribute(returnReferenceList);
158 if(!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())){
159 LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
160 String[] listArray=utils.getListConstraints().split("#");
161 for(String str:listArray){
162 String[] strArr= str.split("=");
164 enumList.put(strArr[0], strArr[1]);
167 msAttributes.setEnumType(enumList);
170 classMap=new LinkedHashMap<>();
171 classMap.put(modelName, msAttributes);
173 } catch (Exception e) {
174 logger.error("Failed to process yml model" + e);
179 private List<File> listModelFiles(String directoryName) {
180 File directory = new File(directoryName);
181 List<File> resultList = new ArrayList<>();
182 File[] fList = directory.listFiles();
183 for (File file : fList) {
185 resultList.add(file);
186 } else if (file.isDirectory()) {
187 resultList.addAll(listModelFiles(file.getAbsolutePath()));
193 @SuppressWarnings("rawtypes")
194 private void extractFolder(String zipFile) {
196 File file = new File(zipFile);
198 try(ZipFile zip = new ZipFile("ExtractDir" + File.separator +file)) {
200 String newPath = zipFile.substring(0, zipFile.length() - 4);
201 new File(newPath).mkdir();
202 Enumeration zipFileEntries = zip.entries();
204 // Process each entry
205 while (zipFileEntries.hasMoreElements()){
206 // grab a zip file entry
207 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
208 String currentEntry = entry.getName();
209 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
210 File destinationParent = destFile.getParentFile();
212 destinationParent.mkdirs();
214 if (!entry.isDirectory()){
215 BufferedInputStream is = new BufferedInputStream(zip
216 .getInputStream(entry));
219 byte data[] = new byte[BUFFER];
220 try(FileOutputStream fos = new FileOutputStream(destFile);
221 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
223 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
224 dest.write(data, 0, currentByte);
231 if (currentEntry.endsWith(".zip")){
232 extractFolder(destFile.getAbsolutePath());
235 } catch (IOException e) {
236 logger.error("Failed to unzip model file " + zipFile + e);
240 public Map<String, String> addValuesToNewModel(String type) {
242 Map<String, String> successMap = new HashMap<>();
243 MSAttributeObject mainClass = null;
244 List<String> dependency = null;
245 String subAttribute = null;
247 if (!classMap.containsKey(this.newModel.getModelName())){
248 logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
249 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
250 successMap.put("error", "MISSING");
253 mainClass = classMap.get(this.newModel.getModelName());
256 if(".yml".equalsIgnoreCase(type)){
258 newModel.setDependency("[]");
259 if(mainClass.getSubClass() != null){
260 String value = new Gson().toJson(mainClass.getSubClass());
261 newModel.setSub_attributes(value);
264 if(mainClass.getAttribute() != null){
265 String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", "");
266 int equalsIndexForAttributes= attributes.indexOf("=");
267 String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1);
268 this.newModel.setAttributes(atttributesAfterFirstEquals);
271 if(mainClass.getRefAttribute() != null){
272 String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", "");
273 int equalsIndex= refAttributes.indexOf("=");
274 String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1);
275 this.newModel.setRef_attributes(refAttributesAfterFirstEquals);
278 if(mainClass.getEnumType() != null){
279 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
282 if(mainClass.getMatchingSet() != null){
283 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
288 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
289 this.newModel.setDependency(dependTemp);
290 if (this.newModel.getDependency() != null && !this.newModel.getDependency().isEmpty()){
291 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
292 dependency = utils.getFullDependencyList(dependency, classMap);
293 if (!dependency.isEmpty()){
294 for (String element : dependency){
295 MSAttributeObject temp = new MSAttributeObject();
296 if (classMap.containsKey(element)){
297 temp = classMap.get(element);
298 mainClass.addAllRefAttribute(temp.getRefAttribute());
299 mainClass.addAllAttribute(temp.getAttribute());
304 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
306 this.newModel.setSub_attributes(subAttribute);
307 if(mainClass.getAttribute() != null && !mainClass.getAttribute().isEmpty()){
308 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
311 if(mainClass.getRefAttribute() != null && !mainClass.getRefAttribute().isEmpty()){
312 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
315 if(mainClass.getEnumType() != null && !mainClass.getEnumType().isEmpty()){
316 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
319 if(mainClass.getMatchingSet() != null && !mainClass.getMatchingSet().isEmpty()){
320 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
323 successMap.put("success", "success");
328 public Map<String, String> saveImportService(){
329 String modelName = this.newModel.getModelName();
330 String imported_by = "API";
331 String version = this.newModel.getVersion();
332 Map<String, String> successMap = new HashMap<>();
333 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
334 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
335 if(result.isEmpty()){
336 MicroServiceModels model = new MicroServiceModels();
337 model.setModelName(modelName);
338 model.setVersion(version);
339 model.setAttributes(this.newModel.getAttributes());
340 model.setAnnotation(this.newModel.getAnnotation());
341 model.setDependency(this.newModel.getDependency());
342 model.setDescription(this.newModel.getDescription());
343 model.setEnumValues(this.newModel.getEnumValues());
344 model.setRef_attributes(this.newModel.getRef_attributes());
345 model.setSub_attributes(this.newModel.getSub_attributes());
346 model.setDataOrderInfo(this.newModel.getDataOrderInfo());
347 UserInfo userInfo = new UserInfo();
348 userInfo.setUserLoginId(imported_by);
349 userInfo.setUserName(imported_by);
350 model.setUserCreatedBy(userInfo);
351 dbConnection.save(model);
352 successMap.put("success", "success");
354 successMap.put("DBError", "EXISTS");
355 logger.error("Import new service failed. Service already exists");