Advertisement
tko_pb

HttpSecureAppServlet

Nov 15th, 2018
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 59.05 KB | None | 0 0
  1. package org.openbravo.base.secureApp;
  2. /*
  3.  ************************************************************************************
  4.  * Copyright (C) 2001-2017 Openbravo S.L.U.
  5.  * Licensed under the Apache Software License version 2.0
  6.  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  7.  * Unless required by applicable law or agreed to  in writing,  software  distributed
  8.  * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
  9.  * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
  10.  * specific language governing permissions and limitations under the License.
  11.  ************************************************************************************
  12.  */
  13.  
  14.  
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. import java.io.PrintWriter;
  20. import java.text.DecimalFormat;
  21. import java.text.DecimalFormatSymbols;
  22. import java.util.HashMap;
  23. import java.util.Locale;
  24. import java.util.Map;
  25. import java.util.Properties;
  26. import java.util.UUID;
  27.  
  28. import javax.servlet.RequestDispatcher;
  29. import javax.servlet.ServletConfig;
  30. import javax.servlet.ServletException;
  31. import javax.servlet.ServletOutputStream;
  32. import javax.servlet.http.HttpServletRequest;
  33. import javax.servlet.http.HttpServletResponse;
  34. import javax.servlet.http.HttpSession;
  35.  
  36. import org.codehaus.jettison.json.JSONObject;
  37. import org.hibernate.criterion.Restrictions;
  38. import org.openbravo.authentication.AuthenticationException;
  39. import org.openbravo.authentication.AuthenticationManager;
  40. import org.openbravo.base.HttpBaseServlet;
  41. import org.openbravo.base.HttpBaseUtils;
  42. import org.openbravo.base.exception.OBException;
  43. import org.openbravo.base.secureApp.LoginUtils.RoleDefaults;
  44. import org.openbravo.base.session.OBPropertiesProvider;
  45. import org.openbravo.client.application.report.ReportingUtils;
  46. import org.openbravo.client.application.report.ReportingUtils.ExportType;
  47. import org.openbravo.client.kernel.RequestContext;
  48. import org.openbravo.dal.core.OBContext;
  49. import org.openbravo.dal.service.OBCriteria;
  50. import org.openbravo.dal.service.OBDal;
  51. import org.openbravo.data.FieldProvider;
  52. import org.openbravo.data.ScrollableFieldProvider;
  53. import org.openbravo.database.ConnectionProvider;
  54. import org.openbravo.database.SessionInfo;
  55. import org.openbravo.erpCommon.obps.ActivationKey;
  56. import org.openbravo.erpCommon.obps.ActivationKey.FeatureRestriction;
  57. import org.openbravo.erpCommon.obps.ActivationKey.LicenseRestriction;
  58. import org.openbravo.erpCommon.security.UsageAudit;
  59. import org.openbravo.erpCommon.utility.JRFieldProviderDataSource;
  60. import org.openbravo.erpCommon.utility.JRScrollableFieldProviderDataSource;
  61. import org.openbravo.erpCommon.utility.OBError;
  62. import org.openbravo.erpCommon.utility.OBMessageUtils;
  63. import org.openbravo.erpCommon.utility.PrintJRData;
  64. import org.openbravo.erpCommon.utility.Utility;
  65. import org.openbravo.model.ad.system.SystemInformation;
  66. import org.openbravo.model.ad.ui.Form;
  67. import org.openbravo.model.ad.ui.FormTrl;
  68. import org.openbravo.model.ad.ui.Process;
  69. import org.openbravo.model.ad.ui.ProcessTrl;
  70. import org.openbravo.model.ad.ui.Tab;
  71. import org.openbravo.model.ad.ui.WindowTrl;
  72. import org.openbravo.service.db.DalConnectionProvider;
  73. import org.openbravo.service.web.UserContextCache;
  74. import org.openbravo.utils.FileUtility;
  75. import org.openbravo.utils.Replace;
  76. import org.openbravo.xmlEngine.XmlDocument;
  77. import org.openbravo.base.secureApp.VariablesSecureApp;
  78.  
  79. import net.sf.jasperreports.engine.JRDataSource;
  80.  
  81. public class HttpSecureAppServlet extends HttpBaseServlet {
  82.   private static final long serialVersionUID = 1L;
  83.   protected boolean boolHist = true;
  84.   // String myTheme = "";
  85.   protected ClassInfoData classInfo;
  86.   private AuthenticationManager m_AuthManager = null;
  87.  
  88.   private String servletClass = this.getClass().getName();
  89.  
  90.   private class Variables extends VariablesHistory {
  91.     private String loggingIn;
  92.  
  93.     public Variables(HttpServletRequest request) {
  94.       super(request);
  95.       loggingIn = getSessionValue("#loggingIn");
  96.     }
  97.  
  98.     public void updateHistory(HttpServletRequest request) {
  99.       if (boolHist) {
  100.         String sufix = getCurrentHistoryIndex();
  101.         if (!(servletClass.equals(getSessionValue("reqHistory.servlet" + sufix, "")))) {
  102.           upCurrentHistoryIndex();
  103.           sufix = getCurrentHistoryIndex();
  104.           setSessionValue("reqHistory.servlet" + sufix, servletClass);
  105.           setSessionValue("reqHistory.path" + sufix, request.getServletPath());
  106.           setSessionValue("reqHistory.command" + sufix, "DEFAULT");
  107.         }
  108.       }
  109.     }
  110.  
  111.     public void setHistoryCommand(String strCommand) {
  112.       final String sufix = getCurrentHistoryIndex();
  113.       setSessionValue("reqHistory.command" + sufix, strCommand);
  114.     }
  115.  
  116.     // Note, see LoginUtils.fillSessionArguments which sets the loggingIn
  117.     // session var to N explicitly
  118.     public boolean isLoggingIn() {
  119.       return loggingIn == null || loggingIn.equals("") || loggingIn.equals("Y");
  120.     }
  121.   }
  122.  
  123.   @Override
  124.   public void init(ServletConfig config) {
  125.     super.init(config);
  126.  
  127.     m_AuthManager = AuthenticationManager.getAuthenticationManager(this);
  128.  
  129.     try {
  130.       log4j.debug("Initializing Servlet " + this.getClass());
  131.  
  132.       if (classInfo == null) {
  133.         // do not use DAL at this point: it's not guaranteed to be executed within a Servlet request
  134.         ClassInfoData[] classInfoAux = ClassInfoData.select(this, this.getClass().getName());
  135.         if (classInfoAux != null && classInfoAux.length > 0) {
  136.           classInfo = classInfoAux[0];
  137.         } else {
  138.           classInfoAux = ClassInfoData.set();
  139.           classInfo = classInfoAux[0];
  140.         }
  141.       }
  142.     } catch (final Exception ex) {
  143.       log4j.error("Error initializing Servlet " + this.getClass(), ex);
  144.       ClassInfoData[] classInfoAux;
  145.       try {
  146.         classInfoAux = ClassInfoData.set();
  147.         classInfo = classInfoAux[0];
  148.       } catch (ServletException e) {
  149.         log4j.error("Error initializing Servlet " + this.getClass(), ex);
  150.       }
  151.     }
  152.   }
  153.  
  154.   /**
  155.    * Sets information about the artifact the servlet is for. This method is called from generated
  156.    * 2.50 windows to set tab and module, before calling this init, so it is not needed to query
  157.    * database to retrieve this info.
  158.    *
  159.    */
  160.   protected void setClassInfo(String type, String id, String module) {
  161.     classInfo = new ClassInfoData();
  162.     classInfo.type = type;
  163.     classInfo.id = id;
  164.     classInfo.adModuleId = module;
  165.   }
  166.  
  167.   @Override
  168.   public void service(HttpServletRequest request, HttpServletResponse response) throws IOException,
  169.       ServletException {
  170.  
  171.     final boolean sessionExists = request.getSession(false) != null;
  172.  
  173.     AllowedCrossDomainsHandler.getInstance().setCORSHeaders(request, response);
  174.  
  175.     // don't process any further requests otherwise sessions are created for OPTIONS
  176.     // requests, the cors headers have already been set so can return
  177.     if (request.getMethod().equals("OPTIONS")) {
  178.       return;
  179.     }
  180.  
  181.     Variables variables = new Variables(request);
  182.  
  183.     // VariablesSecureApp vars = new VariablesSecureApp(request);
  184.  
  185.     // bdErrorGeneral(response, "Error", "No access");
  186.  
  187.     if (log4j.isDebugEnabled())
  188.       log4j.debug("class info type: " + classInfo.type + " - ID: " + classInfo.id);
  189.     String strAjax = "";
  190.     String strHidden = "";
  191.     String strPopUp = "";
  192.     try {
  193.       strAjax = request.getParameter("IsAjaxCall");
  194.     } catch (final Exception ignored) {
  195.     }
  196.     try {
  197.       strHidden = request.getParameter("IsHiddenCall");
  198.     } catch (final Exception ignored) {
  199.     }
  200.     try {
  201.       strPopUp = request.getParameter("IsPopUpCall");
  202.     } catch (final Exception ignored) {
  203.     }
  204.  
  205.     String strUserAuth;
  206.  
  207.     ConnectionProvider cp = new DalConnectionProvider(false);
  208.     try {
  209.  
  210.       OBContext.setAdminMode();
  211.  
  212.       strUserAuth = m_AuthManager.authenticate(request, response);
  213.       if (strUserAuth == null && request.getSession(false) != null
  214.           && "Y".equals(request.getSession().getAttribute("forceLogin"))) {
  215.         strUserAuth = "0";
  216.         variables.loggingIn = "Y";
  217.       }
  218.  
  219.       if (strUserAuth == null) {
  220.         if (AuthenticationManager.isStatelessRequest(request)) {
  221.           response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  222.         }
  223.         // auth-manager return null after redirecting to the login page -> stop request-processing
  224.         return;
  225.       }
  226.  
  227.       // if stateless then stop here, the remaining logic uses the httpsession
  228.       if (AuthenticationManager.isStatelessRequest(request)) {
  229.         if (areThereLicenseRestrictions(null)) {
  230.           throw new AuthenticationException("No valid license");
  231.         }
  232.         // make sure that there is an OBContext for the logged in user also in case of stateless
  233.         // requests
  234.         if (OBContext.getOBContext() == null
  235.             || !strUserAuth.equals(OBContext.getOBContext().getUser().getId())) {
  236.           OBContext.setOBContext(UserContextCache.getInstance().getCreateOBContext(strUserAuth));
  237.         }
  238.         super.serviceInitialized(request, response);
  239.         return;
  240.       }
  241.  
  242.       variables = new Variables(request); // Rebuild variable, auth-mgr could set the role
  243.  
  244.       boolean loggedOK = false;
  245.  
  246.       // NOTE !isLoggingIn assumes that the value of LoggingIn is N, this
  247.       // is done by the fillSessionArguments below
  248.       if (!variables.isLoggingIn()) {
  249.         // log in process is completed, check whether the session in db is still active
  250.         loggedOK = SeguridadData.loggedOK(cp, variables.getDBSession());
  251.         if (!loggedOK) {
  252.           if (request.getSession(false) != null
  253.               && "Y".equals(request.getSession().getAttribute("forceLogin"))) {
  254.             variables.loggingIn = "Y";
  255.             loggedOK = true;
  256.           } else {
  257.             logout(request, response);
  258.             return;
  259.           }
  260.         }
  261.       }
  262.  
  263.       if (strUserAuth != null) {
  264.         if (!loggedOK) {
  265.           String strLanguage = "";
  266.           String strIsRTL = "";
  267.           String strRole = "";
  268.           String strClient = "";
  269.           String strOrg = "";
  270.           String strWarehouse = "";
  271.  
  272.           SystemInformation sysInfo = OBDal.getInstance().get(SystemInformation.class, "0");
  273.           boolean correctSystemStatus = sysInfo.getSystemStatus() == null
  274.               || this.globalParameters.getOBProperty("safe.mode", "false")
  275.                   .equalsIgnoreCase("false") || sysInfo.getSystemStatus().equals("RB70");
  276.  
  277.           final VariablesSecureApp vars = new VariablesSecureApp(request, false);
  278.           boolean onlySystemAdminAvailable = "Y".equals(vars
  279.               .getSessionValue("onlySystemAdminRoleShouldBeAvailableInErp"));
  280.           // We check if there is a Openbravo Professional Subscription restriction in the license,
  281.           // or if the last rebuild didn't go well. If any of these are true, then the user is
  282.           // allowed to login only as system administrator
  283.           if (areThereLicenseRestrictions(variables.getDBSession()) || !correctSystemStatus
  284.               || onlySystemAdminAvailable) {
  285.             // it is only allowed to log as system administrator
  286.             strRole = DefaultOptionsData.getDefaultSystemRole(cp, strUserAuth);
  287.             if (strRole == null || strRole.equals("")) {
  288.               final OBError roleError = new OBError();
  289.               roleError.setType("Error");
  290.               roleError.setMessage(Utility.messageBD(cp, "SystemLoginRequired",
  291.                   variables.getLanguage()));
  292.               invalidLogin(request, response, roleError);
  293.  
  294.               return;
  295.             }
  296.             strClient = "0";
  297.             strOrg = "0";
  298.             strWarehouse = "";
  299.           } else {
  300.             RoleDefaults defaults = LoginUtils.getLoginDefaults(strUserAuth, variables.getRole(),
  301.                 cp);
  302.             strRole = defaults.role;
  303.             strClient = defaults.client;
  304.             strOrg = defaults.org;
  305.             strWarehouse = defaults.warehouse;
  306.           }
  307.  
  308.           DefaultOptionsData dataLanguage[] = DefaultOptionsData.defaultLanguage(cp, strUserAuth);
  309.           if (dataLanguage != null && dataLanguage.length > 0) {
  310.             strLanguage = dataLanguage[0].getField("DEFAULT_AD_LANGUAGE");
  311.             strIsRTL = dataLanguage[0].getField("ISRTL");
  312.           }
  313.           if (strLanguage == null || strLanguage.equals("")) {
  314.             dataLanguage = DefaultOptionsData.getDefaultLanguage(cp);
  315.             if (dataLanguage != null && dataLanguage.length > 0) {
  316.               strLanguage = dataLanguage[0].getField("AD_LANGUAGE");
  317.               strIsRTL = dataLanguage[0].getField("ISRTL");
  318.             }
  319.           }
  320.  
  321.           // note fill session arguments will set the LOGGINGIN session var
  322.           // to N
  323.           if (LoginUtils.fillSessionArguments(cp, vars, strUserAuth, strLanguage, strIsRTL,
  324.               strRole, strClient, strOrg, strWarehouse)) {
  325.             readProperties(vars);
  326.             readNumberFormat(vars, globalParameters.getFormatPath());
  327.             LoginUtils.saveLoginBD(request, vars, "0", "0");
  328.           } else {
  329.             // Re-login
  330.             log4j.error("Unable to fill session Arguments for: " + strUserAuth);
  331.             logout(request, response);
  332.             return;
  333.           }
  334.  
  335.           // Login process if finished, set the flag as not logging in
  336.           // this flag may not be removed from the session, it must be set
  337.           // to N to prevent re-initializing the session continuously
  338.           vars.setSessionValue("#loggingIn", "N");
  339.         } else {
  340.           variables.updateHistory(request);
  341.         }
  342.       }
  343.       if (log4j.isDebugEnabled()) {
  344.         log4j.debug("Call to HttpBaseServlet.service");
  345.       }
  346.     } catch (final DefaultValidationException d) {
  347.       // Added DefaultValidationException class to catch user login
  348.       // without a valid role
  349.  
  350.       String title = Utility.messageBD(myPool, "InvalidDefaultLoginTitle", variables.getLanguage())
  351.           .replace("%0", d.getDefaultField());
  352.       String msg = Utility.messageBD(myPool, "InvalidDefaultLoginMsg", variables.getLanguage())
  353.           .replace("%0", d.getDefaultField());
  354.       final OBError roleError = new OBError();
  355.       roleError.setTitle(title);
  356.       roleError.setType("Error");
  357.       roleError.setMessage(msg);
  358.       invalidLogin(request, response, roleError);
  359.       return;
  360.     } catch (final IllegalStateException ise) {
  361.       log4j.error("HTTPSecureAppServlet.service() - exception caught: ", ise);
  362.       invalidateSession(request);
  363.       return;
  364.     } catch (final Exception e) {
  365.       // Re-login
  366.       log4j.error("HTTPSecureAppServlet.service() - exception caught: ", e);
  367.       logout(request, response);
  368.       return;
  369.     } finally {
  370.       final boolean sessionCreated = !sessionExists && null != request.getSession(false);
  371.       if (AuthenticationManager.isStatelessRequest(request) && sessionCreated) {
  372.         log4j.warn("Stateless request, still a session was created " + request.getRequestURL()
  373.             + " " + request.getQueryString());
  374.       }
  375.       OBContext.restorePreviousMode();
  376.     }
  377.  
  378.     try {
  379.  
  380.       super.initialize(request, response);
  381.       final VariablesSecureApp vars1 = new VariablesSecureApp(request, false);
  382.  
  383.       SessionInfo.setUserId(strUserAuth);
  384.       SessionInfo.setSessionId(vars1.getSessionValue("#AD_Session_ID"));
  385.  
  386.       // Hack to know whether the servlet is a poup. strPopup cannot be used because it indicates in
  387.       // has been called from a popup.
  388.       boolean isPopup = vars1.getCommand().indexOf("BUTTON") != -1
  389.           || vars1.getCommand().indexOf("POPUP") != -1
  390.           || !vars1.getStringParameter("inpProcessId").equals("");
  391.  
  392.       FeatureRestriction featureRestriction = ActivationKey.getInstance().hasLicenseAccess(
  393.           classInfo.type, classInfo.id);
  394.       if (featureRestriction != FeatureRestriction.NO_RESTRICTION) {
  395.         licenseError(classInfo.type, classInfo.id, featureRestriction, response, request, vars1,
  396.             isPopup);
  397.       } else if (vars1.getRole().equals("") || hasAccess(vars1)) {
  398.  
  399.         if (classInfo.id != null && !classInfo.id.equals("") && SessionInfo.getProcessId() == null) {
  400.           // Set process id in session in case there is info for that and it has not been already
  401.           // set by the Servlet itself
  402.           SessionInfo.setProcessId(classInfo.id);
  403.           SessionInfo.setProcessType(classInfo.type);
  404.           SessionInfo.setModuleId(classInfo.adModuleId);
  405.         }
  406.  
  407.         if (SessionInfo.getCommand() == null) {
  408.           // Set command based on vars if it has not explicitly set
  409.           SessionInfo.setCommand(vars1.getCommand());
  410.         }
  411.  
  412.         // Autosave logic
  413.         final Boolean saveRequest = (Boolean) request.getAttribute("autosave");
  414.         final String strTabId = vars1.getStringParameter("inpTabId");
  415.  
  416.         if (saveRequest == null && strTabId != null) {
  417.  
  418.           final String autoSave = request.getParameter("autosave");
  419.           Boolean failedAutosave = (Boolean) vars1.getSessionObject(strTabId + "|failedAutosave");
  420.  
  421.           if (failedAutosave == null) {
  422.             failedAutosave = false;
  423.           }
  424.  
  425.           if (autoSave != null && autoSave.equalsIgnoreCase("Y") && !failedAutosave) {
  426.  
  427.             if (log4j.isDebugEnabled()) {
  428.               log4j.debug("service: saveRequest - " + this.getClass().getCanonicalName()
  429.                   + " - autosave: " + autoSave);
  430.             }
  431.  
  432.             if (log4j.isDebugEnabled()) {
  433.               log4j.debug(this.getClass().getCanonicalName() + " - hash: "
  434.                   + vars1.getPostDataHash());
  435.             }
  436.  
  437.             final String servletMappingName = request.getParameter("mappingName");
  438.  
  439.             if (servletMappingName != null
  440.                 && !Utility.isExcludedFromAutoSave(this.getClass().getCanonicalName())
  441.                 && !vars1.commandIn("DIRECT")) {
  442.  
  443.               final String hash = vars1.getSessionValue(servletMappingName + "|hash");
  444.  
  445.               if (log4j.isDebugEnabled()) {
  446.                 log4j.debug("hash in session: " + hash);
  447.               }
  448.               // Check if the form was previously saved based on
  449.               // the hash of the post data
  450.               if (!hash.equals(vars1.getPostDataHash())) {
  451.                 request.setAttribute("autosave", true);
  452.                 if (isPopup)
  453.                   // Adding pop-up window attribute to close the window on failed auto-save
  454.                   request.setAttribute("popupWindow", true);
  455.                 // forward request
  456.                 if (!forwardRequest(request, response)) {
  457.                   return; // failed save
  458.                 }
  459.               }
  460.             }
  461.           }
  462.         }
  463.         long t = System.currentTimeMillis();
  464.         super.serviceInitialized(request, response);
  465.         UsageAudit.auditActionNoDal(cp, vars1, this.getClass().getName(),
  466.             System.currentTimeMillis() - t);
  467.       } else {
  468.         if ((strPopUp != null && !strPopUp.equals("")) || classInfo.type.equals("S")) {
  469.           bdErrorGeneralPopUp(request, response,
  470.               Utility.messageBD(this, "Error", variables.getLanguage()),
  471.               Utility.messageBD(this, "AccessTableNoView", variables.getLanguage()));
  472.         } else {
  473.           bdError(request, response, "AccessTableNoView", vars1.getLanguage());
  474.         }
  475.         String roleStr = "".equals(vars1.getRole()) ? "" : " (" + vars1.getRole() + ")";
  476.         log4j
  477.             .warn("Role" + roleStr + " tried to access ungranted resource with ID " + classInfo.id);
  478.       }
  479.     } catch (final ServletException ex) {
  480.       log4j.error("Error captured: ", ex);
  481.       final VariablesSecureApp vars1 = new VariablesSecureApp(request, false);
  482.       final OBError myError = Utility.translateError(this, vars1, variables.getLanguage(),
  483.           ex.getMessage());
  484.       if (strAjax != null && !strAjax.equals(""))
  485.         bdErrorAjax(response, myError.getType(), myError.getTitle(), myError.getMessage());
  486.       else if (strHidden != null && !strHidden.equals(""))
  487.         bdErrorHidden(response, myError.getType(), myError.getTitle(), myError.getMessage());
  488.       else if (!myError.isConnectionAvailable())
  489.         bdErrorConnection(response);
  490.       else if (strPopUp != null && !strPopUp.equals(""))
  491.         bdErrorGeneralPopUp(request, response, myError.getTitle(), myError.getMessage());
  492.       else
  493.         bdErrorGeneral(request, response, myError.getTitle(), myError.getMessage());
  494.     } catch (final OBException e) {
  495.       final Boolean isAutosaving = (Boolean) request.getAttribute("autosave");
  496.       if (isAutosaving != null && isAutosaving) {
  497.         request.removeAttribute("autosave");
  498.         request.removeAttribute("popupWindow");
  499.         throw e;
  500.       } else {
  501.         log4j.error("Error captured: ", e);
  502.         if (strPopUp != null && !strPopUp.equals(""))
  503.           bdErrorGeneralPopUp(request, response, "Error", e.toString());
  504.         else
  505.           bdErrorGeneral(request, response, "Error", e.toString());
  506.       }
  507.     } catch (final Exception e) {
  508.       log4j.error("Error captured: ", e);
  509.       if (strPopUp != null && !strPopUp.equals(""))
  510.         bdErrorGeneralPopUp(request, response, "Error", e.toString());
  511.       else
  512.         bdErrorGeneral(request, response, "Error", e.toString());
  513.     }
  514.   }
  515.  
  516.   // We check if there is a Openbravo Professional Subscription restriction in the license,
  517.   // or if the last rebuild didn't go well. If any of these are true, then the user is
  518.   // allowed to login only as system administrator
  519.   private boolean areThereLicenseRestrictions(String sessionId) {
  520.     LicenseRestriction limitation = ActivationKey.getInstance().checkOPSLimitations(sessionId);
  521.     return limitation == LicenseRestriction.OPS_INSTANCE_NOT_ACTIVE
  522.         || limitation == LicenseRestriction.NUMBER_OF_CONCURRENT_USERS_REACHED
  523.         || limitation == LicenseRestriction.MODULE_EXPIRED
  524.         || limitation == LicenseRestriction.NOT_MATCHED_INSTANCE
  525.         || limitation == LicenseRestriction.HB_NOT_ACTIVE
  526.         || limitation == LicenseRestriction.ON_DEMAND_OFF_PLATFORM
  527.         || limitation == LicenseRestriction.POS_TERMINALS_EXCEEDED;
  528.   }
  529.  
  530.   /**
  531.    * Cheks access passing all the parameters
  532.    *
  533.    * @param vars
  534.    * @param type
  535.    *          type of element
  536.    * @param id
  537.    *          id for the element
  538.    * @return true in case it has access false if not
  539.    */
  540.   protected boolean hasGeneralAccess(VariablesSecureApp vars, String type, String id) {
  541.     try {
  542.       ConnectionProvider cp = new DalConnectionProvider(false);
  543.       final String accessLevel = SeguridadData.selectAccessLevel(cp, type, id);
  544.       vars.setSessionValue("#CurrentAccessLevel", accessLevel);
  545.       if (type.equals("W")) {
  546.         return hasLevelAccess(vars, accessLevel)
  547.             && SeguridadData.selectAccess(cp, vars.getRole(), "TABLE", id).equals("0")
  548.             && !SeguridadData.selectAccess(cp, vars.getRole(), type, id).equals("0");
  549.       } else if (type.equals("S")) {
  550.         return !SeguridadData.selectAccessSearch(cp, vars.getRole(), id).equals("0");
  551.       } else if (type.equals("C"))
  552.         return true;
  553.       else
  554.         return hasLevelAccess(vars, accessLevel)
  555.             && !SeguridadData.selectAccess(cp, vars.getRole(), type, id).equals("0");
  556.     } catch (final Exception e) {
  557.       log4j.error("Error checking access: ", e);
  558.       return false;
  559.     }
  560.  
  561.   }
  562.  
  563.   /**
  564.    * Checks if the user has access to the window
  565.    * */
  566.   private boolean hasAccess(VariablesSecureApp vars) {
  567.     try {
  568.       if (classInfo == null || classInfo.id.equals("") || classInfo.type.equals(""))
  569.         return true;
  570.       return hasGeneralAccess(vars, classInfo.type, classInfo.id);
  571.  
  572.     } catch (final Exception e) {
  573.       log4j.error("Error checking access: ", e);
  574.       return false;
  575.     }
  576.   }
  577.  
  578.   /**
  579.    * Checks if the level access is correct.
  580.    *
  581.    */
  582.   private boolean hasLevelAccess(VariablesSecureApp vars, String accessLevel) {
  583.     if (!OBContext.getOBContext().doAccessLevelCheck()) {
  584.       return true;
  585.     }
  586.  
  587.     final String userLevel = vars.getSessionValue("#User_Level");
  588.  
  589.     boolean retValue = true;
  590.  
  591.     // NOTE: if the logic here changes then also the logic in the
  592.     // EntityAccessChecker.hasCorrectAccessLevel needs to be updated
  593.     // Centralizing the logic seemed difficult because of build dependencies
  594.     if (accessLevel.equals("4") && userLevel.indexOf("S") == -1)
  595.       retValue = false;
  596.     else if (accessLevel.equals("1") && userLevel.indexOf("O") == -1)
  597.       retValue = false;
  598.     else if (accessLevel.equals("3")
  599.         && (!(userLevel.indexOf("C") != -1 || userLevel.indexOf("O") != -1)))
  600.       retValue = false;
  601.     else if (accessLevel.equals("6")
  602.         && (!(userLevel.indexOf("S") != -1 || userLevel.indexOf("C") != -1)))
  603.       retValue = false;
  604.  
  605.     return retValue;
  606.   }
  607.  
  608.   protected void logout(HttpServletRequest request, HttpServletResponse response)
  609.       throws IOException, ServletException {
  610.  
  611.     invalidateSession(request);
  612.  
  613.     // reset the obcontext
  614.     OBContext.setOBContext((OBContext) null);
  615.  
  616.     m_AuthManager.logout(request, response);
  617.   }
  618.  
  619.   protected void invalidateSession(HttpServletRequest request) {
  620.     HttpSession session = request.getSession(false);
  621.     if (session != null) {
  622.       // finally invalidate the session (this event will be caught by the session listener
  623.       session.invalidate();
  624.     }
  625.   }
  626.  
  627.   /**
  628.    * Logs the user out of the application, clears the session and returns the HTMLErrorLogin page
  629.    * with the relevant error message passed into the method.
  630.    *
  631.    * @param request
  632.    * @param response
  633.    * @param error
  634.    * @throws IOException
  635.    * @throws ServletException
  636.    */
  637.   private void invalidLogin(HttpServletRequest request, HttpServletResponse response, OBError error)
  638.       throws IOException, ServletException {
  639.  
  640.     HttpSession session = request.getSession(false);
  641.     if (session != null) {
  642.       // finally invalidate the session (this event will be caught by the session listener
  643.       session.invalidate();
  644.     }
  645.     OBContext.setOBContext((OBContext) null);
  646.  
  647.     String discard[] = { "continueButton" };
  648.  
  649.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  650.         "org/openbravo/base/secureApp/HtmlErrorLogin", discard).createXmlDocument();
  651.  
  652.     xmlDocument.setParameter("messageType", error.getType());
  653.     xmlDocument.setParameter("messageTitle", error.getTitle());
  654.     xmlDocument.setParameter("messageMessage", error.getMessage());
  655.  
  656.     response.setContentType("text/html");
  657.     final PrintWriter out = response.getWriter();
  658.     out.println(xmlDocument.print());
  659.     out.close();
  660.  
  661.   }
  662.  
  663.   protected void setHistoryCommand(HttpServletRequest request, String strCommand) {
  664.     final Variables vars = new Variables(request);
  665.     vars.setHistoryCommand(strCommand);
  666.   }
  667.  
  668.   protected void advise(HttpServletRequest request, HttpServletResponse response, String strTipo,
  669.       String strTitulo, String strTexto) throws IOException {
  670.  
  671.     String myTheme;
  672.     if (request != null)
  673.       myTheme = new Variables(request).getSessionValue("#Theme");
  674.     else
  675.       myTheme = "Default";
  676.  
  677.     final XmlDocument xmlDocument = xmlEngine
  678.         .readXmlTemplate("org/openbravo/base/secureApp/Advise").createXmlDocument();
  679.  
  680.     xmlDocument.setParameter("theme", myTheme);
  681.     xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
  682.     xmlDocument.setParameter("ParamTitulo", strTitulo);
  683.     xmlDocument.setParameter("ParamTexto", strTexto);
  684.     response.setContentType("text/html; charset=UTF-8");
  685.     final PrintWriter out = response.getWriter();
  686.     out.println(xmlDocument.print());
  687.     out.close();
  688.   }
  689.  
  690.   protected void advisePopUp(HttpServletRequest request, HttpServletResponse response,
  691.       String strTitulo, String strTexto) throws IOException {
  692.     advisePopUp(request, response, "Error", strTitulo, strTexto);
  693.   }
  694.  
  695.   protected void advisePopUp(HttpServletRequest request, HttpServletResponse response,
  696.       String strTipo, String strTitulo, String strTexto) throws IOException {
  697.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  698.         "org/openbravo/base/secureApp/AdvisePopUp").createXmlDocument();
  699.  
  700.     String myTheme;
  701.     if (request != null)
  702.       myTheme = new Variables(request).getSessionValue("#Theme");
  703.     else
  704.       myTheme = "Default";
  705.     xmlDocument.setParameter("theme", myTheme);
  706.     xmlDocument.setParameter("PopupTitle",
  707.         OBMessageUtils.getI18NMessage("OBUIAPP_" + strTipo, null));
  708.     xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
  709.     xmlDocument.setParameter("ParamTitulo", strTitulo);
  710.     xmlDocument.setParameter("ParamTexto", strTexto);
  711.     response.setContentType("text/html; charset=UTF-8");
  712.     final PrintWriter out = response.getWriter();
  713.     out.println(xmlDocument.print());
  714.     out.close();
  715.   }
  716.  
  717.   /**
  718.    * Creates a pop up that when closed, will refresh the parent window.
  719.    *
  720.    * @param response
  721.    *          the HttpServletResponse object
  722.    * @param strType
  723.    *          the type of message to be displayed (e.g. ERROR, SUCCESS)
  724.    * @param strTitle
  725.    *          the title of the popup window
  726.    * @param strText
  727.    *          the text to be displayed in the popup message area
  728.    * @throws IOException
  729.    *           if an error occurs writing to the output stream
  730.    */
  731.   protected void advisePopUpRefresh(HttpServletRequest request, HttpServletResponse response,
  732.       String strType, String strTitle, String strText) throws IOException {
  733.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  734.         "org/openbravo/base/secureApp/AdvisePopUpRefresh").createXmlDocument();
  735.  
  736.     String myTheme;
  737.     if (request != null)
  738.       myTheme = new Variables(request).getSessionValue("#Theme");
  739.     else
  740.       myTheme = "Default";
  741.  
  742.     xmlDocument.setParameter("theme", myTheme);
  743.     xmlDocument.setParameter("ParamType", strType.toUpperCase());
  744.     xmlDocument.setParameter("ParamTitle", strTitle);
  745.     xmlDocument.setParameter("ParamText", strText);
  746.     response.setContentType("text/html; charset=UTF-8");
  747.     final PrintWriter out = response.getWriter();
  748.     out.println(xmlDocument.print());
  749.     out.close();
  750.   }
  751.  
  752.   protected void bdError(HttpServletRequest request, HttpServletResponse response, String strCode,
  753.       String strLanguage) throws IOException {
  754.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error")
  755.         .createXmlDocument();
  756.  
  757.     String myTheme;
  758.     if (request != null)
  759.       myTheme = new Variables(request).getSessionValue("#Theme");
  760.     else
  761.       myTheme = "Default";
  762.  
  763.     xmlDocument.setParameter("theme", myTheme);
  764.     xmlDocument.setParameter("ParamTitulo", strCode);
  765.     xmlDocument.setParameter("ParamTexto", Utility.messageBD(this, strCode, strLanguage));
  766.     response.setContentType("text/html; charset=UTF-8");
  767.     final PrintWriter out = response.getWriter();
  768.     out.println(xmlDocument.print());
  769.     out.close();
  770.   }
  771.  
  772.   protected void bdErrorGeneralPopUp(HttpServletRequest request, HttpServletResponse response,
  773.       String strTitle, String strText) throws IOException {
  774.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  775.         "org/openbravo/base/secureApp/ErrorPopUp").createXmlDocument();
  776.  
  777.     String myTheme;
  778.     if (request != null)
  779.       myTheme = new Variables(request).getSessionValue("#Theme");
  780.     else
  781.       myTheme = "Default";
  782.  
  783.     xmlDocument.setParameter("theme", myTheme);
  784.     xmlDocument.setParameter("ParamTipo", "ERROR");
  785.     xmlDocument.setParameter("ParamTitulo", strTitle);
  786.     xmlDocument.setParameter("ParamTexto", strText);
  787.     response.setContentType("text/html; charset=UTF-8");
  788.     final PrintWriter out = response.getWriter();
  789.     out.println(xmlDocument.print());
  790.     out.close();
  791.   }
  792.  
  793.   private void bdErrorGeneral(HttpServletRequest request, HttpServletResponse response,
  794.       String strTitle, String strText) throws IOException {
  795.     String discard[] = { "" };
  796.     if (OBContext.getOBContext().isNewUI()) {
  797.       discard[0] = "backButton";
  798.     }
  799.  
  800.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error",
  801.         discard).createXmlDocument();
  802.  
  803.     String myTheme;
  804.     if (request != null)
  805.       myTheme = new Variables(request).getSessionValue("#Theme");
  806.     else
  807.       myTheme = "Default";
  808.  
  809.     xmlDocument.setParameter("theme", myTheme);
  810.     xmlDocument.setParameter("ParamTitulo", strTitle);
  811.     xmlDocument.setParameter("ParamTexto", strText);
  812.  
  813.     response.setContentType("text/html; charset=UTF-8");
  814.     final PrintWriter out = response.getWriter();
  815.     out.println(xmlDocument.print());
  816.     out.close();
  817.   }
  818.  
  819.   protected void bdErrorConnection(HttpServletResponse response) throws IOException {
  820.     if (log4j.isDebugEnabled())
  821.       log4j.debug("Output: Error connection");
  822.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  823.         "org/openbravo/base/secureApp/ErrorConnection").createXmlDocument();
  824.  
  825.     response.setContentType("text/html; charset=UTF-8");
  826.     final PrintWriter out = response.getWriter();
  827.     out.println(xmlDocument.print());
  828.     out.close();
  829.   }
  830.  
  831.   protected void bdErrorAjax(HttpServletResponse response, String strType, String strTitle,
  832.       String strText) throws IOException {
  833.     response.setContentType("text/xml; charset=UTF-8");
  834.     final PrintWriter out = response.getWriter();
  835.     out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
  836.     out.println("<xml-structure>\n");
  837.     out.println("  <status>\n");
  838.     out.println("    <type>" + strType + "</type>\n");
  839.     out.println("    <title>" + strTitle + "</title>\n");
  840.     out.println("    <description><![CDATA[" + strText + "]]></description>\n");
  841.     out.println("  </status>\n");
  842.     out.println("</xml-structure>\n");
  843.     out.close();
  844.   }
  845.  
  846.   protected void bdErrorHidden(HttpServletResponse response, String strType, String strTitle,
  847.       String strText) throws IOException {
  848.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  849.         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
  850.  
  851.     final StringBuffer resultado = new StringBuffer();
  852.     resultado.append("var calloutName='';\n\n");
  853.     resultado.append("var respuesta = new Array(\n");
  854.  
  855.     resultado.append("new Array(\"MESSAGE\", \"");
  856.     resultado.append(strText);
  857.     resultado.append("\")");
  858.     resultado.append("\n);");
  859.  
  860.     xmlDocument.setParameter("array", resultado.toString());
  861.     response.setContentType("text/html; charset=UTF-8");
  862.     final PrintWriter out = response.getWriter();
  863.     out.println(xmlDocument.print());
  864.     out.close();
  865.   }
  866.  
  867.   protected void pageError(HttpServletResponse response) throws IOException {
  868.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  869.         "org/openbravo/base/secureApp/HtmlError").createXmlDocument();
  870.  
  871.     response.setContentType("text/html; charset=UTF-8");
  872.     final PrintWriter out = response.getWriter();
  873.     out.println(xmlDocument.print());
  874.     out.close();
  875.   }
  876.  
  877.   protected void pageErrorPopUp(HttpServletResponse response) throws IOException {
  878.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  879.         "org/openbravo/base/secureApp/HtmlErrorPopUp").createXmlDocument();
  880.  
  881.     response.setContentType("text/html; charset=UTF-8");
  882.     final PrintWriter out = response.getWriter();
  883.     out.println(xmlDocument.print());
  884.     out.close();
  885.   }
  886.  
  887.   protected void whitePage(HttpServletResponse response) throws IOException {
  888.     whitePage(response, "");
  889.   }
  890.  
  891.   protected void licenseError(String type, String id, FeatureRestriction featureRestriction,
  892.       HttpServletResponse response, HttpServletRequest request, VariablesSecureApp vars,
  893.       boolean isPopup) throws IOException {
  894.     String titleText = getArtifactName(type, id, vars.getLanguage());
  895.     String infoText = "";
  896.  
  897.     String editionType = null;
  898.     String completeWindowMsg = "";
  899.     String discard[] = { "" };
  900.     String msg;
  901.  
  902.     switch (featureRestriction) {
  903.     case TIER1_RESTRICTION:
  904.       editionType = "OBPSAnyEdition";
  905.       // do not break continue with next tier restriction
  906.     case TIER2_RESTRICTION:
  907.       if (editionType == null) {
  908.         editionType = "OBPSStandardEdition";
  909.       }
  910.       // <p> in java, to allow multi-paragraph text via the parameter
  911.       infoText = "<p>"
  912.           + Utility.messageBD(this, "FEATURE_OBPS_ONLY", vars.getLanguage())
  913.               .replace("@ProfessionalEditionType@",
  914.                   Utility.messageBD(this, editionType, vars.getLanguage())) + "</p>";
  915.       completeWindowMsg = infoText + "\n"
  916.           + Utility.messageBD(this, "LearnHowToActivate", vars.getLanguage());
  917.       break;
  918.     case GOLDEN_RESTRICTION:
  919.       discard[0] = "links";
  920.       msg = Utility.messageBD(this, "OBPSGoldenKeyRestricted", vars.getLanguage());
  921.       infoText = msg;
  922.       completeWindowMsg = msg;
  923.       break;
  924.     case DISABLED_MODULE_RESTRICTION:
  925.       discard[0] = "links";
  926.       msg = Utility.messageBD(this, "FeatureInDisabledModule", vars.getLanguage());
  927.       infoText = msg;
  928.       completeWindowMsg = msg;
  929.       break;
  930.     default:
  931.       break;
  932.     }
  933.  
  934.     String linkText = Utility.messageBD(this, "LEARN_HOW", vars.getLanguage());
  935.     String afterLinkText = Utility.messageBD(this, "ACTIVATE_INSTANCE", vars.getLanguage());
  936.  
  937.     if (isPopup) {
  938.       XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  939.           "org/openbravo/erpCommon/obps/ErrorActivatedInstancesOnly", discard).createXmlDocument();
  940.  
  941.       xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
  942.       xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
  943.       xmlDocument.setParameter("theme", vars.getTheme());
  944.       xmlDocument.setParameter("titleText", titleText);
  945.       xmlDocument.setParameter("infoText", infoText);
  946.       xmlDocument.setParameter("linkText", linkText);
  947.       xmlDocument.setParameter("afterLinkText", afterLinkText);
  948.  
  949.       response.setContentType("text/html; charset=UTF-8");
  950.       PrintWriter out = response.getWriter();
  951.       out.println(xmlDocument.print());
  952.       out.close();
  953.     } else {
  954.       bdErrorGeneral(request, response, titleText, completeWindowMsg);
  955.     }
  956.   }
  957.  
  958.   private String getArtifactName(String type, String id, String language) {
  959.     OBContext.setAdminMode();
  960.     try {
  961.       if ("W".equals(type)) {
  962.         Tab tab = OBDal.getInstance().get(Tab.class, id);
  963.         if (tab != null) {
  964.           OBCriteria<WindowTrl> qtTrl = OBDal.getInstance().createCriteria(WindowTrl.class);
  965.           qtTrl.add(Restrictions.eq(WindowTrl.PROPERTY_WINDOW, tab.getWindow()));
  966.           qtTrl.add(Restrictions.eq(WindowTrl.PROPERTY_LANGUAGE + ".language", language));
  967.           if (qtTrl.list().size() != 0) {
  968.             return qtTrl.list().get(0).getName();
  969.           } else {
  970.             return tab.getWindow().getName();
  971.           }
  972.         }
  973.       } else if ("X".equals(type)) {
  974.         OBCriteria<FormTrl> qfTrl = OBDal.getInstance().createCriteria(FormTrl.class);
  975.         qfTrl.add(Restrictions.eq(FormTrl.PROPERTY_SPECIALFORM + ".id", id));
  976.         qfTrl.add(Restrictions.eq(FormTrl.PROPERTY_LANGUAGE + ".language", language));
  977.         if (qfTrl.list().size() != 0) {
  978.           return qfTrl.list().get(0).getName();
  979.         }
  980.  
  981.         Form f = OBDal.getInstance().get(Form.class, id);
  982.         if (f != null) {
  983.           return f.getName();
  984.         }
  985.       } else if ("R".endsWith(type) || "P".equals(type)) {
  986.         OBCriteria<ProcessTrl> qfTrl = OBDal.getInstance().createCriteria(ProcessTrl.class);
  987.         qfTrl.add(Restrictions.eq(ProcessTrl.PROPERTY_PROCESS + ".id", id));
  988.         qfTrl.add(Restrictions.eq(ProcessTrl.PROPERTY_LANGUAGE + ".language", language));
  989.         if (qfTrl.list().size() != 0) {
  990.           return qfTrl.list().get(0).getName();
  991.         }
  992.  
  993.         Process f = OBDal.getInstance().get(Process.class, id);
  994.         if (f != null) {
  995.           return f.getName();
  996.         }
  997.       }
  998.     } finally {
  999.       OBContext.restorePreviousMode();
  1000.     }
  1001.     return "";
  1002.   }
  1003.  
  1004.   protected void whitePage(HttpServletResponse response, String strAlert) throws IOException {
  1005.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1006.         "org/openbravo/base/secureApp/HtmlWhitePage").createXmlDocument();
  1007.  
  1008.     xmlDocument.setParameter("body", strAlert == null ? "" : strAlert);
  1009.  
  1010.     response.setContentType("text/html; charset=UTF-8");
  1011.     final PrintWriter out = response.getWriter();
  1012.     out.println(xmlDocument.print());
  1013.     out.close();
  1014.   }
  1015.  
  1016.   protected void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars,
  1017.       String path) throws IOException, ServletException {
  1018.     if (log4j.isDebugEnabled())
  1019.       log4j.debug("Output: PopUp Response");
  1020.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1021.         "org/openbravo/base/secureApp/PopUp_Response").createXmlDocument();
  1022.  
  1023.     xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
  1024.     xmlDocument.setParameter("href", path.equals("") ? "null" : "'" + path + "'");
  1025.     response.setContentType("text/html; charset=UTF-8");
  1026.     final PrintWriter out = response.getWriter();
  1027.     out.println(xmlDocument.print());
  1028.     out.close();
  1029.   }
  1030.  
  1031.   protected void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars,
  1032.       String path, String tabTitle) throws IOException, ServletException {
  1033.     if (log4j.isDebugEnabled())
  1034.       log4j.debug("Output: PopUp Response");
  1035.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1036.         "org/openbravo/base/secureApp/PopUp_Response").createXmlDocument();
  1037.     JSONObject js = new JSONObject();
  1038.     try {
  1039.       js.put("tabTitle", tabTitle);
  1040.       js.put("addToRecents", false);
  1041.     } catch (Exception e) {
  1042.       js = null;
  1043.     }
  1044.     xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
  1045.     xmlDocument.setParameter("href", path.equals("") ? "null" : "'" + path + "'");
  1046.     xmlDocument.setParameter("details", js == null ? "var newTabParams={};" : "var newTabParams="
  1047.         + js.toString() + ";");
  1048.     response.setContentType("text/html; charset=UTF-8");
  1049.     final PrintWriter out = response.getWriter();
  1050.     out.println(xmlDocument.print());
  1051.     out.close();
  1052.   }
  1053.  
  1054.   protected void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars)
  1055.       throws IOException, ServletException {
  1056.     printPageClosePopUp(response, vars, "");
  1057.   }
  1058.  
  1059.   protected void printPagePopUpDownload(ServletOutputStream os, String fileName)
  1060.       throws IOException, ServletException {
  1061.     if (log4j.isDebugEnabled())
  1062.       log4j.debug("Output: PopUp Download");
  1063.     String href = strDireccion + "/utility/DownloadReport.html?report=" + fileName;
  1064.     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1065.         "org/openbravo/base/secureApp/PopUp_Download").createXmlDocument();
  1066.     xmlDocument.setParameter("href", href);
  1067.     os.println(xmlDocument.print());
  1068.     os.close();
  1069.   }
  1070.  
  1071.   protected void printPagePopUpDownloadAndRefresh(ServletOutputStream os, String fileName)
  1072.       throws IOException, ServletException {
  1073.     if (log4j.isDebugEnabled())
  1074.       log4j.debug("Output: PopUp Download");
  1075.     String href = strDireccion + "/utility/DownloadReport.html?report=" + fileName;
  1076.     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1077.         "org/openbravo/base/secureApp/PopUp_DownloadAndRefresh").createXmlDocument();
  1078.     xmlDocument.setParameter("href", href);
  1079.     os.println(xmlDocument.print());
  1080.     os.close();
  1081.   }
  1082.  
  1083.   private void printPageClosePopUpAndRefresh(HttpServletResponse response, VariablesSecureApp vars)
  1084.       throws IOException, ServletException {
  1085.     if (log4j.isDebugEnabled())
  1086.       log4j.debug("Output: PopUp Response");
  1087.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1088.         "org/openbravo/base/secureApp/PopUp_Close_Refresh").createXmlDocument();
  1089.     xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
  1090.     response.setContentType("text/html; charset=UTF-8");
  1091.     final PrintWriter out = response.getWriter();
  1092.     out.println(xmlDocument.print());
  1093.     out.close();
  1094.   }
  1095.  
  1096.   protected void printPageClosePopUpAndRefreshParent(HttpServletResponse response,
  1097.       VariablesSecureApp vars) throws IOException, ServletException {
  1098.     if (log4j.isDebugEnabled())
  1099.       log4j.debug("Output: PopUp Response");
  1100.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1101.         "org/openbravo/base/secureApp/PopUp_Close_And_Refresh").createXmlDocument();
  1102.     xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
  1103.     response.setContentType("text/html; charset=UTF-8");
  1104.     final PrintWriter out = response.getWriter();
  1105.     out.println(xmlDocument.print());
  1106.     out.close();
  1107.   }
  1108.  
  1109.   protected void pageErrorCallOut(HttpServletResponse response) throws IOException {
  1110.     final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
  1111.         "org/openbravo/base/secureApp/HtmlErrorCallOut").createXmlDocument();
  1112.  
  1113.     response.setContentType("text/html; charset=UTF-8");
  1114.     final PrintWriter out = response.getWriter();
  1115.     out.println(xmlDocument.print());
  1116.     out.close();
  1117.   }
  1118.  
  1119.   /**
  1120.    * @deprecated use {@link HttpSecureAppServlet#readProperties(VariablesSecureApp)} instead
  1121.    */
  1122.   protected void readProperties(VariablesSecureApp vars, String strFileProperties) {
  1123.     readProperties(vars);
  1124.   }
  1125.  
  1126.   /**
  1127.    * Reads some configuration properties from Openbravo.properties and sets them in session
  1128.    */
  1129.   protected void readProperties(VariablesSecureApp vars) {
  1130.     // Read properties file.
  1131.     final Properties properties = OBPropertiesProvider.getInstance().getOpenbravoProperties();
  1132.  
  1133.     final String javaDateFormat = properties.getProperty("dateFormat.java");
  1134.     vars.setSessionValue("#AD_JavaDateFormat", javaDateFormat);
  1135.  
  1136.     final String javaDateTimeFormat = properties.getProperty("dateTimeFormat.java");
  1137.     vars.setSessionValue("#AD_JavaDateTimeFormat", javaDateTimeFormat);
  1138.  
  1139.     final String sqlDateTimeFormat = properties.getProperty("dateTimeFormat.sql");
  1140.     vars.setSessionValue("#AD_SqlDateTimeFormat", sqlDateTimeFormat);
  1141.  
  1142.     final String jsDateFormat = properties.getProperty("dateFormat.js");
  1143.     vars.setSessionValue("#AD_JsDateFormat", jsDateFormat);
  1144.  
  1145.     final String sqlDateFormat = properties.getProperty("dateFormat.sql");
  1146.     vars.setSessionValue("#AD_SqlDateFormat", sqlDateFormat);
  1147.  
  1148.     final String pentahoServer = properties.getProperty("pentahoServer");
  1149.     vars.setSessionValue("#pentahoServer", pentahoServer);
  1150.  
  1151.     final String sourcePath = properties.getProperty("source.path");
  1152.     vars.setSessionValue("#sourcePath", sourcePath);
  1153.  
  1154.     if (log4j.isDebugEnabled()) {
  1155.       log4j.debug("javaDateFormat: " + javaDateFormat);
  1156.       log4j.debug("javaDateTimeFormat: " + javaDateTimeFormat);
  1157.       log4j.debug("jsDateFormat: " + jsDateFormat);
  1158.       log4j.debug("sqlDateFormat: " + sqlDateFormat);
  1159.       log4j.debug("pentahoServer: " + pentahoServer);
  1160.       log4j.debug("sourcePath: " + sourcePath);
  1161.     }
  1162.   }
  1163.  
  1164.   protected void readNumberFormat(VariablesSecureApp vars, String strFormatFile) {
  1165.     LoginUtils.readNumberFormat(vars, strFormatFile);
  1166.   }
  1167.  
  1168.   protected void renderJR(VariablesSecureApp variables, HttpServletResponse response,
  1169.       String strReportName, String strOutputType, HashMap<String, Object> designParameters,
  1170.       FieldProvider[] data, Map<Object, Object> exportParameters) throws ServletException {
  1171.     renderJR(variables, response, strReportName, null, strOutputType, designParameters, data,
  1172.         exportParameters, false);
  1173.   }
  1174.  
  1175.   protected void renderJR(VariablesSecureApp variables, HttpServletResponse response,
  1176.       String strReportName, String strFileName, String strOutputType,
  1177.       HashMap<String, Object> designParameters, FieldProvider[] data,
  1178.       Map<Object, Object> exportParameters) throws ServletException {
  1179.     renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
  1180.         data, exportParameters, false);
  1181.   }
  1182.  
  1183.   protected void renderJR(VariablesSecureApp variables, HttpServletResponse response,
  1184.       String strReportName, String strFileName, String strOutputType,
  1185.       HashMap<String, Object> designParameters, FieldProvider[] data,
  1186.       Map<Object, Object> exportParameters, boolean forceRefresh) throws ServletException {
  1187.     if (data != null) {
  1188.       renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
  1189.           new JRFieldProviderDataSource(data, variables.getJavaDateFormat()), exportParameters,
  1190.           forceRefresh);
  1191.     } else {
  1192.       renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
  1193.           (JRDataSource) null, exportParameters, forceRefresh);
  1194.     }
  1195.   }
  1196.  
  1197.   /**
  1198.    * Render a jrxml based report using a {@link ScrollableFieldProvider} as its datasource.
  1199.    *
  1200.    * @see #renderJR(VariablesSecureApp, HttpServletResponse, String, String, String, HashMap,
  1201.    *      JRDataSource, Map, boolean)
  1202.    */
  1203.   protected void renderJR(VariablesSecureApp variables, HttpServletResponse response,
  1204.       String strReportName, String strFileName, String strOutputType,
  1205.       HashMap<String, Object> designParameters, ScrollableFieldProvider sfp,
  1206.       Map<Object, Object> exportParameters) throws ServletException {
  1207.     renderJR(variables, response, strReportName, strFileName, strOutputType, designParameters,
  1208.         new JRScrollableFieldProviderDataSource(sfp, variables.getJavaDateFormat()),
  1209.         exportParameters, false);
  1210.   }
  1211.  
  1212.   private void renderJR(VariablesSecureApp variables, HttpServletResponse response,
  1213.       String strReportName, String strFileName, String strOutputType,
  1214.       HashMap<String, Object> designParameters, JRDataSource data,
  1215.       Map<Object, Object> exportParameters, boolean forceRefresh) throws ServletException {
  1216.     String localStrReportName = strReportName;
  1217.     String localStrOutputType = getExportFormat(strOutputType);
  1218.     String localStrFileName = strFileName;
  1219.     Map<Object, Object> localExportParameters = exportParameters;
  1220.     HashMap<String, Object> localDesignParameters = designParameters;
  1221.     if (localStrReportName == null || localStrReportName.equals(""))
  1222.       localStrReportName = PrintJRData.getReportName(this, classInfo.id);
  1223.  
  1224.     final String strAttach = globalParameters.strFTPDirectory + "/284-" + classInfo.id;
  1225.  
  1226.     final String strLanguage = variables.getLanguage();
  1227.     final Locale locLocale = new Locale(strLanguage.substring(0, 2), strLanguage.substring(3, 5));
  1228.  
  1229.     final String strBaseDesign = getBaseDesignPath(strLanguage);
  1230.  
  1231.     localStrReportName = Replace.replace(
  1232.         Replace.replace(localStrReportName, "@basedesign@", strBaseDesign), "@attach@", strAttach);
  1233.     if (localStrFileName == null) {
  1234.       localStrFileName = localStrReportName.substring(localStrReportName.lastIndexOf("/") + 1);
  1235.     }
  1236.  
  1237.     ServletOutputStream os = null;
  1238.     UUID reportId = null;
  1239.     try {
  1240.       if (localDesignParameters == null)
  1241.         localDesignParameters = new HashMap<String, Object>();
  1242.  
  1243.       localDesignParameters.put("BASE_WEB", strReplaceWithFull);
  1244.       localDesignParameters.put("BASE_DESIGN", strBaseDesign);
  1245.       localDesignParameters.put("ATTACH", strAttach);
  1246.       localDesignParameters.put("USER_CLIENT",
  1247.           Utility.getContext(this, variables, "#User_Client", ""));
  1248.       localDesignParameters.put("USER_ORG", Utility.getContext(this, variables, "#User_Org", ""));
  1249.       localDesignParameters.put("LANGUAGE", strLanguage);
  1250.       localDesignParameters.put("LOCALE", locLocale);
  1251.       localDesignParameters.put("REPORT_TITLE",
  1252.           PrintJRData.getReportTitle(this, variables.getLanguage(), classInfo.id));
  1253.  
  1254.       final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
  1255.       dfs.setDecimalSeparator(variables.getSessionValue("#AD_ReportDecimalSeparator").charAt(0));
  1256.       dfs.setGroupingSeparator(variables.getSessionValue("#AD_ReportGroupingSeparator").charAt(0));
  1257.       final DecimalFormat numberFormat = new DecimalFormat(
  1258.           variables.getSessionValue("#AD_ReportNumberFormat"), dfs);
  1259.       localDesignParameters.put("NUMBERFORMAT", numberFormat);
  1260.  
  1261.       os = response.getOutputStream();
  1262.       if (localExportParameters == null)
  1263.         localExportParameters = new HashMap<Object, Object>();
  1264.  
  1265.       final ExportType expType = ExportType.getExportType(localStrOutputType);
  1266.       ConnectionProvider readOnlyCP = DalConnectionProvider.getReadOnlyConnectionProvider();
  1267.  
  1268.       if (expType == ExportType.HTML) {
  1269.         if (log4j.isDebugEnabled())
  1270.           log4j.debug("JR: Print HTML");
  1271.         response.setHeader("Content-disposition", "inline" + "; filename=" + localStrFileName + "."
  1272.             + localStrOutputType);
  1273.         HttpServletRequest request = RequestContext.get().getRequest();
  1274.         String localAddress = HttpBaseUtils.getLocalAddress(request);
  1275.         localExportParameters.put(ReportingUtils.IMAGES_URI, localAddress
  1276.             + "/servlets/image?image={0}");
  1277.         ReportingUtils.exportJR(localStrReportName, expType, localDesignParameters, os, false,
  1278.             readOnlyCP, data, localExportParameters);
  1279.       } else if (expType != ExportType.XML) {
  1280.         reportId = UUID.randomUUID();
  1281.         File outputFile = new File(globalParameters.strFTPDirectory + "/" + localStrFileName + "-"
  1282.             + (reportId) + "." + localStrOutputType);
  1283.         ReportingUtils.exportJR(localStrReportName, expType, localDesignParameters, outputFile,
  1284.             false, readOnlyCP, data, localExportParameters);
  1285.         response.setContentType("text/html;charset=UTF-8");
  1286.         response.setHeader("Content-disposition", "inline" + "; filename=" + localStrFileName + "-"
  1287.             + (reportId) + ".html");
  1288.         if (forceRefresh) {
  1289.           printPagePopUpDownloadAndRefresh(response.getOutputStream(), localStrFileName + "-"
  1290.               + (reportId) + "." + localStrOutputType);
  1291.         } else {
  1292.           printPagePopUpDownload(response.getOutputStream(), localStrFileName + "-" + (reportId)
  1293.               + "." + localStrOutputType);
  1294.         }
  1295.       }
  1296.  
  1297.     } catch (IOException ioe) {
  1298.       try {
  1299.         FileUtility f = new FileUtility(globalParameters.strFTPDirectory, localStrFileName + "-"
  1300.             + (reportId) + "." + localStrOutputType, false, true);
  1301.         if (f.exists())
  1302.           f.deleteFile();
  1303.       } catch (IOException ioex) {
  1304.         log4j.error("Error trying to delete temporary report file " + localStrFileName + "-"
  1305.             + (reportId) + "." + localStrOutputType + " : " + ioex.getMessage());
  1306.       }
  1307.     } catch (final Exception e) {
  1308.       throw new ServletException(e.getMessage(), e);
  1309.     } finally {
  1310.       try {
  1311.         os.close();
  1312.       } catch (final Exception e) {
  1313.       }
  1314.     }
  1315.   }
  1316.  
  1317.   private String getExportFormat(String outputType) {
  1318.     if (outputType == null || outputType.equals("")) {
  1319.       return ExportType.HTML.getExtension();
  1320.     }
  1321.     if (ExportType.XLS.hasExtension(outputType)) {
  1322.       return ReportingUtils.getExcelExportType().getExtension();
  1323.     }
  1324.     return outputType;
  1325.   }
  1326.  
  1327.   /**
  1328.    * Saves the file and request for download. This approach is required to close the loading pop-up
  1329.    * window.
  1330.    */
  1331.   public void renderFO(String strFo, HttpServletRequest request, HttpServletResponse response)
  1332.       throws ServletException {
  1333.     File baseDir = new File(globalParameters.strFTPDirectory);
  1334.     UUID reportId = UUID.randomUUID();
  1335.  
  1336.     int slashPos = request.getRequestURI().lastIndexOf("/");
  1337.     int dotPos = request.getRequestURI().lastIndexOf(".");
  1338.  
  1339.     String fileName = request.getRequestURI().substring(slashPos + 1, dotPos) + "-" + reportId
  1340.         + ".pdf";
  1341.     File pdffile = new File(baseDir, fileName);
  1342.     OutputStream out = null;
  1343.  
  1344.     try {
  1345.       out = new FileOutputStream(pdffile);
  1346.     } catch (Exception e) {
  1347.       log4j.error(e.getMessage(), e);
  1348.       throw new ServletException(e.getMessage());
  1349.     }
  1350.  
  1351.     // Generating and saving file
  1352.     super.renderFO(strFo, out);
  1353.  
  1354.     try {
  1355.       printPagePopUpDownload(response.getOutputStream(), fileName);
  1356.     } catch (IOException e) {
  1357.       try {
  1358.         FileUtility f = new FileUtility(globalParameters.strFTPDirectory, fileName, false, true);
  1359.         if (f.exists())
  1360.           f.deleteFile();
  1361.       } catch (IOException ioex) {
  1362.         log4j.error("Error trying to delete temporary report file " + fileName + " : "
  1363.             + ioex.getMessage());
  1364.       }
  1365.     }
  1366.   }
  1367.  
  1368.   /**
  1369.    * Forwards request to the referrer servlet to perform operations like "auto-save" Note: The
  1370.    * referrer servlet should have a hidden input field with mappingName (e.g.
  1371.    * /PurchaOrder/Header_Edition.html) to be able to get a RequestDispatcher
  1372.    *
  1373.    * @param request
  1374.    * @param response
  1375.    * @throws IOException
  1376.    * @throws ServletException
  1377.    */
  1378.   private boolean forwardRequest(HttpServletRequest request, HttpServletResponse response)
  1379.       throws IOException, ServletException {
  1380.     final String forwardTo = request.getParameter("mappingName");
  1381.     final String autoSave = request.getParameter("autosave");
  1382.     final String commandType = request.getParameter("inpCommandType");
  1383.     final Boolean popupWindow = request.getAttribute("popupWindow") != null ? (Boolean) request
  1384.         .getAttribute("popupWindow") : false;
  1385.  
  1386.     // Forwarding request to save the modified record
  1387.     if (autoSave != null && autoSave.equalsIgnoreCase("Y")) {
  1388.       if (forwardTo != null && !forwardTo.equals("")) {
  1389.         final RequestDispatcher rd = getServletContext().getRequestDispatcher(forwardTo);
  1390.         if (rd != null) {
  1391.           final long time = System.currentTimeMillis();
  1392.           try {
  1393.             if (log4j.isDebugEnabled())
  1394.               log4j.debug("forward request to: " + forwardTo);
  1395.             rd.include(request, response);
  1396.             if (log4j.isDebugEnabled())
  1397.               log4j.debug("Request forward took: "
  1398.                   + String.valueOf(System.currentTimeMillis() - time) + " ms");
  1399.           } catch (final OBException e) {
  1400.  
  1401.             request.removeAttribute("autosave");
  1402.             request.removeAttribute("popupWindow");
  1403.  
  1404.             final VariablesSecureApp vars = new VariablesSecureApp(request);
  1405.             final String strTabId = vars.getStringParameter("inpTabId");
  1406.             if (!vars.getSessionValue(strTabId + "|concurrentSave").equals("true")) {
  1407.               vars.setSessionObject(strTabId + "|failedAutosave", true);
  1408.             }
  1409.  
  1410.             if (!popupWindow) {
  1411.               vars.setSessionValue(strTabId + "|requestURL", request.getRequestURL().toString());
  1412.               response.sendRedirect(strDireccion + forwardTo + "?Command="
  1413.                   + (commandType != null ? commandType : "NEW"));
  1414.             } else { // close pop-up
  1415.               printPageClosePopUpAndRefresh(response, vars);
  1416.             }
  1417.             return false;
  1418.           }
  1419.         }
  1420.       }
  1421.     }
  1422.     request.removeAttribute("autosave");
  1423.     request.removeAttribute("popupWindow");
  1424.     return true;
  1425.   }
  1426.  
  1427.   @Override
  1428.   public String getServletInfo() {
  1429.     return "This servlet add some functions (autentication, privileges, application menu, ...) over HttpBaseServlet";
  1430.   }
  1431. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement