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.openecomp.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.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.ResultSet;
31 import java.sql.SQLException;
32 import java.sql.Statement;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Enumeration;
36 import java.util.HashMap;
37 import java.util.List;
39 import java.util.zip.ZipEntry;
40 import java.util.zip.ZipFile;
42 import org.apache.commons.io.FileUtils;
43 import org.apache.commons.lang.StringUtils;
44 import org.openecomp.policy.common.logging.eelf.MessageCodes;
45 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
46 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
47 import org.openecomp.policy.common.logging.flexlogger.Logger;
48 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
49 import org.openecomp.policy.rest.XACMLRestProperties;
50 import org.openecomp.policy.rest.jpa.MicroServiceModels;
51 import org.openecomp.policy.rest.jpa.UserInfo;
52 import org.openecomp.policy.rest.util.MSAttributeObject;
53 import org.openecomp.policy.rest.util.MSModelUtils;
54 import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE;
56 import com.att.research.xacml.util.XACMLProperties;
58 public class CreateNewMicroSerivceModel {
59 private static final Logger logger = FlexLogger.getLogger(CreateNewMicroSerivceModel.class);
60 private MicroServiceModels newModel = null;
61 private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
64 * These are the parameters needed for DB access from the PAP
66 private static String papDbDriver = null;
67 private static String papDbUrl = null;
68 private static String papDbUser = null;
69 private static String papDbPassword = null;
71 MSModelUtils utils = new MSModelUtils(XACMLPapServlet.msEcompName, XACMLPapServlet.msPolicyName);
73 public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) {
77 public CreateNewMicroSerivceModel(String importFile, String modelName, String description, String version, String randomID) {
79 this.newModel = new MicroServiceModels();
80 this.newModel.setDescription(description);
81 this.newModel.setVersion(version);
82 this.newModel.setModelName(modelName);
83 UserInfo userInfo = new UserInfo();
84 userInfo.setUserLoginId("API");
85 this.newModel.setUserCreatedBy(userInfo);
86 String cleanUpFile = null;
88 HashMap<String, MSAttributeObject> tempMap = new HashMap<String, MSAttributeObject>();
89 //Need to delete the file
90 if (importFile.contains(".zip")){
91 extractFolder(randomID + ".zip");
92 File directory = new File("ExtractDir" + File.separator + randomID);
93 List<File> fileList = listModelFiles(directory.toString());
94 //get all the files from a director
95 for (File file : fileList){
97 tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
98 classMap.putAll(tempMap);
101 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
103 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
104 FileUtils.deleteDirectory(new File(randomID));
105 File deleteFile = new File(cleanUpFile);
106 FileUtils.forceDelete(deleteFile);
107 } catch (IOException e) {
108 logger.error("Failed to unzip model file " + randomID);
111 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI);
112 classMap.putAll(tempMap);
113 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
114 File deleteFile = new File(cleanUpFile);
119 private List<File> listModelFiles(String directoryName) {
120 File directory = new File(directoryName);
121 List<File> resultList = new ArrayList<File>();
122 File[] fList = directory.listFiles();
123 for (File file : fList) {
125 resultList.add(file);
126 } else if (file.isDirectory()) {
127 resultList.addAll(listModelFiles(file.getAbsolutePath()));
133 @SuppressWarnings("rawtypes")
134 private void extractFolder(String zipFile) {
136 File file = new File(zipFile);
140 zip = new ZipFile("ExtractDir" + File.separator +file);
141 String newPath = zipFile.substring(0, zipFile.length() - 4);
142 new File(newPath).mkdir();
143 Enumeration zipFileEntries = zip.entries();
145 // Process each entry
146 while (zipFileEntries.hasMoreElements())
148 // grab a zip file entry
149 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
150 String currentEntry = entry.getName();
151 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
152 File destinationParent = destFile.getParentFile();
154 destinationParent.mkdirs();
156 if (!entry.isDirectory())
158 BufferedInputStream is = new BufferedInputStream(zip
159 .getInputStream(entry));
162 byte data[] = new byte[BUFFER];
164 FileOutputStream fos = new FileOutputStream(destFile);
165 BufferedOutputStream dest = new BufferedOutputStream(fos,
168 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
169 dest.write(data, 0, currentByte);
176 if (currentEntry.endsWith(".zip"))
178 extractFolder(destFile.getAbsolutePath());
181 } catch (IOException e) {
182 logger.error("Failed to unzip model file " + zipFile);
186 public Map<String, String> addValuesToNewModel() {
188 Map<String, String> successMap = new HashMap<String,String>();
189 MSAttributeObject mainClass = null;
190 ArrayList<String> dependency = null;
191 String subAttribute = null;
193 if (!classMap.containsKey(this.newModel.getModelName())){
194 logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
195 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
196 successMap.put("error", "MISSING");
199 mainClass = classMap.get(this.newModel.getModelName());
200 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
201 this.newModel.setDependency(dependTemp);
202 if (!this.newModel.getDependency().equals("")){
203 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
204 dependency = utils.getFullDependencyList(dependency, classMap);
205 if (!dependency.isEmpty()){
206 for (String element : dependency){
207 MSAttributeObject temp = new MSAttributeObject();
208 if (classMap.containsKey(element)){
209 temp = classMap.get(element);
210 mainClass.addAllRefAttribute(temp.getRefAttribute());
211 mainClass.addAllAttribute(temp.getAttribute());
216 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
218 this.newModel.setSub_attributes(subAttribute);
219 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
220 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
221 this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", ""));
222 this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", ""));
223 successMap.put("success", "success");
228 @SuppressWarnings("resource")
229 public Map<String, String> saveImportService(){
230 Map<String, String> successMap = new HashMap<String,String>();
232 Connection con = null;
235 String modelName = this.newModel.getModelName();
236 String imported_by = "API";////////////////////////////////////////////
237 String version = this.newModel.getVersion();
238 String insertQuery = null;
242 * Retrieve the property values for db access from the xacml.pap.properties
244 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
245 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
246 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
247 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
251 Class.forName(papDbDriver);
252 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
253 st = con.createStatement();
254 String queryString ="SELECT * FROM MicroServiceModels WHERE modelName='" + modelName + "' AND version='" + version+ "';";
255 rs = st.executeQuery(queryString);
258 successMap.put("DBError", "EXISTS");
259 logger.error("Import new service failed. Service already exists");
261 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;");
263 ID = rs.getInt("ID");
267 String newDependency = "[" + this.newModel.getDependency() + "]";
268 this.newModel.setDependency(newDependency);
269 insertQuery = "INSERT INTO MicroServiceModels (ID, modelName, Dependency, DESCRIPTION, attributes, ref_attributes, sub_attributes, version, imported_by, enumValues, annotation) "
270 + "VALUES("+ID+",'"+modelName+"','"+ this.newModel.getDependency()+"','"+this.newModel.getDescription()+"','"+this.newModel.getAttributes()+
271 "','"+this.newModel.getRef_attributes()+"','"+this.newModel.getSub_attributes()+"','"+version+"','"+imported_by+"','"+this.newModel.getEnumValues()+"','"+this.newModel.getAnnotation()+"')";
272 st.executeUpdate(insertQuery);
273 successMap.put("success", "success");
276 }catch (ClassNotFoundException e) {
277 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
278 successMap.put("DBError", "Error Query");
279 } catch (SQLException e) {
280 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
281 successMap.put("DBError", "Error Query");
284 if (con!=null) con.close();
285 if (rs!=null) rs.close();
286 if (st!=null) st.close();
287 } catch (Exception ex){
288 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "saveImportService", "Exception querying MicroServiceModels");