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.controller;
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;
32 import java.util.Properties;
34 import javax.annotation.PostConstruct;
35 import javax.mail.MessagingException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
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;
62 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
63 import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine;
65 import com.att.research.xacml.util.XACMLProperties;
66 import com.fasterxml.jackson.databind.ObjectMapper;
68 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
69 import org.openecomp.policy.common.logging.flexlogger.Logger;
74 public class PolicyController extends RestrictedBaseController {
75 private static final Logger LOGGER = FlexLogger.getLogger(PolicyController.class);
77 private static CommonClassDao commonClassDao;
78 // Our authorization object
80 XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
84 private static PAPPolicyEngine papEngine;
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() {
93 public static void setDropDownMap(Map<String, String> dropDownMap) {
94 PolicyController.dropDownMap = dropDownMap;
97 public static String getDomain() {
98 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
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;
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;
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;
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;
132 public static String papUrl;
134 //MicroService Model Properties
135 public static String msEcompName;
136 public static String msPolicyName;
139 public static String configHome;
140 public static String actionHome;
143 private PolicyController(CommonClassDao commonClassDao){
144 PolicyController.commonClassDao = commonClassDao;
147 public PolicyController() {
152 Properties prop = new Properties();
153 InputStream input = null;
155 input = new FileInputStream("xacml.admin.properties");
156 // load a properties file
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");
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");
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
191 logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
192 systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
194 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
195 logTableLimit = "5000";
196 systemAlertTableLimit = "2000";
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);
205 } catch (IOException e) {
206 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
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());
222 public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
223 synchronized(mapAccess) {
224 if (mapDatatype2Function == null) {
228 return mapDatatype2Function;
231 public static Map<String, FunctionDefinition> getFunctionIDMap() {
232 synchronized(mapAccess) {
233 if (mapID2Function == null) {
237 return mapID2Function;
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>());
250 mapDatatype2Function.get(value.getDatatypeBean()).add(value);
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){
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());
265 LOGGER.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
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);
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);
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());
296 public static List<Object> getRoles(String userId) {
297 return commonClassDao.getDataById(Roles.class, "loginId", userId);
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){
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());
313 LOGGER.error("Exception Occured"+e);
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();
323 // Set the URL for the RESTful PAP Engine
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);
330 Map<String, Object> model = new HashMap<>();
331 return new ModelAndView("policy_Editor","model", model);
334 public static PAPPolicyEngine getPapEngine() {
338 public void setPapEngine(PAPPolicyEngine papEngine) {
339 PolicyController.papEngine = papEngine;
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();
348 public static boolean getActivePolicy(String query) {
349 if(commonClassDao.getDataByQuery(query).size() > 0){
356 public void executeQuery(String query) {
357 commonClassDao.updateQuery(query);
360 public void saveData(Object cloneEntity) {
361 commonClassDao.save(cloneEntity);
364 public void updateData(Object entity) {
365 commonClassDao.update(entity);
368 public void deleteData(Object entity) {
369 commonClassDao.delete(entity);
372 public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
373 return commonClassDao.getData(className);
376 public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
377 PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
378 return policyVersionEntity;
381 public List<Object> getDataByQuery(String query){
382 return commonClassDao.getDataByQuery(query);
386 @SuppressWarnings("rawtypes")
387 public Object getEntityItem(Class className, String columname, String key){
388 return commonClassDao.getEntityItem(className, columname, key);
392 public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
393 PolicyNotificationMail email = new PolicyNotificationMail();
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);
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_");
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);
421 if(policyName.contains("/")){
422 policyName = policyName.replace("/", File.separator);
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());