2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.controller;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Properties;
36 import javax.annotation.PostConstruct;
37 import javax.mail.MessagingException;
38 import javax.script.SimpleBindings;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
42 import org.json.JSONObject;
43 import org.onap.policy.admin.PolicyNotificationMail;
44 import org.onap.policy.admin.RESTfulPAPEngine;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.model.PDPGroupContainer;
48 import org.onap.policy.model.Roles;
49 import org.onap.policy.rest.XACMLRestProperties;
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;
81 private static PAPPolicyEngine papEngine;
83 private static String logTableLimit;
84 private static String systemAlertTableLimit;
85 protected static Map<String, String> dropDownMap = new HashMap<>();
86 public static Map<String, String> getDropDownMap() {
90 public static void setDropDownMap(Map<String, String> dropDownMap) {
91 PolicyController.dropDownMap = dropDownMap;
94 public static String getDomain() {
95 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
98 private static final Object mapAccess = new Object();
99 private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
100 private static Map<String, FunctionDefinition> mapID2Function = null;
102 //Constant variables used across Policy-sdk
103 private static final String policyData = "policyData";
104 private static final String characterEncoding = "UTF-8";
105 private static final String contentType = "application/json";
106 private static final String file = "file";
108 //Smtp Java Mail Properties
109 private static String smtpHost = null;
110 private static String smtpPort = null;
111 private static String smtpUsername = null;
112 private static String smtpPassword = null;
113 private static String smtpApplicationName = null;
114 private static String smtpEmailExtension = null;
116 private static String logdbDriver = null;
117 private static String logdbUrl = null;
118 private static String logdbUserName = null;
119 private static String logdbPassword = null;
120 private static String logdbDialect = null;
121 //Xacml db properties
122 private static String xacmldbUrl = null;
123 private static String xacmldbUserName = null;
124 private static String xacmldbPassword = null;
127 private static String autoPushAvailable;
128 private static String autoPushDSClosedLoop;
129 private static String autoPushDSFirewall;
130 private static String autoPushDSMicroservice;
131 private static String autoPushPDPGroup;
134 private static String papUrl;
136 //MicroService Model Properties
137 private static String msOnapName;
138 private static String msPolicyName;
141 private static String configHome;
142 private static String actionHome;
145 private static long fileSizeLimit;
147 private static boolean jUnit = false;
150 public static boolean isjUnit() {
154 public static void setjUnit(boolean jUnit) {
155 PolicyController.jUnit = jUnit;
159 private PolicyController(CommonClassDao commonClassDao){
160 PolicyController.commonClassDao = commonClassDao;
163 public PolicyController() {
169 Properties prop = new Properties();
174 fileName = new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json";
176 fileName = "xacml.admin.properties";
179 try(InputStream input = new FileInputStream(fileName)) {
180 // 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);
236 //Initialize the FunctionDefinition table at Server Start up
237 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
238 for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
239 List<FunctionDefinition> functionDefinations = entry.getValue();
240 for (FunctionDefinition functionDef : functionDefinations) {
241 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
247 public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
248 synchronized(mapAccess) {
249 if (mapDatatype2Function == null) {
253 return mapDatatype2Function;
256 public static Map<String, FunctionDefinition> getFunctionIDMap() {
257 synchronized(mapAccess) {
258 if (mapID2Function == null) {
262 return mapID2Function;
265 private static void buildFunctionMaps() {
266 mapDatatype2Function = new HashMap<>();
267 mapID2Function = new HashMap<>();
268 List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
269 for (int i = 0; i < functiondefinitions.size(); i ++) {
270 FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
271 mapID2Function.put(value.getXacmlid(), value);
272 if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
273 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
275 mapDatatype2Function.get(value.getDatatypeBean()).add(value);
279 @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
280 public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
282 Map<String, Object> model = new HashMap<>();
283 ObjectMapper mapper = new ObjectMapper();
284 model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
285 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
286 JSONObject j = new JSONObject(msg);
287 response.getWriter().write(j.toString());
290 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
294 public PolicyEntity getPolicyEntityData(String scope, String policyName){
295 String key = scope + ":" + policyName;
296 List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
297 return (PolicyEntity) data.get(0);
300 public static Map<String, Roles> getUserRoles(String userId) {
301 Map<String, Roles> scopes = new HashMap<>();
302 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
303 if (roles != null && !roles.isEmpty()) {
304 for (Object role : roles) {
305 scopes.put(((Roles) role).getScope(), (Roles) role);
311 public List<String> getRolesOfUser(String userId) {
312 List<String> rolesList = new ArrayList<>();
313 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
314 for (Object role: roles) {
315 rolesList.add(((Roles) role).getRole());
320 public List<Object> getRoles(String userId) {
321 return commonClassDao.getDataById(Roles.class, "loginId", userId);
324 //Get List of User Roles
325 @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
326 public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
328 String userId = UserUtils.getUserSession(request).getOrgUserId();
329 Map<String, Object> model = new HashMap<>();
330 ObjectMapper mapper = new ObjectMapper();
331 model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
332 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
333 JSONObject j = new JSONObject(msg);
334 response.getWriter().write(j.toString());
337 policyLogger.error("Exception Occured"+e);
341 //Policy tabs Model and View
342 @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
343 public ModelAndView view(HttpServletRequest request){
344 String myRequestURL = request.getRequestURL().toString();
347 // Set the URL for the RESTful PAP Engine
349 setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
350 new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
351 } catch (Exception e) {
352 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
354 Map<String, Object> model = new HashMap<>();
355 return new ModelAndView("policy_Editor","model", model);
358 public PAPPolicyEngine getPapEngine() {
362 public static void setPapEngine(PAPPolicyEngine papEngine) {
363 PolicyController.papEngine = papEngine;
366 public String getUserName(String createdBy) {
367 String loginId = createdBy;
368 List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
369 return data.get(0).toString();
372 public static boolean getActivePolicy(String query) {
373 if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){
380 public void executeQuery(String query) {
381 commonClassDao.updateQuery(query);
384 public void saveData(Object cloneEntity) {
385 commonClassDao.save(cloneEntity);
388 public void updateData(Object entity) {
389 commonClassDao.update(entity);
392 public void deleteData(Object entity) {
393 commonClassDao.delete(entity);
396 public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
397 return commonClassDao.getData(className);
400 public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
401 return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
404 public List<Object> getDataByQuery(String query, SimpleBindings params){
405 return commonClassDao.getDataByQuery(query, params);
409 @SuppressWarnings("rawtypes")
410 public Object getEntityItem(Class className, String columname, String key){
411 return commonClassDao.getEntityItem(className, columname, key);
415 public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
416 PolicyNotificationMail email = new PolicyNotificationMail();
418 email.sendMail(entity, policyName, mode, commonClassDao);
419 } catch (MessagingException e) {
420 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
425 public JSONObject switchVersionPolicyContent(String policyName) {
426 String dbCheckName = policyName.replace("/", ".");
427 if(dbCheckName.contains("Config_")){
428 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
429 }else if(dbCheckName.contains("Action_")){
430 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
431 }else if(dbCheckName.contains("Decision_")){
432 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
434 String[] splitDBCheckName = dbCheckName.split(":");
435 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
436 SimpleBindings params = new SimpleBindings();
437 params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
438 params.put("splitDBCheckName0", splitDBCheckName[0]);
439 List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
440 List<String> av = new ArrayList<>();
441 for(Object entity : policyEntity){
442 PolicyEntity pEntity = (PolicyEntity) entity;
443 String removeExtension = pEntity.getPolicyName().replace(".xml", "");
444 String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1);
447 if(policyName.contains("/")){
448 policyName = policyName.replace("/", File.separator);
450 PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
451 JSONObject el = new JSONObject();
452 el.put("activeVersion", entity.getActiveVersion());
453 el.put("availableVersions", av);
454 el.put("highestVersion", entity.getHigherVersion());
458 public static String getLogTableLimit() {
459 return logTableLimit;
462 public static void setLogTableLimit(String logTableLimit) {
463 PolicyController.logTableLimit = logTableLimit;
466 public static String getSystemAlertTableLimit() {
467 return systemAlertTableLimit;
470 public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
471 PolicyController.systemAlertTableLimit = systemAlertTableLimit;
474 public static CommonClassDao getCommonClassDao() {
475 return commonClassDao;
478 public static void setCommonClassDao(CommonClassDao commonClassDao) {
479 PolicyController.commonClassDao = commonClassDao;
482 public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
483 return mapDatatype2Function;
486 public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
487 PolicyController.mapDatatype2Function = mapDatatype2Function;
490 public static Map<String, FunctionDefinition> getMapID2Function() {
491 return mapID2Function;
494 public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
495 PolicyController.mapID2Function = mapID2Function;
498 public static String getSmtpHost() {
502 public static void setSmtpHost(String smtpHost) {
503 PolicyController.smtpHost = smtpHost;
506 public static String getSmtpPort() {
510 public static void setSmtpPort(String smtpPort) {
511 PolicyController.smtpPort = smtpPort;
514 public static String getSmtpUsername() {
518 public static void setSmtpUsername(String smtpUsername) {
519 PolicyController.smtpUsername = smtpUsername;
522 public static String getSmtpPassword() {
526 public static void setSmtpPassword(String smtpPassword) {
527 PolicyController.smtpPassword = smtpPassword;
530 public static String getSmtpApplicationName() {
531 return smtpApplicationName;
534 public static void setSmtpApplicationName(String smtpApplicationName) {
535 PolicyController.smtpApplicationName = smtpApplicationName;
538 public static String getSmtpEmailExtension() {
539 return smtpEmailExtension;
542 public static void setSmtpEmailExtension(String smtpEmailExtension) {
543 PolicyController.smtpEmailExtension = smtpEmailExtension;
546 public static String getLogdbDriver() {
550 public static void setLogdbDriver(String logdbDriver) {
551 PolicyController.logdbDriver = logdbDriver;
554 public static String getLogdbUrl() {
558 public static void setLogdbUrl(String logdbUrl) {
559 PolicyController.logdbUrl = logdbUrl;
562 public static String getLogdbUserName() {
563 return logdbUserName;
566 public static void setLogdbUserName(String logdbUserName) {
567 PolicyController.logdbUserName = logdbUserName;
570 public static String getLogdbPassword() {
571 return logdbPassword;
574 public static void setLogdbPassword(String logdbPassword) {
575 PolicyController.logdbPassword = logdbPassword;
578 public static String getLogdbDialect() {
582 public static void setLogdbDialect(String logdbDialect) {
583 PolicyController.logdbDialect = logdbDialect;
586 public static String getXacmldbUrl() {
590 public static void setXacmldbUrl(String xacmldbUrl) {
591 PolicyController.xacmldbUrl = xacmldbUrl;
594 public static String getXacmldbUserName() {
595 return xacmldbUserName;
598 public static void setXacmldbUserName(String xacmldbUserName) {
599 PolicyController.xacmldbUserName = xacmldbUserName;
602 public static String getXacmldbPassword() {
603 return xacmldbPassword;
606 public static void setXacmldbPassword(String xacmldbPassword) {
607 PolicyController.xacmldbPassword = xacmldbPassword;
610 public static String getAutoPushAvailable() {
611 return autoPushAvailable;
614 public static void setAutoPushAvailable(String autoPushAvailable) {
615 PolicyController.autoPushAvailable = autoPushAvailable;
618 public static String getAutoPushDSClosedLoop() {
619 return autoPushDSClosedLoop;
622 public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
623 PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
626 public static String getAutoPushDSFirewall() {
627 return autoPushDSFirewall;
630 public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
631 PolicyController.autoPushDSFirewall = autoPushDSFirewall;
634 public static String getAutoPushDSMicroservice() {
635 return autoPushDSMicroservice;
638 public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
639 PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
642 public static String getAutoPushPDPGroup() {
643 return autoPushPDPGroup;
646 public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
647 PolicyController.autoPushPDPGroup = autoPushPDPGroup;
650 public static String getPapUrl() {
654 public static void setPapUrl(String papUrl) {
655 PolicyController.papUrl = papUrl;
658 public static String getMsOnapName() {
662 public static void setMsOnapName(String msOnapName) {
663 PolicyController.msOnapName = msOnapName;
666 public static String getMsPolicyName() {
670 public static void setMsPolicyName(String msPolicyName) {
671 PolicyController.msPolicyName = msPolicyName;
674 public static String getConfigHome() {
678 public static void setConfigHome(String configHome) {
679 PolicyController.configHome = configHome;
682 public static String getActionHome() {
686 public static void setActionHome(String actionHome) {
687 PolicyController.actionHome = actionHome;
690 public static Object getMapaccess() {
694 public static String getPolicydata() {
698 public static String getCharacterencoding() {
699 return characterEncoding;
702 public static String getContenttype() {
706 public static String getFile() {
710 public static void setFileSizeLimit(String uploadSize) {
711 //Default size limit is 30MB
712 if (uploadSize == null || uploadSize.isEmpty()) {
713 fileSizeLimit = 30000000;
716 fileSizeLimit = Long.parseLong(uploadSize);
720 public static long getFileSizeLimit() {
721 return fileSizeLimit;
723 public String convertDate(String dateTTL) {
724 String formateDate = null;
725 if(dateTTL.contains("-")){
726 formateDate = dateTTL.replace("-", "/");