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)); }
@Override public ClientResponse apply(final ClientRequest jerseyRequest) throws ProcessingException { final Request jettyRequest = translateRequest(jerseyRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(jerseyRequest.getHeaders(), jettyRequest); final ContentProvider entity = getBytesProvider(jerseyRequest); if (entity != null) { jettyRequest.content(entity); } try { final ContentResponse jettyResponse = jettyRequest.send(); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, jerseyRequest.getHeaders(), JettyConnector.this.getClass().getName()); final javax.ws.rs.core.Response.StatusType status = jettyResponse.getReason() == null ? Statuses.from(jettyResponse.getStatus()) : Statuses.from(jettyResponse.getStatus(), jettyResponse.getReason()); final ClientResponse jerseyResponse = new ClientResponse(status, jerseyRequest); processResponseHeaders(jettyResponse.getHeaders(), jerseyResponse); try { jerseyResponse.setEntityStream(new HttpClientResponseInputStream(jettyResponse)); } catch (final IOException e) { LOGGER.log(Level.SEVERE, null, e); } return jerseyResponse; } catch (final Exception e) { throw new ProcessingException(e); } }
public void updateHealthStatus(HealthCheck.Status status) throws Exception { logger.trace("Updating health of {}", serviceProps.getServiceName()); ContentResponse httpResponse = httpClient.newRequest(getHealthCheckUri(status)).method(HttpMethod.PUT).send(); if (httpResponse.getStatus() != 200) { logger.warn("Received {} trying to update health", httpResponse.getStatus()); } }
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 problemGettingHealthInfo() { when(response.getStatus()).thenReturn(404); List<ConsulHealthEntry> entries = worker.loadCurrentHealthList(); assertThat(entries).isEmpty(); when(response.getStatus()).thenReturn(0); entries = worker.loadCurrentHealthList(); assertThat(entries).isEmpty(); }
private boolean sendRegistration(JsonObject request) { try { ContentResponse httpResponse = httpClient.newRequest(getRegistrationUri()). content(new StringContentProvider(request.toString())). method(HttpMethod.PUT).header(HttpHeader.CONTENT_TYPE, "application/json").send(); if (httpResponse.getStatus() == 200) { return true; } } catch (Exception ex) { logger.warn("Caught exception sending registration {}", request.toString(), ex); } return false; }
@Override public Request newRequest(String uri) { Request retval = mock(Request.class); try { if (requestsTimeout || (isFirstRequestTimeout && requests.isEmpty())) { when(retval.send()).thenThrow(new TimeoutException()); } else { when(retval.send()).thenReturn(httpResponse); } if (requestsFail && featureFlag.equals("true")) { when(httpResponse.getStatus()).thenReturn(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else if (responseException != null) { when(httpResponse.getStatus()).thenReturn(responseException.getCategory().getHttpStatus()); } else { when(httpResponse.getStatus()).thenReturn(HttpServletResponse.SC_OK); } } catch (Exception e) { e.printStackTrace(); } when(retval.method(anyString())).thenReturn(retval); when(retval.content(any(ContentProvider.class))).thenReturn(retval); when(retval.timeout(anyLong(), any(TimeUnit.class))).thenReturn(retval); requests.add(uri); return retval; }
if (httpResponse.getStatus() == 200) { try { healths = new ConsulHealthEntryFactory().parse(httpResponse.getContentAsString());
@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"); }
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 void initialize() { httpResponse = mock(ContentResponse.class); when(httpResponse.getHeaders()).thenReturn(new HttpFields()); when(httpResponse.getStatus()).thenReturn(200); try { RpcEnvelope.Response.Builder responseBuilder = RpcEnvelope.Response.newBuilder(); responseBuilder.setServiceMethod("Test.test"); if (requestsFail) { RpcCallException callException = new RpcCallException( RpcCallException.Category.InternalServerError, "requests fail!"); responseBuilder.setError(callException.toJson().toString()); } RpcEnvelope.Response rpcResponse = responseBuilder.build(); byte[] responseHeader = rpcResponse.toByteArray(); byte[] payload = FrameworkTest.Foobar.newBuilder().build().toByteArray(); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(Ints.toByteArray(responseHeader.length)); out.write(responseHeader); out.write(Ints.toByteArray(payload.length)); out.write(payload); out.flush(); when(httpResponse.getContent()).thenReturn(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); } }
TimeUnit.MILLISECONDS).send(); logger.debug(logMarker, "Http send completed"); lastStatusCode = retval.getStatus(); } catch (TimeoutException timeout) { lastStatusCode = RpcCallException.Category.RequestTimedOut.getHttpStatus();
public ResponseAssertion isServiceUnavailable() { Assertions.assertThat(response.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE_503); return this; } }
public ResponseAssertion isUnauthorized() { Assertions.assertThat(response.getStatus()).isEqualTo(HttpStatus.UNAUTHORIZED_401); Assertions.assertThat(response.getHeaders().get(HttpHeader.WWW_AUTHENTICATE)).isNotNull().isNotEmpty(); return this; }
protected void registerProtobuf(String protoFileName, String protoFileContents) throws Exception { String protobufMetadataUrl = getProtobufMetadataUrl(protoFileName); ContentResponse response = client .newRequest(protobufMetadataUrl) .content(new StringContentProvider(protoFileContents)) .method(POST) .send(); assertEquals(response.getStatus(), HttpStatus.OK_200); String errorKey = protoFileName.concat(".error"); ContentResponse errorCheck = client.newRequest(getProtobufMetadataUrl(errorKey)).method(GET).send(); assertEquals(errorCheck.getStatus(), HttpStatus.NOT_FOUND_404); }
protected void write(int id, String contents, HttpMethod method, MediaType contentType) throws Exception { ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%d", pickServer().getPort(), CACHE_NAME, id)) .method(method) .content(new StringContentProvider(contents)) .header(HttpHeader.CONTENT_TYPE, contentType.toString()) .send(); assertEquals(response.getStatus(), HttpStatus.OK_200); }