Beispiel #1
0
  public String getAbsolutePath(String url) {
    int pos;
    if (url == null) return null;
    if (url.startsWith("/")) return url;
    HttpServletRequest request = (HttpServletRequest) (pageContext.getRequest());

    pos = request.getServletPath().lastIndexOf("/");
    return request.getServletPath().substring(0, pos + 1) + url;
  }
  /**
   * This method handles the "POST" submission from two forms: the login form and the message
   * compose form.
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    String servletPath = request.getServletPath();
    servletPath = servletPath.concat(".jsp");

    getServletConfig()
        .getServletContext()
        .getRequestDispatcher("/" + servletPath)
        .forward(request, response);
  }
 /**
  * Show the pieces of the request, for debugging
  *
  * @param req the HttpServletRequest
  * @return parsed request
  */
 public static String getRequestParsed(HttpServletRequest req) {
   return req.getRequestURI()
       + " = "
       + req.getContextPath()
       + "(context), "
       + req.getServletPath()
       + "(servletPath), "
       + req.getPathInfo()
       + "(pathInfo), "
       + req.getQueryString()
       + "(query)";
 }
  public URL getUrl(HttpServletRequest req) throws IOException {
    String servletPath = req.getServletPath();

    String selectedServerFullPath = getServerAddress(servletPath);
    String queryString = req.getQueryString();
    String newUrl = "";
    HttpSession session = req.getSession(false);

    newUrl = selectedServerFullPath + servletPath;

    if (req.getRequestedSessionId() != null)
      newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId();

    if (queryString != null) newUrl = newUrl + "?" + queryString;

    // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId();

    return new URL(newUrl);
  }
  /** This method handles the GET requests from the client. */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    // check to be sure we're still logged in
    // before forwarding the request.
    HttpSession session = request.getSession();
    MailUserBean mailuser = (MailUserBean) session.getAttribute("mailuser");
    String servletPath = request.getServletPath();
    servletPath = servletPath.concat(".jsp");

    if (mailuser.isLoggedIn())
      getServletConfig()
          .getServletContext()
          .getRequestDispatcher("/" + servletPath)
          .forward(request, response);
    else
      getServletConfig()
          .getServletContext()
          .getRequestDispatcher("/index.html")
          .forward(request, response);
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {

      EventEntities entities = new EventEntities();
      entities.setRequest(request);
      entities.setResponse(response);

      String actionName = request.getServletPath();
      actionName = actionName.substring(1, actionName.indexOf(FWConstants.ACTION_SUFFIX));
      FWAction action = FWConfigUtil.getAction(actionName);
      ApplicationExceptionUtil.checkNullPointerException(
          action, "Action name \"" + actionName + "\" is not configured.");
      String viewName = request.getParameter(FWConstants.VIEW_NAME_VALUE);
      BasicValidationUtil.validateData(request);
      Model[] models = ModelsCreator.createModelsForAction(actionName, request);
      ConversionErrors errors = ModelsPopulator.populateModels(actionName, request);
      if (errors.getConversionErrorList().size() > 0) {
        ServletUtil.preserveConversionErrors(request, errors);
        ServletUtil.gotoPage(entities, viewName + FWConstants.VIEW_SUFFIX, false);
        return;
      }

      if (action.getValidators() != null) {
        List<ActionValidationError> validations = new ArrayList<ActionValidationError>();
        List<FWActionValidator> fWValidators = action.getValidators();
        boolean callNext = true;
        for (int i = 0; i < fWValidators.size() && callNext; i++) {
          FWActionValidator fWValidator = fWValidators.get(i);
          ActionValidator validator = ActionValidatorFactory.getValidator(fWValidator.getType());
          callNext = validator.validate(models, validations, entities);
        }
        if (validations.size() > 0) {
          ActionValidationErrors validationErrors = new ActionValidationErrors(validations);
          ServletUtil.preserveValidationErrors(request, validationErrors);
          ServletUtil.gotoPage(entities, viewName + FWConstants.VIEW_SUFFIX, false);
          return;
        }
      }

      ActionViewConnector connector = null;
      connector = ActionViewConnectorFactory.getActionViewConnector(request, true);
      connector.setAction(actionName);

      ActionHandler handler =
          (ActionHandler) ActionHandlerFactory.getActionHandler(action.getHandler());
      AbstractProcessingTube processingTube = ProcessingTubeFactory.getProcessingTube();
      try {
        String viewAfterAction =
            processingTube.processActionTube(handler, models, connector, entities);
        if (viewAfterAction != null) {
          viewName = viewAfterAction;
        }
        ServletUtil.gotoPage(
            entities,
            viewName + FWConstants.VIEW_SUFFIX,
            FWConfigUtil.isSendRedirect(actionName, viewName));
      } catch (Exception ex) {
        FWException actionException = FWConfigUtil.getActionFWException(action, ex);
        ServletUtil.handleException(ex, actionException, connector, entities);
      }
    } catch (Exception exception) {
      throw new ServletException(exception);
    }
  }
  public void writeLandingPage(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    String landingPage = getNewTokenLandingPage();

    /** default to current page * */
    if (landingPage == null) {
      StringBuilder sb = new StringBuilder();

      sb.append(request.getContextPath());
      sb.append(request.getServletPath());

      landingPage = sb.toString();
    }

    /** create auto posting form * */
    StringBuilder sb = new StringBuilder();

    sb.append("<html>\r\n");
    sb.append("<head>\r\n");
    sb.append("<title>OWASP CSRFGuard Project - New Token Landing Page</title>\r\n");
    sb.append("</head>\r\n");
    sb.append("<body>\r\n");
    sb.append("<script type=\"text/javascript\">\r\n");
    sb.append("var form = document.createElement(\"form\");\r\n");
    sb.append("form.setAttribute(\"method\", \"post\");\r\n");
    sb.append("form.setAttribute(\"action\", \"");
    sb.append(landingPage);
    sb.append("\");\r\n");

    /** only include token if needed * */
    if (isProtectedPage(landingPage)) {
      sb.append("var hiddenField = document.createElement(\"input\");\r\n");
      sb.append("hiddenField.setAttribute(\"type\", \"hidden\");\r\n");
      sb.append("hiddenField.setAttribute(\"name\", \"");
      sb.append(getTokenName());
      sb.append("\");\r\n");
      sb.append("hiddenField.setAttribute(\"value\", \"");
      sb.append(getTokenValue(request, landingPage));
      sb.append("\");\r\n");
      sb.append("form.appendChild(hiddenField);\r\n");
    }

    sb.append("document.body.appendChild(form);\r\n");
    sb.append("form.submit();\r\n");
    sb.append("</script>\r\n");
    sb.append("</body>\r\n");
    sb.append("</html>\r\n");

    String code = sb.toString();

    /** setup headers * */
    response.setContentType("text/html");
    response.setContentLength(code.length());

    /** write auto posting form * */
    OutputStream output = null;
    PrintWriter writer = null;

    try {
      output = response.getOutputStream();
      writer = new PrintWriter(output);

      writer.write(code);
      writer.flush();
    } finally {
      Writers.close(writer);
      Streams.close(output);
    }
  }
 /**
  * Return the request URL relative to the server (i.e., starting with the context path).
  *
  * @param req request
  * @return URL relative to the server
  */
 public static String getReletiveURL(HttpServletRequest req) {
   return req.getContextPath() + req.getServletPath() + req.getPathInfo();
 }
  /**
   * Show details about the request
   *
   * @param servlet used to get teh servlet context, may be null
   * @param req the request
   * @return string showing the details of the request.
   */
  public static String showRequestDetail(HttpServlet servlet, HttpServletRequest req) {
    StringBuilder sbuff = new StringBuilder();

    sbuff.append("Request Info\n");
    sbuff.append(" req.getServerName(): ").append(req.getServerName()).append("\n");
    sbuff.append(" req.getServerPort(): ").append(req.getServerPort()).append("\n");
    sbuff.append(" req.getContextPath:").append(req.getContextPath()).append("\n");
    sbuff.append(" req.getServletPath:").append(req.getServletPath()).append("\n");
    sbuff.append(" req.getPathInfo:").append(req.getPathInfo()).append("\n");
    sbuff.append(" req.getQueryString:").append(req.getQueryString()).append("\n");
    sbuff
        .append(" getQueryStringDecoded:")
        .append(EscapeStrings.urlDecode(req.getQueryString()))
        .append("\n");
    /*try {
      sbuff.append(" getQueryStringDecoded:").append(URLDecoder.decode(req.getQueryString(), "UTF-8")).append("\n");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }*/
    sbuff.append(" req.getRequestURI:").append(req.getRequestURI()).append("\n");
    sbuff.append(" getRequestBase:").append(getRequestBase(req)).append("\n");
    sbuff.append(" getRequestServer:").append(getRequestServer(req)).append("\n");
    sbuff.append(" getRequest:").append(getRequest(req)).append("\n");
    sbuff.append("\n");

    sbuff.append(" req.getPathTranslated:").append(req.getPathTranslated()).append("\n");
    String path = req.getPathTranslated();
    if ((path != null) && (servlet != null)) {
      ServletContext context = servlet.getServletContext();
      sbuff.append(" getMimeType:").append(context.getMimeType(path)).append("\n");
    }
    sbuff.append("\n");
    sbuff.append(" req.getScheme:").append(req.getScheme()).append("\n");
    sbuff.append(" req.getProtocol:").append(req.getProtocol()).append("\n");
    sbuff.append(" req.getMethod:").append(req.getMethod()).append("\n");
    sbuff.append("\n");
    sbuff.append(" req.getContentType:").append(req.getContentType()).append("\n");
    sbuff.append(" req.getContentLength:").append(req.getContentLength()).append("\n");

    sbuff.append(" req.getRemoteAddr():").append(req.getRemoteAddr());
    try {
      sbuff
          .append(" getRemoteHost():")
          .append(java.net.InetAddress.getByName(req.getRemoteHost()).getHostName())
          .append("\n");
    } catch (java.net.UnknownHostException e) {
      sbuff.append(" getRemoteHost():").append(e.getMessage()).append("\n");
    }
    sbuff.append(" getRemoteUser():").append(req.getRemoteUser()).append("\n");

    sbuff.append("\n");
    sbuff.append("Request Parameters:\n");
    Enumeration params = req.getParameterNames();
    while (params.hasMoreElements()) {
      String name = (String) params.nextElement();
      String values[] = req.getParameterValues(name);
      if (values != null) {
        for (int i = 0; i < values.length; i++) {
          sbuff
              .append("  ")
              .append(name)
              .append("  (")
              .append(i)
              .append("): ")
              .append(values[i])
              .append("\n");
        }
      }
    }
    sbuff.append("\n");

    sbuff.append("Request Headers:\n");
    Enumeration names = req.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      Enumeration values = req.getHeaders(name); // support multiple values
      if (values != null) {
        while (values.hasMoreElements()) {
          String value = (String) values.nextElement();
          sbuff.append("  ").append(name).append(": ").append(value).append("\n");
        }
      }
    }
    sbuff.append(" ------------------\n");

    return sbuff.toString();
  }
Beispiel #10
0
 /**
  * servletPath + pathInfo
  *
  * @param req the HttpServletRequest
  * @return parsed request servletPath + pathInfo
  */
 public static String getRequestPath(HttpServletRequest req) {
   StringBuffer buff = new StringBuffer();
   if (req.getServletPath() != null) buff.append(req.getServletPath());
   if (req.getPathInfo() != null) buff.append(req.getPathInfo());
   return buff.toString();
 }
  private void printPageEdit(
      HttpServletResponse response,
      HttpServletRequest request,
      VariablesSecureApp vars,
      boolean boolNew,
      String strC_BP_Group_ID,
      TableSQLData tableSQL)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: edit");

    HashMap<String, String> usedButtonShortCuts;

    usedButtonShortCuts = new HashMap<String, String>();

    String strOrderByFilter = vars.getSessionValue(tabId + "|orderby");
    String orderClause = " C_BP_Group.Value";
    if (strOrderByFilter == null || strOrderByFilter.equals("")) strOrderByFilter = orderClause;
    /*{
      if (!strOrderByFilter.equals("") && !orderClause.equals("")) strOrderByFilter += ", ";
      strOrderByFilter += orderClause;
    }*/

    String strCommand = null;
    BusinessPartnerCategoryData[] data = null;
    XmlDocument xmlDocument = null;
    FieldProvider dataField = vars.getEditionData(tabId);
    vars.removeEditionData(tabId);
    String strParamName = vars.getSessionValue(tabId + "|paramName");

    boolean hasSearchCondition = false;
    hasSearchCondition =
        (tableSQL.hasInternalFilter() && ("").equals(strParamName))
            || !(("").equals(strParamName) || ("%").equals(strParamName));

    String strParamSessionDate =
        vars.getGlobalVariable(
            "inpParamSessionDate", Utility.getTransactionalDate(this, vars, windowId), "");
    String buscador = "";
    String[] discard = {"", "isNotTest"};

    if (vars.getSessionValue("#ShowTest", "N").equals("Y")) discard[1] = new String("isTest");
    if (dataField == null) {
      if (!boolNew) {
        discard[0] = new String("newDiscard");
        data =
            BusinessPartnerCategoryData.selectEdit(
                this,
                vars.getSessionValue("#AD_SqlDateTimeFormat"),
                vars.getLanguage(),
                strC_BP_Group_ID,
                Utility.getContext(this, vars, "#User_Client", windowId),
                Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel));

        if (!strC_BP_Group_ID.equals("") && (data == null || data.length == 0)) {
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
          return;
        }
        refreshSessionEdit(vars, data);
        strCommand = "EDIT";
      }

      if (boolNew || data == null || data.length == 0) {
        discard[0] = new String("editDiscard");
        strCommand = "NEW";
        data = new BusinessPartnerCategoryData[0];
      } else {
        discard[0] = new String("newDiscard");
      }
    } else {
      if (dataField.getField("cBpGroupId") == null || dataField.getField("cBpGroupId").equals("")) {
        discard[0] = new String("editDiscard");
        strCommand = "NEW";
        boolNew = true;
      } else {
        discard[0] = new String("newDiscard");
        strCommand = "EDIT";
      }
    }

    if (dataField == null) {
      if (boolNew || data == null || data.length == 0) {
        refreshSessionNew(vars);
        data =
            BusinessPartnerCategoryData.set(
                "",
                Utility.getDefault(
                    this, vars, "AD_Client_ID", "@AD_CLIENT_ID@", "192", "", dataField),
                Utility.getDefault(this, vars, "AD_Org_ID", "@AD_Org_ID@", "192", "", dataField),
                "Y",
                Utility.getDefault(this, vars, "CreatedBy", "", "192", "", dataField),
                BusinessPartnerCategoryData.selectDef4966_0(
                    this, Utility.getDefault(this, vars, "CreatedBy", "", "192", "", dataField)),
                Utility.getDefault(this, vars, "UpdatedBy", "", "192", "", dataField),
                BusinessPartnerCategoryData.selectDef4968_1(
                    this, Utility.getDefault(this, vars, "UpdatedBy", "", "192", "", dataField)),
                Utility.getDefault(this, vars, "Value", "", "192", "", dataField),
                Utility.getDefault(this, vars, "Name", "", "192", "", dataField),
                Utility.getDefault(this, vars, "Description", "", "192", "", dataField),
                Utility.getDefault(this, vars, "IsDefault", "", "192", "N", dataField));
      }
    }

    String currentOrg =
        (boolNew
            ? ""
            : (dataField != null ? dataField.getField("adOrgId") : data[0].getField("adOrgId")));
    if (!currentOrg.equals("") && !currentOrg.startsWith("'")) currentOrg = "'" + currentOrg + "'";
    String currentClient =
        (boolNew
            ? ""
            : (dataField != null
                ? dataField.getField("adClientId")
                : data[0].getField("adClientId")));
    if (!currentClient.equals("") && !currentClient.startsWith("'"))
      currentClient = "'" + currentClient + "'";

    boolean hasReadOnlyAccess =
        org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
            this, vars.getRole(), tabId);
    boolean editableTab =
        (!hasReadOnlyAccess
            && (currentOrg.equals("")
                || Utility.isElementInList(
                    Utility.getContext(this, vars, "#User_Org", windowId, accesslevel), currentOrg))
            && (currentClient.equals("")
                || Utility.isElementInList(
                    Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                    currentClient)));
    if (editableTab)
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpWindows/BusinessPartnerCategory/BusinessPartnerCategory_Edition",
                  discard)
              .createXmlDocument();
    else
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpWindows/BusinessPartnerCategory/BusinessPartnerCategory_NonEditable",
                  discard)
              .createXmlDocument();

    xmlDocument.setParameter("tabId", tabId);
    ToolBar toolbar =
        new ToolBar(
            this,
            editableTab,
            vars.getLanguage(),
            "BusinessPartnerCategory",
            (strCommand.equals("NEW")
                || boolNew
                || (dataField == null && (data == null || data.length == 0))),
            "document.frmMain.inpcBpGroupId",
            "",
            "..",
            "".equals("Y"),
            "BusinessPartnerCategory",
            strReplaceWith,
            true,
            false,
            false,
            Utility.hasTabAttachments(this, vars, tabId, strC_BP_Group_ID),
            !hasReadOnlyAccess);
    toolbar.setTabId(tabId);
    toolbar.setDeleteable(true);
    toolbar.prepareEditionTemplate(
        "N".equals("Y"),
        hasSearchCondition,
        vars.getSessionValue("#ShowTest", "N").equals("Y"),
        "STD",
        Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    xmlDocument.setParameter("toolbar", toolbar.toString());

    // set updated timestamp to manage locking mechanism
    if (!boolNew) {
      xmlDocument.setParameter(
          "updatedTimestamp",
          (dataField != null
              ? dataField.getField("updatedTimeStamp")
              : data[0].getField("updatedTimeStamp")));
    }

    boolean concurrentSave = vars.getSessionValue(tabId + "|concurrentSave").equals("true");
    if (concurrentSave) {
      // after concurrent save error, force autosave
      xmlDocument.setParameter("autosave", "Y");
    } else {
      xmlDocument.setParameter("autosave", "N");
    }
    vars.removeSessionValue(tabId + "|concurrentSave");

    try {
      WindowTabs tabs =
          new WindowTabs(this, vars, tabId, windowId, true, (strCommand.equalsIgnoreCase("NEW")));
      xmlDocument.setParameter("parentTabContainer", tabs.parentTabs());
      xmlDocument.setParameter("mainTabContainer", tabs.mainTabs());
      // if (!strC_BP_Group_ID.equals("")) xmlDocument.setParameter("childTabContainer",
      // tabs.childTabs(false));
      // else xmlDocument.setParameter("childTabContainer", tabs.childTabs(true));
      xmlDocument.setParameter("childTabContainer", tabs.childTabs(false));
      String hideBackButton = vars.getGlobalVariable("hideMenu", "#Hide_BackButton", "");
      NavigationBar nav =
          new NavigationBar(
              this,
              vars.getLanguage(),
              "BusinessPartnerCategory_Relation.html",
              "BusinessPartnerCategory",
              "W",
              strReplaceWith,
              tabs.breadcrumb(),
              hideBackButton.equals("true"),
              !concurrentSave);
      xmlDocument.setParameter("navigationBar", nav.toString());
      LeftTabsBar lBar =
          new LeftTabsBar(
              this, vars.getLanguage(), "BusinessPartnerCategory_Relation.html", strReplaceWith);
      xmlDocument.setParameter("leftTabs", lBar.editionTemplate(strCommand.equals("NEW")));
    } catch (Exception ex) {
      throw new ServletException(ex);
    }

    xmlDocument.setParameter("commandType", strCommand);
    xmlDocument.setParameter("buscador", buscador);
    xmlDocument.setParameter("windowId", windowId);
    xmlDocument.setParameter("changed", "");
    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
    xmlDocument.setParameter("theme", vars.getTheme());
    final String strMappingName = Utility.getTabURL(tabId, "E", false);
    xmlDocument.setParameter("mappingName", strMappingName);
    xmlDocument.setParameter("confirmOnChanges", Utility.getJSConfirmOnChanges(vars, windowId));
    // xmlDocument.setParameter("buttonReference", Utility.messageBD(this, "Reference",
    // vars.getLanguage()));

    xmlDocument.setParameter("paramSessionDate", strParamSessionDate);

    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
    OBError myMessage = vars.getMessage(tabId);
    vars.removeMessage(tabId);
    if (myMessage != null) {
      xmlDocument.setParameter("messageType", myMessage.getType());
      xmlDocument.setParameter("messageTitle", myMessage.getTitle());
      xmlDocument.setParameter("messageMessage", myMessage.getMessage());
    }
    xmlDocument.setParameter("displayLogic", getDisplayLogicContext(vars, boolNew));

    if (dataField == null) {
      xmlDocument.setData("structure1", data);

    } else {

      FieldProvider[] dataAux = new FieldProvider[1];
      dataAux[0] = dataField;

      xmlDocument.setData("structure1", dataAux);
    }

    try {
      ComboTableData comboTableData = null;
      String userOrgList = "";
      if (editableTab)
        userOrgList =
            Utility.getContext(this, vars, "#User_Org", windowId, accesslevel); // editable record
      else userOrgList = currentOrg;
      comboTableData =
          new ComboTableData(
              vars,
              this,
              "19",
              "AD_Org_ID",
              "",
              "",
              userOrgList,
              Utility.getContext(this, vars, "#User_Client", windowId),
              0);
      Utility.fillSQLParameters(
          this,
          vars,
          (dataField == null ? data[0] : dataField),
          comboTableData,
          windowId,
          (dataField == null ? data[0].getField("adOrgId") : dataField.getField("adOrgId")));
      xmlDocument.setData(
          "reportAD_Org_ID", "liststructure", comboTableData.select(!strCommand.equals("NEW")));
      comboTableData = null;
      xmlDocument.setParameter("Created_Format", vars.getSessionValue("#AD_SqlDateTimeFormat"));
      xmlDocument.setParameter(
          "Created_Maxlength",
          Integer.toString(vars.getSessionValue("#AD_SqlDateTimeFormat").length()));
      xmlDocument.setParameter("Updated_Format", vars.getSessionValue("#AD_SqlDateTimeFormat"));
      xmlDocument.setParameter(
          "Updated_Maxlength",
          Integer.toString(vars.getSessionValue("#AD_SqlDateTimeFormat").length()));
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new ServletException(ex);
    }

    xmlDocument.setParameter("scriptOnLoad", getShortcutScript(usedButtonShortCuts));

    final String refererURL = vars.getSessionValue(tabId + "|requestURL");
    vars.removeSessionValue(tabId + "|requestURL");
    if (!refererURL.equals("")) {
      final Boolean failedAutosave = (Boolean) vars.getSessionObject(tabId + "|failedAutosave");
      vars.removeSessionValue(tabId + "|failedAutosave");
      if (failedAutosave != null && failedAutosave) {
        final String jsFunction = "continueUserAction('" + refererURL + "');";
        xmlDocument.setParameter("failedAutosave", jsFunction);
      }
    }

    if (strCommand.equalsIgnoreCase("NEW")) {
      vars.removeSessionValue(tabId + "|failedAutosave");
      vars.removeSessionValue(strMappingName + "|hash");
    }

    response.setContentType("text/html; charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println(xmlDocument.print());
    out.close();
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    TableSQLData tableSQL = null;
    VariablesSecureApp vars = new VariablesSecureApp(request);
    Boolean saveRequest = (Boolean) request.getAttribute("autosave");

    if (saveRequest != null && saveRequest) {
      String currentOrg = vars.getStringParameter("inpadOrgId");
      String currentClient = vars.getStringParameter("inpadClientId");
      boolean editableTab =
          (!org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
                  this, vars.getRole(), tabId)
              && (currentOrg.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Org", windowId, accesslevel),
                      currentOrg))
              && (currentClient.equals("")
                  || Utility.isElementInList(
                      Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                      currentClient)));

      OBError myError = new OBError();
      String commandType = request.getParameter("inpCommandType");
      String strcBpGroupId = request.getParameter("inpcBpGroupId");

      if (editableTab) {
        int total = 0;

        if (commandType.equalsIgnoreCase("EDIT") && !strcBpGroupId.equals(""))
          total = saveRecord(vars, myError, 'U');
        else total = saveRecord(vars, myError, 'I');

        if (!myError.isEmpty() && total == 0) throw new OBException(myError.getMessage());
      }
      vars.setSessionValue(request.getParameter("mappingName") + "|hash", vars.getPostDataHash());
      vars.setSessionValue(tabId + "|Header.view", "EDIT");

      return;
    }

    try {
      tableSQL =
          new TableSQLData(
              vars,
              this,
              tabId,
              Utility.getContext(this, vars, "#AccessibleOrgTree", windowId, accesslevel),
              Utility.getContext(this, vars, "#User_Client", windowId),
              Utility.getContext(this, vars, "ShowAudit", windowId).equals("Y"));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    String strOrderBy = vars.getSessionValue(tabId + "|orderby");
    if (!strOrderBy.equals("")) {
      vars.setSessionValue(tabId + "|newOrder", "1");
    }

    if (vars.commandIn("DEFAULT")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) {
        strView = defaultTabView;

        if (strView.equals("EDIT")) {
          if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("DIRECT")) {
      String strC_BP_Group_ID = vars.getStringParameter("inpDirectKey");

      if (strC_BP_Group_ID.equals(""))
        strC_BP_Group_ID =
            vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      else vars.setSessionValue(windowId + "|C_BP_Group_ID", strC_BP_Group_ID);

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("TAB")) {

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      String strC_BP_Group_ID = "";
      if (strView.equals("")) {
        strView = defaultTabView;
        if (strView.equals("EDIT")) {
          strC_BP_Group_ID = firstElement(vars, tableSQL);
          if (strC_BP_Group_ID.equals("")) strView = "RELATION";
        }
      }
      if (strView.equals("EDIT")) {

        if (strC_BP_Group_ID.equals("")) strC_BP_Group_ID = firstElement(vars, tableSQL);
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

      } else printPageDataSheet(response, vars, "", tableSQL);
    } else if (vars.commandIn("SEARCH")) {
      vars.getRequestGlobalVariable("inpParamName", tabId + "|paramName");

      vars.getRequestGlobalVariable("inpParamUpdated", tabId + "|paramUpdated");
      vars.getRequestGlobalVariable("inpParamUpdatedBy", tabId + "|paramUpdatedBy");
      vars.getRequestGlobalVariable("inpParamCreated", tabId + "|paramCreated");
      vars.getRequestGlobalVariable("inpparamCreatedBy", tabId + "|paramCreatedBy");

      vars.removeSessionValue(windowId + "|C_BP_Group_ID");
      String strC_BP_Group_ID = "";

      String strView = vars.getSessionValue(tabId + "|BusinessPartnerCategory.view");
      if (strView.equals("")) strView = defaultTabView;

      if (strView.equals("EDIT")) {
        strC_BP_Group_ID = firstElement(vars, tableSQL);
        if (strC_BP_Group_ID.equals("")) {
          // filter returns empty set
          strView = "RELATION";
          // switch to grid permanently until the user changes the view again
          vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", strView);
        }
      }

      if (strView.equals("EDIT"))
        printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);
      else printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("RELATION")) {

      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      printPageDataSheet(response, vars, strC_BP_Group_ID, tableSQL);
    } else if (vars.commandIn("NEW")) {

      printPageEdit(response, request, vars, true, "", tableSQL);

    } else if (vars.commandIn("EDIT")) {

      @SuppressWarnings("unused") // In Expense Invoice tab this variable is not used, to be fixed
      String strC_BP_Group_ID =
          vars.getGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID", "");
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "EDIT");

      setHistoryCommand(request, "EDIT");
      printPageEdit(response, request, vars, false, strC_BP_Group_ID, tableSQL);

    } else if (vars.commandIn("NEXT")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strNext, tableSQL);
    } else if (vars.commandIn("PREVIOUS")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");

      String strPrevious = previousElement(vars, strC_BP_Group_ID, tableSQL);

      printPageEdit(response, request, vars, false, strPrevious, tableSQL);
    } else if (vars.commandIn("FIRST_RELATION")) {

      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("PREVIOUS_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      if (strInitRecord.equals("") || strInitRecord.equals("0")) {
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", "0");
      } else {
        int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
        initRecord -= intRecordRange;
        strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      }
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("NEXT_RELATION")) {

      String strInitRecord =
          vars.getSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber");
      String strRecordRange = Utility.getContext(this, vars, "#RecordRange", windowId);
      int intRecordRange = strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange);
      int initRecord = (strInitRecord.equals("") ? 0 : Integer.parseInt(strInitRecord));
      if (initRecord == 0) initRecord = 1;
      initRecord += intRecordRange;
      strInitRecord = ((initRecord < 0) ? "0" : Integer.toString(initRecord));
      vars.setSessionValue(tabId + "|BusinessPartnerCategory.initRecordNumber", strInitRecord);
      vars.removeSessionValue(windowId + "|C_BP_Group_ID");

      response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
    } else if (vars.commandIn("FIRST")) {

      String strFirst = firstElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strFirst, tableSQL);
    } else if (vars.commandIn("LAST_RELATION")) {

      String strLast = lastElement(vars, tableSQL);
      printPageDataSheet(response, vars, strLast, tableSQL);
    } else if (vars.commandIn("LAST")) {

      String strLast = lastElement(vars, tableSQL);

      printPageEdit(response, request, vars, false, strLast, tableSQL);
    } else if (vars.commandIn("SAVE_NEW_RELATION", "SAVE_NEW_NEW", "SAVE_NEW_EDIT")) {

      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'I');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsInserted");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_NEW_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_NEW_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn(
        "SAVE_EDIT_RELATION", "SAVE_EDIT_NEW", "SAVE_EDIT_EDIT", "SAVE_EDIT_NEXT")) {

      String strC_BP_Group_ID =
          vars.getRequiredGlobalVariable("inpcBpGroupId", windowId + "|C_BP_Group_ID");
      OBError myError = new OBError();
      int total = saveRecord(vars, myError, 'U');
      if (!myError.isEmpty()) {
        response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
      } else {
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          vars.setMessage(tabId, myError);
        }
        if (vars.commandIn("SAVE_EDIT_NEW"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=NEW");
        else if (vars.commandIn("SAVE_EDIT_EDIT"))
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        else if (vars.commandIn("SAVE_EDIT_NEXT")) {
          String strNext = nextElement(vars, strC_BP_Group_ID, tableSQL);
          vars.setSessionValue(windowId + "|C_BP_Group_ID", strNext);
          response.sendRedirect(strDireccion + request.getServletPath() + "?Command=EDIT");
        } else response.sendRedirect(strDireccion + request.getServletPath() + "?Command=RELATION");
      }
    } else if (vars.commandIn("DELETE")) {

      String strC_BP_Group_ID = vars.getRequiredStringParameter("inpcBpGroupId");
      // BusinessPartnerCategoryData data = getEditVariables(vars);
      int total = 0;
      OBError myError = null;
      if (org.openbravo.erpCommon.utility.WindowAccessData.hasNotDeleteAccess(
          this, vars.getRole(), tabId)) {
        myError =
            Utility.translateError(
                this,
                vars,
                vars.getLanguage(),
                Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
        vars.setMessage(tabId, myError);
      } else {
        try {
          total =
              BusinessPartnerCategoryData.delete(
                  this,
                  strC_BP_Group_ID,
                  Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                  Utility.getContext(this, vars, "#User_Org", windowId, accesslevel));
        } catch (ServletException ex) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          if (!myError.isConnectionAvailable()) {
            bdErrorConnection(response);
            return;
          } else vars.setMessage(tabId, myError);
        }
        if (myError == null && total == 0) {
          myError =
              Utility.translateError(
                  this,
                  vars,
                  vars.getLanguage(),
                  Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
          vars.setMessage(tabId, myError);
        }
        vars.removeSessionValue(windowId + "|cBpGroupId");
        vars.setSessionValue(tabId + "|BusinessPartnerCategory.view", "RELATION");
      }
      if (myError == null) {
        myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsDeleted");
        myError.setMessage(total + " " + myError.getMessage());
        vars.setMessage(tabId, myError);
      }
      response.sendRedirect(strDireccion + request.getServletPath());

    } else if (vars.commandIn("SAVE_XHR")) {

      OBError myError = new OBError();
      JSONObject result = new JSONObject();
      String commandType = vars.getStringParameter("inpCommandType");
      char saveType = "NEW".equals(commandType) ? 'I' : 'U';
      try {
        int total = saveRecord(vars, myError, saveType);
        if (myError.isEmpty()) {
          myError = Utility.translateError(this, vars, vars.getLanguage(), "@CODE=RowsUpdated");
          myError.setMessage(total + " " + myError.getMessage());
          myError.setType("Success");
        }
        result.put("oberror", myError.toMap());
        result.put("tabid", vars.getStringParameter("tabID"));
        result.put("redirect", strDireccion + request.getServletPath() + "?Command=" + commandType);
      } catch (Exception e) {
        log4j.error("Error saving record (XHR request): " + e.getMessage(), e);
        myError.setType("Error");
        myError.setMessage(e.getMessage());
      }

      response.setContentType("application/json");
      PrintWriter out = response.getWriter();
      out.print(result.toString());
      out.flush();
      out.close();
    } else if (vars.getCommand().toUpperCase().startsWith("BUTTON")
        || vars.getCommand().toUpperCase().startsWith("SAVE_BUTTON")) {
      pageErrorPopUp(response);
    } else pageError(response);
  }