예제 #1
0
 private BaseClientResponse createClientResponse(ClientRequest request, BrowserCache.Entry entry) {
   BaseClientResponse response = new BaseClientResponse(new CachedStreamFactory(entry));
   response.setStatus(200);
   response.setHeaders(entry.getHeaders());
   response.setProviderFactory(request.getProviderFactory());
   return response;
 }
예제 #2
0
  public ClientResponse updateOnNotModified(
      ClientRequest request, BrowserCache.Entry old, BaseClientResponse response) throws Exception {
    old.getHeaders().remove(HttpHeaders.CACHE_CONTROL);
    old.getHeaders().remove(HttpHeaders.EXPIRES);
    old.getHeaders().remove(HttpHeaders.LAST_MODIFIED);
    String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
    String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
    int expires = -1;

    if (cc != null) {
      CacheControl cacheControl = CacheControl.valueOf(cc);
      if (cacheControl.isNoCache()) {
        return createClientResponse(request, old);
      }
      expires = cacheControl.getMaxAge();
    } else if (exp != null) {
      Date date = DateUtil.parseDate(exp);
      expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
    }

    if (cc != null) {
      old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, cc);
    }
    if (exp != null) {
      old.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, exp);
    }

    String lastModified =
        (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
    String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);

    if (etag == null) etag = old.getHeaders().getFirst(HttpHeaders.ETAG);
    else old.getHeaders().putSingle(HttpHeaders.ETAG, etag);

    if (lastModified != null) {
      old.getHeaders().putSingle(HttpHeaders.LAST_MODIFIED, lastModified);
    }

    if (etag == null && lastModified == null && cc == null && exp == null) // don't cache
    {
      return createClientResponse(request, old);
    }

    BrowserCache.Entry entry =
        cache.put(
            request.getUri(),
            old.getMediaType(),
            old.getHeaders(),
            old.getCached(),
            expires,
            etag,
            lastModified);
    return createClientResponse(request, entry);
  }
  @SuppressWarnings("unchecked")
  public ClientResponse execute(ClientRequest request) throws Exception {
    String uri = request.getUri();
    final HttpRequestBase httpMethod = createHttpMethod(uri, request.getHttpMethod());
    try {
      loadHttpMethod(request, httpMethod);

      final HttpResponse res = httpClient.execute(httpMethod, httpContext);

      BaseClientResponse response =
          new BaseClientResponse(
              new BaseClientResponseStreamFactory() {
                InputStream stream;

                public InputStream getInputStream() throws IOException {
                  if (stream == null) {
                    HttpEntity entity = res.getEntity();
                    if (entity == null) return null;
                    stream = new SelfExpandingBufferredInputStream(entity.getContent());
                  }
                  return stream;
                }

                public void performReleaseConnection() {
                  // Apache Client 4 is stupid, You have to get the InputStream and close it if
                  // there is an entity
                  // otherwise the connection is never released. There is, of course, no close()
                  // method on response
                  // to make this easier.
                  try {
                    if (stream != null) {
                      stream.close();
                    } else {
                      InputStream is = getInputStream();
                      if (is != null) {
                        is.close();
                      }
                    }
                  } catch (Exception ignore) {
                  }
                }
              },
              this);
      response.setAttributes(request.getAttributes());
      response.setStatus(res.getStatusLine().getStatusCode());
      response.setHeaders(extractHeaders(res));
      response.setProviderFactory(request.getProviderFactory());
      return response;
    } finally {
      cleanUpAfterExecute(httpMethod);
    }
  }
예제 #4
0
 @SuppressWarnings("rawtypes")
 public void handle(ClientResponse response) throws RuntimeException {
   try {
     BaseClientResponse r = (BaseClientResponse) response;
     String message = "SomeApplikationException. Status Code: " + response.getStatus();
     InputStream stream = r.getStreamFactory().getInputStream();
     stream.reset();
     if (response.getStatus() == 523) {
       System.out.println(
           "ClientExceptionmapper: Mapped Stauscode 523 to SomeApplicationException");
       throw new SomeApplicationException(message);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
예제 #5
0
 /** {@inheritDoc} */
 @Override
 public Message compose(RESTEasyBindingData source, Exchange exchange) throws Exception {
   final Message message = super.compose(source, exchange);
   if (message.getContent() instanceof BaseClientResponse) {
     BaseClientResponse<?> clientResponse = (BaseClientResponse<?>) message.getContent();
     if (clientResponse.getResponseStatus() == Response.Status.NOT_FOUND) {
       throw new ItemNotFoundException("Item not found");
     }
   } else if (source.getOperationName().equals("addItem")
       && (source.getParameters().length == 2)) {
     // Wrap the parameters
     Item item = new Item((Integer) source.getParameters()[0], (String) source.getParameters()[1]);
     message.setContent(item);
   }
   return message;
 }
예제 #6
0
  public RestfulResponse<JsonRepresentation> execute() {
    try {
      if (!args.isEmpty()) {
        clientRequestConfigurer.configureArgs(args);
      }
      final Response response = clientRequestConfigurer.getClientRequest().execute();

      // this is a bit hacky
      @SuppressWarnings("unchecked")
      final BaseClientResponse<String> restEasyResponse = (BaseClientResponse<String>) response;
      restEasyResponse.setReturnType(String.class);

      return RestfulResponse.ofT(response);
    } catch (final Exception ex) {
      throw new RuntimeException(ex);
    }
  }
 private void checkResponse(ClientResponse<?> responseObj) throws Exception {
   ClientResponse<?> test = BaseClientResponse.copyFromError(responseObj);
   responseObj.resetStream();
   if (test.getResponseStatus() == javax.ws.rs.core.Response.Status.BAD_REQUEST) {
     throw new BadRequestException(test.getEntity(String.class));
   } else if (test.getResponseStatus() != javax.ws.rs.core.Response.Status.OK) {
     throw new Exception(
         "Request operation failed. Response status = "
             + test.getResponseStatus()
             + "\n\n"
             + test.getEntity(String.class));
   } else {
     logger.debug("Response: " + test.getEntity(String.class));
   }
 }
예제 #8
0
  public ClientResponse cacheIfPossible(ClientRequest request, BaseClientResponse response)
      throws Exception {
    String cc = (String) response.getResponseHeaders().getFirst(HttpHeaders.CACHE_CONTROL);
    String exp = (String) response.getResponseHeaders().getFirst(HttpHeaders.EXPIRES);
    int expires = -1;

    if (cc != null) {
      CacheControl cacheControl = CacheControl.valueOf(cc);
      if (cacheControl.isNoCache()) return response;
      expires = cacheControl.getMaxAge();
    } else if (exp != null) {
      Date date = DateUtil.parseDate(exp);
      expires = (int) ((date.getTime() - System.currentTimeMillis()) / 1000);
    }

    String lastModified =
        (String) response.getResponseHeaders().getFirst(HttpHeaders.LAST_MODIFIED);
    String etag = (String) response.getResponseHeaders().getFirst(HttpHeaders.ETAG);

    String contentType = (String) response.getResponseHeaders().getFirst(HttpHeaders.CONTENT_TYPE);

    byte[] cached =
        ReadFromStream.readFromStream(1024, response.getStreamFactory().getInputStream());
    response.getStreamFactory().performReleaseConnection();

    MediaType mediaType = MediaType.valueOf(contentType);
    final BrowserCache.Entry entry =
        cache.put(
            request.getUri(),
            mediaType,
            response.getResponseHeaders(),
            cached,
            expires,
            etag,
            lastModified);

    response.setStreamFactory(new CachedStreamFactory(entry));

    return response;
  }
예제 #9
0
  /**
   * Store entity within a byte array input stream because we want to release the connection if a
   * ClientResponseFailure is thrown. Copy status and headers, but ignore all type information
   * stored in the ClientResponse.
   *
   * @param copy
   * @return
   */
  public static ClientResponse copyFromError(ClientResponse copy) {
    if (copy instanceof BaseClientResponse) {
      BaseClientResponse base = (BaseClientResponse) copy;
      InputStream is = null;
      if (copy.getResponseHeaders().containsKey("Content-Type")) {
        try {
          is = base.streamFactory.getInputStream();
          byte[] bytes = ReadFromStream.readFromStream(1024, is);
          is = new ByteArrayInputStream(bytes);
        } catch (IOException e) {
          // ignored
        }
      }
      final InputStream theIs = is;
      BaseClientResponse tmp =
          new BaseClientResponse(
              new BaseClientResponse.BaseClientResponseStreamFactory() {
                InputStream stream;

                public InputStream getInputStream() throws IOException {
                  return theIs;
                }

                public void performReleaseConnection() {}
              });
      tmp.executor = base.executor;
      tmp.status = base.status;
      tmp.providerFactory = base.providerFactory;
      tmp.headers = new CaseInsensitiveMap<String>();
      tmp.headers.putAll(base.headers);
      tmp.readerInterceptors = base.readerInterceptors;
      return tmp;
    } else {
      // Not sure how this codepath could ever be reached.
      InputStream is = null;
      if (copy.getResponseHeaders().containsKey("Content-Type")) {
        GenericType<byte[]> gt = new GenericType<byte[]>() {};
        try {
          byte[] bytes = (byte[]) copy.getEntity(gt);
          is = new ByteArrayInputStream(bytes);
        } catch (Exception ignore) {
        }
      }
      final InputStream theIs = is;
      BaseClientResponse tmp =
          new BaseClientResponse(
              new BaseClientResponse.BaseClientResponseStreamFactory() {
                InputStream stream;

                public InputStream getInputStream() throws IOException {
                  return theIs;
                }

                public void performReleaseConnection() {}
              });
      tmp.status = copy.getStatus();
      tmp.providerFactory = ResteasyProviderFactory.getInstance();
      tmp.headers = new CaseInsensitiveMap<String>();
      tmp.headers.putAll(copy.getResponseHeaders());
      tmp.headers.remove(
          "Content-Encoding"); // remove encoding because we will have already extracted byte array
      return tmp;
    }
  }