Пример #1
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      System.out.println(request.getReader().readLine());
    } catch (Exception e) {
      // e.printStackTrace();
      _log.error(" error " + e.getMessage());
    }
  }
Пример #2
0
  /** @service the servlet service request. called once for each servlet request. */
  public void service(HttpServletRequest servReq, HttpServletResponse servRes) throws IOException {
    String name;
    String value[];
    String val;

    servRes.setHeader("AUTHORIZATION", "user fred:mypassword");
    ServletOutputStream out = servRes.getOutputStream();

    HttpSession session = servReq.getSession(true);
    session.setAttribute("timemilis", new Long(System.currentTimeMillis()));
    if (session.isNew()) {
      out.println("<p> Session is new ");
    } else {
      out.println("<p> Session is not new ");
    }
    Long l = (Long) session.getAttribute("timemilis");
    out.println("<p> Session id = " + session.getId());
    out.println("<p> TimeMillis = " + l);

    out.println("<H2>Servlet Params</H2>");
    Enumeration e = servReq.getParameterNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      value = servReq.getParameterValues(name);
      out.println(name + " : ");
      for (int i = 0; i < value.length; ++i) {
        out.println(value[i]);
      }
      out.println("<p>");
    }

    out.println("<H2> Request Headers : </H2>");
    e = servReq.getHeaderNames();
    while (e.hasMoreElements()) {
      name = (String) e.nextElement();
      val = (String) servReq.getHeader(name);
      out.println("<p>" + name + " : " + val);
    }
    try {
      BufferedReader br = servReq.getReader();
      String line = null;
      while (null != (line = br.readLine())) {
        out.println(line);
      }
    } catch (IOException ie) {
      ie.printStackTrace();
    }

    session.invalidate();
  }
Пример #3
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    // Actual logic goes here.

    // System.out.print("Test");

    StringBuilder sb = new StringBuilder();
    try (BufferedReader reader = request.getReader()) {
      String line;
      while ((line = reader.readLine()) != null) {
        sb.append(line).append('\n');
      }
    }

    try {
      JSONObject jsonObject = new JSONObject(sb.toString());

      JSONObject message = jsonObject.getJSONObject("message");
      String command = message.getString("text");
      if (BotHelper.command(command, "/echo")) {
        functions.echo(jsonObject);
      } else if (BotHelper.command(command, "/engage")) {
        functions.engage(jsonObject);
      } else if (BotHelper.command(command, "/debug")) {
        functions.debugjson(jsonObject);
      } else if (BotHelper.command(command, "/amazon")) {
        functions.searchAmazon(jsonObject);
      } else if (BotHelper.command(command, "/decide")) {
        functions.decide(jsonObject);
      } else if (BotHelper.command(command, "/ohkadsewasessenwirheute")) {
        functions.ohkadsewasessenwirheute(jsonObject);
      } else if (BotHelper.command(command, "/ohmagischekadse")) {
        functions.ohmagischekadse(jsonObject);
      } else if (BotHelper.command(command, "/otherchat")) {
        functions.otherChat(jsonObject);
      } else if ((BotHelper.command(command, "/help")) || (BotHelper.command(command, "/?"))) {
        functions.help(jsonObject);
      } else {
        functions.unknown(jsonObject);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #4
0
  private static String getBody(HttpServletRequest req) {
    try {
      // Try reading the post body using characters.
      // This might throw an exception if something on the
      // server side already called getInputStream().
      // In that case we'll pull as bytes.
      Reader reader = null;
      try {
        reader = new BufferedReader(req.getReader());
      } catch (IOException e) {
        reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
      }

      StringBuffer sbuf = new StringBuffer();
      char[] cbuf = new char[4096];
      int count = 0;
      while ((count = reader.read(cbuf)) != -1) {
        sbuf.append(cbuf, 0, count);
      }
      return sbuf.toString();
    } catch (IOException e2) {
      throw new ServerProblemException("IOException in reading POST body: " + e2.getMessage());
    }
  }
  /*
   * 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 doProcess(HttpServletRequest req, HttpServletResponse res, boolean isPost) {
    StringBuffer bodyContent = null;
    OutputStream out = null;
    PrintWriter writer = null;
    String serviceKey = null;

    try {
      BufferedReader in = req.getReader();
      String line = null;
      while ((line = in.readLine()) != null) {
        if (bodyContent == null) bodyContent = new StringBuffer();
        bodyContent.append(line);
      }
    } catch (Exception e) {
    }
    try {
      if (requireSession) {
        // check to see if there was a session created for this request
        // if not assume it was from another domain and blow up
        // Wrap this to prevent Portlet exeptions
        HttpSession session = req.getSession(false);
        if (session == null) {
          res.setStatus(HttpServletResponse.SC_FORBIDDEN);
          return;
        }
      }
      serviceKey = req.getParameter("id");
      // only to preven regressions - Remove before 1.0
      if (serviceKey == null) serviceKey = req.getParameter("key");
      // check if the services have been loaded or if they need to be reloaded
      if (services == null || configUpdated()) {
        getServices(res);
      }
      String urlString = null;
      String xslURLString = null;
      String userName = null;
      String password = null;
      String format = "json";
      String callback = req.getParameter("callback");
      String urlParams = req.getParameter("urlparams");
      String countString = req.getParameter("count");
      // encode the url to prevent spaces from being passed along
      if (urlParams != null) {
        urlParams = urlParams.replace(' ', '+');
      }

      try {
        if (services.has(serviceKey)) {
          JSONObject service = services.getJSONObject(serviceKey);
          // default to the service default if no url parameters are specified
          if (urlParams == null && service.has("defaultURLParams")) {
            urlParams = service.getString("defaultURLParams");
          }
          String serviceURL = service.getString("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          String apikey = "";
          if (service.has("username")) userName = service.getString("username");
          if (service.has("password")) password = service.getString("password");
          if (service.has("apikey")) apikey = service.getString("apikey");
          urlString = serviceURL + apikey;
          if (urlParams != null) urlString += "&" + urlParams;
          if (service.has("xslStyleSheet")) {
            xslURLString = service.getString("xslStyleSheet");
          }
        }
        // code for passing the url directly through instead of using configuration file
        else if (req.getParameter("url") != null) {
          String serviceURL = req.getParameter("url");
          // build the URL
          if (urlParams != null && serviceURL.indexOf("?") == -1) {
            serviceURL += "?";
          } else if (urlParams != null) {
            serviceURL += "&";
          }
          urlString = serviceURL;
          if (urlParams != null) urlString += urlParams;
        } else {
          writer = res.getWriter();
          if (serviceKey == null)
            writer.write("XmlHttpProxyServlet Error: id parameter specifying serivce required.");
          else
            writer.write(
                "XmlHttpProxyServlet Error : service for id '" + serviceKey + "' not  found.");
          writer.flush();
          return;
        }
      } catch (Exception ex) {
        getLogger().severe("XmlHttpProxyServlet Error loading service: " + ex);
      }

      Map paramsMap = new HashMap();
      paramsMap.put("format", format);
      // do not allow for xdomain unless the context level setting is enabled.
      if (callback != null && allowXDomain) {
        paramsMap.put("callback", callback);
      }
      if (countString != null) {
        paramsMap.put("count", countString);
      }

      InputStream xslInputStream = null;

      if (urlString == null) {
        writer = res.getWriter();
        writer.write(
            "XmlHttpProxyServlet parameters:  id[Required] urlparams[Optional] format[Optional] callback[Optional]");
        writer.flush();
        return;
      }
      // default to JSON
      res.setContentType(responseContentType);
      out = res.getOutputStream();
      // get the stream for the xsl stylesheet
      if (xslURLString != null) {
        // check the web root for the resource
        URL xslURL = null;
        xslURL = ctx.getResource(resourcesDir + "xsl/" + xslURLString);
        // if not in the web root check the classpath
        if (xslURL == null) {
          xslURL =
              XmlHttpProxyServlet.class.getResource(classpathResourcesDir + "xsl/" + xslURLString);
        }
        if (xslURL != null) {
          xslInputStream = xslURL.openStream();
        } else {
          String message =
              "Could not locate the XSL stylesheet provided for service id "
                  + serviceKey
                  + ". Please check the XMLHttpProxy configuration.";
          getLogger().severe(message);
          try {
            out.write(message.getBytes());
            out.flush();
            return;
          } catch (java.io.IOException iox) {
          }
        }
      }
      if (!isPost) {
        xhp.doGet(urlString, out, xslInputStream, paramsMap, userName, password);
      } else {
        if (bodyContent == null)
          getLogger()
              .info(
                  "XmlHttpProxyServlet attempting to post to url "
                      + urlString
                      + " with no body content");
        xhp.doPost(
            urlString,
            out,
            xslInputStream,
            paramsMap,
            bodyContent.toString(),
            req.getContentType(),
            userName,
            password);
      }
    } catch (Exception iox) {
      iox.printStackTrace();
      getLogger().severe("XmlHttpProxyServlet: caught " + iox);
      try {
        writer = res.getWriter();
        writer.write(iox.toString());
        writer.flush();
      } catch (java.io.IOException ix) {
        ix.printStackTrace();
      }
      return;
    } finally {
      try {
        if (out != null) out.close();
        if (writer != null) writer.close();
      } catch (java.io.IOException iox) {
      }
    }
  }
 public BufferedReader getReader() throws IOException {
   return request.getReader();
 }
Пример #8
0
 protected <T> T readRequest(final HttpServletRequest httpServletRequest, final Class<T> classOfT)
     throws IOException {
   final BufferedReader br = new BufferedReader(httpServletRequest.getReader());
   Gson gson = new Gson();
   return gson.fromJson(br, classOfT);
 }
Пример #9
0
  @Override
  /**
   * This method handles the voting on answers
   *
   * @param request request from user
   * @param response response back send to the user
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    WebAppDB db = new WebAppDB();
    ResultSet answer1;
    db.createConnection();
    try {
      db.setAutoCommit();
    } catch (SQLException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    StringBuilder sb = new StringBuilder();
    BufferedReader br = request.getReader();
    String str = null;
    while ((str = br.readLine()) != null) {
      sb.append(str);
    }
    String data = new Gson().fromJson(sb.toString(), String.class);
    String upVotestr = data.substring(1, 2);
    String idstr = data.substring(3, data.length() - 1);
    Integer id = Integer.parseInt(idstr);
    Integer upVote = Integer.parseInt(upVotestr);
    ResultSet numOfLikesSet =
        db.executeQuery("select Likes as A from ANSWERS where AID = " + id.intValue());
    ResultSet QIDSet = db.executeQuery("select QID as A from ANSWERS where AID = " + id.intValue());
    String numOfLikesStr = "";
    String QIDStr = "";
    try {
      if (numOfLikesSet.next()) numOfLikesStr = numOfLikesSet.getString("A");
      if (QIDSet.next()) QIDStr = QIDSet.getString("A");
      int numOfLikesInt =
          Integer.parseInt(
              numOfLikesStr); // numOfLikesInt contains the number of likes at the current moment
      if (upVote == 1) numOfLikesInt++;
      else if (upVote == 0) numOfLikesInt--;
      if (upVote != null && id != null) {
        db.executeUpdate(
            "update ANSWERS set likes =" + numOfLikesInt + "where AID = " + id.intValue());
      }
      List<Answer> answersToPresent = new ArrayList<Answer>();
      answer1 =
          db.executeQuery(
              "select * from "
                  + tableName
                  + " WHERE QID="
                  + QIDStr
                  + " order by Likes desc, Time asc");

      while (answer1.next()) {
        // there is such an answer
        Answer A = new Answer(-1, -1, "", "");
        A.setQID(Integer.parseInt(QIDStr));
        A.setText(answer1.getString("Text"));
        A.setTime(answer1.getString("Time"));
        A.setUID(answer1.getString("UID"));
        A.setAID(answer1.getInt("AID"));
        A.setLikes(answer1.getInt("Likes"));
        answersToPresent.add(A);
      }
      answer1.close();
      String json = new Gson().toJson(answersToPresent);
      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().write(json);
      response.getWriter().close();
      db.closeConnection();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      db.closeConnection();
    }
  }