public void processrequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    try {
      boolean multi = isMultipartRequest(request);
      String svg = getParameter(request, "svg", multi);
      if (svg == null || svg.isEmpty()) {
        throw new ServletException("The required - svg - post parameter is missing");
      }

      if (svg.indexOf(FORBIDDEN_WORD) > -1 || svg.indexOf(FORBIDDEN_WORD.toLowerCase()) > -1) {
        throw new ServletException("The - svg - post parameter could contain a malicious attack");
      }

      String filename = getFilename(getParameter(request, "filename", multi));
      Float width = getWidth(getParameter(request, "width", multi));
      MimeType mime = getMime(getParameter(request, "type", multi));

      ExportController.writeFileContentToHttpResponse(svg, filename, width, mime, response);

    } catch (IOException ioe) {
      logger.error("Oops something happened here redirect to error-page, " + ioe.getMessage());
      sendError(request, response, ioe);
    } catch (ServletException sce) {
      logger.error("Oops something happened here redirect to error-page, " + sce.getMessage());
      sendError(request, response, sce);
    }
  }
  public ReturnStatus login(String Auth, HttpServletRequest req, HttpSession session) {

    System.out.println("login");

    String[] result = decodeToken(Auth);
    System.out.println("login, result = " + result[0]);

    if (result[0].equals("OK")) {

      System.out.println("login : "******" / password = "******"user", req.getRemoteUser());
        } catch (ServletException e) {
          System.out.println("login ServletException");
          return new ReturnStatus(false, "login ServletException" + e.getMessage());
        }
        System.out.println("Login OK, remoteuser = "******"login, RequestedSessionId = " + req.getRequestedSessionId());

        System.out.println("Login OK");
        return new ReturnStatus(true, getroles(result[1]));
      } else {
        System.out.println("user niet gevonden (null)");
        return new ReturnStatus(false, "user niet gevonden (null)");
      }
    } else {
      System.out.println("invalid");
      return new ReturnStatus(false, result[1]);
    }
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    res.setContentType("application/download-xml-file");

    String messageId = req.getParameter("message");

    OMElement report = null;

    try {
      Message m = new Message(messageId);
      m.readMessage();

      report = buildReport(m);

    } catch (LoggerException e) {
      report = omFactory.createOMElement(new QName("NoReportAvailable"));
      report.setText(e.getMessage().replaceAll("<", "&lt;"));
    } catch (ServletException e) {
      report = omFactory.createOMElement(new QName("NoReportAvailable"));
      report.setText(e.getMessage().replaceAll("<", "&lt;"));
    }

    try {
      res.getWriter().write(report.toString());
    } catch (IOException e) {
    }
  }
示例#4
0
 @RequestMapping(value = "/autologin/user", method = RequestMethod.GET)
 public @ResponseBody ResponseEntity<Map<String, Object>> autologin1(HttpServletRequest request) {
   Map<String, Object> map = new HashMap<String, Object>();
   HttpStatus status = null;
   try {
     request.login("author", "1");
     map.put("MESSAGE", "AUTO LOG IN SUCCESS WITH DEFAULT AUTHOR ACCOUNT 'author'");
     map.put("STATUS", "200");
     map.put("IS_LOGIN", isAuthenticated());
     map.put("ROLE", getRole());
     map.put("USERNAME", getUsername());
     status = HttpStatus.OK;
   } catch (ServletException e) {
     // TODO Auto-generated catch block
     map.put("MESSAGE", e.getMessage());
     map.put("IS_LOGIN", isAuthenticated());
     map.put("ROLE", getRole());
     map.put("USERNAME", getUsername());
     status = HttpStatus.BAD_REQUEST;
     e.printStackTrace();
     return new ResponseEntity<Map<String, Object>>(map, status);
   }
   System.out.println(isAuthenticated());
   System.out.println(getRole());
   System.out.println(getUsername());
   return new ResponseEntity<Map<String, Object>>(map, status);
 }
示例#5
0
  @Override
  public JsonObject getJson() {
    if (json == null) {
      boolean isMultiPart = true;
      try {
        getParts();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ServletException e) {
        logger.fatal("The request was not multipart, " + e.getMessage());
        isMultiPart = false;
      }

      if (!isMultiPart) {
        try {
          json = JsonUtils.getJsonRequest(this);
          return json;
        } catch (Exception e) {
          logger.debug("No json body associated with this request, {}", e.getMessage());
        }
      }

      try {
        json = JsonUtils.getJsonFromField(this);
        return json;
      } catch (JsonException e) {
        logger.debug("No json field associated with this request, {}", e.getMessage());
      }

      json = new JsonObject();
    }

    return json;
  }
示例#6
0
 public void valueUnbound(HttpSessionBindingEvent be) {
   if (be.getName().equals("Session")) {
     try {
       cleanUp(); // remove references in hash right away (this method is synchronized)
     } catch (ServletException ex) {
       dbgApp("ServletException: " + ex.getMessage());
     }
   }
 }
  private void initServices(ServletContext context) throws ServletException {

    // get list of OGC services
    String serviceList = this.getRequiredInitParameter(SERVICE);

    String[] serviceNames = StringTools.toArray(serviceList, ",", false);

    ServiceLookup lookup = ServiceLookup.getInstance();
    for (int i = 0; i < serviceNames.length; i++) {
      LOG.logInfo(
          StringTools.concat(100, "---- Initializing ", serviceNames[i].toUpperCase(), " ----"));
      try {
        String className = this.getRequiredInitParameter(serviceNames[i] + HANDLER_CLASS);
        Class<?> handlerClzz = Class.forName(className);

        // initialize each service factory
        String s = this.getRequiredInitParameter(serviceNames[i] + HANDLER_CONF);
        URL serviceConfigurationURL = WebappResourceResolver.resolveFileLocation(s, context, LOG);

        // set configuration
        LOG.logInfo(
            StringTools.concat(
                300,
                "Reading configuration for ",
                serviceNames[i].toUpperCase(),
                " from URL: '",
                serviceConfigurationURL,
                "'."));

        String factoryClassName = SERVICE_FACTORIES_MAPPINGS.get(handlerClzz);

        Class<?> factory = Class.forName(factoryClassName);
        Method method = factory.getMethod("setConfiguration", new Class[] {URL.class});
        method.invoke(factory, new Object[] {serviceConfigurationURL});

        // The csw-ebrim profile adds an alternative service name, it too is registred with the CSW
        // handler.
        if ("CSW".equals(serviceNames[i].toUpperCase())) {
          lookup.addService(OGCRequestFactory.CSW_SERVICE_NAME_EBRIM.toUpperCase(), handlerClzz);
        }
        // put handler to available service list
        lookup.addService(serviceNames[i].toUpperCase(), handlerClzz);

        LOG.logInfo(
            StringTools.concat(300, serviceNames[i].toUpperCase(), " successfully initialized."));
      } catch (ServletException e) {
        LOG.logError(e.getMessage(), e);
      } catch (InvocationTargetException e) {
        e.getTargetException().printStackTrace();
        LOG.logError(this.produceMessage(ERR_MSG, new Object[] {serviceNames[i]}), e);
      } catch (Exception e) {
        LOG.logError("Can't initialize OGC service:" + serviceNames[i], e);
      }
    }
  }
 public void emit(ReplayParseContext context, Node node) throws IOException {
   String found = context.getData(FERRET_DONE_KEY);
   if (found == null) {
     context.putData(FERRET_DONE_KEY, "1");
     try {
       super.emit(context, node);
     } catch (ServletException e) {
       e.printStackTrace();
       throw new IOException(e.getMessage());
     }
   }
 }
示例#9
0
  protected void activate() {
    try {
      logger.debug("Starting up proxy servlet at /" + PROXY_ALIAS);

      Hashtable<String, String> props = new Hashtable<String, String>();
      httpService.registerServlet("/" + PROXY_ALIAS, this, props, createHttpContext());
    } catch (NamespaceException e) {
      logger.error("Error during servlet startup: {}", e.getMessage());
    } catch (ServletException e) {
      logger.error("Error during servlet startup: {}", e.getMessage());
    }
  }
  /**
   * As a servlet, this class' init() method is called automatically. This is how we get context.
   *
   * @param config the configuration describing the run-time environment.
   */
  @Override
  public void init(final ServletConfig config) {
    log.info("ActionRPCServiceImpl::init()");

    try {
      super.init(config);
    } catch (ServletException e) {
      log.error("Caught a ServletException during initialization: " + e.getMessage(), e);
    }

    springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    actionExecutorFactory = (ActionExecutorFactory) springContext.getBean("actionExecutorFactory");
  }
示例#11
0
  protected void deployServlet(final DeploymentInfo deploymentInfo) {
    DeploymentManager manager =
        ServletContainer.Factory.newInstance().addDeployment(deploymentInfo);

    manager.deploy();
    deployment = manager.getDeployment();

    try {
      injectedHost.getValue().registerDeployment(deployment, manager.start());
    } catch (ServletException e) {
      RTSLogger.ROOT_LOGGER.warn(e.getMessage(), e);
      deployment = null;
    }
  }
 public void setServletConfig(ServletConfig servletConfig) {
   try {
     shadowCxfServlet = (Servlet) servletClass.newInstance();
   } catch (InstantiationException e) {
     throw new RuntimeException(e);
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   }
   try {
     shadowCxfServlet.init(servletConfig);
   } catch (ServletException ex) {
     throw new RuntimeException(ex.getMessage(), ex);
   }
 }
 @Override
 public void onAuthenticationSuccess(
     HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
   log.info("Usuário [" + authentication.getName() + "] autenticado com sucesso.");
   request.getSession().setAttribute("usuarioLogado", authentication.getDetails());
   try {
     super.onAuthenticationSuccess(request, response, authentication);
   } catch (ServletException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   } catch (IOException e) {
     log.error(
         "Ocorreu um erro ao redirecionar para a pagina principal [" + e.getMessage() + "].", e);
   }
 }
示例#14
0
  public void init() {
    servletContext.setInitParameter(
        InitParameter.POWER_API_CONFIG_DIR.getParameterName(), "/etc/powerapi");

    // Show me Papi!
    servletContext.setInitParameter("show-me-papi", "true");

    final Map<String, String> powerFilterParams = new HashMap<String, String>();
    final FilterConfig fc = new NXPFilterConfig("power-filter", servletContext, powerFilterParams);

    try {
      ctxManager.contextInitialized(new ServletContextEvent(servletContext));
      powerFilterInstance.init(fc);
    } catch (ServletException servletException) {
      LOG.error(servletException.getMessage(), servletException);
    }
  }
 @SuppressWarnings("rawtypes")
 @Activate
 protected void activate(ComponentContext context) {
   Dictionary props = context.getProperties();
   noUserRedirectLocationFormat =
       PropertiesUtil.toString(
           props.get(NO_USER_REDIRECT_LOCATION_FORMAT), DEFAULT_NO_USER_REDIRECT_FORMAT);
   registrationPath = PropertiesUtil.toString(props.get(REGISTRATION_PATH), "/system/trustedauth");
   defaultDestination = PropertiesUtil.toString(props.get(DEFAULT_DESTINATION), "/dev");
   try {
     httpService.registerServlet(registrationPath, this, null, null);
     LOGGER.info("Registered {} at {} ", this, registrationPath);
   } catch (ServletException e) {
     LOGGER.error(e.getMessage(), e);
   } catch (NamespaceException e) {
     LOGGER.error(e.getMessage(), e);
   }
 }
示例#16
0
 @RequestMapping(value = "/autologin/admin", method = RequestMethod.GET)
 public @ResponseBody ResponseEntity<Map<String, Object>> autologin(HttpServletRequest request) {
   Map<String, Object> map = new HashMap<String, Object>();
   HttpStatus status = null;
   try {
     request.login("*****@*****.**", "1");
     map.put("MESSAGE", "AUTO LOG IN SUCCESS WITH DEFAULT ADMIN ACCOUNT 'admin'");
     map.put("STATUS", "200");
     map.put("IS_LOGIN", isAuthenticated());
     status = HttpStatus.OK;
   } catch (ServletException e) {
     map.put("MESSAGE", e.getMessage());
     map.put("IS_LOGIN", isAuthenticated());
     status = HttpStatus.BAD_REQUEST;
     e.printStackTrace();
     return new ResponseEntity<Map<String, Object>>(map, status);
   }
   return new ResponseEntity<Map<String, Object>>(map, status);
 }
示例#17
0
  public RequestResponsePair handleRequest(
      ExternalConnectionFuture connectionFuture,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException {
    final LastCallFilterChain rootFilterChain = new LastCallFilterChain();

    try {
      powerFilterInstance.doFilter(request, response, rootFilterChain);
    } catch (IOException ioe) {
      LOG.error(ioe.getMessage(), ioe);
    } catch (ServletException se) {
      LOG.error(se.getMessage(), se);
    }

    return new RequestResponsePair(
        rootFilterChain.getLastRequestObjectPassed(),
        rootFilterChain.getLastResponseObjectPassed());
  }
示例#18
0
 private void sendAuthInit(HttpServletRequest req, HttpServletResponse resp, Properties properties)
     throws IOException {
   if (properties == null) {
     properties = new Properties();
   }
   resp.setHeader("WWW-Authenticate", HttpServletRequest.FORM_AUTH);
   resp.setStatus(HttpServletResponse.SC_OK);
   resp.setContentType("application/json");
   String putStyle =
       properties.getProperty(CSS_LINK_PROPERTY) == null
           ? ""
           : "&styles=" + properties.getProperty(CSS_LINK_PROPERTY);
   RequestDispatcher rd =
       req.getRequestDispatcher("/loginform/checkuser?redirect=" + req.getRequestURI() + putStyle);
   try {
     rd.forward(req, resp);
   } catch (ServletException e) {
     throw new IOException(e.getMessage());
   } finally {
     resp.flushBuffer();
   }
 }
示例#19
0
  public void processrequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    try {

      String reqdata = request.getParameter("reqdata");
      if (reqdata != null && reqdata.length() != 0) {

        String uri = request.getRequestURI();
        String url = request.getServletContext().getContextPath();
        String path = request.getServletContext().getRealPath(uri.substring(url.length()));
        String content =
            Config.getReplacedContentFromFile(
                path, "#this_html_is_image_reqdata_template", "var image_url = '" + reqdata + "'");
        if (content == null || content.length() == 0) {
          throw new Exception("File Read Error!");
        }
        byte[] result = content.getBytes("UTF-8");
        response.reset();
        response.setContentLength(result.length);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        ServletOutputStream out = response.getOutputStream();
        out.write(result);
        out.flush();
      }

    } catch (IOException ioe) {
      logger.error("Oops something happened here redirect to error-page, " + ioe.getMessage());
      sendError(request, response, ioe);
    } catch (ServletException sce) {
      logger.error("Oops something happened here redirect to error-page, " + sce.getMessage());
      sendError(request, response, sce);
    } catch (Exception e) {
      logger.error("Oops something happened here redirect to error-page, " + e.getMessage());
      sendError(request, response, e);
    }
  }
示例#20
0
 @RequestMapping(value = "/logout", method = RequestMethod.GET)
 public @ResponseBody ResponseEntity<Map<String, Object>> logout(
     HttpServletRequest request, HttpServletResponse response) {
   Map<String, Object> map = new HashMap<String, Object>();
   HttpStatus status = null;
   try {
     if (isAuthenticated()) {
       request.logout();
       map.put("MESSAGE", "LOG OUT SUCCESS");
       map.put("STATUS", "200");
       status = HttpStatus.OK;
     } else {
       map.put("MESSAGE", "YOU DID NOT LOG IN. CANNOT LOG OUT.");
       status = HttpStatus.FORBIDDEN;
     }
   } catch (ServletException e) {
     // TODO Auto-generated catch block
     map.put("MESSAGE", e.getMessage());
     status = HttpStatus.INTERNAL_SERVER_ERROR;
     e.printStackTrace();
     return new ResponseEntity<Map<String, Object>>(map, status);
   }
   return new ResponseEntity<Map<String, Object>>(map, status);
 }
  /*
   * Procesamiento de peticiones GET y POST
   * @param request
   * @param response
   * @throws ServletException
   * @throws IOException
   */
  public final void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Comprobar si es un GET
    if (request.getMethod().equalsIgnoreCase("GET")) {
      return;
    }

    // Se trata de un POST

    // La respuesta es JSON
    response.setContentType("application/json; charset=UTF-8");

    // Crear los filtros definidos para todos los servicios
    es.tid.frawa.service.servlet.Filter[] filters = new es.tid.frawa.service.servlet.Filter[0];

    PrintWriter output = null;

    StringBuffer input = null;

    String action = "";

    try {
      // Crea una sesión si no existe (esta opción está marcada en el modelo de servicios)
      request.getSession(true);

      // Invocar el método startService() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].startService(request, response);
      }

      // Invocar el método frawaService() de la clase derivada (si está implementado)
      if (!frawaService(request, response)) {
        // Ha retornado false, por tanto abortamos el procesamiento del servicio
        return;
      }

      // Mensaje por defecto para los filtros que no necesitan el texto JSON
      StringBuffer soapStr = new StringBuffer("");

      // Leer el mensaje JSON

      if (request.getParameter("JSONAction") != null
          && request.getParameter("JSONAction").length() > 0) {
        action = request.getParameter("JSONAction");
        String tmp = request.getParameter("JSON");
        if (tmp == null || tmp.length() == 0) {
          throw new Exception(
              getClass().getName()
                  + ".service() JSONAction viene en la URL pero no viene el parámetro JSON con los datos");
        }
        input = new StringBuffer(tmp);
      } else {
        action = request.getHeader("JSONAction");
        if (action == null || action.length() == 0) {
          throw new Exception(
              getClass().getName() + ".service() La cabecera HTTP JSONAction no esta definida");
        }
        // new es.tid.frawa.common.TdiFrawaTraceListener().trace(getClass().getName()+".service()
        // Leyendo mensaje JSON");
        BufferedReader input_r = new BufferedReader(request.getReader());
        input = new StringBuffer();
        String line = input_r.readLine();
        while (line != null) {
          input.append(line);
          line = input_r.readLine();
        }
      }

      // Invocar el método beforeParse() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].beforeParse(request, response, input.toString());
      }

      //
      // Invocar al servicio adecuado en función del header JSONAction
      //

      if (action.equals("http://www.qualipso.org/advdoc/ws/storage/CreateFolder")) {

        // SERVICIO: CreateFolder

        // Parámetro de entrada al servicio
        CreateFolder_req inbean = new CreateFolder_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        CreateFolder_resp outbean = new CreateFolder_resp();

        // Crear un objeto que implementa la operación
        CreateFolderService serviceImplementation = new CreateFolderService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: CreateFolder]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetFiles")) {

        // SERVICIO: GetFiles

        // Parámetro de entrada al servicio
        GetFiles_req inbean = new GetFiles_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        GetFiles_resp outbean = new GetFiles_resp();

        // Crear un objeto que implementa la operación
        GetFilesService serviceImplementation = new GetFilesService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: GetFiles]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/GetSubFolders")) {

        // SERVICIO: GetSubFolders

        // Parámetro de entrada al servicio
        GetSubFolders_req inbean = new GetSubFolders_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        GetSubFolders_resp outbean = new GetSubFolders_resp();

        // Crear un objeto que implementa la operación
        GetSubFoldersService serviceImplementation = new GetSubFoldersService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: GetSubFolders]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadBinaryFile")) {

        // SERVICIO: LoadBinaryFile

        // Parámetro de entrada al servicio
        LoadBinaryFile_req inbean = new LoadBinaryFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        LoadBinaryFile_resp outbean = new LoadBinaryFile_resp();

        // Crear un objeto que implementa la operación
        LoadBinaryFileService serviceImplementation = new LoadBinaryFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: LoadBinaryFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/LoadFile")) {

        // SERVICIO: LoadFile

        // Parámetro de entrada al servicio
        LoadFile_req inbean = new LoadFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        LoadFile_resp outbean = new LoadFile_resp();

        // Crear un objeto que implementa la operación
        LoadFileService serviceImplementation = new LoadFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: LoadFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFile")) {

        // SERVICIO: RemoveFile

        // Parámetro de entrada al servicio
        RemoveFile_req inbean = new RemoveFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        RemoveFile_resp outbean = new RemoveFile_resp();

        // Crear un objeto que implementa la operación
        RemoveFileService serviceImplementation = new RemoveFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: RemoveFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/RemoveFolder")) {

        // SERVICIO: RemoveFolder

        // Parámetro de entrada al servicio
        RemoveFolder_req inbean = new RemoveFolder_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        RemoveFolder_resp outbean = new RemoveFolder_resp();

        // Crear un objeto que implementa la operación
        RemoveFolderService serviceImplementation = new RemoveFolderService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: RemoveFolder]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreBinaryFile")) {

        // SERVICIO: StoreBinaryFile

        // Parámetro de entrada al servicio
        StoreBinaryFile_req inbean = new StoreBinaryFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        StoreBinaryFile_resp outbean = new StoreBinaryFile_resp();

        // Crear un objeto que implementa la operación
        StoreBinaryFileService serviceImplementation = new StoreBinaryFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: StoreBinaryFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/StoreFile")) {

        // SERVICIO: StoreFile

        // Parámetro de entrada al servicio
        StoreFile_req inbean = new StoreFile_req();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        StoreFile_resp outbean = new StoreFile_resp();

        // Crear un objeto que implementa la operación
        StoreFileService serviceImplementation = new StoreFileService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: StoreFile]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestLoopback")) {

        // SERVICIO: TestLoopback

        // Parámetro de entrada al servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestLoopback inbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestLoopback outbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestLoopback();

        // Crear un objeto que implementa la operación
        TestLoopbackService serviceImplementation = new TestLoopbackService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: TestLoopback]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else if (action.equals("http://www.qualipso.org/advdoc/ws/storage/TestParser")) {

        // SERVICIO: TestParser

        // Parámetro de entrada al servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestParser inbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestParser();
        inbean.fromJSON(input.toString());

        // Invocar el método beforeService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].beforeService(request, response, inbean, "QualiPSoStorage", action);
        }

        // Parámetro de salida del servicio
        org.qualipso.advdoc.ws.client.storage.beans.TestParser outbean =
            new org.qualipso.advdoc.ws.client.storage.beans.TestParser();

        // Crear un objeto que implementa la operación
        TestParserService serviceImplementation = new TestParserService();

        // Invocar la implementación de la operación
        Throwable applicationException =
            serviceImplementation.executeImpl(this, request, response, inbean, outbean);

        // Si ha ocurrido una excepción, enviarla al cliente
        if (applicationException != null) {
          // Traza
          // new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          new es.tid.frawa.common.TdiFrawaTraceListener().trace(applicationException);
          output = response.getWriter();
          if (applicationException instanceof TdiServiceException) {
            sendError(output, (TdiServiceException) applicationException);
          } else {
            String inputBean = tdi.text.StringUtil.escapeXML(inbean.toString(), false);
            String rc = "\n";
            sendError(
                output,
                new TdiServiceException(
                    1,
                    "." + rc + "[Operation: TestParser]" + rc + inputBean + rc + ".",
                    applicationException.getClass().getName()
                        + ":"
                        + applicationException.getMessage()));
          }
          return;
        }

        // Invocar el método afterService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterService(request, response, outbean, "QualiPSoStorage", action);
        }

        // Respuesta
        output = response.getWriter();

        // Bean de salida
        String output_str = outbean.toJSON(false);

        // Invocar el método afterParse() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].afterParse(request, response, output_str.toString());
        }

        // Enviar la respuesta
        output.println(output_str);

        // Invocar el método endService() de los filtros
        for (int i = 0; i < filters.length; i++) {
          filters[i].endService(request, response);
        }

      } else {

        throw new Exception(getClass().getName() + ".service() Operación " + action + " no válida");
      }

    } catch (ServletException e) {

      // Ha ocurrido un error en los filtros

      // Traza
      // new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);
      new es.tid.frawa.common.TdiFrawaTraceListener().trace(e);

      // Enviar <Fault> al cliente
      if (output == null) {
        output = response.getWriter();
      }
      TdiServiceException se = new TdiServiceException(-1, "Filter exception", e.getMessage());
      sendError(output, se);

    } catch (Throwable t) {

      // Invocar el método onException() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].onException(request, response, t, "QualiPSoStorage", action);
      }

      // Traza
      // new es.tid.frawa.common.TdiFrawaTraceListener().trace(t);
      new es.tid.frawa.common.TdiFrawaTraceListener().trace(t);

      // Elevar una ServletException
      throw new ServletException(
          getClass().getName()
              + ".service() Server Exception: "
              + t.getClass().getName()
              + " -> "
              + t.getMessage());
      // if (output == null) {
      //	output = response.getWriter();
      // }
      // TdiServiceException se = new TdiServiceException(-2,t.getClass().getName(),t.getMessage());
      // sendError(output,se);

    } finally {

      // Invocar el método onFinally() de los filtros
      for (int i = 0; i < filters.length; i++) {
        filters[i].onFinally(request, response, "QualiPSoStorage", action);
      }
    }
  }
  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);
  }
  /**
   * Adds more detailed logging for unhandled exceptions
   *
   * @see org.apache.struts.action.RequestProcessor#processException(HttpServletRequest,
   *     HttpServletResponse, Exception, ActionForm, ActionMapping)
   */
  @Override
  protected ActionForward processException(
      HttpServletRequest request,
      HttpServletResponse response,
      Exception exception,
      ActionForm form,
      ActionMapping mapping)
      throws IOException, ServletException {
    ActionForward actionForward = null;

    try {
      actionForward = super.processException(request, response, exception, form, mapping);
    } catch (IOException e) {
      logException(e);
      throw e;
    } catch (ServletException e) {
      // special case, to make OptimisticLockExceptions easier to read
      Throwable rootCause = e.getRootCause();
      if (rootCause instanceof OjbOperationException) {
        OjbOperationException ooe = (OjbOperationException) rootCause;

        Throwable subcause = ooe.getCause();
        if (subcause != null) {
          Object sourceObject = null;
          boolean optLockException = false;
          if (subcause instanceof javax.persistence.OptimisticLockException) {
            javax.persistence.OptimisticLockException ole =
                (javax.persistence.OptimisticLockException) subcause;
            sourceObject = ole.getEntity();
            optLockException = true;
          } else if (subcause instanceof OptimisticLockingFailureException) {
            OptimisticLockingFailureException ole = (OptimisticLockingFailureException) subcause;
            sourceObject = ole.getMessage();
            optLockException = true;
          } else {
            if (subcause
                .getClass()
                .getName()
                .equals("org.apache.ojb.broker.OptimisticLockException")) {
              try {
                sourceObject = PropertyUtils.getSimpleProperty(subcause, "sourceObject");
              } catch (Exception ex) {
                LOG.warn("Unable to retrieve source object from OJB OptimisticLockException", ex);
              }
              optLockException = true;
            }
          }
          if (optLockException) {
            StringBuilder message = new StringBuilder(e.getMessage());

            if (sourceObject != null) {
              if (sourceObject instanceof String) {
                message.append(" Embedded Message: ").append(sourceObject);
              } else {
                message.append(" (sourceObject is ");
                message.append(sourceObject.getClass().getName());
                message.append(")");
              }
            }

            e = new ServletException(message.toString(), rootCause);
          }
        }
      }

      logException(e);
      throw e;
    }
    return actionForward;
  }
  private void printPageHtml(
      HttpServletRequest request,
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strComparative,
      String strDateFrom,
      String strDateTo,
      String strPartnerGroup,
      String strcBpartnerId,
      String strProductCategory,
      String strmProductId,
      String strNotShown,
      String strShown,
      String strDateFromRef,
      String strDateToRef,
      String strOrg,
      String strsalesrepId,
      String strmWarehouseId,
      String strOrder,
      String strMayor,
      String strMenor,
      String strRatioMayor,
      String strRatioMenor,
      String strCurrencyId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: print html");
    XmlDocument xmlDocument = null;
    String strOrderby = "";
    String[] discard = {"", "", "", "", "", "", ""};
    String[] discard1 = {
      "selEliminarBody1",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard"
    };
    if (strOrg.equals("")) strOrg = vars.getOrg();
    if (strComparative.equals("Y")) discard1[0] = "selEliminarBody2";
    String strTitle = "";
    strTitle =
        Utility.messageBD(this, "From", vars.getLanguage())
            + " "
            + strDateFrom
            + " "
            + Utility.messageBD(this, "To", vars.getLanguage())
            + " "
            + strDateTo;
    if (!strPartnerGroup.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ForBPartnerGroup", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectBpgroup(this, strPartnerGroup);
    if (!strProductCategory.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ProductCategory", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectProductCategory(
                  this, strProductCategory);
    if (!strsalesrepId.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "TheSalesRep", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectSalesrep(this, strsalesrepId);
    if (!strmWarehouseId.equals(""))
      strTitle =
          strTitle
              + " "
              + Utility.messageBD(this, "And", vars.getLanguage())
              + " "
              + Utility.messageBD(this, "TheWarehouse", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectMwarehouse(this, strmWarehouseId);

    ReportRefundSalesDimensionalAnalysesData[] data = null;
    String[] strShownArray = {"", "", "", "", "", "", ""};
    if (strShown.startsWith("(")) strShown = strShown.substring(1, strShown.length() - 1);
    if (!strShown.equals("")) {
      strShown = Replace.replace(strShown, "'", "");
      strShown = Replace.replace(strShown, " ", "");
      StringTokenizer st = new StringTokenizer(strShown, ",", false);
      int intContador = 0;
      while (st.hasMoreTokens()) {
        strShownArray[intContador] = st.nextToken();
        intContador++;
      }
    }
    String[] strTextShow = {"", "", "", "", "", "", ""};
    int intDiscard = 0;
    int intAuxDiscard = -1;
    for (int i = 0; i < 7; i++) {
      if (strShownArray[i].equals("1")) {
        strTextShow[i] = "C_BP_GROUP.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("2")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('C_Bpartner'), to_char( C_BPARTNER.C_BPARTNER_ID), to_char('"
                + vars.getLanguage()
                + "'))";
        intDiscard++;
      } else if (strShownArray[i].equals("3")) {
        strTextShow[i] = "M_PRODUCT_CATEGORY.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("4")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('M_Product'), to_char( M_PRODUCT.M_PRODUCT_ID), to_char('"
                + vars.getLanguage()
                + "'))|| CASE WHEN uomsymbol IS NULL THEN '' ELSE to_char(' ('||uomsymbol||')') END";
        intAuxDiscard = i;
        intDiscard++;
      } else if (strShownArray[i].equals("5")) {
        strTextShow[i] = "C_ORDER.DOCUMENTNO";
        intDiscard++;
      } else if (strShownArray[i].equals("6")) {
        strTextShow[i] = "AD_USER.FIRSTNAME||' '||' '||AD_USER.LASTNAME";
        intDiscard++;
      } else if (strShownArray[i].equals("7")) {
        strTextShow[i] = "M_WAREHOUSE.NAME";
        intDiscard++;
      } else {
        strTextShow[i] = "''";
        discard[i] = "display:none;";
      }
    }
    if (intDiscard != 0 || intAuxDiscard != -1) {
      int k = 1;
      if (intDiscard == 1) {
        strOrderby = " ORDER BY NIVEL" + k + ",";
      } else {
        strOrderby = " ORDER BY ";
      }
      while (k < intDiscard) {
        strOrderby = strOrderby + "NIVEL" + k + ",";
        k++;
      }
      if (k == 1) {
        if (strOrder.equals("Normal")) {
          strOrderby = " ORDER BY NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby = " ORDER BY LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby = " ORDER BY LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby = " ORDER BY RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby = " ORDER BY RATIO DESC";
        } else {
          strOrderby = "1";
        }
      } else {
        if (strOrder.equals("Normal")) {
          strOrderby += "NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby += "LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby += "LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby += "RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby += "RATIO DESC";
        } else {
          strOrderby = "1";
        }
      }

    } else {
      strOrderby = " ORDER BY 1";
    }
    String strHaving = "";
    if (!strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor + " AND SUM(LINENETAMT) < " + strMenor;
    } else if (!strMayor.equals("") && strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor;
    } else if (strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) < " + strMenor;
    } else {
    }
    if (strHaving.equals("")) {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    } else {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    }
    strOrderby = strHaving + strOrderby;

    // Checks if there is a conversion rate for each of the transactions of
    // the report
    String strConvRateErrorMsg = "";
    OBError myMessage = null;
    myMessage = new OBError();
    if (strComparative.equals("Y")) {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.select(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strDateFromRef,
                DateTimeData.nDaysAfter(this, strDateToRef, "1"),
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    } else {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.selectNoComparative(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    }
    strConvRateErrorMsg = myMessage.getMessage();
    // If a conversion rate is missing for a certain transaction, an error
    // message window pops-up.
    if (!strConvRateErrorMsg.equals("") && strConvRateErrorMsg != null) {
      advisePopUp(
          request,
          response,
          "ERROR",
          Utility.messageBD(this, "NoConversionRateHeader", vars.getLanguage()),
          strConvRateErrorMsg);
    } else { // Otherwise, the report is launched
      if (data.length == 0 || data == null) {
        data = ReportRefundSalesDimensionalAnalysesData.set();
      } else {
        int contador = intDiscard;
        if (intAuxDiscard != -1) contador = intAuxDiscard;
        int k = 1;
        if (strComparative.equals("Y")) {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldTotalQtyNivel" + String.valueOf(j);
            discard1[k + 12] = "fieldTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 24] = "fieldUomsymbol" + String.valueOf(j);
            discard1[k + 6] = "fieldTotalRefQtyNivel" + String.valueOf(j);
            discard1[k + 18] = "fieldTotalRefRefundQtyNivel" + String.valueOf(j);
            k++;
          }
        } else {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldNoncomparativeTotalQtyNivel" + String.valueOf(j);
            discard1[k + 10] = "fieldNoncomparativeTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 20] = "fieldNoncomparativeUomsymbol" + String.valueOf(j);
            k++;
          }
        }
      }
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpCommon/ad_reports/ReportRefundSalesDimensionalAnalysesEdition",
                  discard1)
              .createXmlDocument();
      xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
      xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
      xmlDocument.setParameter("theme", vars.getTheme());
      xmlDocument.setParameter("eliminar2", discard[1]);
      xmlDocument.setParameter("eliminar3", discard[2]);
      xmlDocument.setParameter("eliminar4", discard[3]);
      xmlDocument.setParameter("eliminar5", discard[4]);
      xmlDocument.setParameter("eliminar6", discard[5]);
      xmlDocument.setParameter("eliminar7", discard[6]);
      xmlDocument.setParameter("title", strTitle);
      String strCurISOSym = Utility.stringISOSymbol(this, strCurrencyId);
      strCurISOSym = strCurISOSym.replace('(', ' ');
      strCurISOSym = strCurISOSym.replace(')', ' ');
      xmlDocument.setParameter("convisosym", strCurISOSym);
      xmlDocument.setParameter("constante", "100");
      if (strComparative.equals("Y")) {
        xmlDocument.setData("structure1", data);
      } else {
        xmlDocument.setData("structure2", data);
      }
      response.setContentType("text/html; charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.println(xmlDocument.print());
      out.close();
    }
  }
  @Override
  public void encodeBegin(FacesContext facesContext, UIComponent uiComponent) throws IOException {

    super.encodeBegin(facesContext, uiComponent);

    InputEditorInternal inputEditorInternal = (InputEditorInternal) uiComponent;
    ResponseWriter responseWriter = facesContext.getResponseWriter();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(portletRequest);
    httpServletRequest = new NonNamespacedHttpServletRequest(httpServletRequest);

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(portletResponse);
    PortletRequest liferayPortletRequest = getLiferayPortletRequest(portletRequest);
    boolean resourcePhase = (liferayPortletRequest instanceof ResourceRequest);
    Map<String, Object> attributes = inputEditorInternal.getAttributes();
    String onBlurMethod = (String) attributes.get("onBlurMethod");
    String editorImpl = (String) attributes.get("editorImpl");

    if (editorImpl == null) {
      editorImpl = CKEDITOR;
    }

    // Build up a URL that can be used to invoke the liferay-ui:input-editor JSP tag.
    String url = "/resources/liferay-ui/jsp/input-editor.jsp";
    StringBuilder queryString = new StringBuilder();
    queryString.append(StringPool.QUESTION);
    queryString.append("editorImpl");
    queryString.append(StringPool.EQUAL);
    queryString.append(editorImpl);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("height");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("height"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("initMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("initMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("name");
    queryString.append(StringPool.EQUAL);

    String editorName = (String) attributes.get("name");
    queryString.append(editorName);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("onChangeMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("onChangeMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("skipEditorLoading");
    queryString.append(StringPool.EQUAL);

    if (resourcePhase) {

      // FACES-1439: Ensure that the <script src=".../ckeditor.js" /> element is not included in the
      // response by
      // specifying skipEditorLoading="true" during Ajax requests.
      queryString.append(Boolean.TRUE.toString());
    } else {
      queryString.append(Boolean.FALSE.toString());
    }

    queryString.append(StringPool.AMPERSAND);
    queryString.append("toolbarSet");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("toolbarSet"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("width");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("width"));
    url = url + queryString.toString();

    // Invoke the tag and capture it's output in a String, rather than having the output go directly
    // to the
    // response.
    RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher(url);
    JspIncludeResponse jspIncludeResponse = new JspIncludeResponse(httpServletResponse);

    try {
      requestDispatcher.include(httpServletRequest, jspIncludeResponse);
    } catch (ServletException e) {
      logger.error(e.getMessage());
      throw new IOException(e.getMessage());
    }

    String bufferedResponse = jspIncludeResponse.getBufferedResponse();

    if (bufferedResponse != null) {

      // Note: Trim the buffered response since there is typically over 100 newlines at the
      // beginning.
      bufferedResponse = bufferedResponse.trim();

      // If rendering an instance of the CKEditor, then
      String editorType = EditorUtil.getEditorValue(httpServletRequest, editorImpl);

      if (editorType.indexOf(CKEDITOR) >= 0) {

        String namespace = portletResponse.getNamespace();

        // FACES-1441: The liferay-ui:input-editor JSP tag (and associated ckeditor.jsp file) do not
        // provide a
        // way to hook-in to the "onblur" callback feature of the CKEditor. In order to overcome
        // this
        // limitation, it is necessary to append a <script>...</script> to the response that
        // provides this
        // ability.
        String onBlurScript = getOnBlurScript(editorName, onBlurMethod, namespace);

        // If running within an Ajax request, include the "onblur" callback script must be included
        // directly
        // to the response.
        if (resourcePhase) {

          StringBuilder scriptMarkup = new StringBuilder();
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          scriptMarkup.append(StringPool.CDATA_OPEN);
          scriptMarkup.append(onBlurScript);
          scriptMarkup.append(COMMENT_CDATA_CLOSE);
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.FORWARD_SLASH);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          bufferedResponse = bufferedResponse.concat(scriptMarkup.toString());
        }

        // Otherwise, append the script to the "LIFERAY_SHARED_AUI_SCRIPT_DATA" request attribute,
        // which will
        // cause the script to be rendered at the bottom of the portal page.
        else {

          ScriptData scriptData =
              (ScriptData) externalContext.getRequestMap().get(WebKeys.AUI_SCRIPT_DATA);
          scriptData.append(getPortletId(portletRequest), onBlurScript, null);
        }

        // FACES-1439: If the component was rendered on the page on the previous JSF lifecycle, then
        // prevent it
        // from being re-initialized by removing all <script>...</script> elements.
        boolean scriptsRemoved = false;

        String clientId = inputEditorInternal.getClientId();

        if (resourcePhase && inputEditorInternal.isPreviouslyRendered()) {

          logger.debug("Preventing re-initialization of CKEditor for clientId=[{0}]", clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();
          scriptsRemoved = true;
        }

        // FACES-1422: Move the scripts to the <eval>...</eval> section of the partial-response so
        // that they
        // will execute properly. This has the added benefit of preempt a DOM-diff with ICEfaces.
        if (resourcePhase && !scriptsRemoved) {

          logger.debug(
              "Moving CKEditor scripts to <eval>...</eval> section of the partial-response for clientId=[{0}]",
              clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();

          String scripts = parsedResponse.getScripts();

          LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
          liferayFacesContext.getJavaScriptMap().put(clientId, scripts);
          logger.trace(scripts);
        }
      }

      // Write the captured output from the JSP tag to the Faces responseWriter.
      logger.trace(bufferedResponse);
      responseWriter.write(bufferedResponse);
    }
  }
示例#26
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuffer redirectURL = new StringBuffer(100);
    StringBuffer gotoURL = new StringBuffer(100);

    // Check if user has authenticated to another OpenSSO
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          showError(response, "GOTO or TARGET parameter is missing" + " in the request");
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String cdcurl = SystemProperties.get(Constants.CDCSERVLET_LOGIN_URL);
        if (cdcurl != null && cdcurl.length() > 0) {
          if (cdcurl.indexOf("?") == -1) {
            redirectURLStr = cdcurl + QUESTION_MARK;
          } else {
            redirectURLStr = cdcurl + AMPERSAND;
          }
        } else {
          redirectURLStr = AUTHURI + QUESTION_MARK;
        }
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet init redirect URL is" + "set to= " + redirectURLStr);
        }

        redirectURL.append(redirectURLStr);
        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        // Check for policy advices
        if (policyAdviceList != null) {
          redirectURL.append(AMPERSAND).append(policyAdviceList);
        }
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
示例#27
0
  /**
   * Redirects the HTTP request to the Authentication module. It gets the authentication url from
   * <code>SystemProperties</code>.
   *
   * @param request an HttpServletRequest object that contains the request the client has made of
   *     the servlet.
   * @param response an HttpServletResponse object that contains the response the servlet sends to
   *     the client.
   * @exception IOException If an input or output exception occurs
   */
  private void redirectForAuthentication(
      HttpServletRequest request,
      HttpServletResponse response,
      String policyAdviceList,
      String requestParams)
      throws IOException {
    if (debug.messageEnabled()) {
      debug.message(
          "CDCClientServlet.redirectForAuthentication: " + "requestURL=" + request.getRequestURL());
    }
    StringBuilder redirectURL = new StringBuilder(100);
    StringBuilder gotoURL = new StringBuilder(100);

    // Check if user has authenticated to another OpenAM
    // instance
    String authURL = null;
    Cookie authCookie = CookieUtils.getCookieFromReq(request, authURLCookieName);
    if (authCookie != null) {
      authURL = CookieUtils.getCookieValue(authCookie);
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication: "
                + "got an authenticated URL= "
                + authURL);
      }
    }
    try {
      if (authURL == null
          || authURL.length() == 0
          || !authURL.toLowerCase().startsWith("http")
          || policyAdviceList != null) {
        String finalURL = request.getParameter(GOTO_PARAMETER);

        if (finalURL == null || finalURL.equals("")) {
          finalURL = request.getParameter(TARGET_PARAMETER);
        }

        if (finalURL == null || finalURL.equals("")) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication: "
                    + "goto or target parameter is missing in the request.");
          }

          showError(response, SERVER_ERROR_STR_MATCH);
          return;
        }

        gotoURL
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(TARGET_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(finalURL))
            .append(AMPERSAND)
            .append(requestParams);

        // Construct the login URL
        String loginURI = request.getParameter(LOGIN_URI);
        String cdcUri;

        if (loginURI != null && !loginURI.isEmpty() && isValidCDCURI(loginURI)) {
          if (debug.messageEnabled()) {
            debug.message(
                "CDCClientServlet.redirectForAuthentication:found " + LOGIN_URI + "=" + loginURI);
          }

          cdcUri = loginURI;
        } else {
          cdcUri = cdcAuthURI;
        }

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication: Login URI is set to = " + cdcUri);
        }

        if (cdcUri.indexOf(QUESTION_MARK) == -1) {
          redirectURL.append(cdcUri).append(QUESTION_MARK);
        } else {
          redirectURL.append(cdcUri).append(AMPERSAND);
        }

        if (policyAdviceList != null) {
          redirectURL.append(policyAdviceList).append(AMPERSAND);
        }
        redirectURL
            .append(GOTO_PARAMETER)
            .append(EQUAL_TO)
            .append(URLEncDec.encode(gotoURL.toString()));

        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.redirectForAuthentication"
                  + ":redirectURL before dispatching is="
                  + redirectURL);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(redirectURL.toString());
        dispatcher.forward(request, response);
      } else {
        // Redirect the user to the authenticated URL
        redirectURL
            .append(authURL)
            .append(deployDescriptor)
            .append(CDCURI)
            .append(QUESTION_MARK)
            .append(request.getQueryString());
        // Reset the cookie value to null, to avoid continuous loop
        // when a load balancer is used
        if (authCookie != null) {
          authCookie.setValue("");
          response.addCookie(authCookie);
        }
        response.sendRedirect(redirectURL.toString());
      }

      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.redirectForAuthentication:"
                + "Forwarding for authentication to= "
                + redirectURL);
      }
    } catch (IOException ex) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication: Failed "
              + "in forwarding to Authentication service. IOException",
          ex);
      showError(response, "Could for forward to authentication service:" + ex.getMessage());
    } catch (ServletException se) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. ServletException",
          se);
      showError(response, "Could for forward to authentication service:" + se.getMessage());
    } catch (IllegalStateException ie) {
      debug.error(
          "CDCClientServlet.redirectForAuthentication : Failed "
              + "in forwarding to Authentication service. Illegal state",
          ie);
      showError(response, "Could for forward to authentication service:" + ie.getMessage());
    }
  }
示例#28
0
  /**
   * Creates a transaction from the provided request and response and then processes that
   * transaction by executing the target template.
   *
   * @param request the user's http request
   * @param response the user's http response
   */
  private boolean processTemplate(ApplicationRequest appRequest, ApplicationResponse appResponse)
      throws IOException {

    // check if redirect or erroring out
    if (appResponse.isRedirectOrError()) {
      return false;
    }

    // set initial content type and helper attributes
    appResponse.setContentType("text/html");
    appRequest.setAttribute(this.getClass().getName(), this);

    // lookup template
    Template template = (Template) appRequest.getTemplate();

    // process as resource if no template available
    if (template == null) {
      if (!processResource(appRequest, appResponse)) {
        appResponse.sendError(404);
        return false;
      }
      return true;
    }

    long endTime = 0L;
    long startTime = 0L;
    long contentLength = 0;

    TemplateStats templateStats = null;
    if (mInstrumentationEnabled) {
      templateStats = mTeaServletRequestStats.getStats(template.getName());
    }

    try {
      Object[] params = null;
      try {
        if (templateStats != null) {
          templateStats.incrementServicing();
        }

        // Fill in the parameters to pass to the template.
        Class<?>[] paramTypes = template.getParameterTypes();
        if (paramTypes.length == 0) {
          params = NO_PARAMS;
        } else {
          params = new Object[paramTypes.length];
          String[] paramNames = template.getParameterNames();
          for (int i = 0; i < paramNames.length; i++) {
            String paramName = paramNames[i];
            if (paramName == null) {
              continue;
            }

            Class<?> paramType = paramTypes[i];

            if (!paramType.isArray()) {
              String value = appRequest.getParameter(paramName);
              if (value == null || paramType == String.class) {
                params[i] = value;
              } else {
                params[i] = convertParameter(value, paramType);
              }
            } else {
              String[] values = appRequest.getParameterValues(paramName);
              if (values == null || paramType == String[].class) {
                params[i] = values;
              } else {
                paramType = paramType.getComponentType();
                Object converted = Array.newInstance(paramType, values.length);
                params[i] = converted;
                for (int j = 0; j < values.length; j++) {
                  Array.set(converted, j, convertParameter(values[j], paramType));
                }
              }
            }
          }
        }

        startTime = System.currentTimeMillis();
        try {
          try {
            appRequest.getTemplate().execute(appResponse.getHttpContext(), params);
          } catch (ContextCreationException cce) {
            // unwrap the inner exception
            throw (Exception) cce.getUndeclaredThrowable();
          }
        } catch (AbortTemplateException e) {
          if (DEBUG) {
            mLog.debug("Template execution aborted!");
            mLog.debug(e);
          }
        } catch (RuntimeException e) {
          if (getEngine().getTemplateSource().isExceptionGuardianEnabled()) {
            // Just log the error and use what the template wrote out.
            mLog.error(e);
          } else {
            throw new ServletException(e);
          }
        } catch (IOException e) {
          // TODO: shouldn't we be throwing this as a ServletException?
          //       otherwise its not logged to the TeaLog.
          throw e;
        } catch (ServletException e) {
          throw e;
        } catch (Exception e) {
          throw new ServletException(e);
        }
        // TODO: shouldn't we be catching errors and not just exceptions?
        //       otherwise its not logged to the TeaLog.
        finally {
          endTime = System.currentTimeMillis();
          if (appRequest instanceof TeaServletStats) {
            long duration = endTime - startTime;
            ((TeaServletStats) appRequest).setTemplateDuration(duration);
          }
        }

        if (DEBUG) {
          mLog.debug("Finished executing template");
        }
      } catch (ServletException e) {
        // Log exception
        StringBuffer msg = new StringBuffer();
        msg.append("Error processing request for ");
        msg.append(appRequest.getRequestURI());
        if (appRequest.getQueryString() != null) {
          msg.append('?');
          msg.append(appRequest.getQueryString());
        }
        mLog.error(msg.toString());

        Throwable t = e;
        while (t instanceof ServletException) {
          e = (ServletException) t;
          if (e.getRootCause() != null) {
            String message = e.getMessage();
            if (message != null && message.length() > 0) {
              mLog.error(message);
            }
            mLog.error(t = e.getRootCause());
          } else {
            mLog.error(e);
            break;
          }
        }

        // Internal server error unless header is already set
        if (!appResponse.isRedirectOrError()) {
          String displayMessage = e.getLocalizedMessage();
          if (displayMessage == null || displayMessage.length() == 0) {
            appResponse.sendError(ApplicationResponse.SC_INTERNAL_SERVER_ERROR);
          } else {
            appResponse.sendError(ApplicationResponse.SC_INTERNAL_SERVER_ERROR, displayMessage);
          }
        }
      }
      contentLength = appResponse.getResponseBuffer().getByteCount();
      appResponse.finish();
      if (templateStats != null) {
        templateStats.decrementServicing();
        templateStats.log(startTime, endTime, contentLength, params);
      }
    } catch (Exception e) {
      if (templateStats != null) {
        templateStats.decrementServicing();
      }
    }
    return true;
  }
  private OBError processButton(
      VariablesSecureApp vars,
      String strKey,
      String strProjectType,
      String strDateFrom,
      String windowId) {
    Connection conn = null;
    OBError myMessage = new OBError();
    if (strProjectType == null || strProjectType.equals("")) {
      try {
        releaseRollbackConnection(conn);
      } catch (Exception ignored) {
      }
      log4j.warn("Rollback in transaction");
      myMessage.setType("Error");
      myMessage.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
      myMessage.setMessage(Utility.messageBD(this, "NoProjectTypeSelected", vars.getLanguage()));
    } else {
      try {
        conn = this.getTransactionConnection();
        ProjectSetTypeData[] data = ProjectSetTypeData.select(this, strProjectType);
        ProjectSetTypeData[] dataProject = ProjectSetTypeData.selectProject(this, strKey);
        String strProjectPhase = "";
        String strProjectTask = "";
        // Variables used for Project Scheduling purposes
        DateFormat DateFormatter = Utility.getDateFormatter(vars);
        int firstProjectPhase = 0;
        String strPhaseStartDate = "";
        String strPhaseContractDate = "";
        String strTaskStartDate = "";
        String strTaskContractDate = "";
        String strLastContractDate = "";

        for (int i = 0; data != null && i < data.length; i++) {
          strProjectPhase = SequenceIdData.getUUID();

          // Calculates the Starting Date of the Phase
          if (firstProjectPhase == 0) {
            strPhaseStartDate = strDateFrom;
          } else {
            strPhaseStartDate = calculateStartDate(strLastContractDate, DateFormatter);
          }
          // Calculates the Contract Date of the Phase
          strPhaseContractDate =
              calculateContractDate(strPhaseStartDate, data[i].stdduration, DateFormatter);

          try {
            if (ProjectSetTypeData.insertProjectPhase(
                    conn,
                    this,
                    strKey,
                    dataProject[0].adClientId,
                    dataProject[0].adOrgId,
                    vars.getUser(),
                    data[i].description,
                    data[i].mProductId,
                    data[i].cPhaseId,
                    strProjectPhase,
                    data[i].help,
                    data[i].name,
                    data[i].standardqty,
                    strPhaseStartDate,
                    strPhaseContractDate,
                    data[i].seqno)
                == 1) {
              strLastContractDate = strPhaseContractDate;
              ProjectSetTypeData[] data1 = ProjectSetTypeData.selectTask(this, data[i].cPhaseId);
              int firstProjectTask = 0;
              for (int j = 0; data1 != null && j < data1.length; j++) {
                strProjectTask = SequenceIdData.getUUID();

                // Calculates the Starting Date of the Task
                if (firstProjectTask == 0) {
                  strTaskStartDate = strPhaseStartDate;
                } else {
                  strTaskStartDate = calculateStartDate(strLastContractDate, DateFormatter);
                }
                // Calculates the Contract Date of the Task
                strTaskContractDate =
                    calculateContractDate(strTaskStartDate, data1[j].stdduration, DateFormatter);

                try {
                  ProjectSetTypeData.insertProjectTask(
                      conn,
                      this,
                      strProjectTask,
                      data1[j].cTaskId,
                      dataProject[0].adClientId,
                      dataProject[0].adOrgId,
                      vars.getUser(),
                      data1[j].seqno,
                      data1[j].name,
                      data1[j].description,
                      data1[j].help,
                      data1[j].mProductId,
                      strProjectPhase,
                      data1[j].standardqty,
                      strTaskStartDate,
                      strTaskContractDate);
                } catch (ServletException ex) {
                  myMessage =
                      Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                  releaseRollbackConnection(conn);
                  return myMessage;
                }

                strLastContractDate = strTaskContractDate;
                firstProjectTask++;
              }
              firstProjectPhase++;
            }
          } catch (ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
          }
        }

        // Updates project's Type and category
        String strProjectCategory = ProjectSetTypeData.selectProjectCategory(this, strProjectType);
        try {
          ProjectSetTypeData.update(
              conn, this, vars.getUser(), strProjectType, strProjectCategory, strKey);
        } catch (ServletException ex) {
          myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          releaseRollbackConnection(conn);
          return myMessage;
        }

        // Updates project's Starting and Contract Dates
        ProjectSetTypeData[] dataDates = ProjectSetTypeData.selectDates(this, strKey);
        String strStartDate = strDateFrom.equals("") ? dataDates[0].startdate : strDateFrom;
        String strContractDate =
            strLastContractDate.equals("") ? dataDates[0].datecontract : strLastContractDate;
        try {
          ProjectSetTypeData.updateDates(
              conn, this, vars.getUser(), strStartDate, strContractDate, strKey);
        } catch (ServletException ex) {
          myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
          releaseRollbackConnection(conn);
          return myMessage;
        }

        releaseCommitConnection(conn);
        myMessage.setType("Success");
        myMessage.setTitle(Utility.messageBD(this, "Success", vars.getLanguage()));
      } catch (Exception e) {
        try {
          releaseRollbackConnection(conn);
        } catch (Exception ignored) {
        }
        e.printStackTrace();
        log4j.warn("Rollback in transaction");
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage());
      }
    }
    return myMessage;
  }