org.jboss.resteasy.client.ClientResponse Java Examples

The following examples show how to use org.jboss.resteasy.client.ClientResponse. 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: ActiveMQPushStrategy.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
protected void initialize() throws Exception {
   super.start();
   initialized = true;
   initAuthentication();
   ClientRequest request = executor.createRequest(registration.getTarget().getHref());
   for (XmlHttpHeader header : registration.getHeaders()) {
      request.header(header.getName(), header.getValue());
   }
   ClientResponse<?> res = request.head();
   if (res.getStatus() != 200) {
      throw new RuntimeException("Failed to query REST destination for init information.  Status: " + res.getStatus());
   }
   String url = (String) res.getHeaders().getFirst("msg-create-with-id");
   if (url == null) {
      if (res.getLinkHeader() == null) {
         throw new RuntimeException("Could not find create-with-id URL");
      }
      Link link = res.getLinkHeader().getLinkByTitle("create-with-id");
      if (link == null) {
         throw new RuntimeException("Could not find create-with-id URL");
      }
      url = link.getHref();
   }
   targetUri = ResteasyUriBuilder.fromTemplate(url);
}
 
Example #3
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startEmbedded() throws Exception {
   server = new EmbeddedRestActiveMQ(null);
   assertNotNull(server.getEmbeddedActiveMQ());
   server.getManager().setConfigResourcePath("activemq-rest.xml");

   SecurityConfiguration securityConfiguration = createDefaultSecurityConfiguration();
   ActiveMQJAASSecurityManager securityManager = new ActiveMQJAASSecurityManager(InVMLoginModule.class.getName(), securityConfiguration);
   server.getEmbeddedActiveMQ().setSecurityManager(securityManager);

   server.start();
   factory = ActiveMQJMSClient.createConnectionFactory("vm://0", "cf");

   ClientRequest request = new ClientRequest(TestPortProvider.generateURL("/queues/exampleQueue"));

   ClientResponse<?> response = request.head();
   response.releaseConnection();
   assertEquals(200, response.getStatus());
   Link sender = response.getLinkHeader().getLinkByTitle("create");
   log.debug("create: " + sender);
   Link consumers = response.getLinkHeader().getLinkByTitle("pull-consumers");
   log.debug("pull: " + consumers);
   response = Util.setAutoAck(consumers, true);
   consumeNext = response.getLinkHeader().getLinkByTitle("consume-next");
   log.debug("consume-next: " + consumeNext);
}
 
Example #4
Source File: RecaptchaUtil.java    From oxTrust with MIT License 6 votes vote down vote up
public boolean verifyGoogleRecaptcha(String gRecaptchaResponse, String secretKey) {
	boolean result = false;
	try {
		ClientRequest request = new ClientRequest("https://www.google.com/recaptcha/api/siteverify");
		request.formParameter("secret", secretKey);
		request.formParameter("response", gRecaptchaResponse);
		request.accept("application/json");

		ClientResponse<String> response = request.post(String.class);

		ObjectMapper mapper = new ObjectMapper();
		Map<String, String> map = mapper.readValue(new ByteArrayInputStream(response.getEntity().getBytes()),
				new TypeReference<Map<String, String>>() {
				});

		return Boolean.parseBoolean(map.get("success"));
	} catch (Exception e) {
		log.warn("Exception happened while verifying recaptcha, check your internet connection", e);
		return result;
	}
}
 
Example #5
Source File: TokenRevocationResponse.java    From oxAuth with MIT License 6 votes vote down vote up
/**
 * Constructs an token revocation response.
 */
public TokenRevocationResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);

    if (StringUtils.isNotBlank(entity)) {
        try {
            JSONObject jsonObj = new JSONObject(entity);
            if (jsonObj.has("error")) {
                errorType = TokenRevocationErrorResponseType.getByValue(jsonObj.getString("error"));
            }
            if (jsonObj.has("error_description")) {
                errorDescription = jsonObj.getString("error_description");
            }
            if (jsonObj.has("error_uri")) {
                errorUri = jsonObj.getString("error_uri");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
 
Example #6
Source File: RestSend.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 create = res.getHeaderAsLink("msg-create");

   System.out.println("Send order...");
   Order order = new Order();
   order.setName("Bill");
   order.setItem("iPhone4");
   order.setAmount("$199.99");

   res = create.request().body("application/xml", order).post();
   if (res.getStatus() != 201)
      throw new RuntimeException("Failed to post");
}
 
Example #7
Source File: JwtUtil.java    From oxAuth with MIT License 6 votes vote down vote up
public static JSONObject getJSONWebKeys(String jwksUri, ClientExecutor executor) {
    log.debug("Retrieving jwks " + jwksUri + "...");

    JSONObject jwks = null;
    try {
        if (!StringHelper.isEmpty(jwksUri)) {
            ClientRequest clientRequest = executor != null ? new ClientRequest(jwksUri, executor) : 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 = fromJson(clientResponse.getEntity(String.class));
                log.debug(String.format("JWK: %s", jwks));
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }

    return jwks;
}
 
Example #8
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 #9
Source File: PushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void cleanupSubscription(Link pushSubscription) throws Exception {
   if (pushSubscription != null) {
      ClientResponse<?> response = pushSubscription.request().delete();
      response.releaseConnection();
      Assert.assertEquals(204, response.getStatus());
   }
}
 
Example #10
Source File: AuthorizationResponse.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Constructs an authorization response.
 */
public AuthorizationResponse(ClientResponse<String> clientResponse) {
    super(clientResponse);
    customParams = new HashMap<String, String>();

    if (StringUtils.isNotBlank(entity)) {
        try {
            JSONObject jsonObj = new JSONObject(entity);
            if (jsonObj.has("error")) {
                errorType = AuthorizeErrorResponseType.fromString(jsonObj.getString("error"));
            }
            if (jsonObj.has("error_description")) {
                errorDescription = jsonObj.getString("error_description");
            }
            if (jsonObj.has("error_uri")) {
                errorUri = jsonObj.getString("error_uri");
            }
            if (jsonObj.has("state")) {
                state = jsonObj.getString("state");
            }
            if (jsonObj.has("redirect")) {
                location = jsonObj.getString("redirect");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    processLocation();
}
 
Example #11
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnLink() 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);

   consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
   res.releaseConnection();
   assertNotNull(consumeNext);
}
 
Example #12
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 #13
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 #14
Source File: HMACFilterAuthenticationProviderTest.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testProvideAuthenticationPostFail() throws Exception {
	ClientRequest request = new ClientRequest("http://localhost:8080/hmac", httpExecutor);
	request.queryParameter("a", "b"); // with also params in URI
	request.queryParameter("c", "d");
	request.header(HMACUtils.HEADERS_SIGNED.get(0), "z");
	request.header("r", "f");
	request.body(MediaType.TEXT_PLAIN, "abcdhjk");
	// without providing authentication
	ClientResponse<?> resp = request.post();
	Assert.assertTrue(resp.getStatus() >= 400);
	Assert.assertFalse(DummyServlet.arrived);
}
 
Example #15
Source File: PushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private ClientResponse consume(Link destination, String expectedContent) throws Exception {
   ClientResponse response;
   response = destination.request().header(Constants.WAIT_HEADER, "1").post(String.class);
   Assert.assertEquals(200, response.getStatus());
   Assert.assertEquals(expectedContent, response.getEntity(String.class));
   response.releaseConnection();
   return response;
}
 
Example #16
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseXmlAcceptHeaderToSetContentType() 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);

   assertEquals("application/xml", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());

   consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
   res.releaseConnection();
   assertNotNull(consumeNext);
}
 
Example #17
Source File: PushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testBridge() throws Exception {
   Link destinationForConsumption = null;
   ClientResponse consumerResponse = null;
   Link pushSubscription = null;
   String messageContent = "1";

   try {
      // The name of the queue used for the test should match the name of the test
      String queue = "testBridge";
      String queueToPushTo = "pushedFrom-" + queue;
      log.debug("\n" + queue);
      deployQueue(queue);
      deployQueue(queueToPushTo);

      ClientResponse queueResponse = Util.head(new ClientRequest(generateURL(Util.getUrlPath(queue))));
      Link destination = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), queueResponse, "create");
      Link pushSubscriptions = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), queueResponse, "push-consumers");

      ClientResponse queueToPushToResponse = Util.head(new ClientRequest(generateURL(Util.getUrlPath(queueToPushTo))));
      ClientResponse autoAckResponse = setAutoAck(queueToPushToResponse, true);
      destinationForConsumption = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), autoAckResponse, "consume-next");

      pushSubscription = createPushRegistration(queueToPushTo, pushSubscriptions, PushRegistrationType.BRIDGE);

      sendMessage(destination, messageContent);

      consumerResponse = consume(destinationForConsumption, messageContent);
   } finally {
      cleanupConsumer(consumerResponse);
      cleanupSubscription(pushSubscription);
   }
}
 
Example #18
Source File: PushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testUri() throws Exception {
   Link pushSubscription = null;
   String messageContent = "1";

   try {
      // The name of the queue used for the test should match the name of the test
      String queue = "testUri";
      String queueToPushTo = "pushedFrom-" + queue;
      log.debug("\n" + queue);

      deployQueue(queue);
      deployQueue(queueToPushTo);
      server.getJaxrsServer().getDeployment().getRegistry().addPerRequestResource(MyResource.class);

      ClientResponse queueResponse = Util.head(new ClientRequest(generateURL(Util.getUrlPath(queue))));
      Link destinationForSend = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), queueResponse, "create");
      Link pushSubscriptions = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), queueResponse, "push-consumers");

      pushSubscription = createPushRegistration(generateURL("/my"), pushSubscriptions, PushRegistrationType.URI);

      sendMessage(destinationForSend, messageContent);

      Thread.sleep(100);

      Assert.assertEquals(messageContent, MyResource.got_it);
   } finally {
      cleanupSubscription(pushSubscription);
   }
}
 
Example #19
Source File: EmbeddedRestActiveMQJMSTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseJsonAcceptHeaderToSetContentType() throws Exception {
   TransformTest.Order order = createTestOrder("1", "$5.00");
   publish("exampleQueue", order, null);

   ClientResponse<?> res = consumeNext.request().header("Accept-Wait", "2").accept("application/json").post(String.class);
   assertEquals("application/json", res.getHeaders().getFirst("Content-Type").toString().toLowerCase());

   consumeNext = res.getLinkHeader().getLinkByTitle("consume-next");
   res.releaseConnection();
   assertNotNull(consumeNext);
}
 
Example #20
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 #21
Source File: PushQueueConsumerTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void cleanupConsumer(ClientResponse consumerResponse) throws Exception {
   if (consumerResponse != null) {
      Link consumer = getLinkByTitle(manager.getQueueManager().getLinkStrategy(), consumerResponse, "consumer");
      ClientResponse<?> response = consumer.request().delete();
      response.releaseConnection();
      Assert.assertEquals(204, response.getStatus());
   }
}
 
Example #22
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 #23
Source File: Util.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static ClientResponse setAutoAck(Link link, boolean ack) throws Exception {
   ClientResponse response;
   response = link.request().formParameter("autoAck", Boolean.toString(ack)).post();
   response.releaseConnection();
   Assert.assertEquals(201, response.getStatus());
   return response;
}
 
Example #24
Source File: BaseResponseWithErrors.java    From oxAuth with MIT License 5 votes vote down vote up
public BaseResponseWithErrors(ClientResponse<String> clientResponse) {
    super(clientResponse);
    final String entity = getEntity();
    if (StringUtils.isNotBlank(entity)) {
        injectErrorIfExistSilently(entity);
    }
}
 
Example #25
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 #26
Source File: HttpUtils.java    From pnc with Apache License 2.0 5 votes vote down vote up
/**
 * Process HTTP requests and tests if server responds with expected HTTP code. Request is implicitly set to accept
 * MIME type application/json.
 *
 * @param ecode Expected HTTP error code
 * @param url Request URL
 * @throws Exception Thrown if some error occurs in communication with server
 */
public static void testResponseHttpCode(int ecode, String url) throws Exception {
    ClientRequest request = new ClientRequest(url);
    request.accept(MediaType.APPLICATION_JSON);

    ClientResponse<String> response = request.get(String.class);
    if (response.getStatus() != ecode)
        throw new Exception("Server returned unexpected HTTP code! Returned code:" + response.getStatus());
}
 
Example #27
Source File: CreateDestinationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateTopicWithBadContentType() throws Exception {
   String queueConfig = "<topic name=\"testTopic\"></topic>";
   ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/topics"));
   ClientResponse cRes = create.body("application/x-www-form-urlencoded", queueConfig).post();
   cRes.releaseConnection();
   Assert.assertEquals(415, cRes.getStatus());
}
 
Example #28
Source File: CreateDestinationTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateQueueWithBadContentType() throws Exception {
   String queueConfig = "<queue name=\"testQueue\"><durable>true</durable></queue>";
   ClientRequest create = new ClientRequest(TestPortProvider.generateURL("/queues"));
   ClientResponse cRes = create.body("application/x-www-form-urlencoded", queueConfig).post();
   cRes.releaseConnection();

   Assert.assertEquals(415, cRes.getStatus());
}
 
Example #29
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 #30
Source File: AutoAckTopicTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
   try {
      ClientRequest req = new ClientRequest(url);
      req.header("Accept-Wait", acceptWaitTime);
      ClientResponse<?> response = req.post();
      response.releaseConnection();
      isFinished = true;
   } catch (Exception e) {
      failed = true;
   }
}