protected ResponseEntity<String> executeRequest(URI url, HttpMethod method, HttpHeaders headers, @Nullable String body) { Request httpRequest = this.httpClient.newRequest(url).method(method); addHttpHeaders(httpRequest, headers); if (body != null) { httpRequest.content(new StringContentProvider(body)); } ContentResponse response; try { response = httpRequest.send(); } catch (Exception ex) { throw new SockJsTransportFailureException("Failed to execute request to " + url, ex); } HttpStatus status = HttpStatus.valueOf(response.getStatus()); HttpHeaders responseHeaders = toHttpHeaders(response.getHeaders()); return (response.getContent() != null ? new ResponseEntity<>(response.getContentAsString(), responseHeaders, status) : new ResponseEntity<>(responseHeaders, status)); }
String responseMsg = response.getContentAsString(); XxlJobLogger.log(responseMsg); return SUCCESS;
String responseMsg = response.getContentAsString(); XxlJobLogger.log(responseMsg); return SUCCESS;
@Override public RpcCallException decodeException(ContentResponse response) throws RpcCallException { try { if (response != null) { JsonObject json = (JsonObject) new JsonParser().parse(response.getContentAsString()); JsonElement error = json.get("error"); if (error != null) { return RpcCallException.fromJson(error.toString()); } } } catch (Exception ex) { logger.warn("Caught exception decoding protobuf response exception", ex); throw new RpcCallException(RpcCallException.Category.InternalServerError, RpcCallExceptionDecoder.exceptionToString(ex)); } return null; }
private boolean verifyRegistrationInConsul() { String registryServer = serviceProps.getRegistryServer(); if (StringUtils.isBlank(registryServer)) { return false; } String url = "http://" + registryServer + "/v1/catalog/service/" + serviceProps.getServiceName(); try { ContentResponse httpResponse = httpClient.newRequest(url). method(HttpMethod.GET).header(HttpHeader.CONTENT_TYPE, "application/json").send(); if (httpResponse.getStatus() != 200) { return false; } JsonArray pods = new JsonParser().parse(httpResponse.getContentAsString()).getAsJsonArray(); Iterator<JsonElement> iter = pods.iterator(); while (iter.hasNext()) { JsonElement pod = iter.next(); String serviceId = pod.getAsJsonObject().get("ServiceID").getAsString(); if (serviceProps.getServiceInstanceId().equals(serviceId)) { return true; } } } catch (Exception ex) { logger.warn("Caught exception verifying registration", ex); } return false; }
@Test public void requestHealthListSingleInstance() { when(response.getContentAsString()).thenReturn(healthInfo); List<ConsulHealthEntry> entries = worker.loadCurrentHealthList(); assertThat(entries.size()).isEqualTo(1); }
@Test public void verifyMainLoop() { LoadBalancer lb = mock(LoadBalancer.class); worker.setLoadbalancer(lb); worker.shutdownSemaphore.release(); worker.sleeper = mock(Sleeper.class); when(response.getContentAsString()).thenReturn(null).thenReturn(healthInfo).thenReturn(healthInfo); worker.run(); verify(lb, times(1)).updateServiceEndpoints(any(LoadBalancerUpdate.class)); } }
@Test public void serviceFlappingAfterStartup() throws Exception { //there was a bug where if a consumed service went down and came back, there //were extra and incorrect updates posted to the lb //1. is available 2. becomes unavail 3. becomes avail again when(response.getContentAsString()).thenReturn(healthInfo).thenReturn(emptyHealthInfo). then((Answer<String>) invocation -> { worker.shutdownSemaphore.release(); return healthInfo; }); LoadBalancer lb = mock(LoadBalancer.class); worker.setLoadbalancer(lb); worker.sleeper = mock(Sleeper.class); worker.run(); ArgumentCaptor<LoadBalancerUpdate> captor = ArgumentCaptor.forClass(LoadBalancerUpdate.class); verify(lb, times(3)).updateServiceEndpoints(captor.capture()); assertThat(captor.getAllValues()).hasSize(3); }
@Test public void serviceAppearsAfterStartup() throws Exception { //there was a bug where if a consumed service wasn't available at startup, //even when it came online later, it wouldn't be tracked. String emptyHealthInfo = "[]"; when(response.getContentAsString()).thenReturn(emptyHealthInfo). thenReturn(healthInfo); LoadBalancer lb = mock(LoadBalancer.class); worker.setLoadbalancer(lb); worker.shutdownSemaphore.release(); worker.sleeper = mock(Sleeper.class); worker.run(); ArgumentCaptor<LoadBalancerUpdate> captor = ArgumentCaptor.forClass(LoadBalancerUpdate.class); verify(lb, times(1)).updateServiceEndpoints(captor.capture()); assertThat(captor.getAllValues()).hasSize(1); LoadBalancerUpdate secondUpdate = captor.getAllValues().get(0); assertThat(secondUpdate.getNewServices()).isNotEmpty(); }
if (httpResponse.getStatus() == 200) { try { healths = new ConsulHealthEntryFactory().parse(httpResponse.getContentAsString()); } catch (IOException ex) { logger.error(logMarker,
public String callSynchronous(JsonArray params, OrangeContext orangeContext) throws RpcCallException { HttpClientWrapper clientWrapper = loadBalancer.getHttpClientWrapper(); HttpRequestWrapper balancedPost = clientWrapper.createHttpPost(this); //set custom headers if (orangeContext != null) { orangeContext.getProperties().forEach(balancedPost::setHeader); } balancedPost.setHeader("Content-type", TYPE_JSON); //TODO: fix: Temporary workaround below until go services are more http compliant balancedPost.setHeader("Connection", "close"); JsonRpcRequest jsonRequest = new JsonRpcRequest(null, methodName, params); String json = jsonRequest.toString(); balancedPost.setContentProvider(new StringContentProvider(json)); logger.debug("Sending request of size {}", json.length()); ContentResponse rpcResponse = clientWrapper.execute(balancedPost, new JsonRpcCallExceptionDecoder(), orangeContext); String rawResponse = rpcResponse.getContentAsString(); logger.debug("Json response from the service: {}", rawResponse); return JsonRpcResponse.fromString(rawResponse).getResult().getAsString(); }
@Before public void setup() throws Exception { HttpClient httpClient = mock(HttpClient.class); response = mock(ContentResponse.class); when(response.getStatus()).thenReturn(200); when(response.getContentAsString()).thenReturn(healthInfo); HttpFields headers = new HttpFields(); headers.add(CONSUL_INDEX, "42"); when(response.getHeaders()).thenReturn(headers); Request request = mock(Request.class); when(httpClient.newRequest(anyString())).thenReturn(request); when(request.send()).thenReturn(response); props = new ServiceProperties(); props.addProperty(ServiceProperties.REGISTRY_SERVER_KEY, "localhost:1234"); worker = new RegistrationMonitorWorker(httpClient, props, mock(ServiceDependencyHealthCheck.class)); worker.setServiceName("foobar"); }
protected String sendRequest(String path, String data, HttpMethod method) throws Exception { String url = getServiceUrl(path); Request request = httpClient.newRequest(url).method(method). header(HttpHeader.CONTENT_TYPE, "application/json"); if (data != null) { request.content(new StringContentProvider(data)); } ContentResponse response = request.send(); return response.getContentAsString(); }
public void setResponseException(RpcCallException responseException) { this.responseException = responseException; if (featureFlag.equals("true")) { when(httpResponse.getStatus()).thenReturn(responseException.getCategory().getHttpStatus()); } String response = "{\"error\":" + responseException.toJson() + ",\"result\":{}}"; when(httpResponse.getContentAsString()).thenReturn(response); RpcEnvelope.Response pbResponse = RpcEnvelope.Response.newBuilder(). setError(responseException.toJson().toString()).build(); byte[] responseArray = pbResponse.toByteArray(); byte[] headerLength = Ints.toByteArray(responseArray.length); byte[] bodyLength = Ints.toByteArray(0); byte[] overallPayload = concatAll(headerLength, responseArray, bodyLength); when(httpResponse.getContent()).thenReturn(overallPayload); }
private OAuthTokenResponse httpResponseToOAuthAccessTokenResponse(ContentResponse response) { try { return objectMapper.readValue(response.getContentAsString(), OAuthTokenResponse.class); } catch (IOException e) { throw new OAuthTokenRequestException("An exception occurred while reading token response", e); } }
private void validateHttpResponse(ContentResponse response) { if (response.getStatus() != HttpStatus.OK_200) { throw new OAuthTokenRequestException(String.format("%d %s response when performing token request", response.getStatus(), response.getContentAsString())); } }
public ResponseAssertion hasReturnedText(String... textPossibilities) { Assertions.assertThat(response.getContentAsString()).matches(s -> { for (String possible : textPossibilities) { if (s.equals(possible)) { return true; } } return false; }, "Content: " + response.getContentAsString() + " doesn't match any of " + textPossibilities); return this; }
private void validateHttpResponse(ContentResponse response) { if (response.getStatus() != HttpStatus.OK_200) { throw new OAuthTokenRequestException(String.format("%d %s response when performing token request", response.getStatus(), response.getContentAsString())); } }
private JsonNode query(String q, HttpMethod method, int offset, int maxResults, String cacheName) throws Exception { ContentResponse response = executeQueryRequest(cacheName, method, q, offset, maxResults); String contentAsString = response.getContentAsString(); assertEquals(response.getStatus(), HttpStatus.OK_200); return MAPPER.readTree(contentAsString); }
@Test(dataProvider = "HttpMethodProvider") public void testIncompleteSearch(HttpMethod method) throws Exception { String searchUrl = getUrl(pickServer()); ContentResponse response = client.newRequest(searchUrl).method(method).send(); ResponseAssertion.assertThat(response).isBadRequest(); String contentAsString = response.getContentAsString(); JsonNode jsonNode = MAPPER.readTree(contentAsString); assertTrue(jsonNode.get("error").path("message").asText().contains("Invalid search request")); }