@Override
 public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
   String version = request.getHeaderValue("Version");
   if (!supportedVersions.contains(version)) {
     response.setStatus(301);
     response.setEntity(null);
   }
   return response;
 }
 protected void addLink(String rel, Pagination p, ContainerRequest req, ContainerResponse res) {
   URI uri =
       req.getRequestUriBuilder()
           .replaceQueryParam(RESTConstants.LIMIT, p.getLimit())
           .replaceQueryParam(RESTConstants.PAGE, p.getPage())
           .build();
   MediaType type = res.getMediaType();
   LinkHeader header = LinkHeader.uri(uri).type(type).rel(rel).build();
   res.getHttpHeaders().add(LINK_HEADER, header.toString());
 }
  @Override
  public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {

    ResponseBuilder responseBuilder = Response.fromResponse(response.getResponse());

    responseBuilder.header(ACCESS_CONTROL_ALLOW_ORIGIN, this.origin);

    response.setResponse(responseBuilder.build());

    return response;
  }
Example #4
0
 private boolean isIterable(ContainerResponse response, Class<?> elementType) {
   Type genericType = response.getEntityType();
   if (genericType instanceof ParameterizedType) {
     Type[] typeArgs = ((ParameterizedType) genericType).getActualTypeArguments();
     Class<?> type = response.getEntity().getClass();
     // FIX FOO CHECK THIS OUT!!!!
     if (typeArgs.length == 1
         && Iterable.class.isAssignableFrom(type)
         && elementType.isAssignableFrom((Class<?>) typeArgs[0])) {
       return true;
     }
   }
   return false;
 }
Example #5
0
 @Override
 public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
   try {
     Object entity = response.getEntity();
     if (entity != null) {
       if (entity
           instanceof TopicType) { // Note: type matches both, must take precedence over topic
         firePreSend((TopicType) entity);
       } else if (entity instanceof Topic) {
         firePreSend((Topic) entity);
       } else if (entity instanceof Association) {
         firePreSend((Association) entity);
       } else if (entity instanceof Directives) {
         firePreSend((Directives) entity);
       } else if (isIterable(response, TopicType.class)) {
         firePreSendTopicTypes(DeepaMehtaUtils.<Iterable<TopicType>>cast(entity));
       } else if (isIterable(response, Topic.class)) {
         firePreSendTopics(DeepaMehtaUtils.<Iterable<Topic>>cast(entity));
       }
     }
     return response;
   } catch (Exception e) {
     throw new WebApplicationException(
         new RuntimeException("Jersey response filtering failed", e));
   }
 }
 @Override
 public ContainerResponse filter(
     final ContainerRequest request, final ContainerResponse response) {
   if (request.isSecure()) {
     final String value = String.format("max-age=%s; includeSubDomains", EXPIRY);
     response.getHttpHeaders().add("Strict-Transport-Security", value);
   }
   return response;
 }
  public ClientResponse handle(ClientRequest clientRequest) {
    byte[] requestEntity = writeRequestEntity(clientRequest);

    InBoundHeaders rh = getInBoundHeaders(clientRequest.getMetadata());

    final ContainerRequest cRequest =
        new ContainerRequest(
            w,
            clientRequest.getMethod(),
            baseUri,
            clientRequest.getURI(),
            rh,
            new ByteArrayInputStream(requestEntity));

    // TODO this is a hack
    List<String> cookies = cRequest.getRequestHeaders().get("Cookie");
    if (cookies != null) {
      for (String cookie : cookies) {
        if (cookie != null) cRequest.getCookies().putAll(HttpHeaderReader.readCookies(cookie));
      }
    }

    final TstContainerResponseWriter writer = new TstContainerResponseWriter();
    final ContainerResponse cResponse = new ContainerResponse(w, cRequest, writer);

    try {
      w.handleRequest(cRequest, cResponse);
    } catch (IOException e) {
      throw new ContainerException(e);
    }

    byte[] responseEntity = writer.baos.toByteArray();
    ClientResponse clientResponse =
        new ClientResponse(
            cResponse.getStatus(),
            getInBoundHeaders(cResponse.getHttpHeaders()),
            new ByteArrayInputStream(responseEntity),
            getMessageBodyWorkers());

    clientResponse.getProperties().put("request.entity", requestEntity);
    clientResponse.getProperties().put("response.entity", responseEntity);
    return clientResponse;
  }
 @Override
 public ContainerResponse filter(ContainerRequest req, ContainerResponse res) {
   Object entity = res.getEntity();
   if (entity instanceof PaginatedIterable) {
     PaginatedIterable<?> p = (PaginatedIterable) entity;
     if (p.isPaginated()) {
       insertLinks(p, req, res);
     }
   }
   return res;
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * com.sun.jersey.spi.container.ContainerResponseFilter#filter(com.sun.jersey
   * .spi.container.ContainerRequest,
   * com.sun.jersey.spi.container.ContainerResponse)
   */
  @Override
  public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
    if (logStdOut) {
      // If it is image, then don't call super
      if (response.getMediaType() != null) {
        // logger.info("DELETE ME: Response= mediaType="
        // + response.getMediaType() + ", getType()"
        // + response.getMediaType().getType() + ", getSubType()="
        // + response.getMediaType().getSubtype());
      } else {
        logger.info("DELETE ME: Response= mediaType is null");
      }
      if (response.getMediaType() == null || !response.getMediaType().getType().equals("image")) {

        response = super.filter(request, response);
      }
    }

    return response;
  }
  @Override
  public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {

    LOGGER.info("Enter CORS filter");
    LOGGER.info("Request= { path:" + req.getPath() + ", method:" + req.getMethod() + " }");

    ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
    resp.header("Access-Control-Allow-Origin", "*");
    resp.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");

    String reqHead = req.getHeaderValue("Access-Control-Request-Headers");

    if (null != reqHead && !reqHead.equals(null)) {
      resp.header("Access-Control-Allow-Headers", reqHead);
    }

    contResp.setResponse(resp.build());

    LOGGER.info("Exit CORS filter");

    return contResp;
  }
  public static final void broadcast(
      final AtmosphereResource r, final AtmosphereResourceEvent e, final Broadcaster broadcaster) {
    AtmosphereRequest request = r.getRequest();
    ContainerResponse cr = null;

    // Make sure only one thread can play with the ContainerResponse. Threading issue can arise if
    // there is a scheduler
    // or if ContainerResponse is associated with more than Broadcaster.
    cr = (ContainerResponse) request.getAttribute(FrameworkConfig.CONTAINER_RESPONSE);

    if (cr == null || !r.isSuspended() && !r.getAtmosphereResourceEvent().isResumedOnTimeout()) {
      if (cr == null) {
        logger.warn(
            "Unexpected state. ContainerResponse has been resumed. Caching message {} for {}",
            e.getMessage(),
            r.uuid());
      } else {
        logger.warn("The AtmosphereResource {} hasn't been suspended yet.", r.uuid(), e);
      }

      if (DefaultBroadcaster.class.isAssignableFrom(broadcaster.getClass())) {
        DefaultBroadcaster.class.cast(broadcaster).cacheLostMessage(r, true);
      }
      AtmosphereResourceImpl.class.cast(r)._destroy();
      return;
    }

    synchronized (cr) {
      try {
        // This is required when you change the response's type
        String m = null;

        if (request.getAttribute(FrameworkConfig.EXPECTED_CONTENT_TYPE) != null) {
          m = (String) request.getAttribute(FrameworkConfig.EXPECTED_CONTENT_TYPE);
        }

        if (m == null || m.equalsIgnoreCase("text/event-stream")) {
          if (cr.getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE) != null) {
            m = cr.getHttpHeaders().getFirst(HttpHeaders.CONTENT_TYPE).toString();
          }

          if (m == null || m.equalsIgnoreCase("application/octet-stream")) {
            m = r.getAtmosphereConfig().getInitParameter(ApplicationConfig.SSE_CONTENT_TYPE);
            if (m == null) {
              m = "text/plain";
            }
          }
        }

        if (e.getMessage() instanceof Response) {
          cr.setResponse((Response) e.getMessage());
          cr.getHttpHeaders().add(HttpHeaders.CONTENT_TYPE, m);
          cr.write();
          try {
            cr.getOutputStream().flush();
          } catch (IOException ex) {
            logger.trace("", ex);
          }
        } else if (e.getMessage() instanceof List) {
          for (Object msg : (List<Object>) e.getMessage()) {
            cr.setResponse(Response.ok(msg).build());
            cr.getHttpHeaders().add(HttpHeaders.CONTENT_TYPE, m);
            cr.write();
          }

          // https://github.com/Atmosphere/atmosphere/issues/169
          try {
            cr.getOutputStream().flush();
          } catch (IOException ex) {
            logger.trace("", ex);
          }
        } else {
          if (e.getMessage() == null) {
            logger.warn("Broadcasted message is null");
            return;
          }

          cr.setResponse(Response.ok(e.getMessage()).build());
          cr.getHttpHeaders().add(HttpHeaders.CONTENT_TYPE, m);
          cr.write();
          try {
            cr.getOutputStream().flush();
          } catch (IOException ex) {
            logger.trace("", ex);
          }
        }
      } catch (Throwable t) {
        boolean notifyAndCache = true;
        logger.trace(
            "Unexpected exception for AtmosphereResource {} and Broadcaster {}",
            r.uuid(),
            broadcaster.getID());
        if (isJetty(r)) {
          for (StackTraceElement element : t.getStackTrace()) {
            if (element.getClassName().equals("java.io.BufferedWriter")
                && element.getMethodName().equals("flush")) {
              logger.trace("Workaround issue https://github.com/Atmosphere/atmosphere/issues/710");
              notifyAndCache = false;
            }
          }
        }

        if (DefaultBroadcaster.class.isAssignableFrom(broadcaster.getClass())) {
          DefaultBroadcaster.class.cast(broadcaster).onException(t, r, notifyAndCache);
        } else {
          onException(t, r);
        }
      } finally {
        if (cr != null) {
          cr.setEntity(null);
        }

        Boolean resumeOnBroadcast =
            (Boolean) request.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST);
        if (resumeOnBroadcast != null && resumeOnBroadcast) {

          String uuid = (String) request.getAttribute(AtmosphereFilter.RESUME_UUID);
          if (uuid != null) {
            if (request.getAttribute(AtmosphereFilter.RESUME_CANDIDATES) != null) {
              ((ConcurrentHashMap<String, AtmosphereResource>)
                      request.getAttribute(AtmosphereFilter.RESUME_CANDIDATES))
                  .remove(uuid);
            }
          }
          r.getRequest().setAttribute(FrameworkConfig.CONTAINER_RESPONSE, null);
          r.resume();
        }
      }
    }
  }