2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.dao.CommonClassDao;
50 import org.onap.policy.rest.jpa.Datatype;
51 import org.onap.policy.rest.jpa.FunctionDefinition;
52 import org.onap.policy.rest.jpa.PolicyEntity;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.rest.jpa.UserInfo;
55 import org.onap.policy.xacml.api.XACMLErrorConstants;
56 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
57 import org.onap.portalsdk.core.controller.RestrictedBaseController;
58 import org.onap.portalsdk.core.web.support.JsonMessage;
59 import org.onap.portalsdk.core.web.support.UserUtils;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.http.MediaType;
62 import org.springframework.stereotype.Controller;
63 import org.springframework.web.bind.annotation.RequestMapping;
64 import org.springframework.web.bind.annotation.RequestMethod;
65 import org.springframework.web.servlet.ModelAndView;
67 import com.att.research.xacml.util.XACMLProperties;
68 import com.fasterxml.jackson.databind.ObjectMapper;
73 public class PolicyController extends RestrictedBaseController {
74 private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
76 private static CommonClassDao commonClassDao;
80 private static PAPPolicyEngine papEngine;
82 private static String logTableLimit;
83 private static String systemAlertTableLimit;
84 protected static Map<String, String> dropDownMap = new HashMap<>();
85 public static Map<String, String> getDropDownMap() {
89 public static void setDropDownMap(Map<String, String> dropDownMap) {
90 PolicyController.dropDownMap = dropDownMap;
93 public static String getDomain() {
94 return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
97 private static final Object mapAccess = new Object();
98 private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
99 private static Map<String, FunctionDefinition> mapID2Function = null;
101 //Constant variables used across Policy-sdk
102 private static final String policyData = "policyData";
103 private static final String characterEncoding = "UTF-8";
104 private static final String contentType = "application/json";
105 private static final String file = "file";
107 //Smtp Java Mail Properties
108 private static String smtpHost = null;
109 private static String smtpPort = null;
110 private static String smtpUsername = null;
111 private static String smtpPassword = null;
112 private static String smtpApplicationName = null;
113 private static String smtpEmailExtension = null;
115 private static String logdbDriver = null;
116 private static String logdbUrl = null;
117 private static String logdbUserName = null;
118 private static String logdbPassword = null;
119 private static String logdbDialect = null;
120 //Xacml db properties
121 private static String xacmldbUrl = null;
122 private static String xacmldbUserName = null;
123 private static String xacmldbPassword = null;
126 private static String autoPushAvailable;
127 private static String autoPushDSClosedLoop;
128 private static String autoPushDSFirewall;
129 private static String autoPushDSMicroservice;
130 private static String autoPushPDPGroup;
133 private static String papUrl;
135 //MicroService Model Properties
136 private static String msOnapName;
137 private static String msPolicyName;
140 private static String configHome;
141 private static String actionHome;
144 private static long fileSizeLimit;
146 private static boolean jUnit = false;
149 public static boolean isjUnit() {
153 public static void setjUnit(boolean jUnit) {
154 PolicyController.jUnit = jUnit;
158 private PolicyController(CommonClassDao commonClassDao){
159 PolicyController.commonClassDao = commonClassDao;
162 public PolicyController() {
168 Properties prop = new Properties();
169 InputStream input = null;
172 File file = new File(new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json");
173 input = new FileInputStream(file);
175 input = new FileInputStream("xacml.admin.properties");
177 // load a properties file
179 //file upload size limit property
180 setFileSizeLimit(prop.getProperty("file.size.limit"));
182 setPapUrl(prop.getProperty("xacml.rest.pap.url"));
183 // get the property values
184 setSmtpHost(prop.getProperty("onap.smtp.host"));
185 setSmtpPort(prop.getProperty("onap.smtp.port"));
186 setSmtpUsername(prop.getProperty("onap.smtp.userName"));
187 setSmtpPassword(prop.getProperty("onap.smtp.password"));
188 setSmtpApplicationName(prop.getProperty("onap.application.name"));
189 setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension"));
190 //Log Database Properties
191 setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
192 setLogdbUrl(prop.getProperty("xacml.log.db.url"));
193 setLogdbUserName(prop.getProperty("xacml.log.db.user"));
194 setLogdbPassword(prop.getProperty("xacml.log.db.password"));
195 setLogdbDialect(prop.getProperty("onap.dialect"));
196 //Xacml Database Properties
197 setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
198 setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
199 setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
201 setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
202 setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
203 setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
204 setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
205 setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
206 //Micro Service Properties
207 setMsOnapName(prop.getProperty("xacml.policy.msOnapName"));
208 if(getMsOnapName() == null){
209 setMsOnapName(prop.getProperty("xacml.policy.msEcompName"));
211 policyLogger.info("getMsOnapName => " + getMsOnapName());
212 setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
213 policyLogger.info("setMsPolicyName => " + getMsPolicyName());
215 setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
216 setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
217 //Get the Property Values for Dashboard tab Limit
219 setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
220 setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
222 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
223 setLogTableLimit("5000");
224 setSystemAlertTableLimit("2000");
226 System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
227 } catch (IOException ex) {
228 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
233 } catch (IOException e) {
234 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
239 //Initialize the FunctionDefinition table at Server Start up
240 Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
241 for ( Entry<Datatype, List<FunctionDefinition>> entry : functionMap.entrySet()) {
242 List<FunctionDefinition> functionDefinations = entry.getValue();
243 for (FunctionDefinition functionDef : functionDefinations) {
244 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
250 public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
251 synchronized(mapAccess) {
252 if (mapDatatype2Function == null) {
256 return mapDatatype2Function;
259 public static Map<String, FunctionDefinition> getFunctionIDMap() {
260 synchronized(mapAccess) {
261 if (mapID2Function == null) {
265 return mapID2Function;
268 private static void buildFunctionMaps() {
269 mapDatatype2Function = new HashMap<>();
270 mapID2Function = new HashMap<>();
271 List<Object> functiondefinitions = commonClassDao.getData(FunctionDefinition.class);
272 for (int i = 0; i < functiondefinitions.size(); i ++) {
273 FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
274 mapID2Function.put(value.getXacmlid(), value);
275 if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
276 mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
278 mapDatatype2Function.get(value.getDatatypeBean()).add(value);
282 @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
283 public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){
285 Map<String, Object> model = new HashMap<>();
286 ObjectMapper mapper = new ObjectMapper();
287 model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
288 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
289 JSONObject j = new JSONObject(msg);
290 response.getWriter().write(j.toString());
293 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e);
297 public PolicyEntity getPolicyEntityData(String scope, String policyName){
298 String key = scope + ":" + policyName;
299 List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
300 return (PolicyEntity) data.get(0);
303 public static Map<String, Roles> getUserRoles(String userId) {
304 Map<String, Roles> scopes = new HashMap<>();
305 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
306 if (roles != null && !roles.isEmpty()) {
307 for (Object role : roles) {
308 scopes.put(((Roles) role).getScope(), (Roles) role);
314 public List<String> getRolesOfUser(String userId) {
315 List<String> rolesList = new ArrayList<>();
316 List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
317 for (Object role: roles) {
318 rolesList.add(((Roles) role).getRole());
323 public List<Object> getRoles(String userId) {
324 return commonClassDao.getDataById(Roles.class, "loginId", userId);
327 //Get List of User Roles
328 @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
329 public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){
331 String userId = UserUtils.getUserSession(request).getOrgUserId();
332 Map<String, Object> model = new HashMap<>();
333 ObjectMapper mapper = new ObjectMapper();
334 model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
335 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
336 JSONObject j = new JSONObject(msg);
337 response.getWriter().write(j.toString());
340 policyLogger.error("Exception Occured"+e);
344 //Policy tabs Model and View
345 @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET)
346 public ModelAndView view(HttpServletRequest request){
347 String myRequestURL = request.getRequestURL().toString();
350 // Set the URL for the RESTful PAP Engine
352 setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
353 new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
354 } catch (Exception e) {
355 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e);
357 Map<String, Object> model = new HashMap<>();
358 return new ModelAndView("policy_Editor","model", model);
361 public PAPPolicyEngine getPapEngine() {
365 public static void setPapEngine(PAPPolicyEngine papEngine) {
366 PolicyController.papEngine = papEngine;
369 public String getUserName(String createdBy) {
370 String loginId = createdBy;
371 List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
372 return data.get(0).toString();
375 public static boolean getActivePolicy(String query) {
376 if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){
383 public void executeQuery(String query) {
384 commonClassDao.updateQuery(query);
387 public void saveData(Object cloneEntity) {
388 commonClassDao.save(cloneEntity);
391 public void updateData(Object entity) {
392 commonClassDao.update(entity);
395 public void deleteData(Object entity) {
396 commonClassDao.delete(entity);
399 public List<Object> getData(@SuppressWarnings("rawtypes") Class className){
400 return commonClassDao.getData(className);
403 public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
404 return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
407 public List<Object> getDataByQuery(String query, SimpleBindings params){
408 return commonClassDao.getDataByQuery(query, params);
412 @SuppressWarnings("rawtypes")
413 public Object getEntityItem(Class className, String columname, String key){
414 return commonClassDao.getEntityItem(className, columname, key);
418 public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){
419 PolicyNotificationMail email = new PolicyNotificationMail();
421 email.sendMail(entity, policyName, mode, commonClassDao);
422 } catch (MessagingException e) {
423 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
428 public JSONObject switchVersionPolicyContent(String policyName) {
429 String dbCheckName = policyName.replace("/", ".");
430 if(dbCheckName.contains("Config_")){
431 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
432 }else if(dbCheckName.contains("Action_")){
433 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
434 }else if(dbCheckName.contains("Decision_")){
435 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
437 String[] splitDBCheckName = dbCheckName.split(":");
438 String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
439 SimpleBindings params = new SimpleBindings();
440 params.put("splitDBCheckName1", splitDBCheckName[1] + "%");
441 params.put("splitDBCheckName0", splitDBCheckName[0]);
442 List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
443 List<String> av = new ArrayList<>();
444 for(Object entity : policyEntity){
445 PolicyEntity pEntity = (PolicyEntity) entity;
446 String removeExtension = pEntity.getPolicyName().replace(".xml", "");
447 String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1);
450 if(policyName.contains("/")){
451 policyName = policyName.replace("/", File.separator);
453 PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
454 JSONObject el = new JSONObject();
455 el.put("activeVersion", entity.getActiveVersion());
456 el.put("availableVersions", av);
457 el.put("highestVersion", entity.getHigherVersion());
461 public static String getLogTableLimit() {
462 return logTableLimit;
465 public static void setLogTableLimit(String logTableLimit) {
466 PolicyController.logTableLimit = logTableLimit;
469 public static String getSystemAlertTableLimit() {
470 return systemAlertTableLimit;
473 public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
474 PolicyController.systemAlertTableLimit = systemAlertTableLimit;
477 public static CommonClassDao getCommonClassDao() {
478 return commonClassDao;
481 public static void setCommonClassDao(CommonClassDao commonClassDao) {
482 PolicyController.commonClassDao = commonClassDao;
485 public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
486 return mapDatatype2Function;
489 public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
490 PolicyController.mapDatatype2Function = mapDatatype2Function;
493 public static Map<String, FunctionDefinition> getMapID2Function() {
494 return mapID2Function;
497 public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
498 PolicyController.mapID2Function = mapID2Function;
501 public static String getSmtpHost() {
505 public static void setSmtpHost(String smtpHost) {
506 PolicyController.smtpHost = smtpHost;
509 public static String getSmtpPort() {
513 public static void setSmtpPort(String smtpPort) {
514 PolicyController.smtpPort = smtpPort;
517 public static String getSmtpUsername() {
521 public static void setSmtpUsername(String smtpUsername) {
522 PolicyController.smtpUsername = smtpUsername;
525 public static String getSmtpPassword() {
529 public static void setSmtpPassword(String smtpPassword) {
530 PolicyController.smtpPassword = smtpPassword;
533 public static String getSmtpApplicationName() {
534 return smtpApplicationName;
537 public static void setSmtpApplicationName(String smtpApplicationName) {
538 PolicyController.smtpApplicationName = smtpApplicationName;
541 public static String getSmtpEmailExtension() {
542 return smtpEmailExtension;
545 public static void setSmtpEmailExtension(String smtpEmailExtension) {
546 PolicyController.smtpEmailExtension = smtpEmailExtension;
549 public static String getLogdbDriver() {
553 public static void setLogdbDriver(String logdbDriver) {
554 PolicyController.logdbDriver = logdbDriver;
557 public static String getLogdbUrl() {
561 public static void setLogdbUrl(String logdbUrl) {
562 PolicyController.logdbUrl = logdbUrl;
565 public static String getLogdbUserName() {
566 return logdbUserName;
569 public static void setLogdbUserName(String logdbUserName) {
570 PolicyController.logdbUserName = logdbUserName;
573 public static String getLogdbPassword() {
574 return logdbPassword;
577 public static void setLogdbPassword(String logdbPassword) {
578 PolicyController.logdbPassword = logdbPassword;
581 public static String getLogdbDialect() {
585 public static void setLogdbDialect(String logdbDialect) {
586 PolicyController.logdbDialect = logdbDialect;
589 public static String getXacmldbUrl() {
593 public static void setXacmldbUrl(String xacmldbUrl) {
594 PolicyController.xacmldbUrl = xacmldbUrl;
597 public static String getXacmldbUserName() {
598 return xacmldbUserName;
601 public static void setXacmldbUserName(String xacmldbUserName) {
602 PolicyController.xacmldbUserName = xacmldbUserName;
605 public static String getXacmldbPassword() {
606 return xacmldbPassword;
609 public static void setXacmldbPassword(String xacmldbPassword) {
610 PolicyController.xacmldbPassword = xacmldbPassword;
613 public static String getAutoPushAvailable() {
614 return autoPushAvailable;
617 public static void setAutoPushAvailable(String autoPushAvailable) {
618 PolicyController.autoPushAvailable = autoPushAvailable;
621 public static String getAutoPushDSClosedLoop() {
622 return autoPushDSClosedLoop;
625 public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
626 PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
629 public static String getAutoPushDSFirewall() {
630 return autoPushDSFirewall;
633 public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
634 PolicyController.autoPushDSFirewall = autoPushDSFirewall;
637 public static String getAutoPushDSMicroservice() {
638 return autoPushDSMicroservice;
641 public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
642 PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
645 public static String getAutoPushPDPGroup() {
646 return autoPushPDPGroup;
649 public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
650 PolicyController.autoPushPDPGroup = autoPushPDPGroup;
653 public static String getPapUrl() {
657 public static void setPapUrl(String papUrl) {
658 PolicyController.papUrl = papUrl;
661 public static String getMsOnapName() {
665 public static void setMsOnapName(String msOnapName) {
666 PolicyController.msOnapName = msOnapName;
669 public static String getMsPolicyName() {
673 public static void setMsPolicyName(String msPolicyName) {
674 PolicyController.msPolicyName = msPolicyName;
677 public static String getConfigHome() {
681 public static void setConfigHome(String configHome) {
682 PolicyController.configHome = configHome;
685 public static String getActionHome() {
689 public static void setActionHome(String actionHome) {
690 PolicyController.actionHome = actionHome;
693 public static Object getMapaccess() {
697 public static String getPolicydata() {
701 public static String getCharacterencoding() {
702 return characterEncoding;
705 public static String getContenttype() {
709 public static String getFile() {
713 public static void setFileSizeLimit(String uploadSize) {
714 //Default size limit is 30MB
715 if (uploadSize == null || uploadSize.isEmpty()) {
716 fileSizeLimit = 30000000;
719 fileSizeLimit = Long.parseLong(uploadSize);
723 public static long getFileSizeLimit() {
724 return fileSizeLimit;
726 public String convertDate(String dateTTL) {
727 String formateDate = null;
728 if(dateTTL.contains("-")){
729 formateDate = dateTTL.replace("-", "/");