Advertisement
tko_pb

AlertProcess 29 agustus

Aug 29th, 2018
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 31.05 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 = alertRule2.getTab().getId();
  274.        
  275.         //get context.url
  276.         String contexturl = OBPropertiesProvider.getInstance().getOpenbravoProperties().getProperty("context.url");
  277.     OBContext.restorePreviousMode();
  278.     String documentlinkPrefix = contexturl+"/?tabId="+tabid+"&recordId=";
  279.    
  280.    
  281.     // Insert
  282.     if (alert != null && alert.length != 0) {
  283.       int insertions = 0;
  284.       // final message
  285.       HashMap<String, StringBuilder> messageByClientOrg = new HashMap<String, StringBuilder>();
  286.       StringBuilder msg = new StringBuilder();
  287.  
  288.       for (int i = 0; i < alert.length; i++) {
  289.         String adAlertId = SequenceIdData.getUUID();
  290.  
  291.         StringBuilder newMsg = new StringBuilder();
  292.        
  293.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  294.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  295.             + alert[i].created + "\n");
  296.  
  297.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  298.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  299.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  300.         insertions++;
  301.  
  302.         String messageLine = "\n\nAlert: " + alert[i].description + "\nRecord: "
  303.             + alert[i].recordId;
  304.         msg.append(messageLine);
  305.         newMsg.append(messageLine);
  306.        
  307.         //add document link at the bottom
  308.         String documentlink = documentlinkPrefix+alert[i].referencekeyId;
  309.         msg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  310.         newMsg.append(System.lineSeparator()).append("Link to document: ").append(documentlink);
  311.        
  312.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  313.         if (messageByClientOrg.containsKey(clientOrg)) {
  314.           messageByClientOrg.get(clientOrg).append(newMsg);
  315.         } else {
  316.           messageByClientOrg.put(clientOrg, newMsg);
  317.         }
  318.        
  319.       }
  320.      
  321.       // subject message
  322.       HashMap<String, StringBuilder> messageByClientOrgForSubject = new HashMap<String, StringBuilder>();
  323.  
  324.       for (int i = 0; i < alert.length; i++) {
  325.         String adAlertId = SequenceIdData.getUUID();
  326.  
  327.         StringBuilder newMsg = new StringBuilder();
  328.        
  329.         logger.log("Inserting alert " + adAlertId + " org:" + alert[i].adOrgId + " client:"
  330.             + alert[i].adClientId + " reference key: " + alert[i].referencekeyId + " created"
  331.             + alert[i].created + "\n");
  332.  
  333.         insertAlert(conn, adAlertId, alert[i].adClientId, alert[i].adOrgId, alert[i].created,
  334.             alert[i].createdby, alertRule.adAlertruleId, alert[i].recordId,
  335.             alert[i].referencekeyId, alert[i].description, alert[i].adUserId, alert[i].adRoleId);
  336.         insertions++;
  337.  
  338.         String messageLine = alert[i].description;
  339.      
  340.         newMsg.append(messageLine);
  341.    
  342.         String clientOrg = alert[i].adClientId + CLIENT_ORG_SEPARATOR + alert[i].adOrgId;
  343.         if (messageByClientOrgForSubject.containsKey(clientOrg)) {
  344.             messageByClientOrgForSubject.get(clientOrg).append(newMsg); //tiko
  345.         } else {
  346.             messageByClientOrgForSubject.put(clientOrg, newMsg);
  347.         }
  348.        
  349.       } //subject
  350.  
  351.       if (insertions > 0) {
  352.         // Send mail
  353.  
  354.         // There are two ways of sending the email, depending if the SMTP server is configured in
  355.         // the 'Client' tab or in the 'Email Configuration' tab.
  356.         // The SMTP server configured in 'Client' tab way is @Deprecated in 3.0
  357.  
  358.         final String adClientId = alertRule.adClientId;
  359.         final String adOrgId = alertRule.adOrgId;
  360.         final String deprecatedMailHost = OBDal.getInstance().get(Client.class, adClientId)
  361.             .getMailHost();
  362.         boolean isDeprecatedMode = false;
  363.         if (deprecatedMailHost != null && !"".equals(deprecatedMailHost)) {
  364.           isDeprecatedMode = true;
  365.         }
  366.  
  367.         if (!isDeprecatedMode) {
  368.           // Since it is a background process and each email sending takes some time (may vary
  369.           // depending on the server), they are sent at the end, once all data is recollected, in
  370.           // order to minimize problems/inconsistencies/NPE if the 'Alerts', 'AlertRecipient',
  371.           // 'User' or 'UserRoles' columns change in the middle of the process.
  372.           final List<Object[]> emailsToSendList = new ArrayList<Object[]>();
  373.           OBContext.setAdminMode();
  374.           try {
  375.             // Getting the SMTP server parameters
  376.             OBCriteria<EmailServerConfiguration> mailConfigCriteria = OBDal.getInstance()
  377.                 .createCriteria(EmailServerConfiguration.class);
  378.             mailConfigCriteria.add(Restrictions.eq(EmailServerConfiguration.PROPERTY_CLIENT, OBDal
  379.                 .getInstance().get(Client.class, adClientId)));
  380.             mailConfigCriteria.setFilterOnReadableClients(false);
  381.             mailConfigCriteria.setFilterOnReadableOrganization(false);
  382.             final List<EmailServerConfiguration> mailConfigList = mailConfigCriteria.list();
  383.  
  384.             if (mailConfigList.size() > 0) {
  385.               // TODO: There should be a mechanism to select the desired Email server configuration
  386.               // for alerts, until then, first search for the current organization (and use the
  387.               // first returned one), then for organization '0' (and use the first returned one) and
  388.               // then for any other of the organization tree where current organization belongs to
  389.               // (and use the first returned one).
  390.               EmailServerConfiguration mailConfig = null;
  391.  
  392.               for (EmailServerConfiguration currentOrgConfig : mailConfigList) {
  393.                 if (adOrgId.equals(currentOrgConfig.getOrganization().getId())) {
  394.                   mailConfig = currentOrgConfig;
  395.                   break;
  396.                 }
  397.               }
  398.               if (mailConfig == null) {
  399.                 for (EmailServerConfiguration zeroOrgConfig : mailConfigList) {
  400.                   if ("0".equals(zeroOrgConfig.getOrganization().getId())) {
  401.                     mailConfig = zeroOrgConfig;
  402.                     break;
  403.                   }
  404.                 }
  405.               }
  406.               if (mailConfig == null) {
  407.                 mailConfig = mailConfigList.get(0);
  408.               }
  409.  
  410.               OBCriteria<AlertRecipient> alertRecipientsCriteria = OBDal.getInstance()
  411.                   .createCriteria(AlertRecipient.class);
  412.               alertRecipientsCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ALERTRULE, OBDal
  413.                   .getInstance().get(AlertRule.class, alertRule.adAlertruleId)));
  414.               alertRecipientsCriteria.setFilterOnReadableClients(false);
  415.               alertRecipientsCriteria.setFilterOnReadableOrganization(false);
  416.  
  417.               final List<AlertRecipient> alertRecipientsList = alertRecipientsCriteria.list();
  418.  
  419.               // Mechanism to avoid several mails are sent to the same email address for the same
  420.               // alert
  421.               List<String> alreadySentToList = new ArrayList<String>();
  422.               for (AlertRecipient currentAlertRecipient : alertRecipientsList) {
  423.                 // If 'Send EMail' option is not checked, we are done for this alert recipient
  424.                 if (!currentAlertRecipient.isSendEMail()) {
  425.                   continue;
  426.                 }
  427.  
  428.                 final List<User> usersList = new ArrayList<User>();
  429.                 // If there is a 'Contact' established, take it, if not, take all users for the
  430.                 // selected 'Role'
  431.                 if (currentAlertRecipient.getUserContact() != null) {
  432.                   usersList.add(currentAlertRecipient.getUserContact());
  433.                 } else {
  434.                   OBCriteria<UserRoles> userRolesCriteria = OBDal.getInstance().createCriteria(
  435.                       UserRoles.class);
  436.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_ROLE,
  437.                       currentAlertRecipient.getRole()));
  438.                   userRolesCriteria.add(Restrictions.eq(AlertRecipient.PROPERTY_CLIENT,
  439.                       currentAlertRecipient.getClient()));
  440.                   userRolesCriteria.setFilterOnReadableClients(false);
  441.                   userRolesCriteria.setFilterOnReadableOrganization(false);
  442.  
  443.                   final List<UserRoles> userRolesList = userRolesCriteria.list();
  444.                   for (UserRoles currenUserRole : userRolesList) {
  445.                     usersList.add(currenUserRole.getUserContact());
  446.                   }
  447.                 }
  448.  
  449.                 // If there are no 'Contact' for send the email, we are done for this alert
  450.                 // recipient
  451.                 if (usersList.size() == 0) {
  452.                   continue;
  453.                 }
  454.                
  455.              // Create Subject message
  456.                 final StringBuilder SubjectEmail = new StringBuilder();
  457.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  458.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  459.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  460.                       clientAndOrg[1]);
  461.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  462.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  463.                         .getADRoleOrganizationList()) {
  464.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  465.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  466.                           SubjectEmail.append(messageByClientOrgForSubject.get(currentClientAndOrg)); //tiko
  467.                         break;
  468.                       }
  469.                     }
  470.                   }
  471.                 }
  472.  
  473.                 // Create alert's message
  474.                 final StringBuilder finalMessage = new StringBuilder();
  475.                 for (String currentClientAndOrg : messageByClientOrg.keySet()) {
  476.                   String[] clientAndOrg = currentClientAndOrg.split(CLIENT_ORG_SEPARATOR);
  477.                   Organization orgEntity = OBDal.getInstance().get(Organization.class,
  478.                       clientAndOrg[1]);
  479.                   if (currentAlertRecipient.getClient().getId().equals(clientAndOrg[0])) {
  480.                     for (RoleOrganization roleOrganization : currentAlertRecipient.getRole()
  481.                         .getADRoleOrganizationList()) {
  482.                       if (OBContext.getOBContext().getOrganizationStructureProvider()
  483.                           .isInNaturalTree(roleOrganization.getOrganization(), orgEntity)) {
  484.                         finalMessage.append(messageByClientOrg.get(currentClientAndOrg));
  485.                         break;
  486.                       }
  487.                     }
  488.                   }
  489.                 }
  490.  
  491.                 // For each 'User', get the email parameters (to, subject, body, ...) and store them
  492.                 // to send the email at the end
  493.                 for (User targetUser : usersList) {
  494.                   if (targetUser == null) {
  495.                     continue;
  496.                   }
  497.                   if (!targetUser.isActive()) {
  498.                     continue;
  499.                   }
  500.                   final Client targetUserClient = targetUser.getClient();
  501.                   final String targetUserClientLanguage = (targetUserClient.getLanguage() != null ? targetUserClient
  502.                       .getLanguage().getLanguage() : null);
  503.                   final String targetUserEmail = targetUser.getEmail();
  504.                   if (targetUserEmail == null) {
  505.                     continue;
  506.                   }
  507.  
  508.                   boolean repeatedEmail = false;
  509.                   for (String alreadySentTo : alreadySentToList) {
  510.                     if (targetUserEmail.equals(alreadySentTo)) {
  511.                       repeatedEmail = true;
  512.                       break;
  513.                     }
  514.                   }
  515.                   if (repeatedEmail) {
  516.                     continue;
  517.                   }
  518.  
  519.                   // If there is no message for this user, skip it
  520.                   if (finalMessage.length() == 0) {
  521.                     continue;
  522.                   }
  523.  
  524.                   alreadySentToList.add(targetUserEmail);
  525.  
  526.                   final String host = mailConfig.getSmtpServer();
  527.                   final Boolean auth = mailConfig.isSMTPAuthentification();
  528.                   final String username = mailConfig.getSmtpServerAccount();
  529.                   final String password = FormatUtilities.encryptDecrypt(
  530.                       mailConfig.getSmtpServerPassword(), false);
  531.                   final String connSecurity = mailConfig.getSmtpConnectionSecurity();
  532.                   final int port = mailConfig.getSmtpPort().intValue();
  533.                   final String senderAddress = mailConfig.getSmtpServerSenderAddress();
  534.                   final String recipientTO = targetUserEmail;
  535.                   final String recipientCC = null;
  536.                   final String recipientBCC = null;
  537.                   final String replyTo = null;
  538.                   final String subject = "" + SubjectEmail; //tiko
  539.                   final String content = Utility.messageBD(conn, "AlertMailHead",
  540.                       targetUserClientLanguage) + "\n" + finalMessage;
  541.                   final String contentType = "text/plain; charset=utf-8";
  542.                   final List<File> attachments = null;
  543.                   final Date sentDate = new Date();
  544.                   final List<String> headerExtras = null;
  545.  
  546.                   final Object[] email = { host, auth, username, password, connSecurity, port,
  547.                       senderAddress, recipientTO, recipientCC, recipientBCC, replyTo, subject,
  548.                       content, contentType, attachments, sentDate, headerExtras };
  549.                   emailsToSendList.add(email);
  550.                 }
  551.               }
  552.             }
  553.           } catch (Exception e) {
  554.             throw new JobExecutionException(e.getMessage(), e);
  555.           } finally {
  556.             OBContext.restorePreviousMode();
  557.           }
  558.           // Send all the stored emails
  559.           for (Object[] emailToSend : emailsToSendList) {
  560.             try {
  561.               EmailManager.sendEmail((String) emailToSend[0],
  562.                   ((Boolean) emailToSend[1]).booleanValue(), (String) emailToSend[2],
  563.                   (String) emailToSend[3], (String) emailToSend[4],
  564.                   ((Number) emailToSend[5]).intValue(), (String) emailToSend[6],
  565.                   (String) emailToSend[7], (String) emailToSend[8], (String) emailToSend[9],
  566.                   (String) emailToSend[10], (String) emailToSend[11], (String) emailToSend[12],
  567.                   (String) emailToSend[13], (List<File>) emailToSend[14], (Date) emailToSend[15],
  568.                   (List<String>) emailToSend[16]);
  569.             } catch (Exception exception) {
  570.               log4j.error(exception);
  571.               final String exceptionClass = exception.getClass().toString().replace("class ", "");
  572.               String exceptionString = "Problems while sending the email" + exception;
  573.               exceptionString = exceptionString.replace(exceptionClass, "");
  574.               throw new ServletException(exceptionString);
  575.             }
  576.           }
  577.         } else {
  578.           // @Deprecated : This full "else" statement is deprecated from OB 3.0MP9. It happens only
  579.           // when there is an email configured directly in the AD_CLIENT (new way is configure it in
  580.           // C_POC_CONFIGURATION)
  581.           AlertProcessData[] mail = AlertProcessData.prepareMails(conn, alertRule.adAlertruleId);
  582.  
  583.           if (mail != null) {
  584.             for (int i = 0; i < mail.length; i++) {
  585.               String head = Utility.messageBD(conn, "AlertMailHead", mail[i].adLanguage) + "\n";
  586.               org.openbravo.erpCommon.businessUtility.EMail email = new org.openbravo.erpCommon.businessUtility.EMail(
  587.                   null, mail[i].smtphost, mail[i].mailfrom, mail[i].mailto, "[OB Alert] "
  588.                       + alertRule.name, head + msg);
  589.               String pwd = "";
  590.               try {
  591.                 pwd = FormatUtilities.encryptDecrypt(mail[i].requestuserpw, false);
  592.               } catch (Exception e) {
  593.                 logger
  594.                     .log("Error getting user password to send the mail: " + e.getMessage() + "\n");
  595.                 logger.log("Check email password settings in Client configuration.\n");
  596.                 continue;
  597.               }
  598.               if (!pwd.equals("")) {
  599.                 email.setEMailUser(mail[i].requestuser, pwd);
  600.                 if ("OK".equals(email.send())) {
  601.                   logger.log("Mail sent ok.");
  602.                 } else {
  603.                   logger.log("Error sending mail.");
  604.                 }
  605.               } else {
  606.                 logger
  607.                     .log("Sending email skipped. Check email password settings in Client configuration.\n");
  608.               }
  609.             }
  610.           }
  611.         }
  612.       }
  613.     }
  614.  
  615.     // Update
  616.     if (!alertRule.sql.equals("") && (alertRule.sql.toUpperCase().trim().startsWith("SELECT "))) {
  617.       try {
  618.         Integer count = AlertProcessData.updateAlert(conn, alertRule.adAlertruleId, alertRule.sql);
  619.         logger.log("updated alerts: " + count + "\n");
  620.  
  621.       } catch (Exception ex) {
  622.         logger.log("Error updating: " + ex.toString() + "\n");
  623.       }
  624.     }
  625.   }
  626.  
  627.   private void cobaCoba() {
  628.       //mencari ad tre id untuk product category
  629.       OBCriteria<ClientInformation> clientInfoCriteria = OBDal.getInstance().createCriteria(ClientInformation.class);
  630.       clientInfoCriteria.setFilterOnReadableClients(true);
  631.      
  632.       ClientInformation clientinfo = clientInfoCriteria.list().get(0);
  633.       Tree adTree = clientinfo.getPrimaryTreeProductCategory();
  634.      
  635.       //mendapatkan key dari sub category
  636.       String pcSubID = "9AEEE65DDCA94AB1941E6B402BE791B8"; //TODO ambil id sub product catagory melalui callout
  637.       ProductCategory pcSub = OBDal.getInstance().get(ProductCategory.class, pcSubID);
  638.       String subKey = pcSub.getSearchKey();
  639.      
  640.       //mendapatkan key dari main category
  641.       OBCriteria<TreeNode> treenodeCriteria = OBDal.getInstance().createCriteria(TreeNode.class);
  642.       treenodeCriteria.add(Restrictions.eq(TreeNode.PROPERTY_TREE, adTree));
  643.       treenodeCriteria.add(Restrictions.eq(TreeNode.PROPERTY_NODE, pcSubID));
  644.      
  645.       TreeNode treenode = treenodeCriteria.list().get(0);
  646.       String pcMainID = treenode.getReportSet();
  647.       if (pcMainID.equalsIgnoreCase("0"))
  648.           pcMainID=pcSubID;
  649.       ProductCategory pcMain = OBDal.getInstance().get(ProductCategory.class, pcMainID);
  650.       String mainKey = pcMain.getSearchKey();
  651.      
  652.       //mendapatkan nomor urut
  653.       String sql = "select count(*) as jumlahproduct" +
  654.             " from ad_treenode a" +
  655.             " inner join m_product b on b.m_product_category_id=a.node_id" +
  656.             " where a.parent_id=?" +
  657.             " and a.ad_tree_id=?";
  658.       Connection conn = OBDal.getInstance().getConnection();
  659.       try {
  660.           PreparedStatement ps = conn.prepareStatement(sql);
  661.           ps.setString(1, pcMainID);
  662.           ps.setString(2, adTree.getId());
  663.           ResultSet rs = ps.executeQuery();
  664.           int jumlahproduct=0;
  665.           while(rs.next()) {
  666.               jumlahproduct = rs.getInt("jumlahproduct");
  667.           }
  668.           jumlahproduct++;
  669.          
  670.           DecimalFormat myFormatter = new DecimalFormat("00000000");
  671.           String strJumlahProduct = myFormatter.format(jumlahproduct);
  672.          
  673.           String searchkey = "8"+mainKey+subKey+strJumlahProduct;
  674.          
  675.       } catch (SQLException e) {
  676.           // TODO Auto-generated catch block
  677.           e.printStackTrace();
  678.       }
  679.      
  680.      
  681.      
  682.   }
  683. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement