Example #1
0
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    int a = Integer.parseInt(request.getParameter("a"));
    int b = Integer.parseInt(request.getParameter("b"));
    String op = request.getParameter("op");

    int result = 0;

    switch (op) {
      case "+":
        result = a + b;
        break;
      case "-":
        result = a - b;
        break;
      case "*":
        result = a * b;
        break;
      case "/":
        result = a / b;
        break;
    }

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<body>");
    out.println("<p>" + a + " " + op + " " + b + " = " + result + "</p>");
    out.println("</body>");
    out.println("</html>");
  }
Example #2
0
  private void sendProcessingError(Throwable t, ServletResponse response) {
    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {
      try {
        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
      } catch (Exception ex) {
      }
    }
  }
Example #3
0
  @Override
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
      throws IOException, ServletException {
    m_logger.info("PublisherFilter doFilter");

    HttpServletRequest httpReq = (HttpServletRequest) req;

    String remoteReq = httpReq.getRequestURL().toString();
    int idx = remoteReq.lastIndexOf('/');
    String res = null;
    try {
      String id = req.getParameter("id");
      if (remoteReq.substring(idx).startsWith("/info")) {
        res = m_helper.getInfo(id);
        m_logger.debug(" Pub id=" + id + " " + res);
        if (res == null) {
          req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e200");
        } else {
          resp.setContentType("text/json");
          PrintWriter pm = resp.getWriter();
          pm.write(res);
          pm.close();
        }
      }
    } catch (PaperMinerException ex) {
      req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e201");
    }

    filterChain.doFilter(req, resp);
    return;
  }
Example #4
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse rpo = (HttpServletResponse) response;
    javax.servlet.http.HttpSession session = req.getSession();

    try {
      req.setCharacterEncoding("utf-8");
    } catch (Exception e1) {
      e1.printStackTrace();
    }
    String userId = (String) session.getAttribute("username");
    if (userId != null) {
      try {
        chain.doFilter(request, response);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      try {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        out.print("{'success':false,'msg':'未登录或登录失效'}");
        out.flush();
        out.close();
        // rpo.sendRedirect("/login.jsp");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
      throw new ServletException("Only HttpServletRequest requests are supported");
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // extract the callback method from the request query parameters
    String callback = getCallbackMethod(httpRequest);

    if (!isJSONPRequest(callback)) {
      // Request is not a JSONP request move on
      chain.doFilter(request, response);
    } else {
      // Need to check if the callback method is safe
      if (!SAFE_PRN.matcher(callback).matches()) {
        throw new ServletException(
            "JSONP Callback method '" + CALLBACK_METHOD + "' parameter not valid function");
      }

      // Will stream updated response
      final ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

      // Create a custom response wrapper to adding in the padding
      HttpServletResponseWrapper responseWrapper =
          new HttpServletResponseWrapper(httpResponse) {

            @Override
            public ServletOutputStream getOutputStream() throws IOException {
              return new ServletOutputStream() {
                @Override
                public void write(int b) throws IOException {
                  byteStream.write(b);
                }
              };
            }

            @Override
            public PrintWriter getWriter() throws IOException {
              return new PrintWriter(byteStream);
            }
          };

      // Process the rest of the filter chain, including the JAX-RS request
      chain.doFilter(request, responseWrapper);

      // Override response content and encoding
      response.setContentType(CONTENT_TYPE);
      response.setCharacterEncoding("UTF-8");

      // Write the padded updates to the output stream.
      response.getOutputStream().write((callback + "(").getBytes());
      response.getOutputStream().write(byteStream.toByteArray());
      response.getOutputStream().write(");".getBytes());
    }
  }
Example #6
0
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    System.out.println("service");

    // 최초로 파라미터 값을 꺼내기 전에 클라이언트가 보낸 문자의 코드를 먼저 설정해야 한다.
    // 단, POST 방식에만 해당!
    // GET? 서블릿 컨테이너 마다 달라요!
    // 톰캣은? 구글링!
    request.setCharacterEncoding("UTF-8");

    String name = request.getParameter("name");
    int age = Integer.parseInt(request.getParameter("age"));

    char c;
    for (int i = 0; i < name.length(); i++) {
      c = name.charAt(i);
      System.out.println(Integer.toHexString(c));
    }

    response.setContentType("text/plain;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("안녕하세요!");
    out.println("이름: " + name);
    out.println("나이: " + age);
  }
  @SuppressWarnings("squid:S00112")
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {

    // create response wrapper to capture the output stream from  further down the filter chain
    ResponseWrapper respWrap = new ResponseWrapper((HttpServletResponse) servletResponse);

    filterChain.doFilter(servletRequest, respWrap);

    HttpServletRequest req = (HttpServletRequest) servletRequest;

    // Print out info from request & response wrapper
    LOG.info("URI: {}", req.getRequestURI());
    LOG.info("Status: {}", respWrap.getStatus());
    LOG.info("resp Header 'Content-Type: {}", respWrap.getHeader("Content-Type"));

    String content = respWrap.getContent();

    LOG.info("Content Body: '{}'", content);

    // verify that the content is not empty.  This fails in repose but works in tomcat
    if (content.isEmpty()) {
      throw new RuntimeException("Content is empty");
    }

    // writer content to the actual servletResponse & append additional content
    servletResponse
        .getWriter()
        .write(
            content
                + "<extra> Added by TestFilter, should also see the rest of the content </extra>");
    servletResponse.getWriter().flush();
  }
Example #8
0
  @Override
  public void start() {
    if (_os != null || _writer != null) throw new IllegalStateException();

    ServletResponse next = _response.getResponse();
    if (next == null) throw new NullPointerException();

    if (next instanceof CauchoResponse) {
      CauchoResponse cNext = (CauchoResponse) next;

      if (cNext.isCauchoResponseStream()) _stream = cNext.getResponseStream();
    }

    _isCommitted = false;
    _headerKeys.clear();
    _headerValues.clear();

    super.start();

    // server/053n
    try {
      setEncoding(next.getCharacterEncoding());
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    }
  }
Example #9
0
  @Override
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    int no = Integer.parseInt(request.getParameter("no"));
    productDao.delete(no);

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<mete http-equiv='Refresh' content='5;url=list'>");
    out.println("<link rel='stylesheet' ");
    out.println("href='../../css/bootstrap.min.css'>");
    out.println("<link rel='stylesheet' ");
    out.println("href='../../css/bootstrap-theme.min.css'>");
    out.println("<link rel='stylesheet' href='../../css/common.css'>");
    out.println("</head>");
    out.println("<body>");
    out.println("<div class='container'>");
    out.println("<h1>삭제 결과</h1>");
    out.println("<p>삭제하였습니다.</p>");
    out.println("</div>");

    out.println("</body>");
    out.println("</html>");
  }
  @Test
  public void testPrepareResponse() throws UnknownHostException {
    HttpClientSPIAgent httpClientSPIAgent =
        new HttpClientSPIAgent(
            _spiConfiguration, new MockRegistrationReference(new MockIntraband()));

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();

    mockHttpServletRequest.setAttribute(WebKeys.SPI_AGENT_PORTLET, _portlet);

    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    HttpServletResponse httpServletResponse =
        httpClientSPIAgent.prepareResponse(mockHttpServletRequest, mockHttpServletResponse);

    Assert.assertSame(
        mockHttpServletResponse,
        mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_ORIGINAL_RESPONSE));
    Assert.assertNotNull(mockHttpServletRequest.getAttribute(WebKeys.SPI_AGENT_RESPONSE));

    Assert.assertSame(BufferCacheServletResponse.class, httpServletResponse.getClass());

    BufferCacheServletResponse bufferCacheServletResponse =
        (BufferCacheServletResponse) httpServletResponse;

    ServletResponse servletResponse = bufferCacheServletResponse.getResponse();

    Assert.assertSame(ReadOnlyServletResponse.class, servletResponse.getClass());

    ReadOnlyServletResponse readOnlyServletResponse = (ReadOnlyServletResponse) servletResponse;

    Assert.assertSame(mockHttpServletResponse, readOnlyServletResponse.getResponse());
  }
Example #11
0
  private void generateAPIResponse(ServletRequest request, ServletResponse response) {

    try {
      HttpServletRequest httpRequest = (HttpServletRequest) request;

      String message = "Server is under maintenance mode, please try later.";

      if (requestIsOfType(JSON, httpRequest)) {
        response.setContentType("application/json");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("message", message);
        response.getWriter().print(jsonObject);
      } else if (requestIsOfType(XML, httpRequest)) {
        response.setContentType("application/xml");
        String xml = String.format("<message> %s </message>", message);
        response.getWriter().print(xml);
      } else {
        generateHTMLResponse(response);
      }

    } catch (IOException e) {
      LOGGER.error(String.format("General IOException: %s", e.getMessage()));
    }
    ((HttpServletResponse) response).setStatus(503);
  }
Example #12
0
 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   response.setContentType("text/plain");
   response.getWriter().print("Filter");
   chain.doFilter(request, response);
 }
Example #13
0
  public void service(ServletRequest request, ServletResponse response)
      throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");

    out.println("<h1>hello Servlet</h1>");
  }
 @Override
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws IOException, ServletException {
   req.setCharacterEncoding("UTF-8");
   resp.setCharacterEncoding("UTF-8");
   resp.setLocale(Locale.getDefault());
   chain.doFilter(req, resp);
 }
 @Override
 public void doFilter(
     ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
     throws IOException, ServletException {
   servletResponse.getOutputStream().print("[");
   filterChain.doFilter(servletRequest, servletResponse);
   servletResponse.getOutputStream().print("]");
 }
Example #16
0
 // --> /demo/getAudio/getAudio
 @RequestMapping(value = "/getAudio", method = RequestMethod.GET)
 @ResponseBody
 public void getAudio(ServletResponse response) throws IOException {
   File imageFile = new File("E:\\My Music\\Nhac Chuong\\Sinbad.mp3");
   byte[] byteArray = IOUtils.toByteArray(new FileInputStream(imageFile));
   response.setContentType("audio/mpeg");
   response.getOutputStream().write(byteArray);
 }
Example #17
0
 // --> /demo/getAudio/getImage
 @RequestMapping(value = "/getImage", method = RequestMethod.GET)
 @ResponseBody
 public void getImage(ServletResponse response) throws IOException {
   File imageFile = new File("E:\\Hinh Anh\\WP_000337.png");
   byte[] byteArray = IOUtils.toByteArray(new FileInputStream(imageFile));
   response.setContentType("image/png");
   response.getOutputStream().write(byteArray);
 }
Example #18
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    if (null != request.getAttribute("FLAG")) {
      chain.doFilter(request, response);
      return;
    }
    request.setAttribute("FLAG", FLAG);

    String encoding = this.encoding;
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String resourcePath = req.getServletPath();
    RequestContext requestContext =
        new RequestContext(config.getServletContext(), req, resourcePath);
    request.setAttribute("context", requestContext);

    for (Decorator decorator : decorators) {
      int returned = decorator.parseRequest(req, res, requestContext);
      switch (returned) {
        case Decorator.OK:
          // do nothing
          break;
        case Decorator.REDIRECT:
          res.sendRedirect(requestContext.getResourcePath());
          return;
        case Decorator.MOVED_PERMANENTLY:
          res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
          res.setHeader("Location", requestContext.getResourcePath());
          return;
        default:
          // do nothing
      }
    }

    if (pattern.matcher(requestContext.getResourcePath()).matches()) {
      WebContent content = new WebContent();
      if (requestContext.getResourcePath().startsWith("/WEB-INF/admin/")) {
        encoding = "UTF-8";
      }
      ByteArrayResponseWrapper wrapper = new ByteArrayResponseWrapper(res);
      request.getRequestDispatcher(requestContext.getResourcePath()).include(req, wrapper);
      wrapper.finish();
      content.setWholeContent(wrapper.getString(encoding));
      response.setContentType(wrapper.getContentType());
      content.finish();

      for (Decorator decorator : decorators) {
        decorator.decorate(requestContext, content, content);
        content.finish();
      }
      byte[] theContent = content.toString().getBytes(encoding);
      response.setContentLength(theContent.length);
      response.getOutputStream().write(theContent);
      return;
    }
    request.getRequestDispatcher(requestContext.getResourcePath()).forward(req, res);
  }
Example #19
0
 public void service(ServletRequest req, ServletResponse res)
     throws ServletException, IOException {
   System.out.println("\n\n-----Service called----\n");
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   out.print("<html><body>");
   out.print("<b>hello simple servlet</b>");
   out.print("</body></html>");
 }
 @Override
 public void onError(AsyncEvent event) throws IOException {
   ServletResponse resp = event.getAsyncContext().getResponse();
   resp.getWriter().write("onError-");
   resp.flushBuffer();
   if (completeOnError) {
     event.getAsyncContext().complete();
   }
 }
Example #21
0
 private void generateResponseForIsBackupFinishedAPI(ServletResponse response) {
   response.setContentType("application/json");
   JsonObject json = new JsonObject();
   json.addProperty("is_backing_up", backupService.isBackingUp());
   try {
     response.getWriter().print(json);
   } catch (IOException e) {
     LOGGER.error(String.format("General IOException: %s", e.getMessage()));
   }
 }
 public String execute() throws IOException {
   ArrayList<MeetingRoom> tran;
   ServletResponse response = ServletActionContext.getResponse();
   response.setCharacterEncoding("utf-8");
   PrintWriter out = response.getWriter();
   DeleteMeetingRoomService show = new DeleteMeetingRoomService();
   tran = show.Showlist();
   JSONArray jsonArray = JSONArray.fromObject(tran);
   out.print(jsonArray);
   return null;
 }
 protected void writeData(ServletResponse response, String data) throws IOException {
   idleCheck.activity();
   Log.debug("Session[" + session.getSessionId() + "]: writeData(START): " + data);
   ServletOutputStream os = response.getOutputStream();
   os.println("Content-Type: text/plain");
   os.println();
   os.println(data);
   os.println(boundarySeperator);
   response.flushBuffer();
   Log.debug("Session[" + session.getSessionId() + "]: writeData(END): " + data);
 }
Example #24
0
  /**
   * @param pServletRequest parameter
   * @param pServletResponse parameter
   * @throws IOException exception
   * @throws ServletException exception
   */
  @Override
  public void handleService(ServletRequest pServletRequest, ServletResponse pServletResponse)
      throws IOException, ServletException {
    final ByteArrayOutputStream pdf = new ByteArrayOutputStream();
    final String deliveryId = pServletRequest.getParameter(DELIVERY_ID_PARAM);
    RepositoryItem orderBOItem = mOrderManager.getFactureBO(deliveryId);
    OutputStream out = null;

    if (orderBOItem != null) {
      RepositoryItem orderFOItem = mOrderManager.getOrderFO(orderBOItem);
      String profileId =
          (String) orderFOItem.getPropertyValue(CastoConstantesOrders.ORDER_PROPERTY_PROFILEID);
      String currProfileId = getProfileServices().getCurrentProfileId();
      if (!currProfileId.equalsIgnoreCase(profileId)) {
        if (isLoggingError()) {
          logError(
              "Facture with id="
                  + deliveryId
                  + " doesn't belong to profile with id="
                  + currProfileId);
        }
        return;
      }

      Map params = new HashMap();
      params.put(
          "url",
          pServletRequest.getScheme()
              + "://"
              + pServletRequest.getServerName()
              + ":"
              + pServletRequest.getServerPort());

      try {
        PrintPdfHelper.getInstance().generateInvoicePdf(pdf, orderBOItem, params, mCountryList);

        // Set header
        pServletResponse.setContentType(CONTENT_TYPE_PDF);
        pServletResponse.setContentLength(pdf.size());

        out = pServletResponse.getOutputStream();
        pdf.writeTo(out);
        out.flush();
      } catch (IOException e) {
        logError(e);
      } finally {
        if (out != null) {
          out.close();
        }
      }
    } else {
      logError("Facture with id=" + deliveryId + " was not found.");
    } // end if-else
  }
Example #25
0
 public void service(ServletRequest request, ServletResponse response)
     throws IOException, ServletException {
   PrintWriter out = response.getWriter();
   response.setContentType("text/html");
   out.println(
       "<h1>company "
           + conf.getInitParameter("company")
           + " @ "
           + conf.getInitParameter("location")
           + "</h1>");
 }
Example #26
0
  /**
   * 输出JSON
   *
   * @param response
   * @param json
   * @throws IOException
   */
  public static void writeJsonToResponse(ServletResponse response, JSONObject json)
      throws IOException {
    response.setContentType("text/html;charset=utf-8");

    /*//放开下面注释的代码就可以支持跨域
    if (response instanceof javax.servlet.http.HttpServletResponse) {
     //"*"表明允许任何地址的跨域调用,正式部署时应替换为正式地址
     ((javax.servlet.http.HttpServletResponse)response).addHeader("Access-Control-Allow-Origin", "*");
    }*/

    response.getWriter().write(json.toJSONString());
  }
Example #27
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
      throws IOException, ServletException {
    // Respect the client-specified character encoding
    // (see HTTP specification section 3.4.1)
    if (null == request.getCharacterEncoding()) request.setCharacterEncoding(encoding);

    /** Set the default response content type and encoding */
    response.setContentType("text/html; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");

    next.doFilter(request, response);
  }
 @Override
 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
     throws ServletException, IOException {
   String requestEncoding = req.getCharacterEncoding();
   if (initParamEncoding != null && !initParamEncoding.equalsIgnoreCase(requestEncoding)) {
     req.setCharacterEncoding(initParamEncoding);
     resp.setCharacterEncoding(initParamEncoding);
   }
   resp.setContentType("UTF-8");
   logger.debug("CharacterEncoding was set");
   chain.doFilter(req, resp);
 }
Example #29
0
 /**
  * Services this request in the same way as it would be serviced if configured as a Servlet. Does
  * not invoke any filters further down the chain. See the class-level comment for the reason why
  * this servlet might be configured as a filter.
  */
 @Override
 public void doFilter(
     final ServletRequest request, final ServletResponse response, final FilterChain chain)
     throws IOException, ServletException {
   if (Math.random() > 0.7d) {
     // response.setStatus(404);
     response.getWriter().println("The chaos monkey strikes again!");
     response.flushBuffer();
   } else {
     super.doFilter(request, response, chain);
   }
 }
Example #30
0
  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    servletResponse.setContentType(TYPE);
    servletRequest.setCharacterEncoding(ENCODING);

    servletResponse.setContentType(TYPE);
    servletResponse.setCharacterEncoding(ENCODING);

    filterChain.doFilter(servletRequest, servletResponse);
  }