@Test public void testCustomStatus() { Choir testChoir = new Choir(); Response result = TestUtility.postGetResponse(choirBase + "nameOfChoirBlocking", testChoir.toJson(false)); HttpResponse response = null; try { response = result.returnResponse(); } catch (IOException e1) { e1.printStackTrace(); } assertTrue(response.getStatusLine().getStatusCode() == 400); assertTrue(response.getStatusLine().getReasonPhrase().equals("Choir Name is required!")); }
@Test public void testCustomHeaders() { Choir testChoir = new Choir(); Response result = TestUtility.postGetResponse(choirBase + "nameOfChoirHeaders", testChoir.toJson(false)); HttpResponse response = null; try { response = result.returnResponse(); } catch (IOException e1) { e1.printStackTrace(); } // Normally would return plain text because the ResultType annotation is missing on the handling method assertTrue(response.getHeaders("content-type")[0].getValue().equals("application/json; charset=utf-8")); }
/** * Sends a request to Orion * * @param ctxElement * The context element * @param path * the path from the context broker that determines which "operation"will be executed * @param responseClazz * The class expected for the response * @return The object representing the JSON answer from Orion * @throws OrionConnectorException * if a communication exception happens, either when contacting the context broker at * the given address, or obtaining the answer from it. */ private <E, T> T sendRequestToOrion(E ctxElement, String path, Class<T> responseClazz) { String jsonEntity = gson.toJson(ctxElement); log.debug("Send request to Orion: {}", jsonEntity); Request req = Request.Post(this.orionAddr.toString() + path) .addHeader("Accept", APPLICATION_JSON.getMimeType()) .bodyString(jsonEntity, APPLICATION_JSON).connectTimeout(5000).socketTimeout(5000); Response response; try { response = req.execute(); } catch (IOException e) { throw new OrionConnectorException("Could not execute HTTP request", e); } HttpResponse httpResponse = checkResponse(response); T ctxResp = getOrionObjFromResponse(httpResponse, responseClazz); log.debug("Sent to Orion. Obtained response: {}", httpResponse); return ctxResp; }
public ArrayList<String[]> getVisualRecog(String imageUrl) throws JsonException, URISyntaxException, IOException { String apiKey = bluemixUtil.getApiKey(); String getUrl = bluemixUtil.getBaseUrl().replace("https:", "http:") + CLASSIFY_API + "?url=" + imageUrl + "&api_key=" + apiKey + "&version=" + VERSION; Response response = rest.get(getUrl); //Convert the response into JSON data String content = EntityUtils.toString(response.returnResponse().getEntity()); JsonJavaObject jsonData = rest.parse(content); //Retrieve the list of highest matching classifiers and associated confidences ArrayList<String[]> tags = getSuggestedTags(jsonData); if(tags != null && tags.size() > 0) { return tags; } return null; }
/** * Send POST request with authorization header and additional headers * @param url - The url of the POST request * @param auth - String for authorization header * @param headers - Hashmap of headers to add to the request * @param postData - The body of the POST * @return the Response to the POST request */ public Response post(String url, String auth, HashMap<String, String> headers, JsonJavaObject postData) throws JsonException, IOException, URISyntaxException { URI normUri = new URI(url).normalize(); Request postRequest = Request.Post(normUri); //Add all headers if(StringUtil.isNotEmpty(auth)) { postRequest.addHeader("Authorization", auth); } if(headers != null && headers.size() > 0){ for (Map.Entry<String, String> entry : headers.entrySet()) { postRequest.addHeader(entry.getKey(), entry.getValue()); } } String postDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, postData); Response response = executor.execute(postRequest.bodyString(postDataString, ContentType.APPLICATION_JSON)); return response; }
public Response post(String url, String auth, JsonJavaObject postData, File fileUpload) throws JsonException, IOException, URISyntaxException { URI normUri = new URI(url).normalize(); Request postRequest = Request.Post(normUri); //Add all headers if(StringUtil.isNotEmpty(auth)) { postRequest.addHeader("Authorization", auth); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("images_file", fileUpload, ContentType.APPLICATION_OCTET_STREAM, fileUpload.getName()); if(postData != null) { String postDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, postData); builder.addTextBody("classifier_ids", postDataString, ContentType.MULTIPART_FORM_DATA); } HttpEntity multipart = builder.build(); postRequest.body(multipart); Response response = executor.execute(postRequest); return response; }
/** * Send PUT request with authorization header * @param url - The url of the POST request * @param auth - String for authorization header * @param putData - The body of the PUT */ public Response put(String url, String auth, JsonJavaObject putData) throws URISyntaxException, IOException, JsonException { URI normUri = new URI(url).normalize(); Request putRequest = Request.Put(normUri); //Add auth header if(StringUtil.isNotEmpty(auth)) { putRequest.addHeader("Authorization", auth); } //Add put data String putDataString = JsonGenerator.toJson(JsonJavaFactory.instanceEx, putData); if(putData != null) { putRequest = putRequest.bodyString(putDataString, ContentType.APPLICATION_JSON); } Response response = executor.execute(putRequest); return response; }
@Override public PaymentResult refundPayment(AuthHeader authHeader, Long id, Long amount) { Response response = null; try { response = Request. Post(apiUrl + "/payments/payment/" + id + "/refund") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString("amount=" + amount, ContentType.APPLICATION_JSON) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, PaymentResult.class); }
@Override public Payment createRecurrentPayment(AuthHeader authHeader, Long id, NextPayment createPayment) { Response response = null; try { response = Request. Post(apiUrl + "/payments/payment/" + id + "/create-recurrence") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString(marshall(createPayment), ContentType.TEXT_XML) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, Payment.class); }
@Override public PaymentResult voidRecurrence(AuthHeader authHeader, Long id) { Response response = null; try { response = Request. Post(apiUrl + "/payments/payment/" + id + "/void-recurrence") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new RuntimeException(ex); } return unMarshall(response, PaymentResult.class); }
@Override public PaymentResult capturePayment(AuthHeader authHeader, Long id) { Response response = null; try { response = Request. Post(apiUrl + "/payments/payment/" + id + "/capture") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, PaymentResult.class); }
@Override public PaymentResult voidAuthorization(AuthHeader authHeader, Long id) { Response response = null; try { response = Request. Post(apiUrl + "/payments/payment/" + id + "/void-authorization") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, PaymentResult.class); }
@Override public Payment getPayment(AuthHeader authHeader, Long id) { Response response = null; try { response = Request.Get(apiUrl + "/payments/payment/" + id) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, Payment.class); }
@Override public PaymentInstrumentRoot getPaymentInstruments(AuthHeader authHeader, Long goId, Currency currency) { Response response = null; try { response = Request.Get(apiUrl + "/eshops/eshop/" + goId + "/payment-instruments/" + currency) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, PaymentInstrumentRoot.class); }
@Override public List<EETReceipt> findEETReceiptsByFilter(@BeanParam AuthHeader authHeader, EETReceiptFilter filter) { Response response = null; try { response = Request.Post(apiUrl + "/eet-receipts") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString(marshall(filter), ContentType.APPLICATION_JSON) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshallComplexResponse(response, new TypeReference<List<EETReceipt>>() {}); }
@Override public List<EETReceipt> getEETReceiptByPaymentId(@BeanParam AuthHeader authHeader, Long id) { Response response = null; try { response = Request.Get(apiUrl + "/payments/payment/" + id + "/eet-receipts") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshallComplexResponse(response, new TypeReference<List<EETReceipt>>() {}); }
@Override public byte[] getStatement(AuthHeader authHeader, AccountStatement accountStatement) { Response response = null; try { response = Request.Post(apiUrl + "/accounts/account-statement") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString(marshall(accountStatement), ContentType.APPLICATION_JSON) .execute(); HttpResponse httpresponse = response.returnResponse(); return EntityUtils.toByteArray(httpresponse.getEntity()); } catch (IOException ex) { throw new WebApplicationException(ex); } }
@Override public SupercashCoupon createSupercashCoupon(AuthHeader authHeader, SupercashCouponRequest couponRequest) { Response response = null; try { response = Request.Post(apiUrl + "/supercash/coupon") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader. getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString(marshall(couponRequest), ContentType.APPLICATION_JSON) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashCoupon.class); }
@Override public SupercashBatchResult createSupercashCouponBatch(AuthHeader authHeader, SupercashBatchRequest batchRequest) { Response response = null; try { response = Request.Post(apiUrl + "/supercash/coupon/batch") .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_JSON) .addHeader(AUTHORIZATION, authHeader. getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .bodyString(marshall(batchRequest), ContentType.APPLICATION_JSON) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashBatchResult.class); }
@Override public SupercashBatchState getSupercashCouponBatchStatus(AuthHeader authHeader, Long batchId) { Response response = null; try { response = Request.Get(apiUrl + "/batch/" + batchId) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashBatchState.class); }
@Override public SupercashBatch getSupercashCouponBatch(AuthHeader authHeader, Long goId, Long batchId) { Response response = null; try { response = Request.Get(apiUrl + "/supercash/coupon/find?batch_request_id=" + batchId + "&go_id=" + goId) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashBatch.class); }
@Override public SupercashBatch findSupercashCoupons(AuthHeader authHeader, Long goId, String paymentSessionIds) { Response response = null; try { response = Request.Get(apiUrl + "/supercash/coupon/find?payment_session_id_list=" + paymentSessionIds + "&go_id=" + goId) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashBatch.class); }
@Override public SupercashPayment getSupercashCoupon(AuthHeader authHeader, Long couponId) { Response response = null; try { response = Request.Get(apiUrl + "/supercash/coupon/" + couponId) .addHeader(ACCEPT, MediaType.APPLICATION_JSON) .addHeader(CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(USER_AGENT, IMPLEMENTATION_NAME + "=" + VERSION) .execute(); } catch (IOException ex) { throw new WebApplicationException(ex); } return unMarshall(response, SupercashPayment.class); }
@Override public AccessToken loginApplication(AuthHeader authHeader, String grantType, String scope) { Form form = Form.form(); form.add(SCOPE, scope); form.add(GRANT_TYPE, grantType); Response respose = null; try { respose = Request.Post(apiUrl + "/oauth2/token") .addHeader(AUTHORIZATION, authHeader.getAuhorization()) .addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded") .bodyForm(form.build()) .bodyString("grant_type=client_credentials&scope=" + scope, ContentType.APPLICATION_JSON) .execute(); } catch (IOException ex) { throw new WebApplicationException(); } return unMarshall(respose, AccessToken.class); }
public SoapRawClientResponse callSoapService(InputStream xmlFile) throws InternalBusinessException { SoapRawClientResponse rawSoapResponse = new SoapRawClientResponse(); LOGGER.debug("Calling SoapService with POST on Apache HTTP-Client and configured URL: {}", soapServiceUrl); try { Response httpResponseContainer = Request .Post(soapServiceUrl) .bodyStream(xmlFile, contentTypeTextXmlUtf8()) .addHeader("SOAPAction", "\"" + soapAction + "\"") .execute(); HttpResponse httpResponse = httpResponseContainer.returnResponse(); rawSoapResponse.setHttpStatusCode(httpResponse.getStatusLine().getStatusCode()); rawSoapResponse.setHttpResponseBody(XmlUtils.parseFileStream2Document(httpResponse.getEntity().getContent())); } catch (Exception exception) { throw new InternalBusinessException("Some Error accured while trying to Call SoapService for test: " + exception.getMessage()); } return rawSoapResponse; }
public void destroySession(final Optional<String> sessionKey, final String serviceName) { sessionKey.ifPresent(_sessionKey -> { logger.info("Releasing Consul session"); final String uri = leaderKey(consulUrl, serviceName, "release", _sessionKey); logger.debug("PUT {}", uri); try { final Response response = executor.execute(Request .Put(uri)); final Optional<Boolean> result = Optional.ofNullable(Boolean.valueOf(response.returnContent().asString())); logger.debug("Result: {}", result); destroySession(consulUrl, _sessionKey); } catch (final Exception e) { logger.warn("Failed to release session key in Consul: {}", e); } }); }
@Test public void pollConsulWhenNoSession_EffectivelyEquivalentToCreateSession() throws ClientProtocolException, IOException { final Response response = mock(Response.class); final HttpResponse httpResponse = mock(HttpResponse.class); when(httpResponse.getEntity()).thenReturn(new StringEntity("{\"ID\":\"SESSION\"}")); when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("http", 1, 1), 200, "yay")); when(response.returnResponse()).thenReturn(httpResponse); when(executor.execute(any(Request.class))).thenReturn(response); final ConsulFacadeBean bean = new ConsulFacadeBean("URL", Optional.empty(), Optional.empty(), executor); Optional<Boolean> result = bean.pollConsul("SERVICE"); assertNotNull(result); assertTrue(result.isPresent()); assertFalse(result.get()); }
@Test public void testProxyAuthWithSSL() throws Exception { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(new File(keyStoreFile), keystorePW.toCharArray(), new TrustSelfSignedStrategy()) .build(); try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).build()) { Executor ex = Executor.newInstance(httpclient); Response response = ex.execute(Request.Get("https://localhost:9200/blahobar.234324234/logs/1") .addHeader("Authorization", String.format("Bearer %s", token)) .addHeader("X-Proxy-Remote-User", proxyUser)); System.out.println(response.returnContent().asString()); } catch (Exception e) { System.out.println(e); fail("Test Failed"); } }
@Override public void execute() { try { Response response = retryGet(new ResponseGetter(remotePageUrl), NO_OF_RETRIES, RETRY_WAIT_TIME); HttpResponse httpResponse = response.returnResponse(); assertEquals("http error code does not match", httpErrorCode, httpResponse.getStatusLine().getStatusCode()); if (contentFragment != null) { HttpEntity entity = httpResponse.getEntity(); if (entity == null) { throw new IllegalStateException("Response contains no content"); } try (InputStream is = entity.getContent()) { byte[] bytes = IOUtils.toByteArray(is); String pageContent = new String(bytes, Charset.defaultCharset()); assertNotNull("page content is empty", pageContent); log.debug("\n" + head(pageContent, NO_OF_LINES_TO_LOG)); assertTrue(String.format("page content '%s' does not contain '%s'", pageContent, contentFragment), pageContent.contains(contentFragment)); } } } catch (IOException e) { throw new IllegalStateException(e); } }
@Test public void call_round_robin_lb_multiple_endpoints() throws Exception { Request request = Request.Get("http://localhost:8082/echo/helloworld"); int calls = 20; for(int i = 0 ; i < calls ; i++) { Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String workerHeader = returnResponse.getFirstHeader("worker").getValue(); assertEquals("worker#" + (i%2) , workerHeader); } }
@Test public void call_post_content() throws Exception { InputStream is = this.getClass().getClassLoader().getResourceAsStream("case1/request_content.json"); String content = StringUtils.copy(is); Request request = Request.Post("http://localhost:8082/test/my_team") .bodyString(content, ContentType.APPLICATION_JSON); Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(content, responseContent); }
@Test public void call_case1_raw() throws Exception { String testCase = "case1"; InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json"); String content = StringUtils.copy(is); Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase) .bodyString(content, ContentType.APPLICATION_JSON); Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(content, responseContent); }
@Test public void call_case1_chunked_request() throws Exception { String testCase = "case1"; InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json"); Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase) .bodyStream(is, ContentType.APPLICATION_JSON); try { Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); // Not a chunked response because body content is to small assertEquals(null, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING)); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } }
@Test public void call_case2_chunked() throws Exception { String testCase = "case2"; InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json"); Request request = Request.Post("http://localhost:8082/test/my_team?case=" + testCase) .bodyStream(is, ContentType.APPLICATION_JSON); try { Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); assertEquals(HttpHeadersValues.TRANSFER_ENCODING_CHUNKED, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING).getValue()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(652051, responseContent.length()); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } }
@Test public void call_case3_raw() throws Exception { String testCase = "case3"; InputStream is = this.getClass().getClassLoader().getResourceAsStream(testCase + "/request_content.json"); Request request = Request.Post("http://localhost:8082/test/my_team?mode=chunk&case=" + testCase) .bodyStream(is, ContentType.APPLICATION_JSON); try { Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); // Set chunk mode in request but returns raw because of the size of the content assertEquals(null, returnResponse.getFirstHeader(HttpHeaders.TRANSFER_ENCODING)); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(70, responseContent.length()); } catch (Exception e) { e.printStackTrace(); assertTrue(false); } }
@Test public void simple_request() throws Exception { stubFor(get(urlEqualTo("/team/my_team")) .willReturn(aResponse() .withStatus(HttpStatus.SC_OK) .withBody("{\"key\": \"value\"}"))); org.apache.http.client.fluent.Request request = org.apache.http.client.fluent.Request.Get("http://localhost:8082/test/my_team"); org.apache.http.client.fluent.Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); assertEquals(CorsHandler.ALLOW_ORIGIN_PUBLIC_WILDCARD, returnResponse.getFirstHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN).getValue()); assertEquals("x-forwarded-host", returnResponse.getFirstHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS).getValue()); // Check that the stub has never been invoked by the gateway verify(1, getRequestedFor(urlEqualTo("/team/my_team"))); }
@Test public void call_availableAndUnavailable_api() throws Exception { // Set the endpoint as down api.getProxy().getEndpoints().iterator().next().setStatus(Endpoint.Status.DOWN); Request request = Request.Get("http://localhost:8082/test/my_team"); Response response = request.execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, returnResponse.getStatusLine().getStatusCode()); // Set the endpoint as up api.getProxy().getEndpoints().iterator().next().setStatus(Endpoint.Status.UP); Request request2 = Request.Get("http://localhost:8082/test/my_team"); Response response2 = request2.execute(); HttpResponse returnResponse2 = response2.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse2.getStatusLine().getStatusCode()); }
@Test public void call_get_query_params_emptyvalue() throws Exception { String query = ""; URI target = new URIBuilder("http://localhost:8082/test/my_team") .addParameter("q", null) .build(); Response response = Request.Get(target).execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(query, responseContent); }
@Test public void call_get_query_accent() throws Exception { String query = "poupée"; URI target = new URIBuilder("http://localhost:8082/test/my_team") .addParameter("q", query) .build(); Response response = Request.Get(target).execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(query, responseContent); }
@Test public void call_get_query_with_special_separator() throws Exception { String query = "from:2016-01-01;to:2016-01-31"; URI target = new URIBuilder("http://localhost:8082/test/my_team") .addParameter("id", "20000047") .addParameter("idType", "1") .addParameter("q", query) .build(); Response response = Request.Get(target).execute(); HttpResponse returnResponse = response.returnResponse(); assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode()); String responseContent = StringUtils.copy(returnResponse.getEntity().getContent()); assertEquals(query, responseContent); }