コード例 #1
0
ファイル: HeadTest.java プロジェクト: imranaziz/jersey
  @Test
  public void testHead() throws Exception {
    startServer(Resource.class);

    Client client = ClientFactory.newClient();
    WebTarget r = client.target(getUri().path("/").build());

    Response cr = r.path("string").request("text/plain").head();
    assertEquals(200, cr.getStatus());
    assertEquals(MediaType.TEXT_PLAIN_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());

    cr = r.path("byte").request("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    int length = cr.getLength();
    assertNotNull(length);
    // org.glassfish.jersey.server.model.HeadTest
    // TODO Uncomment once we implement outbound message payload buffering for determining proper
    // Content-Length value.
    //        assertEquals(3, length);
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());

    cr = r.path("ByteArrayInputStream").request("application/octet-stream").head();
    assertEquals(200, cr.getStatus());
    length = cr.getLength();
    assertNotNull(length);
    //        assertEquals(3, length);
    assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE, cr.getMediaType());
    assertFalse(cr.hasEntity());
  }
コード例 #2
0
  private void connect() {

    logger.trace("Setting up an authenticated connection to the Tesla back-end");

    ThingStatusDetail authenticationResult =
        authenticate((String) getConfig().get(USERNAME), (String) getConfig().get(PASSWORD));

    if (authenticationResult != ThingStatusDetail.NONE) {
      updateStatus(ThingStatus.OFFLINE, authenticationResult);
    } else {
      // get a list of vehicles
      logger.trace("Getting a list of vehicles");
      Response response =
          vehiclesTarget
              .request(MediaType.APPLICATION_JSON_TYPE)
              .header("Authorization", "Bearer " + accessToken)
              .get();

      if (response != null && response.getStatus() == 200 && response.hasEntity()) {

        if ((vehicle = queryVehicle()) != null) {

          logger.debug(
              "Found the vehicle with VIN '{}' in the list of vehicles you own",
              getConfig().get(VIN));
          updateStatus(ThingStatus.ONLINE);
        } else {
          logger.warn(
              "Unable to find the vehicle with VIN '{}' in the list of vehicles you own",
              getConfig().get(VIN));
          updateStatus(ThingStatus.OFFLINE);
        }
      }
    }
  }
コード例 #3
0
  @Test
  public void testInvalidContentType() {
    final Response response = target("/").request("foo").get();

    assertThat(response.getStatus()).isEqualTo(406);
    assertThat(response.hasEntity()).isEqualTo(false);
  }
コード例 #4
0
 @Test
 public void testHeadByte() throws Exception {
   Response response = target().path("byte").request().head();
   assertEquals(200, response.getStatus());
   assertEquals(3, Integer.parseInt(response.getHeaderString(HttpHeaders.CONTENT_LENGTH)));
   assertFalse(response.hasEntity());
 }
コード例 #5
0
    @Test
    public void testWadl() throws Exception {
      final Response response = target("/application.wadl").request().get();

      assertThat(response.getStatus(), is(200));
      assertThat(response.hasEntity(), is(true));
    }
コード例 #6
0
  @Test
  public void testConnectionClose() throws Exception {
    final Response response = target().request().header("Connection", "close").delete();

    assertThat(response.getStatus(), equalTo(200));
    assertThat(response.hasEntity(), is(false));
  }
コード例 #7
0
  protected ThingStatusDetail authenticate(String username, String password) {

    TokenRequest token = new TokenRequest(username, password);
    String payLoad = gson.toJson(token);

    Response response =
        tokenTarget.request().post(Entity.entity(payLoad, MediaType.APPLICATION_JSON_TYPE));

    logger.trace("Authenticating : Response : {}", response.getStatusInfo());

    if (response != null) {
      if (response.getStatus() == 200 && response.hasEntity()) {

        String responsePayLoad = response.readEntity(String.class);
        JsonObject readObject = parser.parse(responsePayLoad).getAsJsonObject();

        for (Entry<String, JsonElement> entry : readObject.entrySet()) {
          switch (entry.getKey()) {
            case "access_token":
              {
                accessToken = entry.getValue().getAsString();
                logger.trace("Authenticating : Setting access code to : {}", accessToken);
                return ThingStatusDetail.NONE;
              }
          }
        }
      } else if (response.getStatus() == 401) {
        return ThingStatusDetail.CONFIGURATION_ERROR;
      } else if (response.getStatus() == 503) {
        return ThingStatusDetail.COMMUNICATION_ERROR;
      }
    }
    return ThingStatusDetail.CONFIGURATION_ERROR;
  }
コード例 #8
0
ファイル: IceRestClient.java プロジェクト: JBEI/ice
  public <T> T putWor(
      String url,
      String resourcePath,
      Object object,
      Class<T> responseClass,
      Map<String, Object> queryParams,
      String worToken) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    if (queryParams != null) {
      for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        target = target.queryParam(entry.getKey(), entry.getValue());
      }
    }

    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    setHeaders(invocationBuilder, worToken);
    Response putResponse =
        invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) {
      Logger.error(
          "PUT call to "
              + url
              + "/"
              + resourcePath
              + " returned status of "
              + putResponse.getStatus());
      return null;
    }

    if (responseClass != null
        && putResponse.hasEntity()
        && putResponse.getStatus() == Response.Status.OK.getStatusCode())
      return putResponse.readEntity(responseClass);
    return null;
  }
コード例 #9
0
 @Test
 public void testHeadContentLengthCustomWriter() throws Exception {
   Response response = target().request().head();
   assertEquals(200, response.getStatus());
   assertEquals(
       STR.length(), Integer.parseInt(response.getHeaderString(HttpHeaders.CONTENT_LENGTH)));
   assertFalse(response.hasEntity());
 }
コード例 #10
0
  /**
   * Invoke API by sending HTTP request with the given options.
   *
   * @param path The sub-path of the HTTP URL
   * @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
   * @param queryParams The query parameters
   * @param body The request body object - if it is not binary, otherwise null
   * @param binaryBody The request body object - if it is binary, otherwise null
   * @param headerParams The header parameters
   * @param formParams The form parameters
   * @param accept The request's Accept header
   * @param contentType The request's Content-Type header
   * @param authNames The authentications to apply
   * @return The response body in type of string
   */
  public <T> T invokeAPI(
      String path,
      String method,
      List<Pair> queryParams,
      Object body,
      byte[] binaryBody,
      Map<String, String> headerParams,
      Map<String, Object> formParams,
      String accept,
      String contentType,
      String[] authNames,
      TypeRef returnType)
      throws ApiException {

    Response response =
        getAPIResponse(
            path,
            method,
            queryParams,
            body,
            binaryBody,
            headerParams,
            formParams,
            accept,
            contentType,
            authNames);

    statusCode = response.getStatusInfo().getStatusCode();
    responseHeaders = response.getHeaders();

    if (statusCode == 401) {
      throw new ApiException(
          response.getStatusInfo().getStatusCode(),
          "HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials.",
          response.getHeaders(),
          null);
    } else if (response.getStatusInfo() == Response.Status.NO_CONTENT) {
      return null;
    } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
      if (returnType == null) return null;
      else return deserialize(response, returnType);
    } else {
      String message = "error";
      String respBody = null;
      if (response.hasEntity()) {
        try {
          respBody = response.readEntity(String.class);
          message = respBody;
        } catch (RuntimeException e) {
          // e.printStackTrace();
        }
      }
      throw new ApiException(
          response.getStatusInfo().getStatusCode(), message, response.getHeaders(), respBody);
    }
  }
コード例 #11
0
  /** Deserialize response body to Java object according to the Content-Type. */
  public <T> T deserialize(Response response, TypeRef returnType) throws ApiException {
    String contentType = null;
    List<Object> contentTypes = response.getHeaders().get("Content-Type");
    if (contentTypes != null && !contentTypes.isEmpty()) contentType = (String) contentTypes.get(0);
    if (contentType == null) throw new ApiException(500, "missing Content-Type in response");

    String body;
    if (response.hasEntity()) body = (String) response.readEntity(String.class);
    else body = "";

    if (contentType.startsWith("application/json")) {
      return json.deserialize(body, returnType);
    } else {
      throw new ApiException(500, "can not deserialize Content-Type: " + contentType);
    }
  }
コード例 #12
0
  /**
   * Create a GitLabApiException instance based on the ClientResponse.
   *
   * @param response
   */
  public GitLabApiException(Response response) {

    super();
    statusInfo = response.getStatusInfo();
    httpStatus = response.getStatus();

    if (response.hasEntity()) {
      try {

        ErrorMessage errorMessage = response.readEntity(ErrorMessage.class);
        message = errorMessage.getMessage();

      } catch (Exception ignore) {
      }
    }
  }
コード例 #13
0
ファイル: IceRestClient.java プロジェクト: JBEI/ice
  @Override
  public <T> T post(
      String url,
      String resourcePath,
      Object object,
      Class<T> responseClass,
      Map<String, Object> queryParams) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    if (queryParams != null) {
      for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        target = target.queryParam(entry.getKey(), entry.getValue());
      }
    }

    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response postResponse =
        invocationBuilder.post(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (postResponse.hasEntity() && postResponse.getStatus() == Response.Status.OK.getStatusCode())
      return postResponse.readEntity(responseClass);
    return null;
  }
コード例 #14
0
ファイル: IceRestClient.java プロジェクト: JBEI/ice
  public <T> T put(String url, String resourcePath, Object object, Class<T> responseClass) {
    WebTarget target = client.target("https://" + url).path(resourcePath);
    Invocation.Builder invocationBuilder = target.request(MediaType.APPLICATION_JSON_TYPE);
    Response putResponse =
        invocationBuilder.put(Entity.entity(object, MediaType.APPLICATION_JSON_TYPE));
    if (putResponse.getStatus() != Response.Status.OK.getStatusCode()) {
      Logger.error(
          "PUT call to "
              + url
              + "/"
              + resourcePath
              + " returned status of "
              + putResponse.getStatus());
      return null;
    }

    if (responseClass != null
        && putResponse.hasEntity()
        && putResponse.getStatus() == Response.Status.OK.getStatusCode())
      return putResponse.readEntity(responseClass);
    return null;
  }
コード例 #15
0
  @Test
  public void testGetEmployee() throws IOException {
    if (null == cookie) {
      fail("cannot login!!!");
    }

    Client client = new ResteasyClientBuilder().build();
    client.register(new CookieRequestFilter(cookie));
    WebTarget target = client.target(baseUrl + "/rest/ag/employee/100");
    Response response = target.request().get();

    // System.out.println( response.readEntity(String.class));
    int status = response.getStatus();
    System.out.println("response status code: " + status);
    boolean hasEntity = response.hasEntity();
    System.out.println("response has entity? " + hasEntity);

    Employee epl = response.readEntity(Employee.class);
    System.out.println(epl.toString());

    client.close();
    assertEquals("same first name", "Beyond", epl.getFirstName());
  }
コード例 #16
0
    @Test
    public void testWadl() throws Exception {
      final Response response = target("/application.wadl").request().get();

      assertThat(response.getStatus(), is(200));
      assertThat(response.hasEntity(), is(true));

      final Method method =
          (Method)
              response
                  .readEntity(com.sun.research.ws.wadl.Application.class) // wadl
                  .getResources()
                  .get(0)
                  .getResource()
                  .get(0) // resource
                  .getMethodOrResource()
                  .get(0); // method
      final Param param = method.getRequest().getParam().get(0); // param

      // not interested in returned value, only whether we can compile.
      assertThat(param.isRequired(), notNullValue());
      assertThat(param.isRepeating(), notNullValue());
    }
コード例 #17
0
 private void assertResponse(String path, Response response, String mediaType) {
   System.out.println("Integration test: " + path);
   assertEquals("HTTP status " + path, HttpStatus.SC_OK, response.getStatus());
   assertEquals("Media type " + path, mediaType, response.getMediaType().toString());
   assertTrue(response.hasEntity());
 }