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.onap.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.Map.Entry;
33 import java.util.Properties;
35 import javax.annotation.PostConstruct;
36 import javax.mail.MessagingException;
37 import javax.script.SimpleBindings;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
41 import org.json.JSONObject;
42 import org.onap.policy.admin.PolicyNotificationMail;
43 import org.onap.policy.admin.RESTfulPAPEngine;
44 import org.onap.policy.common.logging.flexlogger.FlexLogger;
45 import org.onap.policy.common.logging.flexlogger.Logger;
46 import org.onap.policy.model.PDPGroupContainer;
47 import org.onap.policy.model.Roles;
48 import org.onap.policy.rest.XACMLRestProperties;
49 import org.onap.policy.rest.XacmlAdminAuthorization;
50 import org.onap.policy.rest.dao.CommonClassDao;
51 import org.onap.policy.rest.jpa.Datatype;
52 import org.onap.policy.rest.jpa.FunctionDefinition;
53 import org.onap.policy.rest.jpa.PolicyEntity;
54 import org.onap.policy.rest.jpa.PolicyVersion;
55 import org.onap.policy.rest.jpa.UserInfo;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
58 import org.onap.portalsdk.core.controller.RestrictedBaseController;
59 import org.onap.portalsdk.core.web.support.JsonMessage;
60 import org.onap.portalsdk.core.web.support.UserUtils;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestMethod;
66 import org.springframework.web.servlet.ModelAndView;
68 import com.att.research.xacml.util.XACMLProperties;
69 import com.fasterxml.jackson.databind.ObjectMapper;
74 public class PolicyController extends RestrictedBaseController {
75 private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
77 private static CommonClassDao commonClassDao;
79 // Our authorization object
81 XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
85 private static PAPPolicyEngine papEngine;
87 private static String logTableLimit;
88 private static String systemAlertTableLimit;
89 protected static Map<String, String> dropDownMap = new HashMap<>();
90 public static Map<String, String> getDropDownMap() {
94 public static void setDropDownMap(Map<String, String> dropDownMap) {
95 PolicyController.dropDownMap = dropDownMap;
98 public static String getDomain() {
99 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
102 private static final Object mapAccess = new Object();
103 private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
104 private static Map<String, FunctionDefinition> mapID2Function = null;
106 //Constant variables used across Policy-sdk
107 private static final String policyData = "policyData";
108 private static final String characterEncoding = "UTF-8";
109 private static final String contentType = "application/json";
110 private static final String file = "file";
112 //Smtp Java Mail Properties
113 private static String smtpHost = null;
114 private static String smtpPort = null;
115 private static String smtpUsername = null;
116 private static String smtpPassword = null;
117 private static String smtpApplicationName = null;
118 private static String smtpEmailExtension = null;
120 private static String logdbDriver = null;
121 private static String logdbUrl = null;
122 private static String logdbUserName = null;
123 private static String logdbPassword = null;
124 private static String logdbDialect = null;
125 //Xacml db properties
126 private static String xacmldbUrl = null;
127 private static String xacmldbUserName = null;
128 private static String xacmldbPassword = null;
131 private static String autoPushAvailable;
132 private static String autoPushDSClosedLoop;
133 private static String autoPushDSFirewall;
134 private static String autoPushDSMicroservice;
135 private static String autoPushPDPGroup;
138 private static String papUrl;
140 //MicroService Model Properties
141 private static String msOnapName;
142 private static String msPolicyName;
145 private static String configHome;
146 private static String actionHome;
149 private static long fileSizeLimit;
151 private static boolean jUnit = false;
154 public static boolean isjUnit() {
158 public static void setjUnit(boolean jUnit) {
159 PolicyController.jUnit = jUnit;
163 private PolicyController(CommonClassDao commonClassDao){
164 PolicyController.commonClassDao = commonClassDao;
167 public PolicyController() {
173 Properties prop = new Properties();
174 InputStream input = null;
177 File file = new File(new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json");
178 input = new FileInputStream(file);
180 input = new FileInputStream("xacml.admin.properties");
182 // load a properties file
184 //file upload size limit property
185 setFileSizeLimit(prop.getProperty("file.size.limit"));
187 setPapUrl(prop.getProperty("xacml.rest.pap.url"));
188 // get the property values
189 setSmtpHost(prop.getProperty("onap.smtp.host"));
190 setSmtpPort(prop.getProperty("onap.smtp.port"));
191 setSmtpUsername(prop.getProperty("onap.smtp.userName"));
192 setSmtpPassword(prop.getProperty("onap.smtp.password"));
193 setSmtpApplicationName(prop.getProperty("onap.application.name"));
194 setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
195 //Log Database Properties
196 setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
197 setLogdbUrl(prop.getProperty("xacml.log.db.url"));
198 setLogdbUserName(prop.getProperty("xacml.log.db.user"));
199 setLogdbPassword(prop.getProperty("xacml.log.db.password"));
200 setLogdbDialect(prop.getProperty("onap.dialect"));
201 //Xacml Database Properties
202 setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
203 setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
204 setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
206 setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
207 setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
208 setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
209 setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
210 setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
211 //Micro Service Properties
212 setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
213 if(getMsOnapName() == null){
214 setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
216 policyLogger.info("getMsOnapName => " + getMsOnapName());
217 setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
218 policyLogger.info("setMsPolicyName => " + getMsPolicyName());
220 setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
221 setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
222 //Get the Property Values for Dashboard tab Limit
224 setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
225 setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
227 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
228 setLogTableLimit("5000");
229 setSystemAlertTableLimit("2000");
231 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
232 } catch (IOException ex) {
233 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
238 } catch (IOException e) {
239 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
244 //Initialize the FunctionDefinition table at Server Start up
245 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
246 for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
247 List<FunctionDefinition> functionDefinations = entry.getValue();
248 for (FunctionDefinition functionDef : functionDefinations) {
249 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
255 public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
256 synchronized(mapAccess) {
257 if (mapDatatype2Function == null) {
261 return mapDatatype2Function;
264 public static Map<String, FunctionDefinition> getFunctionIDMap() {
265 synchronized(mapAccess) {
266 if (mapID2Function == null) {
270 return mapID2Function;
273 private static void buildFunctionMaps() {
274 mapDatatype2Function = new HashMap<>();
275 mapID2Function = new HashMap<>();
276 List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
277 for (int i = 0; i < functiondefinitions.size(); i ++) {
278 FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
279 mapID2Function.put(value.getXacmlid(), value);
280 if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
281 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
283 mapDatatype2Function.get(value.getDatatypeBean()).add(value);
287 @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
288 public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
290 Map<String, Object> model = new HashMap<>();
291 ObjectMapper mapper = new ObjectMapper();
292 model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
293 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
294 JSONObject j = new JSONObject(msg);
295 response.getWriter().write(j.toString());
298 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
302 public PolicyEntity getPolicyEntityData(String scope, String policyName){
303 String key = scope + ":" + policyName;
304 List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
305 return (PolicyEntity) data.get(0);
308 public static Map<String, Roles> getUserRoles(String userId) {
309 Map<String, Roles> scopes = new HashMap<>();
310 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
311 if (roles != null && !roles.isEmpty()) {
312 for (Object role : roles) {
313 scopes.put(((Roles) role).getScope(), (Roles) role);
319 public List<String> getRolesOfUser(String userId) {
320 List<String> rolesList = new ArrayList<>();
321 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
322 for (Object role: roles) {
323 rolesList.add(((Roles) role).getRole());
328 public List<Object> getRoles(String userId) {
329 return commonClassDao.getDataById(Roles.class, "loginId", userId);
332 //Get List of User Roles
333 @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
334 public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
336 String userId = UserUtils.getUserSession(request).getOrgUserId();
337 Map<String, Object> model = new HashMap<>();
338 ObjectMapper mapper = new ObjectMapper();
339 model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
340 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
341 JSONObject j = new JSONObject(msg);
342 response.getWriter().write(j.toString());
345 policyLogger.error("Exception Occured"+e);
349 //Policy tabs Model and View
350 @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
351 public ModelAndView view(HttpServletRequest request){
352 String myRequestURL = request.getRequestURL().toString();
355 // Set the URL for the RESTful PAP Engine
357 setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
358 new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
359 } catch (Exception e) {
360 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
362 Map<String, Object> model = new HashMap<>();
363 return new ModelAndView("policy_Editor","model", model);
366 public PAPPolicyEngine getPapEngine() {
370 public static void setPapEngine(PAPPolicyEngine papEngine) {
371 PolicyController.papEngine = papEngine;
374 public String getUserName(String createdBy) {
375 String loginId = createdBy;
376 List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
377 return data.get(0).toString();
380 public static boolean getActivePolicy(String query) {
381 if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){
388 public void executeQuery(String query) {
389 commonClassDao.updateQuery(query);
392 public void saveData(Object cloneEntity) {
393 commonClassDao.save(cloneEntity);
396 public void updateData(Object entity) {
397 commonClassDao.update(entity);
400 public void deleteData(Object entity) {
401 commonClassDao.delete(entity);
404 public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
405 return commonClassDao.getData(className);
408 public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
409 return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
412 public List<Object> getDataByQuery(String query, SimpleBindings params){
413 return commonClassDao.getDataByQuery(query, params);
417 @SuppressWarnings("rawtypes")
418 public Object getEntityItem(Class className, String columname, String key){
419 return commonClassDao.getEntityItem(className, columname, key);
423 public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
424 PolicyNotificationMail email = new PolicyNotificationMail();
426 email.sendMail(entity, policyName, mode, commonClassDao);
427 } catch (MessagingException e) {
428 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
433 public JSONObject switchVersionPolicyContent(String policyName) {
434 String dbCheckName = policyName.replace("/", ".");
435 if(dbCheckName.contains("Config_")){
436 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
437 }else if(dbCheckName.contains("Action_")){
438 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
439 }else if(dbCheckName.contains("Decision_")){
440 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
442 String[] splitDBCheckName = dbCheckName.split(":");
443 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
444 SimpleBindings params = new SimpleBindings();
445 params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
446 params.put("splitDBCheckName0", splitDBCheckName[0]);
447 List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
448 List<String> av = new ArrayList<>();
449 for(Object entity : policyEntity){
450 PolicyEntity pEntity = (PolicyEntity) entity;
451 String removeExtension = pEntity.getPolicyName().replace(".xml", "");
452 String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1);
455 if(policyName.contains("/")){
456 policyName = policyName.replace("/", File.separator);
458 PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
459 JSONObject el = new JSONObject();
460 el.put("activeVersion", entity.getActiveVersion());
461 el.put("availableVersions", av);
462 el.put("highestVersion", entity.getHigherVersion());
466 public static String getLogTableLimit() {
467 return logTableLimit;
470 public static void setLogTableLimit(String logTableLimit) {
471 PolicyController.logTableLimit = logTableLimit;
474 public static String getSystemAlertTableLimit() {
475 return systemAlertTableLimit;
478 public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
479 PolicyController.systemAlertTableLimit = systemAlertTableLimit;
482 public static CommonClassDao getCommonClassDao() {
483 return commonClassDao;
486 public static void setCommonClassDao(CommonClassDao commonClassDao) {
487 PolicyController.commonClassDao = commonClassDao;
490 public XacmlAdminAuthorization getAuthorizer() {
494 public void setAuthorizer(XacmlAdminAuthorization authorizer) {
495 this.authorizer = authorizer;
498 public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
499 return mapDatatype2Function;
502 public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
503 PolicyController.mapDatatype2Function = mapDatatype2Function;
506 public static Map<String, FunctionDefinition> getMapID2Function() {
507 return mapID2Function;
510 public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
511 PolicyController.mapID2Function = mapID2Function;
514 public static String getSmtpHost() {
518 public static void setSmtpHost(String smtpHost) {
519 PolicyController.smtpHost = smtpHost;
522 public static String getSmtpPort() {
526 public static void setSmtpPort(String smtpPort) {
527 PolicyController.smtpPort = smtpPort;
530 public static String getSmtpUsername() {
534 public static void setSmtpUsername(String smtpUsername) {
535 PolicyController.smtpUsername = smtpUsername;
538 public static String getSmtpPassword() {
542 public static void setSmtpPassword(String smtpPassword) {
543 PolicyController.smtpPassword = smtpPassword;
546 public static String getSmtpApplicationName() {
547 return smtpApplicationName;
550 public static void setSmtpApplicationName(String smtpApplicationName) {
551 PolicyController.smtpApplicationName = smtpApplicationName;
554 public static String getSmtpEmailExtension() {
555 return smtpEmailExtension;
558 public static void setSmtpEmailExtension(String smtpEmailExtension) {
559 PolicyController.smtpEmailExtension = smtpEmailExtension;
562 public static String getLogdbDriver() {
566 public static void setLogdbDriver(String logdbDriver) {
567 PolicyController.logdbDriver = logdbDriver;
570 public static String getLogdbUrl() {
574 public static void setLogdbUrl(String logdbUrl) {
575 PolicyController.logdbUrl = logdbUrl;
578 public static String getLogdbUserName() {
579 return logdbUserName;
582 public static void setLogdbUserName(String logdbUserName) {
583 PolicyController.logdbUserName = logdbUserName;
586 public static String getLogdbPassword() {
587 return logdbPassword;
590 public static void setLogdbPassword(String logdbPassword) {
591 PolicyController.logdbPassword = logdbPassword;
594 public static String getLogdbDialect() {
598 public static void setLogdbDialect(String logdbDialect) {
599 PolicyController.logdbDialect = logdbDialect;
602 public static String getXacmldbUrl() {
606 public static void setXacmldbUrl(String xacmldbUrl) {
607 PolicyController.xacmldbUrl = xacmldbUrl;
610 public static String getXacmldbUserName() {
611 return xacmldbUserName;
614 public static void setXacmldbUserName(String xacmldbUserName) {
615 PolicyController.xacmldbUserName = xacmldbUserName;
618 public static String getXacmldbPassword() {
619 return xacmldbPassword;
622 public static void setXacmldbPassword(String xacmldbPassword) {
623 PolicyController.xacmldbPassword = xacmldbPassword;
626 public static String getAutoPushAvailable() {
627 return autoPushAvailable;
630 public static void setAutoPushAvailable(String autoPushAvailable) {
631 PolicyController.autoPushAvailable = autoPushAvailable;
634 public static String getAutoPushDSClosedLoop() {
635 return autoPushDSClosedLoop;
638 public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
639 PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
642 public static String getAutoPushDSFirewall() {
643 return autoPushDSFirewall;
646 public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
647 PolicyController.autoPushDSFirewall = autoPushDSFirewall;
650 public static String getAutoPushDSMicroservice() {
651 return autoPushDSMicroservice;
654 public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
655 PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
658 public static String getAutoPushPDPGroup() {
659 return autoPushPDPGroup;
662 public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
663 PolicyController.autoPushPDPGroup = autoPushPDPGroup;
666 public static String getPapUrl() {
670 public static void setPapUrl(String papUrl) {
671 PolicyController.papUrl = papUrl;
674 public static String getMsOnapName() {
678 public static void setMsOnapName(String msOnapName) {
679 PolicyController.msOnapName = msOnapName;
682 public static String getMsPolicyName() {
686 public static void setMsPolicyName(String msPolicyName) {
687 PolicyController.msPolicyName = msPolicyName;
690 public static String getConfigHome() {
694 public static void setConfigHome(String configHome) {
695 PolicyController.configHome = configHome;
698 public static String getActionHome() {
702 public static void setActionHome(String actionHome) {
703 PolicyController.actionHome = actionHome;
706 public static Object getMapaccess() {
710 public static String getPolicydata() {
714 public static String getCharacterencoding() {
715 return characterEncoding;
718 public static String getContenttype() {
722 public static String getFile() {
726 public static void setFileSizeLimit(String uploadSize) {
727 //Default size limit is 30MB
728 if (uploadSize == null || uploadSize.isEmpty()) {
729 fileSizeLimit = 30000000;
732 fileSizeLimit = Long.parseLong(uploadSize);
736 public static long getFileSizeLimit() {
737 return fileSizeLimit;
739 public String convertDate(String dateTTL) {
740 String formateDate = null;
741 if(dateTTL.contains("-")){
742 formateDate = dateTTL.replace("-", "/");