@Override
 protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType(getContentType());
   response.addHeader("Pragma", "no-cache");
   response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
   response.addDateHeader("Expires", 0);
 }
  /** Sets mandatory headers, notably for anti-clickjacking. */
  @Override
  public void setCSPHeaders(DefDescriptor<?> top, HttpServletRequest req, HttpServletResponse rsp) {
    ContentSecurityPolicy csp =
        Aura.getConfigAdapter()
            .getContentSecurityPolicy(top == null ? null : top.getQualifiedName(), req);

    if (csp != null) {
      rsp.setHeader(CSP.Header.SECURE, csp.getCspHeaderValue());
      Collection<String> terms = csp.getFrameAncestors();
      if (terms != null) {
        // not open to the world; figure whether we can express an X-FRAME-OPTIONS header:
        if (terms.size() == 0) {
          // closed to any framing at all
          rsp.setHeader(HDR_FRAME_OPTIONS, HDR_FRAME_DENY);
        } else if (terms.size() == 1) {
          // With one ancestor term, we're either SAMEORIGIN or ALLOWFROM
          for (String site : terms) {
            if (site == null) {
              // Add same-origin headers and policy terms
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_SAMEORIGIN);
            } else if (!site.contains("*") && !site.matches("^[a-z]+:$")) {
              // XFO can't express wildcards or protocol-only, so set only for a specific site:
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_ALLOWFROM + site);
            } else {
              // When XFO can't express it, still set an ALLOWALL so filters don't jump in
              rsp.addHeader(HDR_FRAME_OPTIONS, HDR_FRAME_ALLOWALL);
            }
          }
        }
      }
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    String communityLogo = "PoweredByOpenbravo.png";
    String opsLogo = "PoweredByOpenbravoOPS.png";

    // get instance active status from db
    boolean active = false;
    OBContext.setAdminMode();
    try {
      active = ActivationKey.getInstance().isActive();
      log4j.debug("GetOpsLogo: activated: " + active);
    } finally {
      OBContext.restorePreviousMode();
    }

    String activeLogo;
    if (active) {
      activeLogo = opsLogo;
    } else {
      activeLogo = communityLogo;
    }

    FileUtility f =
        new FileUtility(this.globalParameters.prefix + "web/images", activeLogo, false, true);
    response.setContentType("image/png");
    // mark response as cache-forever
    response.addHeader("Expires", "Sun, 17 Jan 2038 19:14:07 GMT");
    response.addHeader("Cache-Control", "public");

    f.dumpFile(response.getOutputStream());
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }
  private void goodB2G_sink(String data, HttpServletRequest request, HttpServletResponse response)
      throws Throwable {

    /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
    data = URLEncoder.encode(data, "UTF-16");
    response.addHeader("Location", "/author.jsp?lang=" + data);
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    } else {

      java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");

      /* FIX: Use a hardcoded string */
      data = "foo";
    }
    if (IO.static_returns_t_or_f()) {
      /* POTENTIAL FLAW: Input from file not verified */
      response.addHeader("Location", "/author.jsp?lang=" + data);
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    }
  }
Exemple #6
0
  private void handlePartialPlayback(
      HttpServletRequest request,
      HttpServletResponse response,
      Vertex artifactVertex,
      String fileName,
      User user)
      throws IOException {
    String type = getRequiredParameter(request, "type");

    InputStream in;
    Long totalLength = null;
    long partialStart = 0;
    Long partialEnd = null;
    String range = request.getHeader("Range");

    if (range != null) {
      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

      Matcher m = RANGE_PATTERN.matcher(range);
      if (m.matches()) {
        partialStart = Long.parseLong(m.group(1));
        if (m.group(2).length() > 0) {
          partialEnd = Long.parseLong(m.group(2));
        }
      }
    }

    response.setCharacterEncoding(null);
    response.setContentType(type);
    response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

    StreamingPropertyValue mediaPropertyValue = getStreamingPropertyValue(artifactVertex, type);

    totalLength = mediaPropertyValue.getLength();
    in = mediaPropertyValue.getInputStream();

    if (partialEnd == null) {
      partialEnd = totalLength;
    }

    // Ensure that the last byte position is less than the instance-length
    partialEnd = Math.min(partialEnd, totalLength - 1);
    long partialLength = totalLength;

    if (range != null) {
      partialLength = partialEnd - partialStart + 1;
      response.addHeader(
          "Content-Range", "bytes " + partialStart + "-" + partialEnd + "/" + totalLength);
      if (partialStart > 0) {
        in.skip(partialStart);
      }
    }

    response.addHeader("Content-Length", "" + partialLength);

    OutputStream out = response.getOutputStream();
    copy(in, out, partialLength);

    response.flushBuffer();
  }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

    if (request.getHeader(ORIGIN) == null || request.getHeader(ORIGIN).equals("null")) {
      response.addHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.addHeader("Access-Control-Max-Age", "10");

      String reqHead = request.getHeader("Access-Control-Request-Headers");

      if (!StringUtils.isEmpty(reqHead)) {
        response.addHeader("Access-Control-Allow-Headers", reqHead);
      }
    }
    if (request.getMethod().equals("OPTIONS")) {
      try {
        response.getWriter().print("OK");
        response.getWriter().flush();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      filterChain.doFilter(request, response);
    }
  }
Exemple #8
0
 private void generaReporte(String tipo, List<Entrada> entradas, HttpServletResponse response)
     throws JRException, IOException {
   log.debug("Generando reporte {}", tipo);
   byte[] archivo = null;
   switch (tipo) {
     case "PDF":
       archivo =
           reporteUtil.generaPdf(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/pdf");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.pdf");
       break;
     case "CSV":
       archivo =
           reporteUtil.generaCsv(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("text/csv");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.csv");
       break;
     case "XLS":
       archivo =
           reporteUtil.generaXls(entradas, "/mx/edu/um/mateo/inventario/reportes/entradas.jrxml");
       response.setContentType("application/vnd.ms-excel");
       response.addHeader("Content-Disposition", "attachment; filename=entradas.xls");
   }
   if (archivo != null) {
     response.setContentLength(archivo.length);
     try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
       bos.write(archivo);
       bos.flush();
     }
   }
 }
  /* goodB2G() - use badsource and goodsink by changing the second "if" so that
   * both branches use the GoodSink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } else {

      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    }

    if (IO.staticReturnsTrueOrFalse()) {
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      if (data != null) {
        data = URLEncoder.encode(data, "UTF-8");
        response.addHeader("Location", "/author.jsp?lang=" + data);
      }
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      if (data != null) {
        data = URLEncoder.encode(data, "UTF-8");
        response.addHeader("Location", "/author.jsp?lang=" + data);
      }
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    int dbId = Integer.valueOf(req.getParameter("dbUsers"));

    try {

      UserResult userResult = dispatcher.execute(new GetUsers(dbId));

      DbUserExport export = new DbUserExport(userResult.getData());
      export.createSheet();

      resp.setContentType("application/vnd.ms-excel");
      if (req.getHeader("User-Agent").indexOf("MSIE") != -1) {
        resp.addHeader("Content-Disposition", "attachment; filename=ActivityInfo.xls");
      } else {
        resp.addHeader(
            "Content-Disposition",
            "attachment; filename="
                + ("ActivityInfo Export " + new Date().toString() + ".xls").replace(" ", "_"));
      }

      OutputStream os = resp.getOutputStream();
      export.getBook().write(os);

    } catch (Exception e) {
      e.printStackTrace();
      resp.setStatus(500);
    }
  }
  public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.staticReturnsTrueOrFalse()) {
      /* POTENTIAL FLAW: Read data from a querystring using getParameter */
      data = request.getParameter("name");
    } else {

      /* FIX: Use a hardcoded string */
      data = "foo";
    }

    if (IO.staticReturnsTrueOrFalse()) {
      /* POTENTIAL FLAW: Input from file not verified */
      if (data != null) {
        response.addHeader("Location", "/author.jsp?lang=" + data);
      }
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      if (data != null) {
        data = URLEncoder.encode(data, "UTF-8");
        response.addHeader("Location", "/author.jsp?lang=" + data);
      }
    }
  }
 /**
  * Download file entry of given path.
  *
  * @param user current user
  * @param path user
  * @param response response
  */
 @RequestMapping("/download/**")
 public void download(User user, @RemainedPath String path, HttpServletResponse response) {
   FileEntry fileEntry = fileEntryService.getFileEntry(user, path);
   if (fileEntry == null) {
     LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
     return;
   }
   response.reset();
   try {
     response.addHeader(
         "Content-Disposition",
         "attachment;filename="
             + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
   } catch (UnsupportedEncodingException e1) {
     LOG.error(e1.getMessage(), e1);
   }
   response.setContentType("application/octet-stream; charset=UTF-8");
   response.addHeader("Content-Length", "" + fileEntry.getFileSize());
   byte[] buffer = new byte[4096];
   ByteArrayInputStream fis = null;
   OutputStream toClient = null;
   try {
     fis = new ByteArrayInputStream(fileEntry.getContentBytes());
     toClient = new BufferedOutputStream(response.getOutputStream());
     int readLength;
     while (((readLength = fis.read(buffer)) != -1)) {
       toClient.write(buffer, 0, readLength);
     }
   } catch (IOException e) {
     throw new NGrinderRuntimeException("error while download file", e);
   } finally {
     IOUtils.closeQuietly(fis);
     IOUtils.closeQuietly(toClient);
   }
 }
  @Override
  public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) rsp;
    String contentEncoding = request.getHeader("content-encoding");
    String acceptEncoding = request.getHeader("accept-encoding");
    String contentType = request.getHeader("content-type");
    response.addHeader("access-control-allow-methods", "HEAD, POST, GET, PUT, PATCH, DELETE");
    response.addHeader("access-control-max-age", "86400");
    response.addHeader(
        "access-control-allow-headers",
        "accept, accept-charset, accept-encoding, accept-language, authorization, content-length, content-type, host, origin, proxy-connection, referer, user-agent, x-requested-with");
    response.addHeader("access-control-allow-credentials", "true");
    response.addHeader("access-control-allow-origin", "*");

    if ((contentEncoding != null) && (contentEncoding.toLowerCase().indexOf("gzip") > -1)) {
      request = new GZIPRequestWrapper(request);
    }
    if (((acceptEncoding != null) && (acceptEncoding.toLowerCase().indexOf("gzip") > -1))
        || ((contentType != null) && mimeTypes.contains(contentType))) {
      response = new GZIPResponseWrapper(response);
    }
    chain.doFilter(request, response);
    if (response instanceof GZIPResponseWrapper) {
      OutputStream os = response.getOutputStream();
      if (os instanceof GZIPResponseStream) {
        ((GZIPResponseStream) os).finish();
      }
    }
  }
Exemple #14
0
  private void doFilter0(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain)
      throws IOException, ServletException {

    boolean wrap = false;
    String contentEncoding = req.getHeader("Content-Encoding");
    String acceptEncoding = req.getHeader("Accept-Encoding");

    if (null == contentEncoding
        && null != acceptEncoding
        && -1 != acceptEncoding.toLowerCase().indexOf("gzip")) {

      String varyHeaders = req.getHeader("Vary");
      if (null == varyHeaders) {
        varyHeaders = "Accept-Encoding";
      } else if (-1 == varyHeaders.indexOf("Accept-Encoding")) {
        varyHeaders += ", Accept-Encoding";
      }
      resp.addHeader("Vary", varyHeaders);

      resp.addHeader("Content-Encoding", "gzip");
      resp = new GZipResponse(resp);
      wrap = true;
    }

    filterChain.doFilter(req, resp);

    if (wrap) {
      resp.getOutputStream().close();
    }
  }
  @GET
  //	@Produces( "text/tab-separated-values" )
  @Path("{id}/export")
  public final Response export(
      @PathParam("id") long id,
      @Context HttpServletRequest httpRequest,
      @Context HttpServletResponse httpResponse) {
    try {
      final FormBean form = dbManager.selectFormBean(id);
      if (form == null) {
        return Response.status(Status.NOT_FOUND).build();
      }

      final List<CollectionBean> collections = dbManager.selectCollectionBeanList(id);
      if (collections.isEmpty()) {
        return Response.noContent().build();
      }

      form.setCollections(collections);
      final String date = String.format("%tF_%<tH-%<tM-%<tS", Calendar.getInstance().getTime());
      final String filename = String.format("collections_form%s_%s", id, date);
      final String contentDisposition = String.format("attachment; filename=\"%s.tsv\"", filename);
      httpResponse.addHeader("Content-Disposition", contentDisposition);
      httpResponse.addHeader("Cache-Control", "no-cache");

      final ServletOutputStream out = httpResponse.getOutputStream();
      final OutputStreamWriter writer = new OutputStreamWriter(out, Charset.forName("UTF-16LE"));
      Exporter.writeTsv(writer, form);
      return Response.ok().build();
    } catch (final Throwable e) {
      logger.error("Error exporting collections", e);
      return Response.serverError().build();
    }
  }
  /*
   * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
   * javax.servlet.ServletResponse, javax.servlet.FilterChain)
   */
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    if (domainCross) {
      response.addHeader("Access-Control-Allow-Origin", "*");
      response.addHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
      response.addHeader("Access-Control-Allow-Credentials", "true");
      response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token");
      response.addHeader("Access-Control-Max-Age", "600000");
    }

    // jsonp
    if (RestConstant.REQ_METHOD_GET.equals(request.getMethod())) {
      String callBack = request.getParameter(RestConstant.RESP_CALLBACK);
      if (StringUtils.isNotEmpty(callBack)) {
        ResourceResponseWrapper wapper = new ResourceResponseWrapper(response);
        chain.doFilter(req, wapper);
        byte[] json = wapper.getResponseData();
        StringBuffer jsonStr = new StringBuffer(new String(json, "UTF-8"));
        jsonStr.insert(0, callBack + "(");
        jsonStr.append(")");
        ServletOutputStream output = response.getOutputStream();
        output.write(jsonStr.toString().getBytes("UTF-8"));
        output.flush();
      } else {
        chain.doFilter(req, response);
      }
    } else {
      chain.doFilter(req, response);
    }
  }
 @Override
 public void doFilter(
     final ServletRequest request, ServletResponse response, final FilterChain chain)
     throws IOException, ServletException {
   TraceResponseWrapper wrappedResponse = null;
   if (((HttpServletRequest) request).getHeader(X_NO_FILTER_HEADER) == null) {
     response = wrappedResponse = new TraceResponseWrapper((HttpServletResponse) response);
   }
   String status = "n/a";
   final long startTime = System.nanoTime();
   try {
     chain.doFilter(request, response);
     status = "OK";
   } catch (final Throwable th) {
     status = "FAIL";
   } finally {
     final long duration = System.nanoTime() - startTime;
     ((HttpServletResponse) response)
         .addHeader(X_SERVER_DURATION_HEADER, String.valueOf(duration));
     ((HttpServletResponse) response).addHeader(X_STATUS_HEADER, status);
     if (wrappedResponse != null) {
       ((HttpServletResponse) response)
           .setHeader(HttpHeaders.CONTENT_LENGTH, wrappedResponse.getContentLength());
       wrappedResponse.writeBodyAndClose(response.getCharacterEncoding());
     }
   }
 }
 /**
  * Do filter.
  *
  * @param servletRequest the request
  * @param servletResponse the response
  * @param chain the chain
  * @throws IOException Signals that an I/O exception has occurred.
  * @throws ServletException the servlet exception
  * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
  *     javax.servlet.FilterChain)
  */
 @Override
 public void doFilter(
     final ServletRequest servletRequest,
     final ServletResponse servletResponse,
     final FilterChain chain)
     throws IOException, ServletException {
   // Apply the headers
   final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
   final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
   for (final String[] replyHeader : this.mReplyHeaders) {
     final String name = replyHeader[0];
     final String value = replyHeader[1];
     httpResponse.addHeader(name, value);
   }
   if (this.cacheTime > 0L) {
     final long now = System.currentTimeMillis();
     final DateFormat httpDateFormat =
         new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
     httpDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
     httpResponse.addHeader(LAST_MODIFIED_HEADER, httpDateFormat.format(new Date(now)));
     httpResponse.addHeader(
         EXPIRES_HEADER,
         httpDateFormat.format(
             new Date(now + (this.cacheTime.longValue() * MILLISECONDS_IN_SECOND))));
   }
   httpRequest.setAttribute(REQUEST_ATTRIBUTE, true);
   chain.doFilter(servletRequest, servletResponse);
 }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.addHeader("Cache-Control", "no-cache,no-store,must-revalidate,post-check=0,pre-check=0");
    resp.addHeader("Expires", "0");
    resp.addHeader("Pragma", "no-cache");
    resp.setContentType("text/xml; charset=utf-8");
    PrintWriter out = resp.getWriter();
    String type = req.getParameter("type");
    String username = req.getParameter("username");
    String account = req.getParameter("account");
    if (type.equals("smppuser")) {
      SmppuserDAO smppuserDAO = new SmppuserDAO();
      if (smppuserDAO.findSmppuser(username)) {
        out.println("1");
      } else {
        out.println("0");
      }
    } else if (type.equals("admin")) {
      AdminDAO adminDAO = new AdminDAO();
      if (adminDAO.findAdmin(account)) {
        out.println("1");
      } else {
        out.println("0");
      }
    }

    out.flush();
    out.close();
  }
  /* goodB2G() - use badsource and goodsink by changing the second "if" so that
  both branches use the GoodSink */
  private void goodB2G(HttpServletRequest request, HttpServletResponse response) throws Throwable {
    String data;
    if (IO.static_returns_t_or_f()) {
      Logger log_bad = Logger.getLogger("local-logger");
      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    } else {

      Logger log_bad = Logger.getLogger("local-logger");

      /* read parameter from cookie */
      Cookie cookieSources[] = request.getCookies();
      if (cookieSources != null) {
        data = cookieSources[0].getValue();
      } else {
        data = null;
      }
    }
    if (IO.static_returns_t_or_f()) {
      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    } else {

      /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
      data = URLEncoder.encode(data, "UTF-16");
      response.addHeader("Location", "/author.jsp?lang=" + data);
    }
  }
Exemple #21
0
  /**
   * Send any deliveries, or at least something javascrip eval()'able.
   *
   * @param res
   * @param deliveries The list (possibly empty) of deliveries
   * @throws IOException
   */
  protected void sendDeliveries(HttpServletResponse res, List deliveries) throws IOException {
    res.setContentType("text/plain; charset=UTF-8");
    res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L));
    res.addDateHeader("Last-Modified", System.currentTimeMillis());
    res.addHeader(
        "Cache-Control",
        "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
    res.addHeader("Pragma", "no-cache");

    // get the writer
    PrintWriter out = res.getWriter();

    for (Iterator i = deliveries.iterator(); i.hasNext(); ) {
      Delivery d = (Delivery) i.next();
      String s = d.compose();
      if (M_log.isDebugEnabled()) M_log.debug("sending delivery: " + s);
      out.println(s);
    }

    // make sure we send something
    if (deliveries.isEmpty()) {
      String s = "//";
      if (M_log.isDebugEnabled()) M_log.debug("sending delivery: " + s);
      out.println(s);
    }
  }
    /* @Override */
    public void handle(
        String pathInContext,
        org.eclipse.jetty.server.Request request,
        HttpServletRequest httpRequest,
        HttpServletResponse httpResponse)
        throws IOException, ServletException {

      final boolean expectGet = (httpRequest.getHeader("x-expect-get") != null);
      final boolean expectPost = (httpRequest.getHeader("x-expect-post") != null);
      if (expectGet) {
        final String method = request.getMethod();
        if (!"GET".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected GET, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      } else if (expectPost) {
        final String method = request.getMethod();
        if (!"POST".equals(method)) {
          httpResponse.sendError(500, "Incorrect method.  Expected POST, received " + method);
          return;
        }
        httpResponse.setStatus(200);
        httpResponse.getOutputStream().write("OK".getBytes());
        httpResponse.getOutputStream().flush();
        return;
      }

      String header = httpRequest.getHeader("x-redirect");
      if (header != null) {
        // format for header is <status code>|<location url>
        String[] parts = header.split("@");
        int redirectCode;
        try {
          redirectCode = Integer.parseInt(parts[0]);
        } catch (Exception ex) {
          ex.printStackTrace();
          httpResponse.sendError(500, "Unable to parse redirect code");
          return;
        }
        httpResponse.setStatus(redirectCode);
        if (httpRequest.getHeader("x-negative") == null) {
          httpResponse.addHeader("x-expect-get", "true");
        } else {
          httpResponse.addHeader("x-expect-post", "true");
        }
        httpResponse.setContentLength(0);
        httpResponse.addHeader("Location", parts[1] + counter.getAndIncrement());
        httpResponse.getOutputStream().flush();
        return;
      }

      httpResponse.sendError(500);
      httpResponse.getOutputStream().flush();
      httpResponse.getOutputStream().close();
    }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   HttpServletResponse res = (HttpServletResponse) response;
   res.addHeader("Access-Control-Allow-Origin", "*");
   res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
   res.addHeader("Access-Control-Allow-Headers", "Content-Type");
   chain.doFilter(request, response);
 }
  /**
   * Processes a single redirection rule that matched the request URI. If this method returns true,
   * the request should be considered handled.
   *
   * @param request: HttpServletRequest object for this request.
   * @param response: HttpServletResponse object for this request.
   * @param rule: The rule that matched the request URI.
   * @param targetURL: The preprocessed target URL.
   * @return true if the rule action has been recognised, false otherwise. If the rule action has
   *     been recognised but the handling fails, an exception will be thrown.
   * @throws ServletException
   * @throws IOException
   */
  protected boolean processRule(
      HttpServletRequest request, HttpServletResponse response, RedirectRule rule, String targetURL)
      throws ServletException, IOException {

    String finalURL = getFinalURL(request, response, rule, targetURL);

    if (rule instanceof RedirectAction) {
      RedirectAction redirectRule = (RedirectAction) rule;
      if (redirectRule.cache != null) {
        response.addHeader("Cache-Control", redirectRule.cache);
      }
      if (redirectRule.permanent == true) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.addHeader("Location", finalURL);

      } else {
        response.sendRedirect(finalURL);
      }

      if (logRedirects == true) {
        filterConfig
            .getServletContext()
            .log(
                filterName
                    + ": "
                    + "Redirected '"
                    + getRequestURI(request)
                    + "' to '"
                    + finalURL
                    + "'");
      }

      return true;

    } else if (rule instanceof ForwardAction) {
      RequestDispatcher reqDisp = request.getRequestDispatcher(targetURL);
      reqDisp.forward(request, response);

      if (logRedirects == true) {
        filterConfig
            .getServletContext()
            .log(
                filterName
                    + ": "
                    + "Forwarded '"
                    + getRequestURI(request)
                    + "' to '"
                    + targetURL
                    + "'");
      }

      return true;
    }

    return false;
  }
Exemple #25
0
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletResponse resp = (HttpServletResponse) response;

    resp.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigin);
    resp.addHeader(ACCESS_CONTROL_ALLOW_METHODS, ALLOWED_METHODS);
    resp.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, ALLOWED_HEADERS);

    filterChain.doFilter(request, response);
  }
Exemple #26
0
 @Override
 protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType(getContentType());
   response.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
   if (disableCaching) {
     response.addHeader(PRAGMA_HEADER_NAME, DISABLED_CACHING_PRAGMA_HEADER_VALUE);
     response.addHeader(CACHE_CONTROL_HEADER_NAME, DISABLED_CACHING_CACHE_CONTROL_HEADER_VALUE);
     response.addDateHeader(EXPIRES_HEADER_NAME, DISABLED_CACHING_EXPIRES_HEADER_VALUE);
   }
 }
 @Override
 protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
   response.setContentType(getContentType());
   response.setCharacterEncoding(this.encoding.getJavaName());
   if (this.disableCaching) {
     response.addHeader("Pragma", "no-cache");
     response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
     response.addDateHeader("Expires", 1L);
   }
 }
  @Override
  protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain fc)
      throws ServletException, IOException {
    try {
      log.debug("in doFilterInternal");
      resp.addHeader("Pragma", "no-cache");
      resp.addHeader("Cache-Control", "no-cache");
      // resp.addHeader("Expires", "Thu,01 Jan 1970 00:00:01 GMT");
      String reqUrl = req.getRequestURI();
      req.setAttribute("reqUrl", reqUrl);
      String refererUrl = req.getHeader("referer");
      req.setAttribute("refererUrl", refererUrl);
      log.debug("reqURL =" + reqUrl + " ,refererUrl =" + refererUrl);

      if (!(req instanceof HttpServletRequest)) {
        fc.doFilter(req, resp);
        return;
      }
      // --例外;
      for (String u : EXCLUDED_PAGES) {
        if (reqUrl.indexOf(u) > -1) {
          fc.doFilter(req, resp);
          // log.info("reqUrl is exclued:{}",reqUrl);
          return;
        }
      }

      // clear session if session id in URL
      if (req.isRequestedSessionIdFromURL()) {
        HttpSession session = req.getSession();
        if (session != null) session.invalidate();
      }

      // wrap response to remove URL encoding
      HttpServletResponseWrapper wrappedResponse =
          new HttpServletResponseWrapper(resp) {
            @Override
            public String encodeRedirectURL(String url) {
              return url;
            }

            @Override
            public String encodeURL(String url) {
              return url;
            }
          };

      fc.doFilter(req, resp);
    } catch (Exception e) {
      log.error("LoginFilter error:", e);
    }
  }
  /**
   * Peticion para exportar las etiquetas pendientes de generar
   *
   * @param request Peticion
   * @param response Respuesta
   * @return Componente tile al que se redirige (si es correcta la generación del pdf se devuelve
   *     null)
   */
  @RequestMapping(value = "/persona/etiquetasPendientes")
  public String etiquetasPendientes(HttpServletRequest request, HttpServletResponse response) {

    // Generar el informe en formato Excel
    PersonaQueryBean personaQueryBean =
        (PersonaQueryBean) request.getSession().getAttribute("personaQueryBean");

    String username = (String) SecurityAccess.getUserInformation().getUsername();

    String reportName = "etiquetasPersonasReport";
    String reportTitle =
        this.messageSource.getMessage("page.breadcrumb.persona", null, WebCoreUtils.getLocale());
    String reportType = "PDF";
    String fullReportName = null;
    String contentType = null;

    Boolean vacio = false;

    try {
      fullReportName = "etiquetasPendientesReport.pdf";
      contentType = "application/pdf";

      byte[] byteArray =
          this.personaService.etiquetasPersonas(
              username, personaQueryBean, reportType, reportName, reportTitle);
      if (byteArray == null) {
        vacio = true;
      } else {
        response.reset();
        response.setContentType(contentType);
        response.setHeader(
            "Content-disposition", "attachment" + ";filename=\"" + fullReportName + "\"");
        response.addHeader("Pragma", "no cache");
        response.addHeader("Cache-control", "private, must-revalidate");

        ServletOutputStream outstream = response.getOutputStream();
        outstream.write(byteArray);
        outstream.flush();
        outstream.close();
      }
    } catch (IOException e) {
      LOGGER.error(e.getMessage());
      return "app/errorEtiquetas";
    }

    if (vacio) {
      LOGGER.info("No hay registros");
      return "app/sinEtiquetas";
    }

    return null;
  }
  /**
   * Add an expires header to matching files to help browsers avoid reloading static files.
   * {@inheritDoc}
   */
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;

    long now = System.currentTimeMillis();
    // res being the HttpServletResponse of the request
    response.addHeader("Cache-Control", "max-age=" + CACHE_DURATION_IN_SECOND);
    response.addHeader("Cache-Control", "must-revalidate"); // optional
    response.setDateHeader("Last-Modified", now);
    response.setDateHeader("Expires", now + CACHE_DURATION_IN_MS);

    chain.doFilter(req, response);
  }