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.apache.commons.logging.Log;
45 import org.apache.commons.logging.LogFactory;
46 //import org.eclipse.emf.common.util.URI;
47 //import org.eclipse.emf.ecore.EPackage;
48 //import org.eclipse.emf.ecore.resource.Resource;
49 //import org.eclipse.emf.ecore.resource.ResourceSet;
50 //import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
51 //import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
52 import org.openecomp.policy.rest.XACMLRestProperties;
53 import org.openecomp.policy.rest.jpa.MicroServiceModels;
54 import org.openecomp.policy.rest.jpa.UserInfo;
55 import org.openecomp.policy.rest.util.MSAttributeObject;
56 import org.openecomp.policy.rest.util.MSModelUtitils;
58 import com.att.research.xacml.util.XACMLProperties;
60 import org.openecomp.policy.common.logging.eelf.MessageCodes;
61 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
62 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
63 import org.openecomp.policy.common.logging.flexlogger.Logger;
65 public class CreateNewMicroSerivceModel {
66 private static final Logger logger = FlexLogger.getLogger(CreateNewMicroSerivceModel.class);
67 private MicroServiceModels newModel = null;
68 private HashMap<String,MSAttributeObject > classMap = new HashMap<String,MSAttributeObject>();
69 private String directory;
72 * These are the parameters needed for DB access from the PAP
74 private static String papDbDriver = null;
75 private static String papDbUrl = null;
76 private static String papDbUser = null;
77 private static String papDbPassword = null;
79 MSModelUtitils utils = new MSModelUtitils();
81 public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) {
85 public CreateNewMicroSerivceModel(String importFile, String modelName, String description, String version, String randomID) {
87 Map<String, String> successMap = new HashMap<String,String>();
88 this.newModel = new MicroServiceModels();
89 this.newModel.setDescription(description);
90 this.newModel.setVersion(version);
91 this.newModel.setModelName(modelName);
92 UserInfo userInfo = new UserInfo();
93 userInfo.setUserLoginId("API");
94 this.newModel.setUserCreatedBy(userInfo);
95 String cleanUpFile = null;
97 HashMap<String, MSAttributeObject> tempMap = new HashMap<String, MSAttributeObject>();
98 //Need to delete the file
99 if (importFile.contains(".zip")){
100 extractFolder(randomID + ".zip");
101 File directory = new File("ExtractDir" + File.separator + randomID);
102 List<File> fileList = listModelFiles(directory.toString());
103 //get all the files from a directory
104 File[] fList = directory.listFiles();
105 for (File file : fileList){
107 tempMap = utils.processEpackage(file.getAbsolutePath());
108 classMap.putAll(tempMap);
111 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
113 FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID));
114 FileUtils.deleteDirectory(new File(randomID));
115 File deleteFile = new File(cleanUpFile);
116 FileUtils.forceDelete(deleteFile);
117 } catch (IOException e) {
118 logger.error("Failed to unzip model file " + randomID);
121 tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi");
122 classMap.putAll(tempMap);
123 cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi";
124 File deleteFile = new File(cleanUpFile);
128 // addValuesToNewModel();
133 private List<File> listModelFiles(String directoryName) {
134 File directory = new File(directoryName);
135 List<File> resultList = new ArrayList<File>();
136 File[] fList = directory.listFiles();
137 for (File file : fList) {
139 resultList.add(file);
140 } else if (file.isDirectory()) {
141 resultList.addAll(listModelFiles(file.getAbsolutePath()));
147 private void extractFolder(String zipFile) {
149 File file = new File(zipFile);
153 zip = new ZipFile("ExtractDir" + File.separator +file);
154 String newPath = zipFile.substring(0, zipFile.length() - 4);
155 this.directory = "ExtractDir" + File.separator + zipFile.substring(0, zipFile.length() - 4);
156 new File(newPath).mkdir();
157 Enumeration zipFileEntries = zip.entries();
159 // Process each entry
160 while (zipFileEntries.hasMoreElements())
162 // grab a zip file entry
163 ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
164 String currentEntry = entry.getName();
165 File destFile = new File("ExtractDir" + File.separator + newPath + File.separator + currentEntry);
166 File destinationParent = destFile.getParentFile();
168 destinationParent.mkdirs();
170 if (!entry.isDirectory())
172 BufferedInputStream is = new BufferedInputStream(zip
173 .getInputStream(entry));
176 byte data[] = new byte[BUFFER];
178 FileOutputStream fos = new FileOutputStream(destFile);
179 BufferedOutputStream dest = new BufferedOutputStream(fos,
182 while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
183 dest.write(data, 0, currentByte);
190 if (currentEntry.endsWith(".zip"))
192 extractFolder(destFile.getAbsolutePath());
195 } catch (IOException e) {
196 logger.error("Failed to unzip model file " + zipFile);
200 public Map<String, String> addValuesToNewModel() {
202 Map<String, String> successMap = new HashMap<String,String>();
203 MSAttributeObject mainClass = null;
204 ArrayList<String> dependency = null;
205 String subAttribute = null;
207 if (!classMap.containsKey(this.newModel.getModelName())){
208 logger.error("Model Provided does not contain the service name provided in request. Unable to import new model");
209 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request");
210 successMap.put("error", "MISSING");
213 mainClass = classMap.get(this.newModel.getModelName());
214 String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""});
215 this.newModel.setDependency(dependTemp);
216 if (!this.newModel.getDependency().equals("")){
217 dependency = new ArrayList<String>(Arrays.asList(dependTemp.split(",")));
218 dependency = utils.getFullDependencyList(dependency, classMap);
219 if (!dependency.isEmpty()){
220 for (String element : dependency){
221 MSAttributeObject temp = new MSAttributeObject();
222 if (classMap.containsKey(element)){
223 temp = classMap.get(element);
224 mainClass.addAllRefAttribute(temp.getRefAttribute());
225 mainClass.addAllAttribute(temp.getAttribute());
230 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
232 this.newModel.setSub_attributes(subAttribute);
233 this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", ""));
234 this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""));
235 successMap.put("success", "success");
240 public Map<String, String> saveImportService(){
241 Map<String, String> successMap = new HashMap<String,String>();
243 Connection con = null;
246 String modelName = this.newModel.getModelName();
247 String imported_by = "API";////////////////////////////////////////////
248 String version = this.newModel.getVersion();
249 String insertQuery = null;
253 * Retrieve the property values for db access from the xacml.pap.properties
255 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
256 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
257 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
258 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
262 Class.forName(papDbDriver);
263 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
264 st = con.createStatement();
265 String queryString ="SELECT * FROM MicroServiceModels WHERE modelName='" + modelName + "' AND version='" + version+ "';";
266 rs = st.executeQuery(queryString);
269 successMap.put("DBError", "EXISTS");
270 logger.error("Import new service failed. Service already exists");
272 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;");
274 ID = rs.getInt("ID");
278 insertQuery = "INSERT INTO MicroServiceModels (ID, modelName, Dependency, DESCRIPTION, attributes, ref_attributes, sub_attributes, version, imported_by) "
279 + "VALUES("+ID+",'"+modelName+"','"+ this.newModel.getDependency()+"','"+this.newModel.getDescription()+"','"+this.newModel.getAttributes()+
280 "','"+this.newModel.getRef_attributes()+"','"+this.newModel.getSub_attributes()+"','"+version+"','"+imported_by+"')";
281 st.executeUpdate(insertQuery);
282 successMap.put("success", "success");
285 }catch (ClassNotFoundException e) {
286 //TODO:EELF Cleanup - Remove logger
287 //logger.error(e.getMessage());
288 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
289 successMap.put("DBError", "Error Query");
290 } catch (SQLException e) {
291 //TODO:EELF Cleanup - Remove logger
292 //logger.error(e.getMessage());
293 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
294 successMap.put("DBError", "Error Query");
297 if (con!=null) con.close();
298 if (rs!=null) rs.close();
299 if (st!=null) st.close();
300 } catch (Exception ex){}