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<String, String>();
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 private PolicyController(CommonClassDao commonClassDao){
140 PolicyController.commonClassDao = commonClassDao;
143 public PolicyController() {
148 Properties prop = new Properties();
149 InputStream input = null;
151 input = new FileInputStream("xacml.admin.properties");
152 // load a properties file
155 papUrl = prop.getProperty("xacml.rest.pap.url");
156 // get the property values
157 smtpHost = prop.getProperty("ecomp.smtp.host");
158 smtpPort = prop.getProperty("ecomp.smtp.port");
159 smtpUsername = prop.getProperty("ecomp.smtp.userName");
160 smtpPassword = prop.getProperty("ecomp.smtp.password");
161 smtpApplicationName = prop.getProperty("ecomp.application.name");
162 smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension");
163 //Log Database Properties
164 logdbDriver = prop.getProperty("xacml.log.db.driver");
165 logdbUrl = prop.getProperty("xacml.log.db.url");
166 logdbUserName = prop.getProperty("xacml.log.db.user");
167 logdbPassword = prop.getProperty("xacml.log.db.password");
168 logdbDialect = prop.getProperty("ecomp.dialect");
169 //Xacml Database Properties
170 xacmldbUrl = prop.getProperty("javax.persistence.jdbc.url");
171 xacmldbUserName = prop.getProperty("javax.persistence.jdbc.user");
172 xacmldbPassword = prop.getProperty("javax.persistence.jdbc.password");
174 autoPushAvailable=prop.getProperty("xacml.automatic.push");
175 autoPushDSClosedLoop=prop.getProperty("xacml.autopush.closedloop");
176 autoPushDSFirewall=prop.getProperty("xacml.autopush.firewall");
177 autoPushDSMicroservice=prop.getProperty("xacml.autopush.microservice");
178 autoPushPDPGroup=prop.getProperty("xacml.autopush.pdpGroup");
179 //Micro Service Properties
180 msEcompName=prop.getProperty("xacml.policy.msEcompName");
181 msPolicyName=prop.getProperty("xacml.policy.msPolicyName");
182 //Get the Property Values for Dashboard tab Limit
184 logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
185 systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
187 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
188 logTableLimit = "5000";
189 systemAlertTableLimit = "2000";
191 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
192 } catch (IOException ex) {
193 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
198 } catch (IOException e) {
199 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
204 //Initialize the FunctionDefinition table at Server Start up
205 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
206 for (Datatype id : functionMap.keySet()) {
207 List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id);
208 for (FunctionDefinition functionDef : functionDefinations) {
209 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
215 public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
216 synchronized(mapAccess) {
217 if (mapDatatype2Function == null) {
221 return mapDatatype2Function;
224 public static Map<String, FunctionDefinition> getFunctionIDMap() {
225 synchronized(mapAccess) {
226 if (mapID2Function == null) {
230 return mapID2Function;
233 private static void buildFunctionMaps() {
234 mapDatatype2Function = new HashMap<Datatype, List<FunctionDefinition>>();
235 mapID2Function = new HashMap<String, FunctionDefinition>();
236 List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
237 for (int i = 0; i < functiondefinitions.size(); i ++) {
238 FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
239 mapID2Function.put(value.getXacmlid(), value);
240 if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
241 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
243 mapDatatype2Function.get(value.getDatatypeBean()).add(value);
247 @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
248 public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
250 Map<String, Object> model = new HashMap<String, Object>();
251 ObjectMapper mapper = new ObjectMapper();
252 model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
253 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
254 JSONObject j = new JSONObject(msg);
255 response.getWriter().write(j.toString());
258 LOGGER.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
262 public PolicyEntity getPolicyEntityData(String scope, String policyName){
263 String key = scope + ":" + policyName;
264 List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
265 PolicyEntity entity = (PolicyEntity) data.get(0);
269 public static Map<String, Roles> getUserRoles(String userId) {
270 Map<String, Roles> scopes = new HashMap<String, Roles>();
271 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
272 if (roles != null && roles.size() > 0) {
273 for (Object role : roles) {
274 scopes.put(((Roles) role).getScope(), (Roles) role);
280 public static List<String> getRolesOfUser(String userId) {
281 List<String> rolesList = new ArrayList<String>();
282 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
283 for (Object role: roles) {
284 rolesList.add(((Roles) role).getRole());
289 public static List<Object> getRoles(String userId) {
290 return commonClassDao.getDataById(Roles.class, "loginId", userId);
293 //Get List of User Roles
294 @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
295 public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
297 String userId = UserUtils.getUserSession(request).getOrgUserId();
298 Map<String, Object> model = new HashMap<String, Object>();
299 ObjectMapper mapper = new ObjectMapper();
300 model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
301 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
302 JSONObject j = new JSONObject(msg);
303 response.getWriter().write(j.toString());
306 LOGGER.error("Exception Occured"+e);
310 //Policy tabs Model and View
311 @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
312 public ModelAndView view(HttpServletRequest request){
313 String myRequestURL = request.getRequestURL().toString();
316 // Set the URL for the RESTful PAP Engine
318 setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
319 new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
320 } catch (Exception e) {
321 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
323 Map<String, Object> model = new HashMap<String, Object>();
324 return new ModelAndView("policy_Editor","model", model);
327 public static PAPPolicyEngine getPapEngine() {
331 public void setPapEngine(PAPPolicyEngine papEngine) {
332 PolicyController.papEngine = papEngine;
335 public String getUserName(String createdBy) {
336 String loginId = createdBy;
337 List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
338 return data.get(0).toString();
341 public static boolean getActivePolicy(String query) {
342 if(commonClassDao.getDataByQuery(query).size() > 0){
349 public void executeQuery(String query) {
350 commonClassDao.updateQuery(query);
353 public void saveData(Object cloneEntity) {
354 commonClassDao.save(cloneEntity);
357 public void updateData(Object entity) {
358 commonClassDao.update(entity);
361 public void deleteData(Object entity) {
362 commonClassDao.delete(entity);
365 public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
366 return commonClassDao.getData(className);
369 public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
370 PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
371 return policyVersionEntity;
374 public List<Object> getDataByQuery(String query){
375 return commonClassDao.getDataByQuery(query);
379 @SuppressWarnings("rawtypes")
380 public Object getEntityItem(Class className, String columname, String key){
381 return commonClassDao.getEntityItem(className, columname, key);
385 public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
386 PolicyNotificationMail email = new PolicyNotificationMail();
388 email.sendMail(entity, policyName, mode, commonClassDao);
389 } catch (MessagingException e) {
390 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
395 public JSONObject switchVersionPolicyContent(String policyName) {
396 String dbCheckName = policyName.replace("/", ".");
397 if(dbCheckName.contains("Config_")){
398 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
399 }else if(dbCheckName.contains("Action_")){
400 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
401 }else if(dbCheckName.contains("Decision_")){
402 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
404 String[] splitDBCheckName = dbCheckName.split(":");
405 String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'";
406 List<Object> policyEntity = commonClassDao.getDataByQuery(query);
407 List<String> av = new ArrayList<String>();
408 for(Object entity : policyEntity){
409 PolicyEntity pEntity = (PolicyEntity) entity;
410 String removeExtension = pEntity.getPolicyName().replace(".xml", "");
411 String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1);
414 if(policyName.contains("/")){
415 policyName = policyName.replace("/", File.separator);
417 PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
418 JSONObject el = new JSONObject();
419 el.put("activeVersion", entity.getActiveVersion());
420 el.put("availableVersions", av);
421 el.put("highestVersion", entity.getHigherVersion());