Example usage for org.springframework.http HttpInputMessage getHeaders

List of usage examples for org.springframework.http HttpInputMessage getHeaders

Introduction

In this page you can find the example usage for org.springframework.http HttpInputMessage getHeaders.

Prototype

HttpHeaders getHeaders();

Source Link

Document

Return the headers of this message.

Usage

From source file:com.sti.rest.error.RestExceptionHandler.java

@SuppressWarnings({ "unchecked", "resource" })
private ModelAndView handleResponseBody(Object body, ServletWebRequest webRequest)
        throws ServletException, IOException {

    HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest());

    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }// w  w w  .ja  v a 2 s  .c  o  m

    MediaType.sortByQualityValue(acceptedMediaTypes);

    HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse());

    Class<?> bodyType = body.getClass();

    List<HttpMessageConverter<?>> converters = this.allMessageConverters;

    if (converters != null) {
        for (MediaType acceptedMediaType : acceptedMediaTypes) {
            for (@SuppressWarnings("rawtypes")
            HttpMessageConverter messageConverter : converters) {
                if (messageConverter.canWrite(bodyType, acceptedMediaType)) {
                    messageConverter.write(body, acceptedMediaType, outputMessage);
                    //return empty model and view to short circuit the iteration and to let
                    //Spring know that we've rendered the view ourselves:
                    return new ModelAndView();
                }
            }
        }
    }

    if (logger.isWarnEnabled()) {
        logger.warn("Could not find HttpMessageConverter that supports return type [" + bodyType + "] and "
                + acceptedMediaTypes);
    }

    return null;
}

From source file:org.molgenis.util.GsonHttpMessageConverter.java

@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
    Reader json = new InputStreamReader(inputMessage.getBody(), getCharset(inputMessage.getHeaders()));
    try {/*  w  w  w. j av  a2 s  .  c  o  m*/
        Type typeOfT = getType();
        if (LOG.isTraceEnabled()) {
            String jsonStr = IOUtils.toString(json);
            LOG.trace("Json request:\n" + jsonStr);

            if (typeOfT != null) {
                return this.gson.fromJson(jsonStr, typeOfT);
            }

            return this.gson.fromJson(jsonStr, clazz);
        } else {
            if (typeOfT != null) {
                return this.gson.fromJson(json, typeOfT);
            }

            return this.gson.fromJson(json, clazz);
        }
    } catch (JsonSyntaxException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } catch (JsonIOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } catch (JsonParseException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(json);
    }
}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Return the {@link HttpTunnelPayload} for the given message or {@code null} if there
 * is no payload.//from w  w w. j av  a2s .c o m
 * @param message the HTTP message
 * @return the payload or {@code null}
 * @throws IOException in case of I/O errors
 */
public static HttpTunnelPayload get(HttpInputMessage message) throws IOException {
    long length = message.getHeaders().getContentLength();
    if (length <= 0) {
        return null;
    }
    String seqHeader = message.getHeaders().getFirst(SEQ_HEADER);
    Assert.state(StringUtils.hasLength(seqHeader), "Missing sequence header");
    ReadableByteChannel body = Channels.newChannel(message.getBody());
    ByteBuffer payload = ByteBuffer.allocate((int) length);
    while (payload.hasRemaining()) {
        body.read(payload);
    }
    body.close();
    payload.flip();
    return new HttpTunnelPayload(Long.valueOf(seqHeader), payload);
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

private HttpEntity resolveHttpEntityRequest(MethodParameter methodParam, NativeWebRequest webRequest)
        throws Exception {

    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    Class<?> paramType = getHttpEntityType(methodParam);
    Object body = readWithMessageConverters(methodParam, inputMessage, paramType);
    return new HttpEntity<Object>(body, inputMessage.getHeaders());
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage,
        Class paramType) throws Exception {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    if (contentType == null) {
        StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
        String paramName = methodParam.getParameterName();
        if (paramName != null) {
            builder.append(' ');
            builder.append(paramName);//from  w w  w. j  a  v a2 s.  c o  m
        }
        throw new HttpMediaTypeNotSupportedException(
                "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
    }

    List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
    if (this.messageConverters != null) {
        for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
            allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
            if (messageConverter.canRead(paramType, contentType)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using ["
                            + messageConverter + "]");
                }
                return messageConverter.read(paramType, inputMessage);
            }
        }
    }
    throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
}

From source file:org.springframework.flex.security3.FlexAuthenticationEntryPoint.java

/**
 * If the incoming message is an {@link ActionMessage}, indicating a standard Flex Remoting or Messaging 
 * request, invokes Spring BlazeDS's {@link ExceptionTranslator}s with the {@link AuthenticationException} and 
 * sends the resulting {@link MessageException} as an AMF response to the client.
 * //w  ww  . jav  a2 s .  c  o  m
 * <p>If the request is unabled to be deserialized to AMF, if the resulting deserialized object is not an 
 * <code>ActionMessage</code>, or if no appropriate <code>ExceptionTranslator</code> is found, will simply 
 * delegate to the parent class to return a 403 response.
 */
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    if (CollectionUtils.isEmpty(this.exceptionTranslators)) {
        exceptionTranslators = Collections.singleton(DEFAULT_TRANSLATOR);
    }

    HttpInputMessage inputMessage = new ServletServerHttpRequest(request);
    HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);

    if (!converter.canRead(Object.class, inputMessage.getHeaders().getContentType())) {
        super.commence(request, response, authException);
        return;
    }

    ActionMessage deserializedInput = null;
    try {
        deserializedInput = (ActionMessage) this.converter.read(ActionMessage.class, inputMessage);
    } catch (HttpMessageNotReadableException ex) {
        log.info("Authentication failure detected, but request could not be read as AMF.", ex);
        super.commence(request, response, authException);
        return;
    }

    if (deserializedInput instanceof ActionMessage) {
        for (ExceptionTranslator translator : this.exceptionTranslators) {
            if (translator.handles(authException.getClass())) {
                MessageException result = translator.translate(authException);
                ErrorMessage err = result.createErrorMessage();
                MessageBody body = (MessageBody) ((ActionMessage) deserializedInput).getBody(0);
                Message amfInputMessage = body.getDataAsMessage();
                err.setCorrelationId(amfInputMessage.getMessageId());
                err.setDestination(amfInputMessage.getDestination());
                err.setClientId(amfInputMessage.getClientId());
                ActionMessage responseMessage = new ActionMessage();
                responseMessage.setVersion(((ActionMessage) deserializedInput).getVersion());
                MessageBody responseBody = new MessageBody();
                responseMessage.addBody(responseBody);
                responseBody.setData(err);
                responseBody.setTargetURI(body.getResponseURI());
                responseBody.setReplyMethod(MessageIOConstants.STATUS_METHOD);
                converter.write(responseMessage, amfMediaType, outputMessage);
                response.flushBuffer();
                return;
            }
        }
    }
    super.commence(request, response, authException);
}

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

@Override
public MultiValueMap<String, String> read(@Nullable Class<? extends MultiValueMap<String, ?>> clazz,
        HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = (contentType != null && contentType.getCharset() != null ? contentType.getCharset()
            : this.charset);
    String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");
    MultiValueMap<String, String> result = new LinkedMultiValueMap<>(pairs.length);
    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {/*from  ww w . ja v  a 2s. c  o m*/
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }
    return result;
}

From source file:org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void writeWithMessageConverters(Object returnValue, HttpInputMessage inputMessage,
        HttpOutputMessage outputMessage) throws IOException, HttpMediaTypeNotAcceptableException {
    List<MediaType> acceptedMediaTypes = inputMessage.getHeaders().getAccept();
    if (acceptedMediaTypes.isEmpty()) {
        acceptedMediaTypes = Collections.singletonList(MediaType.ALL);
    }/* ww  w  .j  a va2 s . c o m*/
    MediaType.sortByQualityValue(acceptedMediaTypes);
    Class<?> returnValueType = returnValue.getClass();
    List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
    for (MediaType acceptedMediaType : acceptedMediaTypes) {
        for (HttpMessageConverter messageConverter : messageConverters) {
            if (messageConverter.canWrite(returnValueType, acceptedMediaType)) {
                messageConverter.write(returnValue, acceptedMediaType, outputMessage);
                if (logger.isDebugEnabled()) {
                    MediaType contentType = outputMessage.getHeaders().getContentType();
                    if (contentType == null) {
                        contentType = acceptedMediaType;
                    }
                    logger.debug("Written [" + returnValue + "] as \"" + contentType + "\" using ["
                            + messageConverter + "]");
                }
                return;
            }
        }
    }
    for (HttpMessageConverter messageConverter : messageConverters) {
        allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
    }
    throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes);
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

private HttpEntity<?> resolveHttpEntityRequest(MethodParameter methodParam, NativeWebRequest webRequest)
        throws Exception {

    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    Class<?> paramType = getHttpEntityType(methodParam);
    Object body = readWithMessageConverters(methodParam, inputMessage, paramType);
    return new HttpEntity<Object>(body, inputMessage.getHeaders());
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage,
        Class<?> paramType) throws Exception {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    if (contentType == null) {
        StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType()));
        String paramName = methodParam.getParameterName();
        if (paramName != null) {
            builder.append(' ');
            builder.append(paramName);//from  w w  w.  j ava 2s.  c  o m
        }
        throw new HttpMediaTypeNotSupportedException(
                "Cannot extract parameter (" + builder.toString() + "): no Content-Type found");
    }

    List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
    if (this.messageConverters != null) {
        for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
            allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
            if (messageConverter.canRead(paramType, contentType)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType + "\" using ["
                            + messageConverter + "]");
                }
                return messageConverter.read((Class) paramType, inputMessage);
            }
        }
    }
    throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
}