Example usage for org.springframework.http HttpHeaders TRANSFER_ENCODING

List of usage examples for org.springframework.http HttpHeaders TRANSFER_ENCODING

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders TRANSFER_ENCODING.

Prototype

String TRANSFER_ENCODING

To view the source code for org.springframework.http HttpHeaders TRANSFER_ENCODING.

Click Source Link

Document

The HTTP Transfer-Encoding header field name.

Usage

From source file:io.github.microcks.web.RestController.java

@RequestMapping(value = "/{service}/{version}/**")
public ResponseEntity<?> execute(@PathVariable("service") String serviceName,
        @PathVariable("version") String version, @RequestParam(value = "delay", required = false) Long delay,
        @RequestBody(required = false) String body, HttpServletRequest request) {

    log.info("Servicing mock response for service [{}, {}] on uri {} with verb {}", serviceName, version,
            request.getRequestURI(), request.getMethod());
    log.debug("Request body: " + body);

    long startTime = System.currentTimeMillis();

    // Extract resourcePath for matching with correct operation.
    String requestURI = request.getRequestURI();
    String serviceAndVersion = null;
    String resourcePath = null;/*  www.  jav  a2s .c  om*/

    try {
        // Build the encoded URI fragment to retrieve simple resourcePath.
        serviceAndVersion = "/" + UriUtils.encodeFragment(serviceName, "UTF-8") + "/" + version;
        resourcePath = requestURI.substring(requestURI.indexOf(serviceAndVersion) + serviceAndVersion.length());
    } catch (UnsupportedEncodingException e1) {
        return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    log.info("Found resourcePath: " + resourcePath);

    Service service = serviceRepository.findByNameAndVersion(serviceName, version);
    Operation rOperation = null;
    for (Operation operation : service.getOperations()) {
        // Select operation based onto Http verb (GET, POST, PUT, etc ...)
        if (operation.getMethod().equals(request.getMethod().toUpperCase())) {
            // ... then check is we have a matching resource path.
            if (operation.getResourcePaths().contains(resourcePath)) {
                rOperation = operation;
                break;
            }
        }
    }

    if (rOperation != null) {
        log.debug("Found a valid operation {} with rules: {}", rOperation.getName(),
                rOperation.getDispatcherRules());

        Response response = null;
        String uriPattern = getURIPattern(rOperation.getName());
        String dispatchCriteria = null;

        // Depending on dispatcher, evaluate request with rules.
        if (DispatchStyles.SEQUENCE.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.SCRIPT.equals(rOperation.getDispatcher())) {
            ScriptEngineManager sem = new ScriptEngineManager();
            try {
                // Evaluating request with script coming from operation dispatcher rules.
                ScriptEngine se = sem.getEngineByExtension("groovy");
                SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
                dispatchCriteria = (String) se.eval(rOperation.getDispatcherRules());
            } catch (Exception e) {
                log.error("Error during Script evaluation", e);
            }
        }
        // New cases related to services/operations/messages coming from a postman collection file.
        else if (DispatchStyles.URI_PARAMS.equals(rOperation.getDispatcher())) {
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        } else if (DispatchStyles.URI_PARTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
        } else if (DispatchStyles.URI_ELEMENTS.equals(rOperation.getDispatcher())) {
            dispatchCriteria = DispatchCriteriaHelper.extractFromURIPattern(uriPattern, resourcePath);
            String fullURI = request.getRequestURL() + "?" + request.getQueryString();
            dispatchCriteria += DispatchCriteriaHelper.extractFromURIParams(rOperation.getDispatcherRules(),
                    fullURI);
        }

        log.debug("Dispatch criteria for finding response is {}", dispatchCriteria);
        List<Response> responses = responseRepository.findByOperationIdAndDispatchCriteria(
                IdBuilder.buildOperationId(service, rOperation), dispatchCriteria);
        if (!responses.isEmpty()) {
            response = responses.get(0);
        }

        if (response != null) {
            // Setting delay to default one if not set.
            if (delay == null && rOperation.getDefaultDelay() != null) {
                delay = rOperation.getDefaultDelay();
            }

            if (delay != null && delay > -1) {
                log.debug("Mock delay is turned on, waiting if necessary...");
                long duration = System.currentTimeMillis() - startTime;
                if (duration < delay) {
                    Object semaphore = new Object();
                    synchronized (semaphore) {
                        try {
                            semaphore.wait(delay - duration);
                        } catch (Exception e) {
                            log.debug("Delay semaphore was interrupted");
                        }
                    }
                }
                log.debug("Delay now expired, releasing response !");
            }

            // Publish an invocation event before returning.
            MockInvocationEvent event = new MockInvocationEvent(this, service.getName(), version,
                    response.getName(), new Date(startTime), startTime - System.currentTimeMillis());
            applicationContext.publishEvent(event);
            log.debug("Mock invocation event has been published");

            HttpStatus status = (response.getStatus() != null
                    ? HttpStatus.valueOf(Integer.parseInt(response.getStatus()))
                    : HttpStatus.OK);

            // Deal with specific headers (content-type and redirect directive).
            HttpHeaders responseHeaders = new HttpHeaders();
            if (response.getMediaType() != null) {
                responseHeaders.setContentType(MediaType.valueOf(response.getMediaType() + ";charset=UTF-8"));
            }

            // Adding other generic headers (caching directives and so on...)
            if (response.getHeaders() != null) {
                for (Header header : response.getHeaders()) {
                    if ("Location".equals(header.getName())) {
                        // We should process location in order to make relative URI specified an absolute one from
                        // the client perspective.
                        String location = "http://" + request.getServerName() + ":" + request.getServerPort()
                                + request.getContextPath() + "/rest" + serviceAndVersion
                                + header.getValues().iterator().next();
                        responseHeaders.add(header.getName(), location);
                    } else {
                        if (!HttpHeaders.TRANSFER_ENCODING.equalsIgnoreCase(header.getName())) {
                            responseHeaders.put(header.getName(), new ArrayList<>(header.getValues()));
                        }
                    }
                }
            }
            return new ResponseEntity<Object>(response.getContent(), responseHeaders, status);
        }
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
}

From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilterTests.java

public void contentLengthTest(Long expectedContentLength, SimpleHostRoutingFilter filter,
        MockMultipartHttpServletRequest request) throws IOException {
    byte[] data = "poprqwueproqiwuerpoqweiurpo".getBytes();
    MockMultipartFile file = new MockMultipartFile("test.zip", "test.zip", "application/zip", data);
    String boundary = "q1w2e3r4t5y6u7i8o9";
    request.setContentType("multipart/form-data; boundary=" + boundary);
    request.setContent(createFileContent(data, boundary, "application/zip", "test.zip"));
    request.addFile(file);//from   www .j a v a2s .co  m
    request.setMethod("POST");
    request.setParameter("variant", "php");
    request.setParameter("os", "mac");
    request.setParameter("version", "3.4");
    request.setRequestURI("/app/echo");

    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext.getCurrentContext().setRequest(request);
    RequestContext.getCurrentContext().setResponse(new MockHttpServletResponse());
    URL url = new URL("http://localhost:" + this.port);
    RequestContext.getCurrentContext().set("routeHost", url);
    filter.run();

    String responseString = IOUtils.toString(
            new GZIPInputStream(((CloseableHttpResponse) RequestContext.getCurrentContext().get("zuulResponse"))
                    .getEntity().getContent()));
    assertTrue(!responseString.isEmpty());
    if (expectedContentLength < 0) {
        assertThat(responseString,
                containsString("\"" + HttpHeaders.TRANSFER_ENCODING.toLowerCase() + "\":\"chunked\""));
        assertThat(responseString, not(containsString(HttpHeaders.CONTENT_LENGTH.toLowerCase())));
    } else {
        assertThat(responseString, containsString(
                "\"" + HttpHeaders.CONTENT_LENGTH.toLowerCase() + "\":\"" + expectedContentLength + "\""));
    }
}

From source file:org.springframework.http.codec.EncoderHttpMessageWriter.java

@SuppressWarnings("unchecked")
@Override/*from   ww  w .j a  v a  2  s.  c om*/
public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType elementType,
        @Nullable MediaType mediaType, ReactiveHttpOutputMessage message, Map<String, Object> hints) {

    MediaType contentType = updateContentType(message, mediaType);

    Flux<DataBuffer> body = this.encoder.encode(inputStream, message.bufferFactory(), elementType, contentType,
            hints);

    if (inputStream instanceof Mono) {
        HttpHeaders headers = message.getHeaders();
        if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
            return Mono.from(body).flatMap(dataBuffer -> {
                headers.setContentLength(dataBuffer.readableByteCount());
                return message.writeWith(Mono.just(dataBuffer));
            });
        }
    }

    return (isStreamingMediaType(contentType) ? message.writeAndFlushWith(body.map(Flux::just))
            : message.writeWith(body));
}

From source file:org.springframework.http.converter.AbstractHttpMessageConverter.java

/**
 * Add default headers to the output message.
 * <p>This implementation delegates to {@link #getDefaultContentType(Object)} if a
 * content type was not provided, set if necessary the default character set, calls
 * {@link #getContentLength}, and sets the corresponding headers.
 * @since 4.2/*from w  ww.j a va2 s .co m*/
 */
protected void addDefaultHeaders(HttpHeaders headers, T t, @Nullable MediaType contentType) throws IOException {
    if (headers.getContentType() == null) {
        MediaType contentTypeToUse = contentType;
        if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
            contentTypeToUse = getDefaultContentType(t);
        } else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
            MediaType mediaType = getDefaultContentType(t);
            contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
        }
        if (contentTypeToUse != null) {
            if (contentTypeToUse.getCharset() == null) {
                Charset defaultCharset = getDefaultCharset();
                if (defaultCharset != null) {
                    contentTypeToUse = new MediaType(contentTypeToUse, defaultCharset);
                }
            }
            headers.setContentType(contentTypeToUse);
        }
    }
    if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
        Long contentLength = getContentLength(t, headers.getContentType());
        if (contentLength != null) {
            headers.setContentLength(contentLength);
        }
    }
}