[Policy-17] Removed the sql scripts from sdk app
[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.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;
55
56 import com.att.research.xacml.util.XACMLProperties;
57
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<>();
62
63         /*
64          * These are the parameters needed for DB access from the PAP
65          */
66         private static String papDbDriver = null;
67         private static String papDbUrl = null;
68         private static String papDbUser = null;
69         private static String papDbPassword = null;
70         
71         MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName());
72
73         public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) {
74                 super();
75         }
76
77         public CreateNewMicroSerivceModel(String importFile, String  modelName, String description, String version, String randomID) {
78         
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;
87         
88             HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
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){
96                     if (file.isFile()){
97                                     tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI);
98                                     classMap.putAll(tempMap);
99                     }
100                 }
101                 cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip";
102                 try {
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);
109                         }
110             }else {
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); 
115                         deleteFile.delete();
116             }
117         }
118         
119         private List<File> listModelFiles(String directoryName) {
120                 File directory = new File(directoryName);
121                 List<File> resultList = new ArrayList<>();
122                 File[] fList = directory.listFiles();
123                 for (File file : fList) {
124                         if (file.isFile()) {
125                                 resultList.add(file);
126                         } else if (file.isDirectory()) {
127                                 resultList.addAll(listModelFiles(file.getAbsolutePath()));
128                         }
129                 }
130                 return resultList;
131         }
132
133         @SuppressWarnings("rawtypes")
134         private void extractFolder(String zipFile) {
135             int BUFFER = 2048;
136             File file = new File(zipFile);
137
138             ZipFile zip;
139                 try {
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();
144         
145                     // Process each entry
146                     while (zipFileEntries.hasMoreElements())
147                     {
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();
153         
154                         destinationParent.mkdirs();
155         
156                         if (!entry.isDirectory())
157                         {
158                             BufferedInputStream is = new BufferedInputStream(zip
159                             .getInputStream(entry));
160                             int currentByte;
161
162                             byte data[] = new byte[BUFFER];
163         
164                             FileOutputStream fos = new FileOutputStream(destFile);
165                             BufferedOutputStream dest = new BufferedOutputStream(fos,
166                             BUFFER);
167         
168                             while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
169                                 dest.write(data, 0, currentByte);
170                             }
171                             dest.flush();
172                             dest.close();
173                             is.close();
174                         }
175         
176                         if (currentEntry.endsWith(".zip"))
177                         {
178                             extractFolder(destFile.getAbsolutePath());
179                         }
180                     }
181             } catch (IOException e) {
182                         logger.error("Failed to unzip model file " + zipFile);
183                 }
184         }
185
186         public Map<String, String> addValuesToNewModel() {
187                 
188                 Map<String, String> successMap = new HashMap<>();
189                 MSAttributeObject mainClass  = null;
190                 ArrayList<String> dependency = null;
191                 String subAttribute = null;
192                 
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");
197                         return successMap;
198                 }
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());
212                                         }
213                                 }
214                         }               
215                 }
216                 subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName());
217
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");
224                 return successMap;
225                 
226         }
227         
228         @SuppressWarnings("resource")
229         public Map<String, String> saveImportService(){
230                 Map<String, String> successMap = new HashMap<>();
231                 
232                 Connection con = null;
233                 Statement st = null;
234                 ResultSet rs = null;
235                 String modelName = this.newModel.getModelName();
236                 String imported_by = "API";
237                 String version = this.newModel.getVersion();
238                 String insertQuery = null;
239                 int ID = 0;
240                 
241                 /*
242                  * Retrieve the property values for db access from the xacml.pap.properties
243                  */
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);
248                 
249                 try {
250                         //Get DB Connection
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);
256                 
257                         if(rs.next()){
258                                 successMap.put("DBError", "EXISTS");
259                                 logger.error("Import new service failed.  Service already exists");
260                         }else{
261                                 rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;");
262                                 if(rs.next()){
263                                         ID = rs.getInt("ID");
264                                         ID++;
265                                 }
266         
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");
274                         }
275                         rs.close();
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");
282                 } finally {
283                         try{
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");
289                         }
290                 }
291
292                 return successMap;
293         }
294 }