Advertisement
tko_pb

AlertProcess 3 September

Sep 3rd, 2018
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 57.90 KB | None | 0 0
  1. /*
  2.  *************************************************************************
  3.  * The contents of this file are subject to the Openbravo  Public  License
  4.  * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
  5.  * Version 1.1  with a permitted attribution clause; you may not  use this
  6.  * file except in compliance with the License. You  may  obtain  a copy of
  7.  * the License at http://www.openbravo.com/legal/license.html
  8.  * Software distributed under the License  is  distributed  on  an "AS IS"
  9.  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  10.  * License for the specific  language  governing  rights  and  limitations
  11.  * under the License.
  12.  * The Original Code is Openbravo ERP.
  13.  * The Initial Developer of the Original Code is Openbravo SLU
  14.  * All portions are Copyright (C) 2008-2017 Openbravo SLU
  15.  * All Rights Reserved.
  16.  * Contributor(s):  ______________________________________.
  17.  ************************************************************************
  18.  */
  19.  
  20. package org.openbravo.erpCommon.ad_process;
  21.  
  22. import java.io.File;
  23. import java.sql.Connection;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.sql.SQLException;
  27. import java.text.DecimalFormat;
  28. import java.util.ArrayList;
  29. import java.util.Date;
  30. import java.util.HashMap;
  31. import java.util.List;
  32. import java.util.Vector;
  33.  
  34. import javax.servlet.ServletException;
  35.  
  36. import org.apache.commons.lang.StringEscapeUtils;
  37. import org.apache.log4j.Logger;
  38. import org.hibernate.criterion.Restrictions;
  39. import org.openbravo.base.session.OBPropertiesProvider;
  40. import org.openbravo.dal.core.OBContext;
  41. import org.openbravo.dal.service.OBCriteria;
  42. import org.openbravo.dal.service.OBDal;
  43. import org.openbravo.data.UtilSql;
  44. import org.openbravo.database.ConnectionProvider;
  45. import org.openbravo.erpCommon.utility.SequenceIdData;
  46. import org.openbravo.erpCommon.utility.Utility;
  47. import org.openbravo.erpCommon.utility.poc.EmailManager;
  48. import org.openbravo.model.ad.access.RoleOrganization;
  49. import org.openbravo.model.ad.access.User;
  50. import org.openbravo.model.ad.access.UserRoles;
  51. import org.openbravo.model.ad.alert.AlertRecipient;
  52. import org.openbravo.model.ad.alert.AlertRule;
  53. import org.openbravo.model.ad.system.Client;
  54. import org.openbravo.model.ad.system.ClientInformation;
  55. import org.openbravo.model.ad.utility.Tree;
  56. import org.openbravo.model.ad.utility.TreeNode;
  57. import org.openbravo.model.common.enterprise.EmailServerConfiguration;
  58. import org.openbravo.model.common.enterprise.Organization;
  59. import org.openbravo.model.common.plm.ProductCategory;
  60. import org.openbravo.scheduling.Process;
  61. import org.openbravo.scheduling.ProcessBundle;
  62. import org.openbravo.scheduling.ProcessLogger;
  63. import org.openbravo.utils.FormatUtilities;
  64. import org.quartz.JobExecutionException;
  65.  
  66. public class AlertProcess implements Process {
  67.  
  68.   private static final Logger log4j = Logger.getLogger(AlertProcess.class);
  69.  
  70.   private static int counter = 0;
  71.  
  72.   private ConnectionProvider connection;
  73.   private ProcessLogger logger;
  74.   private static final String SYSTEM_CLIENT_ID = "0";
  75.   private static final String CLIENT_ORG_SEPARATOR = "-";
  76.   private static String LANGUAGE = null;
  77.  
  78.   public void execute(ProcessBundle bundle) throws Exception {
  79.  
  80.     logger = bundle.getLogger();
  81.     connection = bundle.getConnection();
  82.  
  83.     logger.log("Starting Alert Backgrouond Process. Loop " + counter + "\n");
  84.  
  85.     try {
  86.       AlertProcessData[] alertRule = null;
  87.       final String adClientId = bundle.getContext().getClient();
  88.       LANGUAGE = bundle.getContext().getLanguage();
  89.  
  90.       if (adClientId.equals(SYSTEM_CLIENT_ID)) {
  91.         // Process all clients
  92.         alertRule = AlertProcessData.selectSQL(connection);
  93.       } else {
  94.         // Filter by Process Request's client
  95.         alertRule = AlertProcessData.selectSQL(connection, adClientId);
  96.       }
  97.  
  98.       if (alertRule != null && alertRule.length != 0) {
  99.  
  100.         for (int i = 0; i < alertRule.length; i++) {
  101.           processAlert(alertRule[i], connection, adClientId);
  102.         }
  103.       }
  104.     } catch (Exception e) {
  105.       throw new JobExecutionException(e.getMessage(), e);
  106.     } finally {
  107.       OBDal.getInstance().commitAndClose();
  108.     }
  109.   }
  110.  
  111.   private static AlertProcessData[] selectAlert(ConnectionProvider connectionProvider,
  112.       String alertRule, String alertRuleId, String clientID) throws ServletException {
  113.     String alertRuleSQL = (alertRule == null || alertRule.equals("")) ? "" : alertRule;
  114.     String strSql = "SELECT * FROM (" + alertRuleSQL + ") AAA where not exists ("
  115.         + "select 1 from ad_alert a where a.ad_alertrule_id = ? "
  116.         + "and a.referencekey_id = aaa.referencekey_id and coalesce(a.status, 'NEW') != 'SOLVED')";
  117.     if (!clientID.equalsIgnoreCase("0"))
  118.         strSql += " and aaa.ad_client_id='"+clientID+"'";
  119.  
  120.     String dateTimeFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
  121.         .getProperty("dateTimeFormat.java");
  122.  
  123.     ResultSet result;
  124.     Vector<AlertProcessData> vector = new Vector<>(0);
  125.     PreparedStatement st = null;
  126.  
  127.     try {
  128.       connectionProvider.getConnection().setReadOnly(true);
  129.       st = connectionProvider.getPreparedStatement(strSql);
  130.       st.setString(1, alertRuleId);
  131.       result = st.executeQuery();
  132.       while (result.next()) {
  133.         AlertProcessData objectAlertProcessData = new AlertProcessData();
  134.         objectAlertProcessData.adClientId = UtilSql.getValue(result, "ad_client_id");
  135.         objectAlertProcessData.adOrgId = UtilSql.getValue(result, "ad_org_id");
  136.         objectAlertProcessData.created = UtilSql
  137.             .getDateTimeValue(result, "created", dateTimeFormat);
  138.         objectAlertProcessData.createdby = UtilSql.getValue(result, "createdby");
  139.         objectAlertProcessData.updated = UtilSql.getValue(result, "updated");
  140.         objectAlertProcessData.updatedby = UtilSql.getValue(result, "updatedby");
  141.         objectAlertProcessData.recordId = UtilSql.getValue(result, "record_id");
  142.         objectAlertProcessData.referencekeyId = UtilSql.getValue(result, "referencekey_id");
  143.         objectAlertProcessData.description = UtilSql.getValue(result, "description");
  144.         objectAlertProcessData.isactive = UtilSql.getValue(result, "isactive");
  145.         objectAlertProcessData.adUserId = UtilSql.getValue(result, "ad_user_id");
  146.         objectAlertProcessData.adRoleId = UtilSql.getValue(result, "ad_role_id");
  147.         vector.addElement(objectAlertProcessData);
  148.       }
  149.       result.close();
  150.     } catch (SQLException e) {
  151.       log4j.error("SQL error in query: " + strSql + "Exception:" + e);
  152.       throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@"
  153.           + e.getMessage());
  154.     } catch (Exception ex) {
  155.       log4j.error("Exception in query: " + strSql + "Exception:" + ex);
  156.       throw new ServletException("@CODE=@" + ex.getMessage());
  157.     } finally {
  158.       try {
  159.         connectionProvider.getConnection().setReadOnly(false);
  160.         connectionProvider.releasePreparedStatement(st);
  161.       } catch (Exception e) {
  162.         log4j.error("Error during release*Statement of query: " + strSql, e);
  163.       }
  164.     }
  165.     AlertProcessData objectAlertProcessData[] = new AlertProcessData[vector.size()];
  166.     vector.copyInto(objectAlertProcessData);
  167.     return (objectAlertProcessData);
  168.   }
  169.  
  170.   private static int insertAlert(ConnectionProvider connectionProvider, String alertId,
  171.       String clientId, String orgId, String created, String createdBy, String ruleId,
  172.       String recordId, String referenceKey, String description, String user, String role)
  173.       throws ServletException {
  174.  
  175.     String dateTimeFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
  176.         .getProperty("dateTimeFormat.sql");
  177.  
  178.     // These fields are foreign keys that might be null
  179.  
  180.     String userStr = user.isEmpty() ? null : user;
  181.     String roleStr = role.isEmpty() ? null : role;
  182.     String ruleIdStr = ruleId.isEmpty() ? null : ruleId;
  183.     String recordIdStr = recordId.isEmpty() ? null : recordId;
  184.     // The date needs to be formated
  185.     String createdStr = "to_timestamp(\'" + created + "\', \'" + dateTimeFormat + "\')";
  186.     // These field needs to be escaped
  187.     String descriptionStr = StringEscapeUtils.escapeSql(description);
  188.  
  189.     StringBuilder sqlBuilder = new StringBuilder();
  190.     sqlBuilder.append("INSERT INTO AD_ALERT ");
  191.     sqlBuilder.append("(AD_ALERT_ID, AD_CLIENT_ID, AD_ORG_ID, ");
  192.     sqlBuilder.append("ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY, ");
  193.     sqlBuilder.append("AD_ALERTRULE_ID, RECORD_ID, REFERENCEKEY_ID, ");
  194.     sqlBuilder.append("DESCRIPTION, AD_USER_ID, AD_ROLE_ID, STATUS) ");
  195.     sqlBuilder.append("VALUES ");
  196.     sqlBuilder.append("(?, ?, ?, " + "\'Y\', " + createdStr + ", ?, " + "now()" + ", " + "\'0\'"
  197.         + ", ?, ?, ?, ?, ?, ?, " + "\'NEW\')");
  198.     String strSql = sqlBuilder.toString();
  199.  
  200.     int updateCount = 0;
  201.     PreparedStatement st = null;
  202.  
  203.     int iParameter = 0;
  204.  
  205.     try {
  206.       st = connectionProvider.getPreparedStatement(strSql);
  207.  
  208.       iParameter++;
  209.       UtilSql.setValue(st, iParameter, 12, null, alertId);
  210.       iParameter++;
  211.       UtilSql.setValue(st, iParameter, 12, null, clientId);
  212.       iParameter++;
  213.       UtilSql.setValue(st, iParameter, 12, null, orgId);
  214.       iParameter++;
  215.       UtilSql.setValue(st, iParameter, 12, null, createdBy);
  216.       iParameter++;
  217.       UtilSql.setValue(st, iParameter, 12, null, ruleIdStr);
  218.       iParameter++;
  219.       UtilSql.setValue(st, iParameter, 12, null, recordIdStr);
  220.       iParameter++;
  221.       UtilSql.setValue(st, iParameter, 12, null, referenceKey);
  222.       iParameter++;
  223.       UtilSql.setValue(st, iParameter, 12, null, descriptionStr);
  224.       iParameter++;
  225.       UtilSql.setValue(st, iParameter, 12, null, userStr);
  226.       iParameter++;
  227.       UtilSql.setValue(st, iParameter, 12, null, roleStr);
  228.  
  229.       updateCount = st.executeUpdate();
  230.     } catch (SQLException e) {
  231.       log4j.error("SQL error in query: " + strSql + "Exception:" + e);
  232.       throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@"
  233.           + e.getMessage());
  234.     } catch (Exception ex) {
  235.       log4j.error("Exception in query: " + strSql + "Exception:" + ex);
  236.       throw new ServletException("@CODE=@" + ex.getMessage());
  237.     } finally {
  238.       try {
  239.         connectionProvider.releasePreparedStatement(st);
  240.       } catch (Exception e) {
  241.         log4j.error("Error during release*Statement of query: " + strSql, e);
  242.       }
  243.     }
  244.     return (updateCount);
  245.   }
  246.  
  247.   /**
  248.    * @param alertRule
  249.    * @param conn
  250.    * @throws Exception
  251.    */
  252.   @SuppressWarnings({ "unchecked", "deprecation" })
  253.   private void processAlert(AlertProcessData alertRule, ConnectionProvider conn, String clientID) throws Exception {
  254.     logger.log("Processing rule " + alertRule.name + "\n");
  255.  
  256.     AlertProcessData[] alert = null;
  257.     if (!alertRule.sql.equals("")) {
  258.       try {
  259.         if (!alertRule.sql.toUpperCase().trim().startsWith("SELECT ")) {
  260.           logger.log(Utility.messageBD(conn, "AlertSelectConstraint", LANGUAGE) + " \n");
  261.         } else {
  262.           alert = selectAlert(conn, alertRule.sql, alertRule.adAlertruleId, clientID);
  263.         }
  264.       } catch (Exception ex) {
  265.         logger.log("Error processing: " + ex.getMessage() + "\n");
  266.         return;
  267.       }
  268.     }
  269.     // build document link prefix
  270.     OBContext.setAdminMode();
  271.         //get tab id
  272.         AlertRule alertRule2 = OBDal.getInstance().get(AlertRule.class, alertRule.adAlertruleId);
  273.         String tabid = "";
  274.         if (alertRule2.getTab()!=null)
  275.             tabid = alertRule2.getTab().getId();
  276.        
  277.         //get context.url
  278.         String contexturl = OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("context.url");
  279.     OBContext.restorePreviousMode();
  280.     String documentlinkPrefix = contexturl+"/?tabId="+tabid+"&recordId=";
  281.    
  282.    
  283.     // Insert
  284.     if (alert != null && alert.length != 0) {
  285.       int insertions = 0;
  286.       // final message
  287.       HashMap<String, StringBuilder> messageByClientOrg = new HashMap<String, StringBuilder>();
  288.       StringBuilder msg = new StringBuilder();
  289.  
  290.       for (int i = 0; i < alert.length; i++) {
  291.         String adAlertId = SequenceIdData.getUUID();
  292.  
  293.         StringBuilder newMsg = new StringBuilder();
  294.        
  295.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  296.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  297.             + alert[i].created + "\n");
  298.  
  299.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  300.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  301.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  302.         insertions++;
  303.  
  304.         String messageLine = "\n\nAlert: " + alert[i].description + "\nRecord: "
  305.             + alert[i].recordId;
  306.         msg.append(messageLine);
  307.         newMsg.append(messageLine);
  308.        
  309.         //add document link at the bottom
  310.         String documentlink = documentlinkPrefix+alert[i].referencekeyId;
  311.         msg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  312.         newMsg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  313.        
  314.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  315.         if (messageByClientOrg.containsKey(clientOrg)) {
  316.           messageByClientOrg.get(clientOrg).append(newMsg);
  317.         } else {
  318.           messageByClientOrg.put(clientOrg, newMsg);
  319.         }
  320.        
  321.       }
  322.      
  323.       // subject message
  324.       HashMap<String, StringBuilder> messageByClientOrgForSubject = new HashMap<String, StringBuilder>();
  325.  
  326.       for (int i = 0; i < alert.length; i++) {
  327.         String adAlertId = SequenceIdData.getUUID();
  328.  
  329.         StringBuilder newMsg = new StringBuilder();
  330.        
  331.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  332.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  333.             + alert[i].created + "\n");
  334.  
  335.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  336.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  337.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  338.         insertions++;
  339.  
  340.         String messageLine = alert[i].description;
  341.      
  342.         newMsg.append(messageLine);
  343.    
  344.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  345.         if (messageByClientOrgForSubject.containsKey(clientOrg)) {
  346.             messageByClientOrgForSubject.get(clientOrg).append(newMsg);
  347.         } else {
  348.             messageByClientOrgForSubject.put(clientOrg, newMsg);
  349.         }
  350.        
  351.       } //subject
  352.  
  353.       if (insertions > 0) {
  354.         // Send mail
  355.  
  356.         // There are two ways of sending the email, depending if the SMTP server is configured in
  357.         // the 'Client' tab or in the 'Email Configuration' tab.
  358.         // The SMTP server configured in 'Client' tab way is @Deprecated in 3.0
  359.  
  360.         final String adClientId = alertRule.adClientId;
  361.         final String adOrgId = alertRule.adOrgId;
  362.         final String deprecatedMailHost = OBDal.getInstance().get(Client.class, adClientId)
  363.             .getMailHost();
  364.         boolean isDeprecatedMode = false;
  365.         if (deprecatedMailHost != null && !"".equals(deprecatedMailHost)) {
  366.           isDeprecatedMode = true;
  367.         }
  368.  
  369.         if (!isDeprecatedMode) {
  370.           // Since it is a background process and each email sending takes some time (may vary
  371.           // depending on the server), they are sent at the end, once all data is recollected, in
  372.           // order to minimize problems/inconsistencies/NPE if the 'Alerts', 'AlertRecipient',
  373.           // 'User' or 'UserRoles' columns change in the middle of the process.
  374.           final List<Object[]> emailsToSendList = new ArrayList<Object[]>();
  375.           OBContext.setAdminMode();
  376.           try {
  377.             // Getting the SMTP server parameters
  378.             OBCriteria<EmailServerConfiguration> mailConfigCriteria = OBDal.getInstance()
  379.                 .createCriteria(EmailServerConfiguration.class);
  380.             mailConfigCriteria.add(Restrictions.eq(EmailServerConfiguration.PROPERTY_CLIENT, OBDal
  381.                 .getInstance().get(Client.class, adClientId)));
  382.             mailConfigCriteria.setFilterOnReadableClients(false);
  383.             mailConfigCriteria.setFilterOnReadableOrganization(false);
  384.             final List<EmailServerConfiguration> mailConfigList = mailConfigCriteria.list();
  385.  
  386.             if (mailConfigList.size() > 0) {
  387.               // TODO: There should be a mechanism to select the desired Email server configuration
  388.               // for alerts, until then, first search for the current organization (and use the
  389.               // first returned one), then for organization '0' (and use the first returned one) and
  390.               // then for any other of the organization tree where current organization belongs to
  391.               // (and use the first returned one).
  392.               EmailServerConfiguration mailConfig = null;
  393.  
  394.               for (EmailServerConfiguration currentOrgConfig : mailConfigList) {
  395.                 if (adOrgId.equals(currentOrgConfig.getOrganization().getId())) {
  396.                   mailConfig = currentOrgConfig;
  397.                   break;
  398.                 }
  399.               }
  400.               if (mailConfig == null) {
  401.                 for (EmailServerConfiguration zeroOrgConfig : mailConfigList) {
  402.                   if ("0".equals(zeroOrgConfig.getOrganization().getId())) {
  403.                     mailConfig = zeroOrgConfig;
  404.                     break;
  405.                   }
  406.                 }
  407.               }
  408.               if (mailConfig == null) {
  409.                 mailConfig = mailConfigList.get(0);
  410.               }
  411.  
  412.               OBCriteria<AlertRecipient> alertRecipientsCriteria = OBDal.getInstance()
  413.                   .createCriteria(AlertRecipient.class);
  414.               alertRecipientsCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ALERTRULE, OBDal
  415.                   .getInstance().get(AlertRule.class, alertRule.adAlertruleId)));
  416.               alertRecipientsCriteria.setFilterOnReadableClients(false);
  417.               alertRecipientsCriteria.setFilterOnReadableOrganization(false);
  418.  
  419.               final List<AlertRecipient> alertRecipientsList = alertRecipientsCriteria.list();
  420.  
  421.               // Mechanism to avoid several mails are sent to the same email address for the same
  422.               // alert
  423.               List<String> alreadySentToList = new ArrayList<String>();
  424.               for (AlertRecipient currentAlertRecipient : alertRecipientsList) {
  425.                 // If 'Send EMail' option is not checked, we are done for this alert recipient
  426.                 if (!currentAlertRecipient.isSendEMail()) {
  427.                   continue;
  428.                 }
  429.  
  430.                 final List<User> usersList = new ArrayList<User>();
  431.                 // If there is a 'Contact' established, take it, if not, take all users for the
  432.                 // selected 'Role'
  433.                 if (currentAlertRecipient.getUserContact() != null) {
  434.                   usersList.add(currentAlertRecipient.getUserContact());
  435.                 } else {
  436.                   OBCriteria<UserRoles> userRolesCriteria = OBDal.getInstance().createCriteria(
  437.                       UserRoles.class);
  438.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ROLE,
  439.                       currentAlertRecipient.getRole()));
  440.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_CLIENT,
  441.                       currentAlertRecipient.getClient()));
  442.                   userRolesCriteria.setFilterOnReadableClients(false);
  443.                   userRolesCriteria.setFilterOnReadableOrganization(false);
  444.  
  445.                   final List<UserRoles> userRolesList = userRolesCriteria.list();
  446.                   for (UserRoles currenUserRole : userRolesList) {
  447.                     usersList.add(currenUserRole.getUserContact());
  448.                   }
  449.                 }
  450.  
  451.                 // If there are no 'Contact' for send the email, we are done for this alert
  452.                 // recipient
  453.                 if (usersList.size() == 0) {
  454.                   continue;
  455.                 }
  456.                
  457.              // Create Subject message
  458.                 final StringBuilder SubjectEmail = new StringBuilder();
  459.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  460.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  461.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  462.                       clientAndOrg[1]);
  463.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  464.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  465.                         .getADRoleOrganizationList()) {
  466.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  467.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  468.                           SubjectEmail.append(messageByClientOrgForSubject.get(currentClientAndOrg));
  469.                         break;
  470.                       }
  471.                     }
  472.                   }
  473.                 }
  474.  
  475.                 // Create alert's message
  476.                 final StringBuilder finalMessage = new StringBuilder();
  477.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  478.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  479.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  480.                       clientAndOrg[1]);
  481.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  482.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  483.                         .getADRoleOrganizationList()) {
  484.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  485.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  486.                         finalMessage.append(messageByClientOrg.get(currentClientAndOrg));
  487.                         break;
  488.                       }
  489.                     }
  490.                   }
  491.                 }
  492.  
  493.                 // For each 'User', get the email parameters (to, subject, body, ...) and store them
  494.                 // to send the email at the end
  495.                 for (User targetUser : usersList) {
  496.                   if (targetUser == null) {
  497.                     continue;
  498.                   }
  499.                   if (!targetUser.isActive()) {
  500.                     continue;
  501.                   }
  502.                   final Client targetUserClient = targetUser.getClient();
  503.                   final String targetUserClientLanguage = (targetUserClient.getLanguage() != null ? targetUserClient
  504.                       .getLanguage().getLanguage() : null);
  505.                   final String targetUserEmail = targetUser.getEmail();
  506.                   if (targetUserEmail == null) {
  507.                     continue;
  508.                   }
  509.  
  510.                   boolean repeatedEmail = false;
  511.                   for (String alreadySentTo : alreadySentToList) {
  512.                     if (targetUserEmail.equals(alreadySentTo)) {
  513.                       repeatedEmail = true;
  514.                       break;
  515.                     }
  516.                   }
  517.                   if (repeatedEmail) {
  518.                     continue;
  519.                   }
  520.  
  521.                   // If there is no message for this user, skip it
  522.                   if (finalMessage.length() == 0) {
  523.                     continue;
  524.                   }
  525.  
  526.                   alreadySentToList.add(targetUserEmail);
  527.  
  528.                   final String host = mailConfig.getSmtpServer();
  529.                   final Boolean auth = mailConfig.isSMTPAuthentification();
  530.                   final String username = mailConfig.getSmtpServerAccount();
  531.                   final String password = FormatUtilities.encryptDecrypt(
  532.                       mailConfig.getSmtpServerPassword(), false);
  533.                   final String connSecurity = mailConfig.getSmtpConnectionSecurity();
  534.                   final int port = mailConfig.getSmtpPort().intValue();
  535.                   final String senderAddress = mailConfig.getSmtpServerSenderAddress();
  536.                   final String recipientTO = targetUserEmail;
  537.                   final String recipientCC = null;
  538.                   final String recipientBCC = null;
  539.                   final String replyTo = null;
  540.                   final String subject = "[OB Alert] " + SubjectEmail; //tiko
  541.                   final String content = Utility.messageBD(conn, "AlertMailHead",
  542.                       targetUserClientLanguage) + "\n" + finalMessage;
  543.                   final String contentType = "text/plain; charset=utf-8";
  544.                   final List<File> attachments = null;
  545.                   final Date sentDate = new Date();
  546.                   final List<String> headerExtras = null;
  547.  
  548.                   final Object[] email = { host, auth, username, password, connSecurity, port,
  549.                       senderAddress, recipientTO, recipientCC, recipientBCC, replyTo, subject,
  550.                       content, contentType, attachments, sentDate, headerExtras };
  551.                   emailsToSendList.add(email);
  552.                 }
  553.               }
  554.             }
  555.           } catch (Exception e) {
  556.             throw new JobExecutionException(e.getMessage(), e);
  557.           } finally {
  558.             OBContext.restorePreviousMode();
  559.           }
  560.           // Send all the stored emails
  561.           for (Object[] emailToSend : emailsToSendList) {
  562.             try {
  563.               EmailManager.sendEmail((String) emailToSend[0],
  564.                   ((Boolean) emailToSend[1]).booleanValue(), (String) emailToSend[2],
  565.                   (String) emailToSend[3], (String) emailToSend[4],
  566.                   ((Number) emailToSend[5]).intValue(), (String) emailToSend[6],
  567.                   (String) emailToSend[7], (String) emailToSend[8], (String) emailToSend[9],
  568.                   (String) emailToSend[10], (String) emailToSend[11], (String) emailToSend[12],
  569.                   (String) emailToSend[13], (List<File>) emailToSend[14], (Date) emailToSend[15],
  570.                   (List<String>) emailToSend[16]);
  571.             } catch (Exception exception) {
  572.               log4j.error(exception);
  573.               final String exceptionClass = exception.getClass().toString().replace("class ", "");
  574.               String exceptionString = "Problems while sending the email" + exception;
  575.               exceptionString = exceptionString.replace(exceptionClass, "");
  576.               throw new ServletException(exceptionString);
  577.             }
  578.           }
  579.         } else {
  580.           // @Deprecated : This full "else" statement is deprecated from OB 3.0MP9. It happens only
  581.           // when there is an email configured directly in the AD_CLIENT (new way is configure it in
  582.           // C_POC_CONFIGURATION)
  583.           AlertProcessData[] mail = AlertProcessData.prepareMails(conn, alertRule.adAlertruleId);
  584.  
  585.           if (mail != null) {
  586.             for (int i = 0; i < mail.length; i++) {
  587.               String head = Utility.messageBD(conn, "AlertMailHead", mail[i].adLanguage) + "\n";
  588.               org.openbravo.erpCommon.businessUtility.EMail email = new org.openbravo.erpCommon.businessUtility.EMail(
  589.                   null, mail[i].smtpho/*
  590.  *************************************************************************
  591.  * The contents of this file are subject to the Openbravo  Public  License
  592.  * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
  593.  * Version 1.1  with a permitted attribution clause; you may not  use this
  594.  * file except in compliance with the License. You  may  obtain  a copy of
  595.  * the License at http://www.openbravo.com/legal/license.html
  596.  * Software distributed under the License  is  distributed  on  an "AS IS"
  597.  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
  598.  * License for the specific  language  governing  rights  and  limitations
  599.  * under the License.
  600.  * The Original Code is Openbravo ERP.
  601.  * The Initial Developer of the Original Code is Openbravo SLU
  602.  * All portions are Copyright (C) 2008-2017 Openbravo SLU
  603.  * All Rights Reserved.
  604.  * Contributor(s):  ______________________________________.
  605.  ************************************************************************
  606.  */
  607.  
  608. package org.openbravo.erpCommon.ad_process;
  609.  
  610. import java.io.File;
  611. import java.sql.Connection;
  612. import java.sql.PreparedStatement;
  613. import java.sql.ResultSet;
  614. import java.sql.SQLException;
  615. import java.text.DecimalFormat;
  616. import java.util.ArrayList;
  617. import java.util.Date;
  618. import java.util.HashMap;
  619. import java.util.List;
  620. import java.util.Vector;
  621.  
  622. import javax.servlet.ServletException;
  623.  
  624. import org.apache.commons.lang.StringEscapeUtils;
  625. import org.apache.log4j.Logger;
  626. import org.hibernate.criterion.Restrictions;
  627. import org.openbravo.base.session.OBPropertiesProvider;
  628. import org.openbravo.dal.core.OBContext;
  629. import org.openbravo.dal.service.OBCriteria;
  630. import org.openbravo.dal.service.OBDal;
  631. import org.openbravo.data.UtilSql;
  632. import org.openbravo.database.ConnectionProvider;
  633. import org.openbravo.erpCommon.utility.SequenceIdData;
  634. import org.openbravo.erpCommon.utility.Utility;
  635. import org.openbravo.erpCommon.utility.poc.EmailManager;
  636. import org.openbravo.model.ad.access.RoleOrganization;
  637. import org.openbravo.model.ad.access.User;
  638. import org.openbravo.model.ad.access.UserRoles;
  639. import org.openbravo.model.ad.alert.AlertRecipient;
  640. import org.openbravo.model.ad.alert.AlertRule;
  641. import org.openbravo.model.ad.system.Client;
  642. import org.openbravo.model.ad.system.ClientInformation;
  643. import org.openbravo.model.ad.utility.Tree;
  644. import org.openbravo.model.ad.utility.TreeNode;
  645. import org.openbravo.model.common.enterprise.EmailServerConfiguration;
  646. import org.openbravo.model.common.enterprise.Organization;
  647. import org.openbravo.model.common.plm.ProductCategory;
  648. import org.openbravo.scheduling.Process;
  649. import org.openbravo.scheduling.ProcessBundle;
  650. import org.openbravo.scheduling.ProcessLogger;
  651. import org.openbravo.utils.FormatUtilities;
  652. import org.quartz.JobExecutionException;
  653.  
  654. public class AlertProcess implements Process {
  655.  
  656.   private static final Logger log4j = Logger.getLogger(AlertProcess.class);
  657.  
  658.   private static int counter = 0;
  659.  
  660.   private ConnectionProvider connection;
  661.   private ProcessLogger logger;
  662.   private static final String SYSTEM_CLIENT_ID = "0";
  663.   private static final String CLIENT_ORG_SEPARATOR = "-";
  664.   private static String LANGUAGE = null;
  665.  
  666.   public void execute(ProcessBundle bundle) throws Exception {
  667.  
  668.     logger = bundle.getLogger();
  669.     connection = bundle.getConnection();
  670.  
  671.     logger.log("Starting Alert Backgrouond Process. Loop " + counter + "\n");
  672.  
  673.     try {
  674.       AlertProcessData[] alertRule = null;
  675.       final String adClientId = bundle.getContext().getClient();
  676.       LANGUAGE = bundle.getContext().getLanguage();
  677.  
  678.       if (adClientId.equals(SYSTEM_CLIENT_ID)) {
  679.         // Process all clients
  680.         alertRule = AlertProcessData.selectSQL(connection);
  681.       } else {
  682.         // Filter by Process Request's client
  683.         alertRule = AlertProcessData.selectSQL(connection, adClientId);
  684.       }
  685.  
  686.       if (alertRule != null && alertRule.length != 0) {
  687.  
  688.         for (int i = 0; i < alertRule.length; i++) {
  689.           processAlert(alertRule[i], connection, adClientId);
  690.         }
  691.       }
  692.     } catch (Exception e) {
  693.       throw new JobExecutionException(e.getMessage(), e);
  694.     } finally {
  695.       OBDal.getInstance().commitAndClose();
  696.     }
  697.   }
  698.  
  699.   private static AlertProcessData[] selectAlert(ConnectionProvider connectionProvider,
  700.       String alertRule, String alertRuleId, String clientID) throws ServletException {
  701.     String alertRuleSQL = (alertRule == null || alertRule.equals("")) ? "" : alertRule;
  702.     String strSql = "SELECT * FROM (" + alertRuleSQL + ") AAA where not exists ("
  703.         + "select 1 from ad_alert a where a.ad_alertrule_id = ? "
  704.         + "and a.referencekey_id = aaa.referencekey_id and coalesce(a.status, 'NEW') != 'SOLVED')";
  705.     if (!clientID.equalsIgnoreCase("0"))
  706.         strSql += " and aaa.ad_client_id='"+clientID+"'";
  707.  
  708.     String dateTimeFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
  709.         .getProperty("dateTimeFormat.java");
  710.  
  711.     ResultSet result;
  712.     Vector<AlertProcessData> vector = new Vector<>(0);
  713.     PreparedStatement st = null;
  714.  
  715.     try {
  716.       connectionProvider.getConnection().setReadOnly(true);
  717.       st = connectionProvider.getPreparedStatement(strSql);
  718.       st.setString(1, alertRuleId);
  719.       result = st.executeQuery();
  720.       while (result.next()) {
  721.         AlertProcessData objectAlertProcessData = new AlertProcessData();
  722.         objectAlertProcessData.adClientId = UtilSql.getValue(result, "ad_client_id");
  723.         objectAlertProcessData.adOrgId = UtilSql.getValue(result, "ad_org_id");
  724.         objectAlertProcessData.created = UtilSql
  725.             .getDateTimeValue(result, "created", dateTimeFormat);
  726.         objectAlertProcessData.createdby = UtilSql.getValue(result, "createdby");
  727.         objectAlertProcessData.updated = UtilSql.getValue(result, "updated");
  728.         objectAlertProcessData.updatedby = UtilSql.getValue(result, "updatedby");
  729.         objectAlertProcessData.recordId = UtilSql.getValue(result, "record_id");
  730.         objectAlertProcessData.referencekeyId = UtilSql.getValue(result, "referencekey_id");
  731.         objectAlertProcessData.description = UtilSql.getValue(result, "description");
  732.         objectAlertProcessData.isactive = UtilSql.getValue(result, "isactive");
  733.         objectAlertProcessData.adUserId = UtilSql.getValue(result, "ad_user_id");
  734.         objectAlertProcessData.adRoleId = UtilSql.getValue(result, "ad_role_id");
  735.         vector.addElement(objectAlertProcessData);
  736.       }
  737.       result.close();
  738.     } catch (SQLException e) {
  739.       log4j.error("SQL error in query: " + strSql + "Exception:" + e);
  740.       throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@"
  741.           + e.getMessage());
  742.     } catch (Exception ex) {
  743.       log4j.error("Exception in query: " + strSql + "Exception:" + ex);
  744.       throw new ServletException("@CODE=@" + ex.getMessage());
  745.     } finally {
  746.       try {
  747.         connectionProvider.getConnection().setReadOnly(false);
  748.         connectionProvider.releasePreparedStatement(st);
  749.       } catch (Exception e) {
  750.         log4j.error("Error during release*Statement of query: " + strSql, e);
  751.       }
  752.     }
  753.     AlertProcessData objectAlertProcessData[] = new AlertProcessData[vector.size()];
  754.     vector.copyInto(objectAlertProcessData);
  755.     return (objectAlertProcessData);
  756.   }
  757.  
  758.   private static int insertAlert(ConnectionProvider connectionProvider, String alertId,
  759.       String clientId, String orgId, String created, String createdBy, String ruleId,
  760.       String recordId, String referenceKey, String description, String user, String role)
  761.       throws ServletException {
  762.  
  763.     String dateTimeFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
  764.         .getProperty("dateTimeFormat.sql");
  765.  
  766.     // These fields are foreign keys that might be null
  767.  
  768.     String userStr = user.isEmpty() ? null : user;
  769.     String roleStr = role.isEmpty() ? null : role;
  770.     String ruleIdStr = ruleId.isEmpty() ? null : ruleId;
  771.     String recordIdStr = recordId.isEmpty() ? null : recordId;
  772.     // The date needs to be formated
  773.     String createdStr = "to_timestamp(\'" + created + "\', \'" + dateTimeFormat + "\')";
  774.     // These field needs to be escaped
  775.     String descriptionStr = StringEscapeUtils.escapeSql(description);
  776.  
  777.     StringBuilder sqlBuilder = new StringBuilder();
  778.     sqlBuilder.append("INSERT INTO AD_ALERT ");
  779.     sqlBuilder.append("(AD_ALERT_ID, AD_CLIENT_ID, AD_ORG_ID, ");
  780.     sqlBuilder.append("ISACTIVE, CREATED, CREATEDBY, UPDATED, UPDATEDBY, ");
  781.     sqlBuilder.append("AD_ALERTRULE_ID, RECORD_ID, REFERENCEKEY_ID, ");
  782.     sqlBuilder.append("DESCRIPTION, AD_USER_ID, AD_ROLE_ID, STATUS) ");
  783.     sqlBuilder.append("VALUES ");
  784.     sqlBuilder.append("(?, ?, ?, " + "\'Y\', " + createdStr + ", ?, " + "now()" + ", " + "\'0\'"
  785.         + ", ?, ?, ?, ?, ?, ?, " + "\'NEW\')");
  786.     String strSql = sqlBuilder.toString();
  787.  
  788.     int updateCount = 0;
  789.     PreparedStatement st = null;
  790.  
  791.     int iParameter = 0;
  792.  
  793.     try {
  794.       st = connectionProvider.getPreparedStatement(strSql);
  795.  
  796.       iParameter++;
  797.       UtilSql.setValue(st, iParameter, 12, null, alertId);
  798.       iParameter++;
  799.       UtilSql.setValue(st, iParameter, 12, null, clientId);
  800.       iParameter++;
  801.       UtilSql.setValue(st, iParameter, 12, null, orgId);
  802.       iParameter++;
  803.       UtilSql.setValue(st, iParameter, 12, null, createdBy);
  804.       iParameter++;
  805.       UtilSql.setValue(st, iParameter, 12, null, ruleIdStr);
  806.       iParameter++;
  807.       UtilSql.setValue(st, iParameter, 12, null, recordIdStr);
  808.       iParameter++;
  809.       UtilSql.setValue(st, iParameter, 12, null, referenceKey);
  810.       iParameter++;
  811.       UtilSql.setValue(st, iParameter, 12, null, descriptionStr);
  812.       iParameter++;
  813.       UtilSql.setValue(st, iParameter, 12, null, userStr);
  814.       iParameter++;
  815.       UtilSql.setValue(st, iParameter, 12, null, roleStr);
  816.  
  817.       updateCount = st.executeUpdate();
  818.     } catch (SQLException e) {
  819.       log4j.error("SQL error in query: " + strSql + "Exception:" + e);
  820.       throw new ServletException("@CODE=" + Integer.toString(e.getErrorCode()) + "@"
  821.           + e.getMessage());
  822.     } catch (Exception ex) {
  823.       log4j.error("Exception in query: " + strSql + "Exception:" + ex);
  824.       throw new ServletException("@CODE=@" + ex.getMessage());
  825.     } finally {
  826.       try {
  827.         connectionProvider.releasePreparedStatement(st);
  828.       } catch (Exception e) {
  829.         log4j.error("Error during release*Statement of query: " + strSql, e);
  830.       }
  831.     }
  832.     return (updateCount);
  833.   }
  834.  
  835.   /**
  836.    * @param alertRule
  837.    * @param conn
  838.    * @throws Exception
  839.    */
  840.   @SuppressWarnings({ "unchecked", "deprecation" })
  841.   private void processAlert(AlertProcessData alertRule, ConnectionProvider conn, String clientID) throws Exception {
  842.     logger.log("Processing rule " + alertRule.name + "\n");
  843.  
  844.     AlertProcessData[] alert = null;
  845.     if (!alertRule.sql.equals("")) {
  846.       try {
  847.         if (!alertRule.sql.toUpperCase().trim().startsWith("SELECT ")) {
  848.           logger.log(Utility.messageBD(conn, "AlertSelectConstraint", LANGUAGE) + " \n");
  849.         } else {
  850.           alert = selectAlert(conn, alertRule.sql, alertRule.adAlertruleId, clientID);
  851.         }
  852.       } catch (Exception ex) {
  853.         logger.log("Error processing: " + ex.getMessage() + "\n");
  854.         return;
  855.       }
  856.     }
  857.     // build document link prefix
  858.     OBContext.setAdminMode();
  859.         //get tab id
  860.         AlertRule alertRule2 = OBDal.getInstance().get(AlertRule.class, alertRule.adAlertruleId);
  861.         String tabid = "";
  862.         if (alertRule2.getTab()!=null)
  863.             tabid = alertRule2.getTab().getId();
  864.        
  865.         //get context.url
  866.         String contexturl = OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("context.url");
  867.     OBContext.restorePreviousMode();
  868.     String documentlinkPrefix = contexturl+"/?tabId="+tabid+"&recordId=";
  869.    
  870.    
  871.     // Insert
  872.     if (alert != null && alert.length != 0) {
  873.       int insertions = 0;
  874.       // final message
  875.       HashMap<String, StringBuilder> messageByClientOrg = new HashMap<String, StringBuilder>();
  876.       StringBuilder msg = new StringBuilder();
  877.  
  878.       for (int i = 0; i < alert.length; i++) {
  879.         String adAlertId = SequenceIdData.getUUID();
  880.  
  881.         StringBuilder newMsg = new StringBuilder();
  882.        
  883.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  884.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  885.             + alert[i].created + "\n");
  886.  
  887.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  888.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  889.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  890.         insertions++;
  891.  
  892.         String messageLine = "\n\nAlert: " + alert[i].description + "\nRecord: "
  893.             + alert[i].recordId;
  894.         msg.append(messageLine);
  895.         newMsg.append(messageLine);
  896.        
  897.         //add document link at the bottom
  898.         String documentlink = documentlinkPrefix+alert[i].referencekeyId;
  899.         msg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  900.         newMsg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  901.        
  902.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  903.         if (messageByClientOrg.containsKey(clientOrg)) {
  904.           messageByClientOrg.get(clientOrg).append(newMsg);
  905.         } else {
  906.           messageByClientOrg.put(clientOrg, newMsg);
  907.         }
  908.        
  909.       }
  910.      
  911.       // subject message
  912.       HashMap<String, StringBuilder> messageByClientOrgForSubject = new HashMap<String, StringBuilder>();
  913.  
  914.       for (int i = 0; i < alert.length; i++) {
  915.         String adAlertId = SequenceIdData.getUUID();
  916.  
  917.         StringBuilder newMsg = new StringBuilder();
  918.        
  919.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  920.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  921.             + alert[i].created + "\n");
  922.  
  923.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  924.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  925.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  926.         insertions++;
  927.  
  928.         String messageLine = alert[i].description;
  929.      
  930.         newMsg.append(messageLine);
  931.    
  932.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  933.         if (messageByClientOrgForSubject.containsKey(clientOrg)) {
  934.             messageByClientOrgForSubject.get(clientOrg).append(newMsg);
  935.         } else {
  936.             messageByClientOrgForSubject.put(clientOrg, newMsg);
  937.         }
  938.        
  939.       } //subject
  940.  
  941.       if (insertions > 0) {
  942.         // Send mail
  943.  
  944.         // There are two ways of sending the email, depending if the SMTP server is configured in
  945.         // the 'Client' tab or in the 'Email Configuration' tab.
  946.         // The SMTP server configured in 'Client' tab way is @Deprecated in 3.0
  947.  
  948.         final String adClientId = alertRule.adClientId;
  949.         final String adOrgId = alertRule.adOrgId;
  950.         final String deprecatedMailHost = OBDal.getInstance().get(Client.class, adClientId)
  951.             .getMailHost();
  952.         boolean isDeprecatedMode = false;
  953.         if (deprecatedMailHost != null && !"".equals(deprecatedMailHost)) {
  954.           isDeprecatedMode = true;
  955.         }
  956.  
  957.         if (!isDeprecatedMode) {
  958.           // Since it is a background process and each email sending takes some time (may vary
  959.           // depending on the server), they are sent at the end, once all data is recollected, in
  960.           // order to minimize problems/inconsistencies/NPE if the 'Alerts', 'AlertRecipient',
  961.           // 'User' or 'UserRoles' columns change in the middle of the process.
  962.           final List<Object[]> emailsToSendList = new ArrayList<Object[]>();
  963.           OBContext.setAdminMode();
  964.           try {
  965.             // Getting the SMTP server parameters
  966.             OBCriteria<EmailServerConfiguration> mailConfigCriteria = OBDal.getInstance()
  967.                 .createCriteria(EmailServerConfiguration.class);
  968.             mailConfigCriteria.add(Restrictions.eq(EmailServerConfiguration.PROPERTY_CLIENT, OBDal
  969.                 .getInstance().get(Client.class, adClientId)));
  970.             mailConfigCriteria.setFilterOnReadableClients(false);
  971.             mailConfigCriteria.setFilterOnReadableOrganization(false);
  972.             final List<EmailServerConfiguration> mailConfigList = mailConfigCriteria.list();
  973.  
  974.             if (mailConfigList.size() > 0) {
  975.               // TODO: There should be a mechanism to select the desired Email server configuration
  976.               // for alerts, until then, first search for the current organization (and use the
  977.               // first returned one), then for organization '0' (and use the first returned one) and
  978.               // then for any other of the organization tree where current organization belongs to
  979.               // (and use the first returned one).
  980.               EmailServerConfiguration mailConfig = null;
  981.  
  982.               for (EmailServerConfiguration currentOrgConfig : mailConfigList) {
  983.                 if (adOrgId.equals(currentOrgConfig.getOrganization().getId())) {
  984.                   mailConfig = currentOrgConfig;
  985.                   break;
  986.                 }
  987.               }
  988.               if (mailConfig == null) {
  989.                 for (EmailServerConfiguration zeroOrgConfig : mailConfigList) {
  990.                   if ("0".equals(zeroOrgConfig.getOrganization().getId())) {
  991.                     mailConfig = zeroOrgConfig;
  992.                     break;
  993.                   }
  994.                 }
  995.               }
  996.               if (mailConfig == null) {
  997.                 mailConfig = mailConfigList.get(0);
  998.               }
  999.  
  1000.               OBCriteria<AlertRecipient> alertRecipientsCriteria = OBDal.getInstance()
  1001.                   .createCriteria(AlertRecipient.class);
  1002.               alertRecipientsCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ALERTRULE, OBDal
  1003.                   .getInstance().get(AlertRule.class, alertRule.adAlertruleId)));
  1004.               alertRecipientsCriteria.setFilterOnReadableClients(false);
  1005.               alertRecipientsCriteria.setFilterOnReadableOrganization(false);
  1006.  
  1007.               final List<AlertRecipient> alertRecipientsList = alertRecipientsCriteria.list();
  1008.  
  1009.               // Mechanism to avoid several mails are sent to the same email address for the same
  1010.               // alert
  1011.               List<String> alreadySentToList = new ArrayList<String>();
  1012.               for (AlertRecipient currentAlertRecipient : alertRecipientsList) {
  1013.                 // If 'Send EMail' option is not checked, we are done for this alert recipient
  1014.                 if (!currentAlertRecipient.isSendEMail()) {
  1015.                   continue;
  1016.                 }
  1017.  
  1018.                 final List<User> usersList = new ArrayList<User>();
  1019.                 // If there is a 'Contact' established, take it, if not, take all users for the
  1020.                 // selected 'Role'
  1021.                 if (currentAlertRecipient.getUserContact() != null) {
  1022.                   usersList.add(currentAlertRecipient.getUserContact());
  1023.                 } else {
  1024.                   OBCriteria<UserRoles> userRolesCriteria = OBDal.getInstance().createCriteria(
  1025.                       UserRoles.class);
  1026.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ROLE,
  1027.                       currentAlertRecipient.getRole()));
  1028.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_CLIENT,
  1029.                       currentAlertRecipient.getClient()));
  1030.                   userRolesCriteria.setFilterOnReadableClients(false);
  1031.                   userRolesCriteria.setFilterOnReadableOrganization(false);
  1032.  
  1033.                   final List<UserRoles> userRolesList = userRolesCriteria.list();
  1034.                   for (UserRoles currenUserRole : userRolesList) {
  1035.                     usersList.add(currenUserRole.getUserContact());
  1036.                   }
  1037.                 }
  1038.  
  1039.                 // If there are no 'Contact' for send the email, we are done for this alert
  1040.                 // recipient
  1041.                 if (usersList.size() == 0) {
  1042.                   continue;
  1043.                 }
  1044.                
  1045.              // Create Subject message
  1046.                 final StringBuilder SubjectEmail = new StringBuilder();
  1047.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  1048.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  1049.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  1050.                       clientAndOrg[1]);
  1051.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  1052.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  1053.                         .getADRoleOrganizationList()) {
  1054.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  1055.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  1056.                           SubjectEmail.append(messageByClientOrgForSubject.get(currentClientAndOrg));
  1057.                         break;
  1058.                       }
  1059.                     }
  1060.                   }
  1061.                 }
  1062.  
  1063.                 // Create alert's message
  1064.                 final StringBuilder finalMessage = new StringBuilder();
  1065.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  1066.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  1067.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  1068.                       clientAndOrg[1]);
  1069.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  1070.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  1071.                         .getADRoleOrganizationList()) {
  1072.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  1073.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  1074.                         finalMessage.append(messageByClientOrg.get(currentClientAndOrg));
  1075.                         break;
  1076.                       }
  1077.                     }
  1078.                   }
  1079.                 }
  1080.  
  1081.                 // For each 'User', get the email parameters (to, subject, body, ...) and store them
  1082.                 // to send the email at the end
  1083.                 for (User targetUser : usersList) {
  1084.                   if (targetUser == null) {
  1085.                     continue;
  1086.                   }
  1087.                   if (!targetUser.isActive()) {
  1088.                     continue;
  1089.                   }
  1090.                   final Client targetUserClient = targetUser.getClient();
  1091.                   final String targetUserClientLanguage = (targetUserClient.getLanguage() != null ? targetUserClient
  1092.                       .getLanguage().getLanguage() : null);
  1093.                   final String targetUserEmail = targetUser.getEmail();
  1094.                   if (targetUserEmail == null) {
  1095.                     continue;
  1096.                   }
  1097.  
  1098.                   boolean repeatedEmail = false;
  1099.                   for (String alreadySentTo : alreadySentToList) {
  1100.                     if (targetUserEmail.equals(alreadySentTo)) {
  1101.                       repeatedEmail = true;
  1102.                       break;
  1103.                     }
  1104.                   }
  1105.                   if (repeatedEmail) {
  1106.                     continue;
  1107.                   }
  1108.  
  1109.                   // If there is no message for this user, skip it
  1110.                   if (finalMessage.length() == 0) {
  1111.                     continue;
  1112.                   }
  1113.  
  1114.                   alreadySentToList.add(targetUserEmail);
  1115.  
  1116.                   final String host = mailConfig.getSmtpServer();
  1117.                   final Boolean auth = mailConfig.isSMTPAuthentification();
  1118.                   final String username = mailConfig.getSmtpServerAccount();
  1119.                   final String password = FormatUtilities.encryptDecrypt(
  1120.                       mailConfig.getSmtpServerPassword(), false);
  1121.                   final String connSecurity = mailConfig.getSmtpConnectionSecurity();
  1122.                   final int port = mailConfig.getSmtpPort().intValue();
  1123.                   final String senderAddress = mailConfig.getSmtpServerSenderAddress();
  1124.                   final String recipientTO = targetUserEmail;
  1125.                   final String recipientCC = null;
  1126.                   final String recipientBCC = null;
  1127.                   final String replyTo = null;
  1128.                   final String subject = "[OB Alert] " + SubjectEmail; //tiko
  1129.                   final String content = Utility.messageBD(conn, "AlertMailHead",
  1130.                       targetUserClientLanguage) + "\n" + finalMessage;
  1131.                   final String contentType = "text/plain; charset=utf-8";
  1132.                   final List<File> attachments = null;
  1133.                   final Date sentDate = new Date();
  1134.                   final List<String> headerExtras = null;
  1135.  
  1136.                   final Object[] email = { host, auth, username, password, connSecurity, port,
  1137.                       senderAddress, recipientTO, recipientCC, recipientBCC, replyTo, subject,
  1138.                       content, contentType, attachments, sentDate, headerExtras };
  1139.                   emailsToSendList.add(email);
  1140.                 }
  1141.               }
  1142.             }
  1143.           } catch (Exception e) {
  1144.             throw new JobExecutionException(e.getMessage(), e);
  1145.           } finally {
  1146.             OBContext.restorePreviousMode();
  1147.           }
  1148.           // Send all the stored emails
  1149.           for (Object[] emailToSend : emailsToSendList) {
  1150.             try {
  1151.               EmailManager.sendEmail((String) emailToSend[0],
  1152.                   ((Boolean) emailToSend[1]).booleanValue(), (String) emailToSend[2],
  1153.                   (String) emailToSend[3], (String) emailToSend[4],
  1154.                   ((Number) emailToSend[5]).intValue(), (String) emailToSend[6],
  1155.                   (String) emailToSend[7], (String) emailToSend[8], (String) emailToSend[9],
  1156.                   (String) emailToSend[10], (String) emailToSend[11], (String) emailToSend[12],
  1157.                   (String) emailToSend[13], (List<File>) emailToSend[14], (Date) emailToSend[15],
  1158.                   (List<String>) emailToSend[16]);
  1159.             } catch (Exception exception) {
  1160.               log4j.error(exception);
  1161.               final String exceptionClass = exception.getClass().toString().replace("class ", "");
  1162.               String exceptionString = "Problems while sending the email" + exception;
  1163.               exceptionString = exceptionString.replace(exceptionClass, "");
  1164.               throw new ServletException(exceptionString);
  1165.             }
  1166.           }
  1167.         } else {
  1168.           // @Deprecated : This full "else" statement is deprecated from OB 3.0MP9. It happens only
  1169.           // when there is an email configured directly in the AD_CLIENT (new way is configure it in
  1170.           // C_POC_CONFIGURATION)
  1171.           AlertProcessData[] mail = AlertProcessData.prepareMails(conn, alertRule.adAlertruleId);
  1172.  
  1173.           if (mail != null) {
  1174.             for (int i = 0; i < mail.length; i++) {
  1175.               String head = Utility.messageBD(conn, "AlertMailHead", mail[i].adLanguage) + "\n";
  1176.               org.openbravo.erpCommon.businessUtility.EMail email = new org.openbravo.erpCommon.businessUtility.EMail(
  1177.                   null, mail[i].smtphost, mail[i].mailfrom, mail[i].mailto, "[OB Alert] "
  1178.                       + alertRule.name, head + msg);
  1179.               String pwd = "";
  1180.               try {
  1181.                 pwd = FormatUtilities.encryptDecrypt(mail[i].requestuserpw, false);
  1182.               } catch (Exception e) {
  1183.                 logger
  1184.                     .log("Error getting user password to send the mail: " + e.getMessage() + "\n");
  1185.                 logger.log("Check email password settings in Client configuration.\n");
  1186.                 continue;
  1187.               }
  1188.               if (!pwd.equals("")) {
  1189.                 email.setEMailUser(mail[i].requestuser, pwd);
  1190.                 if ("OK".equals(email.send())) {
  1191.                   logger.log("Mail sent ok.");
  1192.                 } else {
  1193.                   logger.log("Error sending mail.");
  1194.                 }
  1195.               } else {
  1196.                 logger
  1197.                     .log("Sending email skipped. Check email password settings in Client configuration.\n");
  1198.               }
  1199.             }
  1200.           }
  1201.         }
  1202.       }
  1203.     }
  1204.  
  1205.     // Update
  1206.     if (!alertRule.sql.equals("") && (alertRule.sql.toUpperCase().trim().startsWith("SELECT "))) {
  1207.       try {
  1208.         Integer count = AlertProcessData.updateAlert(conn, alertRule.adAlertruleId, alertRule.sql);
  1209.         logger.log("updated alerts: " + count + "\n");
  1210.  
  1211.       } catch (Exception ex) {
  1212.         logger.log("Error updating: " + ex.toString() + "\n");
  1213.       }
  1214.     }
  1215.   }
  1216. }
  1217. st, mail[i].mailfrom, mail[i].mailto, "[OB Alert] "
  1218.                       + alertRule.name, head + msg);
  1219.               String pwd = "";
  1220.               try {
  1221.                 pwd = FormatUtilities.encryptDecrypt(mail[i].requestuserpw, false);
  1222.               } catch (Exception e) {
  1223.                 logger
  1224.                     .log("Error getting user password to send the mail: " + e.getMessage() + "\n");
  1225.                 logger.log("Check email password settings in Client configuration.\n");
  1226.                 continue;
  1227.               }
  1228.               if (!pwd.equals("")) {
  1229.                 email.setEMailUser(mail[i].requestuser, pwd);
  1230.                 if ("OK".equals(email.send())) {
  1231.                   logger.log("Mail sent ok.");
  1232.                 } else {
  1233.                   logger.log("Error sending mail.");
  1234.                 }
  1235.               } else {
  1236.                 logger
  1237.                     .log("Sending email skipped. Check email password settings in Client configuration.\n");
  1238.               }
  1239.             }
  1240.           }
  1241.         }
  1242.       }
  1243.     }
  1244.  
  1245.     // Update
  1246.     if (!alertRule.sql.equals("") && (alertRule.sql.toUpperCase().trim().startsWith("SELECT "))) {
  1247.       try {
  1248.         Integer count = AlertProcessData.updateAlert(conn, alertRule.adAlertruleId, alertRule.sql);
  1249.         logger.log("updated alerts: " + count + "\n");
  1250.  
  1251.       } catch (Exception ex) {
  1252.         logger.log("Error updating: " + ex.toString() + "\n");
  1253.       }
  1254.     }
  1255.   }
  1256. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement