Java Code Examples for org.springframework.http.client.ClientHttpResponse#close()

The following examples show how to use org.springframework.http.client.ClientHttpResponse#close() . 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: ChaosPluginTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldInjectErrorResponse() throws IOException {
    when(errorResponseProbability.test()).thenReturn(true);

    driver.addExpectation(onRequestTo("/foo"), giveEmptyResponse());

    final ClientHttpResponse response = unit.get("/foo")
            .call(pass())
            .join();

    // users are required to close Closeable resources by contract
    response.close();

    assertThat(response.getStatusCode(), is(oneOf(INTERNAL_SERVER_ERROR, SERVICE_UNAVAILABLE)));
    assertThat(response.getRawStatusCode(), is(oneOf(500, 503)));
    assertThat(response.getStatusText(), is(oneOf("Internal Server Error", "Service Unavailable")));
    assertThat(response.getHeaders(), is(anEmptyMap())); // TODO can we do better?
}
 
Example 2
Source File: ErrorResponseInjection.java    From riptide with MIT License 6 votes vote down vote up
private ClientHttpResponse injectIfNecessary(
        final ClientHttpResponse response) throws IOException {

    final HttpStatus statusCode = response.getStatusCode();

    if (isError(statusCode)) {
        // only inject error response if not failed already
        return response;
    }

    try {
        final HttpStatus status = choose();
        log.debug("Injecting '{}' error response", status);
        return new ErrorClientHttpResponse(status);
    } finally {
        response.close();
    }
}
 
Example 3
Source File: AsyncRestTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected final T adapt(ClientHttpResponse response) throws ExecutionException {
	try {
		if (!getErrorHandler().hasError(response)) {
			logResponseStatus(this.method, this.url, response);
		}
		else {
			handleResponseError(this.method, this.url, response);
		}
		return convertResponse(response);
	}
	catch (Throwable ex) {
		throw new ExecutionException(ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 4
Source File: AsyncRestTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
protected final T adapt(ClientHttpResponse response) throws ExecutionException {
	try {
		if (!getErrorHandler().hasError(response)) {
			logResponseStatus(this.method, this.url, response);
		}
		else {
			handleResponseError(this.method, this.url, response);
		}
		return convertResponse(response);
	}
	catch (Throwable ex) {
		throw new ExecutionException(ex);
	}
	finally {
		response.close();
	}
}
 
Example 5
Source File: AsyncRestTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected final T adapt(ClientHttpResponse response) throws ExecutionException {
	try {
		if (!getErrorHandler().hasError(response)) {
			logResponseStatus(this.method, this.url, response);
		}
		else {
			handleResponseError(this.method, this.url, response);
		}
		return convertResponse(response);
	}
	catch (Throwable ex) {
		throw new ExecutionException(ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 6
Source File: RestTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
		@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "URI is required");
	Assert.notNull(method, "HttpMethod is required");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		return (responseExtractor != null ? responseExtractor.extractData(response) : null);
	}
	catch (IOException ex) {
		String resource = url.toString();
		String query = url.getRawQuery();
		resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
		throw new ResourceAccessException("I/O error on " + method.name() +
				" request for \"" + resource + "\": " + ex.getMessage(), ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 7
Source File: DefaultMessageReader.java    From riptide with MIT License 5 votes vote down vote up
private <I> void closeIfNecessary(final I body, final ClientHttpResponse response) {
    if (body instanceof AutoCloseable) {
        return;
    }

    response.close();
}
 
Example 8
Source File: RestTemplate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "'url' must not be null");
	Assert.notNull(method, "'method' must not be null");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		if (responseExtractor != null) {
			return responseExtractor.extractData(response);
		}
		else {
			return null;
		}
	}
	catch (IOException ex) {
		throw new ResourceAccessException("I/O error on " + method.name() +
				" request for \"" + url + "\": " + ex.getMessage(), ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 9
Source File: RestTemplateXhrTransport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	if (!HttpStatus.OK.equals(response.getStatusCode())) {
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 10
Source File: JvmServiceImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public JvmHttpRequestResult pingAndUpdateJvmState(final Jvm jvm) {
    ClientHttpResponse response = null;
    JvmState jvmState = jvm.getState();
    String responseDetails = StringUtils.EMPTY;
    try {
        response = clientFactoryHelper.requestGet(jvm.getStatusUri());
        LOGGER.info(">>> Response = {} from jvm {}", response.getStatusCode(), jvm.getId().getId());
        jvmState = JvmState.JVM_STARTED;
        if (response.getStatusCode() == HttpStatus.OK) {
            jvmStateService.updateState(jvm, jvmState, StringUtils.EMPTY);
        } else {
            // As long as we get a response even if it's not a 200 it means that the JVM is alive
            jvmStateService.updateState(jvm, jvmState, StringUtils.EMPTY);
            responseDetails = MessageFormat.format("Request {0} sent expecting a response code of {1} but got {2} instead",
                    jvm.getStatusUri(), HttpStatus.OK.value(), response.getRawStatusCode());

        }
    } catch (final IOException ioe) {
        LOGGER.info(ioe.getMessage(), ioe);
        jvmStateService.updateState(jvm, JvmState.JVM_STOPPED, StringUtils.EMPTY);
        responseDetails = MessageFormat.format("Request {0} sent and got: {1}", jvm.getStatusUri(), ioe.getMessage());
        jvmState = JvmState.JVM_STOPPED;
    } catch (RuntimeException rte) {
        LOGGER.error(rte.getMessage(), rte);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return new JvmHttpRequestResult(jvmState, responseDetails);
}
 
Example 11
Source File: JvmStateResolverWorker.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Async("jvmTaskExecutor")
public Future<CurrentState<Jvm, JvmState>> pingAndUpdateJvmState(final Jvm jvm, final JvmStateService jvmStateService) {
    LOGGER.debug("The reverse heartbeat has kicked in! This means that we're not receiving any states from Jvm {}@{}.",
            jvm.getJvmName(), jvm.getHostName());
    LOGGER.debug("+++ pingAndUpdateJvmState");
    ClientHttpResponse response = null;
    CurrentState<Jvm, JvmState> currentState = null;

    // if the jvm was just created do not check its state
    if (jvm.getState().equals(JvmState.JVM_NEW)){
        return new AsyncResult<>(new CurrentState<>(jvm.getId(), jvm.getState(), DateTime.now(), StateType.JVM));
    }

    try {
        response = clientFactoryHelper.requestGet(jvm.getStatusUri());
        LOGGER.debug("Response = {} from JVM {}", response.getStatusCode(), jvm.getJvmName());
        jvmStateService.updateNotInMemOrStaleState(jvm, JvmState.JVM_STARTED, StringUtils.EMPTY);
        currentState = new CurrentState<>(jvm.getId(), JvmState.JVM_STARTED, DateTime.now(), StateType.JVM);
    } catch (final IOException ioe) {
        LOGGER.warn("{} {} {}", jvm.getJvmName(), ioe.getMessage(), "Setting JVM state to STOPPED.", ioe);
        jvmStateService.updateNotInMemOrStaleState(jvm, JvmState.JVM_STOPPED, StringUtils.EMPTY);
        currentState = new CurrentState<>(jvm.getId(), JvmState.JVM_STOPPED, DateTime.now(), StateType.JVM);
    } catch (final RuntimeException rte) {
        // This method is executed asynchronously and we do not want to interrupt the thread's lifecycle so we
        // just catch and log runtime exceptions instead of rethrowing it
        LOGGER.error(rte.getMessage(), rte);
    } finally {
        if (response != null) {
            response.close();
            LOGGER.debug("response closed");
        }
        LOGGER.debug("--- pingAndUpdateJvmState");
    }
    return new AsyncResult<>(currentState);
}
 
Example 12
Source File: RestTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "'url' must not be null");
	Assert.notNull(method, "'method' must not be null");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		if (responseExtractor != null) {
			return responseExtractor.extractData(response);
		}
		else {
			return null;
		}
	}
	catch (IOException ex) {
		String resource = url.toString();
		String query = url.getRawQuery();
		resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
		throw new ResourceAccessException("I/O error on " + method.name() +
				" request for \"" + resource + "\": " + ex.getMessage(), ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 13
Source File: RestTemplate.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Execute the given method on the provided URI.
 * <p>The {@link ClientHttpRequest} is processed using the {@link RequestCallback};
 * the response with the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
@Nullable
protected <T> T doExecute(URI url, @Nullable HttpMethod method, @Nullable RequestCallback requestCallback,
		@Nullable ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "URI is required");
	Assert.notNull(method, "HttpMethod is required");
	ClientHttpResponse response = null;
	try {
		ClientHttpRequest request = createRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		response = request.execute();
		handleResponse(url, method, response);
		return (responseExtractor != null ? responseExtractor.extractData(response) : null);
	}
	catch (IOException ex) {
		String resource = url.toString();
		String query = url.getRawQuery();
		resource = (query != null ? resource.substring(0, resource.indexOf('?')) : resource);
		throw new ResourceAccessException("I/O error on " + method.name() +
				" request for \"" + resource + "\": " + ex.getMessage(), ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
Example 14
Source File: WebServerStateSetterWorker.java    From jwala with Apache License 2.0 4 votes vote down vote up
/**
 * Ping the web server via http get.
 *
 * @param webServer the web server to ping.
 */
@Async("webServerTaskExecutor")
public void pingWebServer(final WebServer webServer) {

    if (!webServerCanBePinged(webServer)) {
        return;
    }

    synchronized (webServersToPing) {
        if (webServersToPing.contains(webServer.getId())) {
            LOGGER.debug("List of web servers currently being pinged: {}", webServersToPing);
            LOGGER.debug("Cannot ping web server {} since it is currently being pinged", webServer.getName(),
                         webServer);
            return;
        }
        webServersToPing.add(webServer.getId());
    }

    LOGGER.debug("Requesting {} for web server {}", webServer.getStatusUri(), webServer.getName());
    ClientHttpResponse response = null;
    try {
        final ClientHttpRequest request;
        request = httpRequestFactory.createRequest(webServer.getStatusUri(), HttpMethod.GET);
        response = request.execute();
        LOGGER.debug("Web server {} status code = {}", webServer.getName(), response.getStatusCode());

        if (HttpStatus.OK.equals(response.getStatusCode())) {
            setState(webServer, WebServerReachableState.WS_REACHABLE, StringUtils.EMPTY);
        } else {
            setState(webServer, WebServerReachableState.WS_UNREACHABLE,
                    MessageFormat.format(RESPONSE_NOT_OK_MSG, webServer.getStatusUri(), response.getStatusCode()));
        }
    } catch (final IOException e) {
        if (!WebServerReachableState.WS_UNREACHABLE.equals(webServer.getState())) {
            LOGGER.warn("Failed to ping {}!", webServer.getName(), e);
            setState(webServer, WebServerReachableState.WS_UNREACHABLE, StringUtils.EMPTY);
        }
    } finally {
        if (response != null) {
            response.close();
        }
        webServersToPing.remove(webServer.getId());
    }

}
 
Example 15
Source File: RestTemplateXhrTransport.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 16
Source File: HttpResponse.java    From charon-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
HttpResponse(ClientHttpResponse response) throws IOException {
    status = response.getStatusCode();
    headers = response.getHeaders();
    body = toByteArray(response.getBody());
    response.close();
}
 
Example 17
Source File: JwtSsoResponseErrorHandler.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        errorHandler.handleError(response);
    } else {
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {
            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
        };

        List<String> authenticateHeaders = bufferedResponse.getHeaders()
                .get(JwtSsoClientContext.HEADER_WWW_AUTHENTICATE);
        if (authenticateHeaders != null) {
            for (String authenticateHeader : authenticateHeaders) {
                if (authenticateHeader.startsWith(JwtSsoClientContext.PREFIX_BEARER_TOKEN)) {
                    throw new JwtSsoAccessTokenRequiredException("access token required.");
                }
            }
        }
        errorHandler.handleError(bufferedResponse);
    }

}
 
Example 18
Source File: HttpTestRunner.java    From microcks with Apache License 2.0 4 votes vote down vote up
@Override
public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult,
                                List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException{
   if (log. isDebugEnabled()){
      log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)");
   }

   if (requests.isEmpty()) {
      return null;
   }

   // Initialize result container.
   List<TestReturn> result = new ArrayList<TestReturn>();

   for (Request request : requests){
      // Reset status code, message and request each time.
      int code = TestReturn.SUCCESS_CODE;
      String message = null;
      String customizedEndpointUrl = endpointUrl;
      if (service.getType().equals(ServiceType.REST)){
         String operationName = operation.getName();
         // Name may start with verb, remove it if present.
         if (operationName.indexOf(' ') > 0 && operationName.indexOf(' ') < operationName.length()) {
            operationName = operationName.split(" ")[1];
         }

         customizedEndpointUrl += URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters());
         log.debug("Using customized endpoint url: " + customizedEndpointUrl);
      }
      ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(new URI(customizedEndpointUrl), method);

      // Set headers to request if any. Start with those coming from request itself.
      // Add or override existing headers with test specific ones for operation and globals.
      Set<Header> headers = new HashSet<>();
      if (request.getHeaders() != null) {
         headers.addAll(request.getHeaders());
      }
      if (testResult.getOperationsHeaders() != null) {
         if (testResult.getOperationsHeaders().getGlobals() != null) {
            headers.addAll(testResult.getOperationsHeaders().getGlobals());
         }
         if (testResult.getOperationsHeaders().get(operation.getName()) != null) {
            headers.addAll(testResult.getOperationsHeaders().get(operation.getName()));
         }
      }
      if (headers.size() > 0){
         for (Header header : headers){
            log.debug("Adding header " + header.getName() + " to request");
            httpRequest.getHeaders().add(header.getName(), buildValue(header.getValues()));
         }
         // Update request headers for traceability of possibly added ones.
         request.setHeaders(headers);
      }
      // If there's input content, add it to request.
      if (request.getContent() != null) {
         httpRequest.getBody().write(request.getContent().getBytes());
      }

      // Actually execute request.
      long startTime = System.currentTimeMillis();
      ClientHttpResponse httpResponse = null;
      try{
         httpResponse = httpRequest.execute();
      } catch (IOException ioe){
         log.error("IOException while executing request " + request.getName() + " on " + endpointUrl, ioe);
         code = TestReturn.FAILURE_CODE;
         message = ioe.getMessage();
      }
      long duration = System.currentTimeMillis() - startTime;

      // Extract and store response body so that stream may not be consumed more than o1 time ;-)
      String responseContent = null;
      if (httpResponse != null){
         StringWriter writer = new StringWriter();
         IOUtils.copy(httpResponse.getBody(), writer);
         responseContent = writer.toString();
      }

      // If still in success, check if http code is out of correct ranges (20x and 30x).
      if (code == TestReturn.SUCCESS_CODE){
         code = extractTestReturnCode(service, operation, request, httpResponse, responseContent);
         message = extractTestReturnMessage(service, operation, request, httpResponse);
      }

      // Create a Response object for returning.
      Response response = new Response();
      if (httpResponse != null){
         response.setContent(responseContent);
         response.setStatus(String.valueOf(httpResponse.getRawStatusCode()));
         response.setMediaType(httpResponse.getHeaders().getContentType().toString());
         headers = buildHeaders(httpResponse);
         if (headers != null){
            response.setHeaders(headers);
         }
         httpResponse.close();
      }

      result.add(new TestReturn(code, duration, message, request, response));
   }
   return result;
}
 
Example 19
Source File: RestTemplateXhrTransport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object extractData(ClientHttpResponse response) throws IOException {
	HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
	if (httpStatus == null) {
		throw new UnknownHttpStatusCodeException(
				response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
	}
	if (httpStatus != HttpStatus.OK) {
		throw new HttpServerErrorException(
				httpStatus, response.getStatusText(), response.getHeaders(), null, null);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("XHR receive headers: " + response.getHeaders());
	}
	InputStream is = response.getBody();
	ByteArrayOutputStream os = new ByteArrayOutputStream();

	while (true) {
		if (this.sockJsSession.isDisconnected()) {
			if (logger.isDebugEnabled()) {
				logger.debug("SockJS sockJsSession closed, closing response.");
			}
			response.close();
			break;
		}
		int b = is.read();
		if (b == -1) {
			if (os.size() > 0) {
				handleFrame(os);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("XHR receive completed");
			}
			break;
		}
		if (b == '\n') {
			handleFrame(os);
		}
		else {
			os.write(b);
		}
	}
	return null;
}
 
Example 20
Source File: PostmanTestStepsRunner.java    From microcks with Apache License 2.0 4 votes vote down vote up
@Override
public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult,
                                List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException {
   if (log. isDebugEnabled()){
      log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)");
   }

   if (endpointUrl.endsWith("/")) {
      endpointUrl = endpointUrl.substring(0, endpointUrl.length() - 1);
   }

   // Microcks-postman-runner interface object building.
   JsonNode jsonArg = mapper.createObjectNode();
   ((ObjectNode) jsonArg).put("operation", operation.getName());
   ((ObjectNode) jsonArg).put("callbackUrl", testsCallbackUrl + "/api/tests/" + testResult.getId() + "/testCaseResult");

   // First we have to retrieved and add the test script for this operation from within Postman collection.
   JsonNode testScript = extractOperationTestScript(operation);
   if (testScript != null) {
      log.debug("Found a testScript for this operation !");
      ((ObjectNode) jsonArg).set("testScript", testScript);
   }

   // Then we have to add the corresponding 'requests' objects.
   ArrayNode jsonRequests = mapper.createArrayNode();
   for (Request request : requests) {
      JsonNode jsonRequest = mapper.createObjectNode();

      String operationName = operation.getName().substring(operation.getName().indexOf(" ") + 1);
      String customizedEndpointUrl = endpointUrl + URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters());
      log.debug("Using customized endpoint url: " + customizedEndpointUrl);

      ((ObjectNode) jsonRequest).put("endpointUrl", customizedEndpointUrl);
      ((ObjectNode) jsonRequest).put("method", operation.getMethod());
      ((ObjectNode) jsonRequest).put("name", request.getName());

      if (request.getContent() != null && request.getContent().length() > 0) {
         ((ObjectNode) jsonRequest).put("body", request.getContent());
      }
      if (request.getQueryParameters() != null && request.getQueryParameters().size() > 0) {
         ArrayNode jsonParams = buildQueryParams(request.getQueryParameters());
         ((ObjectNode) jsonRequest).set("queryParams", jsonParams);
      }
      // Set headers to request if any. Start with those coming from request itself.
      // Add or override existing headers with test specific ones for operation and globals.
      Set<Header> headers = new HashSet<>();

      if (request.getHeaders() != null) {
         headers.addAll(request.getHeaders());
      }
      if (testResult.getOperationsHeaders() != null) {
         if (testResult.getOperationsHeaders().getGlobals() != null) {
            headers.addAll(testResult.getOperationsHeaders().getGlobals());
         }
         if (testResult.getOperationsHeaders().get(operation.getName()) != null) {
            headers.addAll(testResult.getOperationsHeaders().get(operation.getName()));
         }
      }
      if (headers != null && headers.size() > 0) {
         ArrayNode jsonHeaders = buildHeaders(headers);
         ((ObjectNode) jsonRequest).set("headers", jsonHeaders);
      }

      jsonRequests.add(jsonRequest);
   }
   ((ObjectNode) jsonArg).set("requests", jsonRequests);

   URI postmanRunnerURI = new URI(postmanRunnerUrl + "/tests/" + testResult.getId());
   ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(postmanRunnerURI, HttpMethod.POST);
   httpRequest.getBody().write(mapper.writeValueAsBytes(jsonArg));
   httpRequest.getHeaders().add("Content-Type", "application/json");

   // Actually execute request.
   ClientHttpResponse httpResponse = null;
   try{
      httpResponse = httpRequest.execute();
   } catch (IOException ioe){
      log.error("IOException while executing request ", ioe);
   } finally {
      if (httpResponse != null) {
         httpResponse.close();
      }
   }

   return new ArrayList<TestReturn>();
}