Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / CreateNewMicroSerivceModel.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.components;
22
23 import java.io.BufferedInputStream;
24 import java.io.BufferedOutputStream;
25 import java.io.File;
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;
38 import java.util.Map;
39 import java.util.zip.ZipEntry;
40 import java.util.zip.ZipFile;
41
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;
57
58 import com.att.research.xacml.util.XACMLProperties;
59
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; 
64
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;
70         
71         /*
72          * These are the parameters needed for DB access from the PAP
73          */
74         private static String papDbDriver = null;
75         private static String papDbUrl = null;
76         private static String papDbUser = null;
77         private static String papDbPassword = null;
78         
79         MSModelUtitils utils = new MSModelUtitils();
80
81         public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) {
82                 super();
83         }
84
85         public CreateNewMicroSerivceModel(String importFile, String  modelName, String description, String version, String randomID) {
86                 
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;
96         
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){
106                     if (file.isFile()){
107                                     tempMap = utils.processEpackage(file.getAbsolutePath());
108                                     classMap.putAll(tempMap);
109                     }
110                 }
111                 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
112                 try {
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);
119                         }
120             }else {
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); 
125                         deleteFile.delete();
126             }
127
128             //  addValuesToNewModel();
129
130
131         }
132         
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) {
138                         if (file.isFile()) {
139                                 resultList.add(file);
140                         } else if (file.isDirectory()) {
141                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
142                         }
143                 }
144                 return resultList;
145         }
146
147         private void extractFolder(String zipFile) {
148             int BUFFER = 2048;
149             File file = new File(zipFile);
150
151             ZipFile zip;
152                 try {
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();
158         
159                     // Process each entry
160                     while (zipFileEntries.hasMoreElements())
161                     {
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();
167         
168                         destinationParent.mkdirs();
169         
170                         if (!entry.isDirectory())
171                         {
172                             BufferedInputStream is = new BufferedInputStream(zip
173                             .getInputStream(entry));
174                             int currentByte;
175
176                             byte data[] = new byte[BUFFER];
177         
178                             FileOutputStream fos = new FileOutputStream(destFile);
179                             BufferedOutputStream dest = new BufferedOutputStream(fos,
180                             BUFFER);
181         
182                             while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
183                                 dest.write(data, 0, currentByte);
184                             }
185                             dest.flush();
186                             dest.close();
187                             is.close();
188                         }
189         
190                         if (currentEntry.endsWith(".zip"))
191                         {
192                             extractFolder(destFile.getAbsolutePath());
193                         }
194                     }
195             } catch (IOException e) {
196                         logger.error("Failed to unzip model file " + zipFile);
197                 }
198         }
199
200         public Map<String, String> addValuesToNewModel() {
201                 
202                 Map<String, String> successMap = new HashMap<String,String>();
203                 MSAttributeObject mainClass  = null;
204                 ArrayList<String> dependency = null;
205                 String subAttribute = null;
206                 
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");
211                         return successMap;
212                 }
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());
226                                         }
227                                 }
228                         }               
229                 }
230                 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
231
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");
236                 return successMap;
237                 
238         }
239         
240         public Map<String, String> saveImportService(){
241                 Map<String, String> successMap = new HashMap<String,String>();
242                 
243                 Connection con = null;
244                 Statement st = null;
245                 ResultSet rs = null;
246                 String modelName = this.newModel.getModelName();
247                 String imported_by = "API";////////////////////////////////////////////
248                 String version = this.newModel.getVersion();
249                 String insertQuery = null;
250                 int ID = 0;
251                 
252                 /*
253                  * Retrieve the property values for db access from the xacml.pap.properties
254                  */
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);
259                 
260                 try {
261                         //Get DB Connection
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);
267                 
268                         if(rs.next()){
269                                 successMap.put("DBError", "EXISTS");
270                                 logger.error("Import new service failed.  Service already exists");
271                         }else{
272                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;");
273                                 if(rs.next()){
274                                         ID = rs.getInt("ID");
275                                         ID++;
276                                 }
277         
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");
283                         }
284                         rs.close();
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");
295                 } finally {
296                         try{
297                                 if (con!=null) con.close();
298                                 if (rs!=null) rs.close();
299                                 if (st!=null) st.close();
300                         } catch (Exception ex){}
301                 }
302
303                 return successMap;
304         }
305 }