Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / POLICY-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.FileInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Properties;
33
34 import javax.annotation.PostConstruct;
35 import javax.mail.MessagingException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.json.JSONObject;
40 import org.openecomp.policy.admin.PolicyNotificationMail;
41 import org.openecomp.policy.admin.RESTfulPAPEngine;
42 import org.openecomp.policy.model.PDPGroupContainer;
43 import org.openecomp.policy.model.Roles;
44 import org.openecomp.policy.rest.XACMLRestProperties;
45 import org.openecomp.policy.rest.XacmlAdminAuthorization;
46 import org.openecomp.policy.rest.dao.CommonClassDao;
47 import org.openecomp.policy.rest.jpa.Datatype;
48 import org.openecomp.policy.rest.jpa.FunctionDefinition;
49 import org.openecomp.policy.rest.jpa.PolicyEntity;
50 import org.openecomp.policy.rest.jpa.PolicyVersion;
51 import org.openecomp.policy.rest.jpa.UserInfo;
52 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
53 import org.openecomp.portalsdk.core.web.support.JsonMessage;
54 import org.openecomp.portalsdk.core.web.support.UserUtils;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.http.MediaType;
57 import org.springframework.stereotype.Controller;
58 import org.springframework.web.bind.annotation.RequestMapping;
59 import org.springframework.web.bind.annotation.RequestMethod;
60 import org.springframework.web.servlet.ModelAndView;
61
62 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
63 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
64
65 import com.att.research.xacml.util.XACMLProperties;
66 import com.fasterxml.jackson.databind.ObjectMapper;
67
68 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
69 import org.openecomp.policy.common.logging.flexlogger.Logger;
70
71
72 @Controller
73 @RequestMapping("/")
74 public class PolicyController extends RestrictedBaseController {
75         private static final Logger     LOGGER  = FlexLogger.getLogger(PolicyController.class);
76
77         private static CommonClassDao commonClassDao;
78         // Our authorization object
79         //
80         XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
81         //
82         // The PAP Engine
83         //
84         private static PAPPolicyEngine papEngine;
85
86         public static String logTableLimit;
87         public static String systemAlertTableLimit;
88         protected static Map<String, String> dropDownMap = new HashMap<>();
89         public static Map<String, String> getDropDownMap() {
90                 return dropDownMap;
91         }
92
93         public static void setDropDownMap(Map<String, String> dropDownMap) {
94                 PolicyController.dropDownMap = dropDownMap;
95         }
96
97         public static String getDomain() {
98                 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
99         }
100
101         private static final Object mapAccess = new Object();
102         private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
103         private static Map<String, FunctionDefinition> mapID2Function = null;
104
105
106         //Smtp Java Mail Properties
107         public static String smtpHost = null;
108         public static String smtpPort = null;
109         public static String smtpUsername = null;
110         public static String smtpPassword = null;
111         public static String smtpApplicationName = null;
112         public static String smtpEmailExtension = null;
113         //log db Properties
114         public static String logdbDriver = null;
115         public static String logdbUrl = null;
116         public static String logdbUserName = null;
117         public static String logdbPassword = null;
118         public static String logdbDialect = null;
119         //Xacml db properties
120         public static String xacmldbUrl = null;
121         public static String xacmldbUserName = null;
122         public static String xacmldbPassword = null;
123
124         //AutoPush feature. 
125         public static String autoPushAvailable;
126         public static String autoPushDSClosedLoop;
127         public static String autoPushDSFirewall;
128         public static String autoPushDSMicroservice;
129         public static String autoPushPDPGroup;
130         
131         //papURL
132         public static String papUrl;
133         
134         //MicroService Model Properties
135         public static String msEcompName;
136         public static String msPolicyName;
137         
138         //WebApp directories
139         public static String configHome;
140         public static String actionHome;
141
142         @Autowired
143         private PolicyController(CommonClassDao commonClassDao){
144                 PolicyController.commonClassDao = commonClassDao;
145         }
146
147         public PolicyController() {
148         }
149
150         @PostConstruct
151         public void init(){
152                 Properties prop = new Properties();
153                 InputStream input = null;
154                 try {
155                         input = new FileInputStream("xacml.admin.properties");
156                         // load a properties file
157                         prop.load(input);
158                         //pap url
159                         papUrl = prop.getProperty("xacml.rest.pap.url"); 
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                         //Xacml Database Properties
174                         xacmldbUrl = prop.getProperty("javax.persistence.jdbc.url");
175                         xacmldbUserName = prop.getProperty("javax.persistence.jdbc.user");
176                         xacmldbPassword = prop.getProperty("javax.persistence.jdbc.password");
177                         //AutoPuh
178                         autoPushAvailable=prop.getProperty("xacml.automatic.push");
179                         autoPushDSClosedLoop=prop.getProperty("xacml.autopush.closedloop");
180                         autoPushDSFirewall=prop.getProperty("xacml.autopush.firewall");
181                         autoPushDSMicroservice=prop.getProperty("xacml.autopush.microservice");
182                         autoPushPDPGroup=prop.getProperty("xacml.autopush.pdpGroup");
183                         //Micro Service Properties
184                         msEcompName=prop.getProperty("xacml.policy.msEcompName");
185                         msPolicyName=prop.getProperty("xacml.policy.msPolicyName");
186                         //WebApp directories
187                         configHome = prop.getProperty("xacml.rest.config.webapps") + "Config";
188                         actionHome = prop.getProperty("xacml.rest.config.webapps") + "Action";
189                         //Get the Property Values for Dashboard tab Limit 
190                         try{
191                                 logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
192                                 systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
193                         }catch(Exception e){
194                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
195                                 logTableLimit = "5000";
196                                 systemAlertTableLimit = "2000";
197                         }
198                         System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
199                 } catch (IOException ex) {
200                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
201                 } finally {
202                         if (input != null) {
203                                 try {
204                                         input.close();
205                                 } catch (IOException e) {
206                                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
207                                 }
208                         }
209                 }
210
211                 //Initialize the FunctionDefinition table at Server Start up 
212                 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
213                 for (Datatype id : functionMap.keySet()) {
214                         List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id);
215                         for (FunctionDefinition functionDef : functionDefinations) {
216                                 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
217                         }
218                 }
219
220         }
221
222         public static  Map<Datatype, List<FunctionDefinition>>  getFunctionDatatypeMap() {                              
223                 synchronized(mapAccess) {
224                         if (mapDatatype2Function == null) {
225                                 buildFunctionMaps();
226                         }
227                 }
228                 return mapDatatype2Function;
229         }
230
231         public static Map<String, FunctionDefinition> getFunctionIDMap() {
232                 synchronized(mapAccess) {
233                         if (mapID2Function == null) {
234                                 buildFunctionMaps();
235                         }
236                 }
237                 return mapID2Function;
238         }
239
240         private static  void buildFunctionMaps() {
241                 mapDatatype2Function = new HashMap<>();
242                 mapID2Function = new  HashMap<>(); 
243                 List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);    
244                 for (int i = 0; i < functiondefinitions.size(); i ++) {
245                         FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
246                         mapID2Function.put(value.getXacmlid(), value);
247                         if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
248                                 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
249                         }
250                         mapDatatype2Function.get(value.getDatatypeBean()).add(value);
251                 }
252         }
253
254         @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
255         public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
256                 try{
257                         Map<String, Object> model = new HashMap<>();
258                         ObjectMapper mapper = new ObjectMapper();
259                         model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
260                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
261                         JSONObject j = new JSONObject(msg);
262                         response.getWriter().write(j.toString());
263                 }
264                 catch (Exception e){
265                         LOGGER.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
266                 }
267         }
268         
269         public PolicyEntity getPolicyEntityData(String scope, String policyName){
270                 String key = scope + ":" + policyName;
271                 List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
272                 PolicyEntity entity = (PolicyEntity) data.get(0);
273                 return entity;
274         }
275
276         public static Map<String, Roles> getUserRoles(String userId) {
277                 Map<String, Roles> scopes = new HashMap<>();
278                 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
279                 if (roles != null && roles.size() > 0) {
280                         for (Object role : roles) {
281                                 scopes.put(((Roles) role).getScope(), (Roles) role);
282                         }
283                 }
284                 return scopes;
285         }
286
287         public static  List<String> getRolesOfUser(String userId) {
288                 List<String> rolesList = new ArrayList<String>();
289                 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
290                 for (Object role: roles) {
291                         rolesList.add(((Roles) role).getRole());
292                 }
293                 return rolesList;
294         }
295
296         public static List<Object> getRoles(String userId) {
297                 return commonClassDao.getDataById(Roles.class, "loginId", userId);
298         }
299
300         //Get List of User Roles
301         @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
302         public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
303                 try{
304                         String userId = UserUtils.getUserSession(request).getOrgUserId();
305                         Map<String, Object> model = new HashMap<>();
306                         ObjectMapper mapper = new ObjectMapper();
307                         model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
308                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
309                         JSONObject j = new JSONObject(msg);
310                         response.getWriter().write(j.toString());
311                 }
312                 catch (Exception e){
313                         LOGGER.error("Exception Occured"+e);
314                 }
315         }
316
317         //Policy tabs Model and View 
318         @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
319         public ModelAndView view(HttpServletRequest request){
320                 String myRequestURL = request.getRequestURL().toString();
321                 try {
322                         //
323                         // Set the URL for the RESTful PAP Engine
324                         //      
325                         setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
326                         new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
327                 } catch (Exception e) {
328                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
329                 }       
330                 Map<String, Object> model = new HashMap<>();
331                 return new ModelAndView("policy_Editor","model", model);
332         }
333
334         public static PAPPolicyEngine getPapEngine() {
335                 return papEngine;
336         }
337
338         public void setPapEngine(PAPPolicyEngine papEngine) {
339                 PolicyController.papEngine = papEngine;
340         }
341
342         public String getUserName(String createdBy) {
343                 String loginId = createdBy;
344                 List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
345                 return data.get(0).toString();
346         }
347
348         public static boolean getActivePolicy(String query) {
349                 if(commonClassDao.getDataByQuery(query).size() > 0){
350                         return true;
351                 }else{
352                         return false;
353                 }
354         }
355
356         public void executeQuery(String query) {
357                 commonClassDao.updateQuery(query);      
358         }
359         
360         public void saveData(Object cloneEntity) {
361                 commonClassDao.save(cloneEntity);
362         }
363
364         public void updateData(Object entity) {
365                 commonClassDao.update(entity);
366         }
367
368         public void deleteData(Object entity) {
369                 commonClassDao.delete(entity);
370         }
371         
372         public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
373                 return commonClassDao.getData(className);
374         }
375
376         public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
377                 PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
378                 return policyVersionEntity;     
379         }
380
381         public List<Object> getDataByQuery(String query){
382                 return commonClassDao.getDataByQuery(query);
383         }
384
385
386         @SuppressWarnings("rawtypes")
387         public Object getEntityItem(Class className, String columname, String key){
388                 return commonClassDao.getEntityItem(className, columname, key);
389         }
390         
391         
392         public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
393                 PolicyNotificationMail email = new PolicyNotificationMail();
394                 try {
395                         email.sendMail(entity, policyName, mode, commonClassDao);
396                 } catch (MessagingException e) {
397                         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
398                 }
399         }
400
401         //Switch Version
402         public JSONObject switchVersionPolicyContent(String policyName) {
403                 String dbCheckName = policyName.replace("/", ".");
404                 if(dbCheckName.contains("Config_")){
405                         dbCheckName = dbCheckName.replace(".Config_", ":Config_");
406                 }else if(dbCheckName.contains("Action_")){
407                         dbCheckName = dbCheckName.replace(".Action_", ":Action_");
408                 }else if(dbCheckName.contains("Decision_")){
409                         dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
410                 }
411                 String[] splitDBCheckName = dbCheckName.split(":");
412                 String query =   "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'";
413                 List<Object> policyEntity = commonClassDao.getDataByQuery(query);
414                 List<String> av = new ArrayList<>();
415                 for(Object entity : policyEntity){
416                         PolicyEntity pEntity = (PolicyEntity) entity;
417                         String removeExtension = pEntity.getPolicyName().replace(".xml", "");
418                         String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1);
419                         av.add(version);
420                 }
421                 if(policyName.contains("/")){
422                         policyName = policyName.replace("/", File.separator);
423                 }
424                 PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
425                 JSONObject el = new JSONObject();
426                 el.put("activeVersion", entity.getActiveVersion());
427                 el.put("availableVersions", av);
428                 el.put("highestVersion", entity.getHigherVersion());
429                 return el;
430         }
431 }
432