Java Code Examples for org.jboss.resteasy.client.ClientResponse#getEntity()

The following examples show how to use org.jboss.resteasy.client.ClientResponse#getEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestEndPointMockerTest.java    From zerocode with Apache License 2.0 6 votes vote down vote up
@Test
public void willMockASimpleGetEndPoint() throws Exception {

    final MockStep mockStep = mockSteps.getMocks().get(0);
    String jsonBodyRequest = mockStep.getResponse().get("body").toString();

    WireMock.configureFor(9073);
    givenThat(get(urlEqualTo(mockStep.getUrl()))
            .willReturn(aResponse()
                    .withStatus(mockStep.getResponse().get("status").asInt())
                    .withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(jsonBodyRequest)));

    ApacheHttpClientExecutor httpClientExecutor = new ApacheHttpClientExecutor();
    ClientRequest clientExecutor = httpClientExecutor.createRequest("http://localhost:9073" + mockStep.getUrl());
    clientExecutor.setHttpMethod("GET");
    ClientResponse serverResponse = clientExecutor.execute();

    final String respBodyAsString = (String) serverResponse.getEntity(String.class);
    JSONAssert.assertEquals(jsonBodyRequest, respBodyAsString, true);

    System.out.println("### zerocode: \n" + respBodyAsString);

}
 
Example 2
Source File: ReceiveOrder.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // first get the create URL for the shipping queue
   ClientRequest request = new ClientRequest("http://localhost:8080/queues/orders");
   ClientResponse res = request.head();
   Link pullConsumers = res.getHeaderAsLink("msg-pull-consumers");
   res.releaseConnection();
   res = pullConsumers.request().post();
   Link consumeNext = res.getHeaderAsLink("msg-consume-next");
   res.releaseConnection();
   while (true) {
      System.out.println("Waiting...");
      res = consumeNext.request().header("Accept-Wait", "10").post();
      if (res.getStatus() == 503) {
         System.out.println("Timeout...");
         consumeNext = res.getHeaderAsLink("msg-consume-next");
      } else if (res.getStatus() == 200) {
         Order order = (Order) res.getEntity(Order.class);
         System.out.println(order);
         consumeNext = res.getHeaderAsLink("msg-consume-next");
      } else {
         throw new RuntimeException("Failure! " + res.getStatus());
      }
      res.releaseConnection();
   }
}
 
Example 3
Source File: RestReceive.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
   // first get the create URL for the shipping queue
   ClientRequest request = new ClientRequest("http://localhost:8080/queues/orders");
   ClientResponse res = request.head();
   Link pullConsumers = res.getHeaderAsLink("msg-pull-consumers");
   res = pullConsumers.request().formParameter("autoAck", "false").post();
   Link ackNext = res.getHeaderAsLink("msg-acknowledge-next");
   res.releaseConnection();
   while (true) {
      System.out.println("Waiting...");
      res = ackNext.request().header("Accept-Wait", "10").header("Accept", "application/xml").post();
      if (res.getStatus() == 503) {
         System.out.println("Timeout...");
         ackNext = res.getHeaderAsLink("msg-acknowledge-next");
      } else if (res.getStatus() == 200) {
         Order order = (Order) res.getEntity(Order.class);
         System.out.println(order);
         Link ack = res.getHeaderAsLink("msg-acknowledgement");
         res = ack.request().formParameter("acknowledge", "true").post();
         ackNext = res.getHeaderAsLink("msg-acknowledge-next");
      } else {
         throw new RuntimeException("Failure! " + res.getStatus());
      }
      res.releaseConnection();
   }
}
 
Example 4
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnPublishedEntity() throws Exception {
   TransformTest.Order order = createTestOrder("1", "$5.00");

   publish("exampleQueue", order, null);
   ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/xml").post(String.class);

   TransformTest.Order order2 = res.getEntity(TransformTest.Order.class);
   assertEquals(order, order2);
   res.releaseConnection();
}
 
Example 5
Source File: WireMockJsonContentTesting.java    From zerocode with Apache License 2.0 5 votes vote down vote up
@Test
public void bioViaJson() throws Exception{
    String jsonBodyRequest = "{\n" +
            "    \"id\": \"303021\",\n" +
            "    \"names\": [\n" +
            "        {\n" +
            "            \"firstName\": \"You First\",\n" +
            "            \"lastName\": \"Me Last\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";

    givenThat(WireMock.get(urlEqualTo("/identitymanagement-services/identitymanagement-services/person/internalHandle/person_id_009/biographics/default"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", APPLICATION_JSON)
                    .withBody(jsonBodyRequest)));

    ApacheHttpClientExecutor httpClientExecutor = new ApacheHttpClientExecutor();
    ClientRequest clientExecutor = httpClientExecutor.createRequest("http://localhost:9073/identitymanagement-services/identitymanagement-services/person/internalHandle/person_id_009/biographics/default");
    clientExecutor.setHttpMethod("GET");
    ClientResponse serverResponse = clientExecutor.execute();

    final String respBodyAsString = (String)serverResponse.getEntity(String.class);
    JSONAssert.assertEquals(jsonBodyRequest, respBodyAsString, true);

    System.out.println("### bio response from mapping: \n" + respBodyAsString);
}
 
Example 6
Source File: SelectorTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private Link consumeOrder(Order order, Link consumeNext) throws Exception {
   ClientResponse<?> response = consumeNext.request().header("Accept-Wait", "4").accept("application/xml").post(String.class);
   Assert.assertEquals(200, response.getStatus());
   Assert.assertEquals("application/xml", response.getHeaders().getFirst("Content-Type").toString().toLowerCase());
   Order order2 = response.getEntity(Order.class);
   Assert.assertEquals(order, order2);
   consumeNext = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "consume-next");
   Assert.assertNotNull(consumeNext);
   response.releaseConnection();
   return consumeNext;
}
 
Example 7
Source File: FirebaseCloudMessagingResponse.java    From oxAuth with MIT License 5 votes vote down vote up
public FirebaseCloudMessagingResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    String entity = clientResponse.getEntity(String.class);
    setEntity(entity);
    setHeaders(clientResponse.getMetadata());
    injectDataFromJson(entity);
}
 
Example 8
Source File: RegisterResponse.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Constructs a register response.
 */
public RegisterResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    String entity = clientResponse.getEntity(String.class);
    setEntity(entity);
    setHeaders(clientResponse.getMetadata());
    injectDataFromJson(entity);
}
 
Example 9
Source File: BaseResponse.java    From oxAuth with MIT License 5 votes vote down vote up
public BaseResponse(ClientResponse<String> clientResponse) {
    if (clientResponse != null) {
        status = clientResponse.getStatus();
        if (clientResponse.getLocationLink() != null) {
            location = clientResponse.getLocationLink().getHref();
        }
        entity = clientResponse.getEntity(String.class);
        headers = clientResponse.getMetadata();
    }
}
 
Example 10
Source File: PushTokenDeliveryResponse.java    From oxAuth with MIT License 5 votes vote down vote up
public PushTokenDeliveryResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    String entity = clientResponse.getEntity(String.class);
    setEntity(entity);
    setHeaders(clientResponse.getMetadata());
}
 
Example 11
Source File: PushErrorResponse.java    From oxAuth with MIT License 5 votes vote down vote up
public PushErrorResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    String entity = clientResponse.getEntity(String.class);
    setEntity(entity);
    setHeaders(clientResponse.getMetadata());
}
 
Example 12
Source File: PingCallbackResponse.java    From oxAuth with MIT License 5 votes vote down vote up
public PingCallbackResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    String entity = clientResponse.getEntity(String.class);
    setEntity(entity);
    setHeaders(clientResponse.getMetadata());
}
 
Example 13
Source File: JwtUtil.java    From oxAuth with MIT License 4 votes vote down vote up
public static JSONObject getJsonKey(String jwksUri, String jwks, String keyId) {
    log.debug("Retrieving JWK Key...");

    JSONObject jsonKey = null;
    try {
        if (StringHelper.isEmpty(jwks)) {
            ClientRequest clientRequest = new ClientRequest(jwksUri);
            clientRequest.setHttpMethod(HttpMethod.GET);
            ClientResponse<String> clientResponse = clientRequest.get(String.class);

            int status = clientResponse.getStatus();
            log.debug(String.format("Status: %n%d", status));

            if (status == 200) {
                jwks = clientResponse.getEntity(String.class);
                log.debug(String.format("JWK: %s", jwks));
            }
        }
        if (StringHelper.isNotEmpty(jwks)) {
            JSONObject jsonObject = new JSONObject(jwks);
            JSONArray keys = jsonObject.getJSONArray(JSON_WEB_KEY_SET);
            if (keys.length() > 0) {
                if (StringHelper.isEmpty(keyId)) {
                    jsonKey = keys.getJSONObject(0);
                } else {
                    for (int i = 0; i < keys.length(); i++) {
                        JSONObject kv = keys.getJSONObject(i);
                        if (kv.getString(KEY_ID).equals(keyId)) {
                            jsonKey = kv;
                            break;
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    return jsonKey;
}
 
Example 14
Source File: RedirectionUriService.java    From oxAuth with MIT License 4 votes vote down vote up
public String validateRedirectionUri(@NotNull Client client, String redirectionUri) {
    try {
        String sectorIdentifierUri = client.getSectorIdentifierUri();
        String[] redirectUris = client.getRedirectUris();

        if (StringUtils.isNotBlank(sectorIdentifierUri)) {
            ClientRequest clientRequest = new ClientRequest(sectorIdentifierUri);
            clientRequest.setHttpMethod(HttpMethod.GET);

            ClientResponse<String> clientResponse = clientRequest.get(String.class);
            int status = clientResponse.getStatus();

            if (status == 200) {
                String entity = clientResponse.getEntity(String.class);
                JSONArray sectorIdentifierJsonArray = new JSONArray(entity);
                redirectUris = new String[sectorIdentifierJsonArray.length()];
                for (int i = 0; i < sectorIdentifierJsonArray.length(); i++) {
                    redirectUris[i] = sectorIdentifierJsonArray.getString(i);
                }
            } else {
                return null;
            }
        }

        if (StringUtils.isNotBlank(redirectionUri) && redirectUris != null) {
            log.debug("Validating redirection URI: clientIdentifier = {}, redirectionUri = {}, found = {}",
                    client.getClientId(), redirectionUri, redirectUris.length);

            if (isUriEqual(redirectionUri, redirectUris)) {
                return redirectionUri;
            }
        } else {
            // Accept Request Without redirect_uri when One Registered
            if (redirectUris != null && redirectUris.length == 1) {
                return redirectUris[0];
            }
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}
 
Example 15
Source File: CIBARegisterParamsValidatorService.java    From oxAuth with MIT License 4 votes vote down vote up
public boolean validateParams(
        BackchannelTokenDeliveryMode backchannelTokenDeliveryMode, String backchannelClientNotificationEndpoint,
        AsymmetricSignatureAlgorithm backchannelAuthenticationRequestSigningAlg, Boolean backchannelUserCodeParameter,
        List<GrantType> grantTypes, SubjectType subjectType, String sectorIdentifierUri, String jwks, String jwksUri) {
    try {
        // Not CIBA Registration
        if (backchannelTokenDeliveryMode == null && Strings.isBlank(backchannelClientNotificationEndpoint) && backchannelAuthenticationRequestSigningAlg == null) {
            return true;
        }

        // Required parameter.
        if (backchannelTokenDeliveryMode == null
                || !appConfiguration.getBackchannelTokenDeliveryModesSupported().contains(backchannelTokenDeliveryMode.getValue())) {
            return false;
        }

        // Required if the token delivery mode is set to ping or push.
        if ((backchannelTokenDeliveryMode == PING || backchannelTokenDeliveryMode == PUSH)
                && Strings.isBlank(backchannelClientNotificationEndpoint)) {
            return false;
        }

        // Grant type urn:openid:params:grant-type:ciba is required if the token delivery mode is set to ping or poll.
        if (backchannelTokenDeliveryMode == PING || backchannelTokenDeliveryMode == POLL) {
            if (!appConfiguration.getGrantTypesSupported().contains(CIBA) || !grantTypes.contains(CIBA)) {
                return false;
            }
        }

        // If the server does not support backchannel_user_code_parameter_supported, the default value is false.
        if (appConfiguration.getBackchannelUserCodeParameterSupported() == null || appConfiguration.getBackchannelUserCodeParameterSupported() == false) {
            backchannelUserCodeParameter = false;
        }

        if (subjectType != null && subjectType == SubjectType.PAIRWISE) {

            if (backchannelTokenDeliveryMode == PING || backchannelTokenDeliveryMode == POLL) {
                if (Strings.isBlank(jwks) && Strings.isBlank(jwksUri)) {
                    return false;
                }
            }

            if (Strings.isNotBlank(sectorIdentifierUri)) {
                ClientRequest clientRequest = new ClientRequest(sectorIdentifierUri);
                clientRequest.setHttpMethod(HttpMethod.GET);

                ClientResponse<String> clientResponse = clientRequest.get(String.class);
                int status = clientResponse.getStatus();

                if (status != 200) {
                    return false;
                }

                String entity = clientResponse.getEntity(String.class);
                JSONArray sectorIdentifierJsonArray = new JSONArray(entity);

                if (backchannelTokenDeliveryMode == PING || backchannelTokenDeliveryMode == POLL) {
                    // If a sector_identifier_uri is explicitly provided, then the jwks_uri must be included in the list of
                    // URIs pointed to by the sector_identifier_uri.
                    if (!Strings.isBlank(jwksUri) && !Util.asList(sectorIdentifierJsonArray).contains(jwksUri)) {
                        return false;
                    }
                } else if (backchannelTokenDeliveryMode == PUSH) {
                    // In case a sector_identifier_uri is explicitly provided, then the backchannel_client_notification_endpoint
                    // must be included in the list of URIs pointed to by the sector_identifier_uri.
                    if (!Util.asList(sectorIdentifierJsonArray).contains(backchannelClientNotificationEndpoint)) {
                        return false;
                    }
                }
            }
        }
    } catch (Exception e) {
        log.trace(e.getMessage(), e);
        return false;
    }

    return true;
}
 
Example 16
Source File: HttpUtils.java    From pnc with Apache License 2.0 4 votes vote down vote up
public static String processGetRequest(String url) throws Exception {
    ClientRequest request = new ClientRequest(url);
    request.accept(MediaType.APPLICATION_JSON);
    ClientResponse<String> response = request.get(String.class);
    return response.getEntity();
}
 
Example 17
Source File: PersistentPushTopicConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() throws Exception {
   try {
      String testName = "testFailure";
      startup();
      deployTopic(testName);

      ClientRequest request = new ClientRequest(generateURL("/topics/" + testName));

      ClientResponse<?> response = request.head();
      response.releaseConnection();
      Assert.assertEquals(200, response.getStatus());
      Link sender = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "create");
      log.debug("create: " + sender);
      Link pushSubscriptions = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "push-subscriptions");
      log.debug("push subscriptions: " + pushSubscriptions);

      PushTopicRegistration reg = new PushTopicRegistration();
      reg.setDurable(true);
      XmlLink target = new XmlLink();
      target.setHref("http://localhost:3333/error");
      target.setRelationship("uri");
      reg.setTarget(target);
      reg.setDisableOnFailure(true);
      reg.setMaxRetries(3);
      reg.setRetryWaitMillis(10);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      Assert.assertEquals(201, response.getStatus());
      Link pushSubscription = response.getLocationLink();
      response.releaseConnection();

      ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post();
      res.releaseConnection();
      Assert.assertEquals(201, res.getStatus());

      Thread.sleep(5000);

      response = pushSubscription.request().get();
      PushTopicRegistration reg2 = response.getEntity(PushTopicRegistration.class);
      response.releaseConnection();
      Assert.assertEquals(reg.isDurable(), reg2.isDurable());
      Assert.assertEquals(reg.getTarget().getHref(), reg2.getTarget().getHref());
      Assert.assertFalse(reg2.isEnabled());
      response.releaseConnection();

      String destination = reg2.getDestination();
      ClientSession session = manager.getQueueManager().getSessionFactory().createSession(false, false, false);
      ClientSession.QueueQuery query = session.queueQuery(new SimpleString(destination));
      Assert.assertFalse(query.isExists());

      manager.getQueueManager().getPushStore().removeAll();
   } finally {
      shutdown();
   }
}
 
Example 18
Source File: PersistentPushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test
public void testFailure() throws Exception {
   try {
      startup();

      String testName = "testFailure";
      QueueDeployment deployment = new QueueDeployment();
      deployment.setDuplicatesAllowed(true);
      deployment.setDurableSend(false);
      deployment.setName(testName);
      manager.getQueueManager().deploy(deployment);

      ClientRequest request = new ClientRequest(generateURL("/queues/" + testName));

      ClientResponse<?> response = request.head();
      response.releaseConnection();
      Assert.assertEquals(200, response.getStatus());
      Link sender = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "create");
      log.debug("create: " + sender);
      Link pushSubscriptions = MessageTestBase.getLinkByTitle(manager.getQueueManager().getLinkStrategy(), response, "push-consumers");
      log.debug("push subscriptions: " + pushSubscriptions);

      PushRegistration reg = new PushRegistration();
      reg.setDurable(true);
      XmlLink target = new XmlLink();
      target.setHref("http://localhost:3333/error");
      target.setRelationship("uri");
      reg.setTarget(target);
      reg.setDisableOnFailure(true);
      reg.setMaxRetries(3);
      reg.setRetryWaitMillis(10);
      response = pushSubscriptions.request().body("application/xml", reg).post();
      Assert.assertEquals(201, response.getStatus());
      Link pushSubscription = response.getLocationLink();
      response.releaseConnection();

      ClientResponse<?> res = sender.request().body("text/plain", Integer.toString(1)).post();
      res.releaseConnection();
      Assert.assertEquals(201, res.getStatus());

      Thread.sleep(5000);

      response = pushSubscription.request().get();
      PushRegistration reg2 = response.getEntity(PushRegistration.class);
      Assert.assertEquals(reg.isDurable(), reg2.isDurable());
      Assert.assertEquals(reg.getTarget().getHref(), reg2.getTarget().getHref());
      Assert.assertFalse(reg2.isEnabled()); // make sure the failure disables the PushRegistration
      response.releaseConnection();

      manager.getQueueManager().getPushStore().removeAll();
   } finally {
      shutdown();
   }
}
 
Example 19
Source File: HttpUtils.java    From pnc with Apache License 2.0 3 votes vote down vote up
/**
 * Process HTTP GET request and get the data as type specified as parameter. Client accepts application/json MIME
 * type.
 *
 * @param clazz Class to which the data are unmarshalled
 * @param <T> module config
 * @param url Request URL
 * @throws Exception Thrown if some error occurs in communication with server
 * @return Unmarshalled entity data
 */
public static <T> T processGetRequest(Class<T> clazz, String url) throws Exception {
    ClientRequest request = new ClientRequest(url);
    request.accept(MediaType.APPLICATION_JSON);

    ClientResponse<T> response = request.get(clazz);
    return response.getEntity();
}