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.List;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipFile;
37 import org.apache.commons.io.FileUtils;
38 import org.apache.commons.lang.StringUtils;
39 import org.onap.policy.common.logging.eelf.MessageCodes;
40 import org.onap.policy.common.logging.eelf.PolicyLogger;
41 import org.onap.policy.common.logging.flexlogger.FlexLogger;
42 import org.onap.policy.common.logging.flexlogger.Logger;
43 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
44 import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
45 import org.onap.policy.rest.jpa.MicroServiceModels;
46 import org.onap.policy.rest.jpa.UserInfo;
47 import org.onap.policy.rest.util.MSAttributeObject;
48 import org.onap.policy.rest.util.MSModelUtils;
49 import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
51 public class CreateNewMicroServiceModel {
52 private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
53 private MicroServiceModels newModel = null;
54 private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
57 MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName());
59 public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
63 public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) {
65 this.newModel = new MicroServiceModels();
66 this.newModel.setVersion(version);
67 this.newModel.setModelName(modelName);
68 UserInfo userInfo = new UserInfo();
69 userInfo.setUserLoginId("API");
70 this.newModel.setUserCreatedBy(userInfo);
71 String cleanUpFile = null;
73 Map<String, MSAttributeObject> tempMap = new HashMap<>();
74 //Need to delete the file
75 if (importFile.contains(".zip")){
76 extractFolder(randomID + ".zip");
77 File directory = new File("ExtractDir" + File.separator + randomID);
78 List<File> fileList = listModelFiles(directory.toString());
79 //get all the files from a director
80 for (File file : fileList){
82 tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
83 classMap.putAll(tempMap);
86 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
88 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
89 FileUtils.deleteDirectory(new File(randomID));
90 File deleteFile = new File(cleanUpFile);
91 FileUtils.forceDelete(deleteFile);
92 } catch (IOException e) {
93 logger.error("Failed to unzip model file " + randomID, e);
96 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
97 classMap.putAll(tempMap);
98 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
99 File deleteFile = new File(cleanUpFile);
104 private List<File> listModelFiles(String directoryName) {
105 File directory = new File(directoryName);
106 List<File> resultList = new ArrayList<>();
107 File[] fList = directory.listFiles();
108 for (File file : fList) {
110 resultList.add(file);
111 } else if (file.isDirectory()) {
112 resultList.addAll(listModelFiles(file.getAbsolutePath()));
118 @SuppressWarnings("rawtypes")
119 private void extractFolder(String zipFile) {
121 File file = new File(zipFile);
125 zip = new ZipFile("ExtractDir" + File.separator +file);
126 String newPath = zipFile.substring(0, zipFile.length() - 4);
127 new File(newPath).mkdir();
128 Enumeration zipFileEntries = zip.entries();
130 // Process each entry
131 while (zipFileEntries.hasMoreElements()){
132 // grab a zip file entry
133 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
134 String currentEntry = entry.getName();
135 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
136 File destinationParent = destFile.getParentFile();
138 destinationParent.mkdirs();
140 if (!entry.isDirectory()){
141 BufferedInputStream is = new BufferedInputStream(zip
142 .getInputStream(entry));
145 byte data[] = new byte[BUFFER];
146 try(FileOutputStream fos = new FileOutputStream(destFile);
147 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
149 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
150 dest.write(data, 0, currentByte);
157 if (currentEntry.endsWith(".zip")){
158 extractFolder(destFile.getAbsolutePath());
161 } catch (IOException e) {
162 logger.error("Failed to unzip model file " + zipFile + e);
167 } catch (Exception e) {
168 logger.error("Exception Occured while closing the zip file"+e);
174 public Map<String, String> addValuesToNewModel() {
176 Map<String, String> successMap = new HashMap<>();
177 MSAttributeObject mainClass = null;
178 List<String> dependency = null;
179 String subAttribute = null;
181 if (!classMap.containsKey(this.newModel.getModelName())){
182 logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
183 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
184 successMap.put("error", "MISSING");
187 mainClass = classMap.get(this.newModel.getModelName());
188 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
189 this.newModel.setDependency(dependTemp);
190 if (!this.newModel.getDependency().equals("")){
191 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
192 dependency = utils.getFullDependencyList(dependency, classMap);
193 if (!dependency.isEmpty()){
194 for (String element : dependency){
195 MSAttributeObject temp;
196 if (classMap.containsKey(element)){
197 temp = classMap.get(element);
198 mainClass.addAllRefAttribute(temp.getRefAttribute());
199 mainClass.addAllAttribute(temp.getAttribute());
204 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
206 this.newModel.setSub_attributes(subAttribute);
207 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
208 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
209 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
210 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
211 successMap.put("success", "success");
216 public Map<String, String> saveImportService(){
217 String modelName = this.newModel.getModelName();
218 String imported_by = "API";
219 String version = this.newModel.getVersion();
220 Map<String, String> successMap = new HashMap<>();
221 CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
222 List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
223 if(result.isEmpty()){
224 MicroServiceModels model = new MicroServiceModels();
225 model.setModelName(modelName);
226 model.setVersion(version);
227 model.setAttributes(this.newModel.getAttributes());
228 model.setAnnotation(this.newModel.getAnnotation());
229 model.setDependency(this.newModel.getDependency());
230 model.setDescription(this.newModel.getDescription());
231 model.setEnumValues(this.newModel.getEnumValues());
232 model.setRef_attributes(this.newModel.getRef_attributes());
233 model.setSub_attributes(this.newModel.getSub_attributes());
234 UserInfo userInfo = new UserInfo();
235 userInfo.setUserLoginId(imported_by);
236 userInfo.setUserName(imported_by);
237 model.setUserCreatedBy(userInfo);
238 dbConnection.save(model);
239 successMap.put("success", "success");
241 successMap.put("DBError", "EXISTS");
242 logger.error("Import new service failed. Service already exists");