Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / PolicyController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
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.controller;
22
23
24 import java.io.File;
25 import java.io.FileFilter;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Properties;
36
37 import javax.annotation.PostConstruct;
38 import javax.mail.MessagingException;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41
42 import org.apache.commons.io.filefilter.WildcardFileFilter;
43 import org.json.JSONObject;
44 import org.openecomp.policy.admin.PolicyNotificationMail;
45 import org.openecomp.policy.admin.RESTfulPAPEngine;
46 import org.openecomp.policy.dao.FunctionDefinitionDao;
47 import org.openecomp.policy.dao.PolicyEditorScopesDao;
48 import org.openecomp.policy.dao.PolicyVersionDao;
49 import org.openecomp.policy.dao.RolesDao;
50 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
51 import org.openecomp.policy.model.PDPGroupContainer;
52 import org.openecomp.policy.model.Roles;
53 import org.openecomp.policy.rest.XACMLRestProperties;
54 import org.openecomp.policy.rest.XacmlAdminAuthorization;
55 import org.openecomp.policy.rest.dao.UserInfoDao;
56 import org.openecomp.policy.rest.jpa.Datatype;
57 import org.openecomp.policy.rest.jpa.FunctionDefinition;
58 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
59 import org.openecomp.policy.rest.jpa.PolicyVersion;
60 import org.openecomp.policy.rest.util.Webapps;
61 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
62 import org.openecomp.portalsdk.core.web.support.JsonMessage;
63 import org.openecomp.portalsdk.core.web.support.UserUtils;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.http.MediaType;
66 import org.springframework.stereotype.Controller;
67 import org.springframework.web.bind.annotation.RequestMapping;
68 import org.springframework.web.bind.annotation.RequestMethod;
69 import org.springframework.web.servlet.ModelAndView;
70
71 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
72 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
73
74 import com.att.research.xacml.api.pap.PAPEngine;
75 import com.att.research.xacml.util.XACMLProperties;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
78 import org.openecomp.policy.common.logging.flexlogger.Logger;
79
80
81 @Controller
82 @RequestMapping("/")
83 public class PolicyController extends RestrictedBaseController {
84         private static final Logger     LOGGER  = FlexLogger.getLogger(PolicyController.class);
85         private static UserInfoDao userInfoDao;
86         private static PolicyVersionDao policyVersionDao;
87         private static RolesDao rolesDao;
88         private static PolicyEditorScopesDao policyEditorScopesDao;
89         private static WatchPolicyNotificationDao watchPolicyNotificationDao;
90         // Our authorization object
91         //
92         XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
93         //
94         // The PAP Engine
95         //
96         private static PAPPolicyEngine papEngine;
97         private Path repositoryPath =  null;
98         private static Path workspacePath;
99         private static Path gitPath;
100         public static String logTableLimit;
101         public static String systemAlertTableLimit;
102         public static String CONFIG_HOME = PolicyController.getConfigHome();
103         public static String ACTION_HOME = PolicyController.getActionHome();
104         protected static Map<String, String> dropDownMap = new HashMap<String, String>();
105         public static Map<String, String> getDropDownMap() {
106                 return dropDownMap;
107         }
108
109         public static void setDropDownMap(Map<String, String> dropDownMap) {
110                 PolicyController.dropDownMap = dropDownMap;
111         }
112
113         public static String getDomain() {
114                 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
115         }
116
117         private static final Object mapAccess = new Object();
118         private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
119         private static Map<String, FunctionDefinition> mapID2Function = null;
120
121         private static FunctionDefinitionDao functionDefinitionDao;
122         
123         //Smtp Java Mail Properties
124         public static String smtpHost = null;
125         public static String smtpPort = null;
126         public static String smtpUsername = null;
127         public static String smtpPassword = null;
128         public static String smtpApplicationName = null;
129         public static String smtpEmailExtension = null;
130         //log db Properties
131         public static String logdbDriver = null;
132         public static String logdbUrl = null;
133         public static String logdbUserName = null;
134         public static String logdbPassword = null;
135         public static String logdbDialect = null;
136
137
138         @Autowired
139         private PolicyController(UserInfoDao userinfoDao, PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao,
140                         RolesDao rolesDao, PolicyEditorScopesDao policyEditorScopesDao, WatchPolicyNotificationDao watchPolicyNotificationDao){
141                 PolicyController.userInfoDao = userinfoDao;
142                 PolicyController.policyVersionDao = policyVersionDao;
143                 PolicyController.functionDefinitionDao = functionDefinitionDao;
144                 PolicyController.rolesDao = rolesDao;
145                 PolicyController.policyEditorScopesDao = policyEditorScopesDao;
146                 PolicyController.watchPolicyNotificationDao = watchPolicyNotificationDao;
147         }
148
149         public PolicyController() {
150         }
151
152         @PostConstruct
153         public void init(){
154                 Properties prop = new Properties();
155                 InputStream input = null;
156                 try {
157                         input = new FileInputStream("xacml.admin.properties");
158                         // load a properties file
159                         prop.load(input);
160                         // get the property values
161                         smtpHost = prop.getProperty("ecomp.smtp.host");
162                         smtpPort = prop.getProperty("ecomp.smtp.port");
163                         smtpUsername = prop.getProperty("ecomp.smtp.userName");
164                         smtpPassword = prop.getProperty("ecomp.smtp.password");
165                         smtpApplicationName = prop.getProperty("ecomp.application.name");
166                         smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension");
167                         //Log Database Properties
168                         logdbDriver = prop.getProperty("xacml.log.db.driver");
169                         logdbUrl = prop.getProperty("xacml.log.db.url");
170                         logdbUserName = prop.getProperty("xacml.log.db.user");
171                         logdbPassword = prop.getProperty("xacml.log.db.password");
172                         logdbDialect = prop.getProperty("ecomp.dialect");
173                         //Get the Property Values for Dashboard tab Limit 
174                         try{
175                                 logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
176                                 systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
177                         }catch(Exception e){
178                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
179                                 logTableLimit = "5000";
180                                 systemAlertTableLimit = "2000";
181                         }
182                         repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY));
183                         PolicyController.workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE), getDefaultWorkspace());
184                         setGitPath(Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString()));
185                         System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
186                 } catch (IOException ex) {
187                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
188                 } finally {
189                         if (input != null) {
190                                 try {
191                                         input.close();
192                                 } catch (IOException e) {
193                                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
194                                 }
195                         }
196                 }
197                 
198                 //Initialize the FunctionDefinition table at Server Start up 
199                 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
200                 for (Datatype id : functionMap.keySet()) {
201                         List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id);
202                         for (FunctionDefinition functionDef : functionDefinations) {
203                                 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
204                         }
205                 }
206
207         }
208
209         public static  Map<Datatype, List<FunctionDefinition>>  getFunctionDatatypeMap() {                              
210                 synchronized(mapAccess) {
211                         if (mapDatatype2Function == null) {
212                                 buildFunctionMaps();
213                         }
214                 }
215                 return mapDatatype2Function;
216         }
217
218         public static Map<String, FunctionDefinition> getFunctionIDMap() {
219                 synchronized(mapAccess) {
220                         if (mapID2Function == null) {
221                                 buildFunctionMaps();
222                         }
223                 }
224                 return mapID2Function;
225         }
226         
227         private static  void buildFunctionMaps() {
228                 mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
229                 mapID2Function = new  HashMap<String, FunctionDefinition>(); 
230                 List<FunctionDefinition> functiondefinitions = functionDefinitionDao.getFunctionDefinition();   
231                 for (int i = 0; i < functiondefinitions.size(); i ++) {
232                         FunctionDefinition value = functiondefinitions.get(i);
233                         mapID2Function.put(value.getXacmlid(), value);
234                         if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
235                                 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
236                         }
237                         mapDatatype2Function.get(value.getDatatypeBean()).add(value);
238                 }
239         }
240         
241         public static Map<String, Roles> getUserRoles(String userId) {
242                 Map<String, Roles> scopes = new HashMap<String, Roles>();
243                 List<Roles> roles = rolesDao.getUserRoles(userId);
244                 if (roles != null && roles.size() > 0) {
245                         for (Roles role : roles) {
246                                 scopes.put(role.getScope(), role);
247                         }
248                 }
249                 return scopes;
250         }
251         
252         public static  List<String> getRolesOfUser(String userId) {
253                 List<String> rolesList = new ArrayList<String>();
254                 List<Roles> roles = rolesDao.getUserRoles(userId);
255                 for (Roles role: roles) {
256                         rolesList.add(role.getRole());
257                 }
258                 return rolesList;
259         }
260
261         public static List<Roles> getRoles(String userId) {
262                 return rolesDao.getUserRoles(userId);
263         }
264
265         //Get List of User Roles
266         @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
267         public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
268                 try{
269                         String userId = UserUtils.getUserIdFromCookie(request);
270                         Map<String, Object> model = new HashMap<String, Object>();
271                         ObjectMapper mapper = new ObjectMapper();
272                         model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
273                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
274                         JSONObject j = new JSONObject(msg);
275                         response.getWriter().write(j.toString());
276                 }
277                 catch (Exception e){
278                         e.printStackTrace();
279                 }
280         }
281
282         //Policy tabs Model and View 
283         @RequestMapping(value= {"/policy", "/policy/*" }, method = RequestMethod.GET)
284         public ModelAndView view(HttpServletRequest request){
285                 String myRequestURL = request.getRequestURL().toString();
286                 try {
287                         //
288                         // Set the URL for the RESTful PAP Engine
289                         //      
290                         setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
291                         new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
292                 } catch (Exception e) {
293                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
294                 }       
295                 Map<String, Object> model = new HashMap<String, Object>();
296                 return new ModelAndView("policy_Editor","model", model);
297         }
298
299         public static String getDefaultWorkspace() {
300                 return "admin";
301         }
302
303         public static PAPPolicyEngine getPapEngine() {
304                 return papEngine;
305         }
306
307         public void setPapEngine(PAPPolicyEngine papEngine) {
308                 PolicyController.papEngine = papEngine;
309         }
310     
311         //Config and Action Directory's
312         public static String getConfigHome() {
313                 return Webapps.getConfigHome();
314         }
315
316         public static String getActionHome() {
317                 return Webapps.getActionHome();
318         }
319
320         public static Path getGitPath() {
321                 return gitPath;
322         }
323
324         public static void setGitPath(Path gitPath) {
325                 PolicyController.gitPath = gitPath;
326         }
327
328         public static String getUserName(String createdBy) {
329                 String loginId = createdBy;
330                 return userInfoDao.getUserName(loginId);
331         }
332
333         public static boolean getActivePolicy(String query) {
334                 if(policyVersionDao.getActiveVersionPolicy(query).size() > 0){
335                         return true;
336                 }else{
337                         return false;
338                 }
339
340         }
341
342         //Get the Active Version of Policy List from Policy Version table
343         public static List<PolicyVersion> getListOfActivePolicies(String query){
344                 return policyVersionDao.getActiveVersionPolicy(query);
345         }
346
347         public static void updatePolicyVersion(String query) {
348                 policyVersionDao.updateQuery(query);    
349         }
350
351         public static void SaveToPolicyVersion(PolicyVersion policyversion) {
352                 policyVersionDao.Save(policyversion);   
353         }
354
355         public static PolicyVersion getPolicyEntityFromPolicyVersion(String query){
356                 PolicyVersion policyVersionEntity = policyVersionDao.getPolicyVersionEntityByName(query).get(0);
357                 return policyVersionEntity;     
358         }
359         
360         public static void SavePolicyScope(PolicyEditorScopes policyScope){
361                 policyEditorScopesDao.Save(policyScope);
362         }
363         
364         public static List<PolicyEditorScopes> getListOfPolicyEditorScopes(String query){
365                 return policyEditorScopesDao.getListOfPolicyScopes(query);
366         }
367         
368         public static void updatePolicyScopeEditorWithQuery(String policyScopeQuery) {
369                 policyEditorScopesDao.updateQuery(policyScopeQuery);
370                 
371         }
372
373         public static void updatePolicyScopeEditor(PolicyEditorScopes policyScopeQuery) {
374                 policyEditorScopesDao.update(policyScopeQuery);
375                 
376         }
377         
378         public void WatchPolicyFunction(PolicyVersion entity, String policyName, String mode){
379                 PolicyNotificationMail email = new PolicyNotificationMail();
380                 try {
381                         email.sendMail(entity, policyName, mode, watchPolicyNotificationDao);
382                 } catch (MessagingException e) {
383                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
384                 }
385         }
386
387         //Switch Version
388         public JSONObject SwitchVersionPolicyContent(File policyFile) {
389                 Path parent = Paths.get(policyFile.toString().substring(0, policyFile.toString().lastIndexOf(File.separator)));
390                 String policyName = policyFile.toString().substring(policyFile.toString().indexOf("repository") +11);
391                 String removeExtension = policyName.replace(".xml", "");
392                 String activeVersion = removeExtension.substring(removeExtension.lastIndexOf(".")+1);
393                 String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
394                 String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1);
395                 FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml");
396                 File[] files = ((File) parent.toFile()).listFiles(fileFilter);
397                 List<String> av = new ArrayList<String>();
398                 for(File file : files){
399                         String fileName = file.toString().substring(file.toString().indexOf("repository") +11);
400                         String removeXMLExtension = fileName.replace(".xml", "");
401                         String availableVersion = removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1);
402                         av.add(availableVersion);
403                 }
404                 PolicyVersion entity = (PolicyVersion) policyVersionDao.getPolicyVersionEntityByName(dbPolicyName).get(0);
405                 String highestVersion = Integer.toString(entity.getHigherVersion());
406                 JSONObject el = new JSONObject();
407                 el.put("activeVersion", activeVersion);
408                 el.put("availableVersions", av);
409                 el.put("highestVersion", highestVersion);
410                 return el;
411         }
412
413         public static Path getUserWorkspace() {
414                 return PolicyController.workspacePath;
415         }
416
417 }
418