Example usage for io.netty.handler.codec.http HttpResponseStatus UNSUPPORTED_MEDIA_TYPE

List of usage examples for io.netty.handler.codec.http HttpResponseStatus UNSUPPORTED_MEDIA_TYPE

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus UNSUPPORTED_MEDIA_TYPE.

Prototype

HttpResponseStatus UNSUPPORTED_MEDIA_TYPE

To view the source code for io.netty.handler.codec.http HttpResponseStatus UNSUPPORTED_MEDIA_TYPE.

Click Source Link

Document

415 Unsupported Media Type

Usage

From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java

License:Apache License

private SerializationFormat validateRequestAndDetermineSerializationFormat(Object originalRequest)
        throws InvalidHttpRequestException {
    if (!(originalRequest instanceof HttpRequest)) {
        return defaultSerializationFormat;
    }/*w  w  w . j  a  v  a2  s. c o  m*/
    final SerializationFormat serializationFormat;
    HttpRequest httpRequest = (HttpRequest) originalRequest;
    if (httpRequest.method() != HttpMethod.POST) {
        throw new InvalidHttpRequestException(HttpResponseStatus.METHOD_NOT_ALLOWED,
                HTTP_METHOD_NOT_ALLOWED_EXCEPTION);
    }

    final String contentTypeHeader = httpRequest.headers().get(HttpHeaderNames.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        serializationFormat = SerializationFormat.fromMimeType(contentTypeHeader)
                .orElse(defaultSerializationFormat);
        if (!allowedSerializationFormats.contains(serializationFormat)) {
            throw new InvalidHttpRequestException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                    THRIFT_PROTOCOL_NOT_SUPPORTED);
        }
    } else {
        serializationFormat = defaultSerializationFormat;
    }

    final String acceptHeader = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
    if (acceptHeader != null) {
        // If accept header is present, make sure it is sane. Currently, we do not support accept
        // headers with a different format than the content type header.
        SerializationFormat outputSerializationFormat = SerializationFormat.fromMimeType(acceptHeader)
                .orElse(serializationFormat);
        if (outputSerializationFormat != serializationFormat) {
            throw new InvalidHttpRequestException(HttpResponseStatus.NOT_ACCEPTABLE,
                    ACCEPT_THRIFT_PROTOCOL_MUST_MATCH_CONTENT_TYPE);
        }
    }
    return serializationFormat;
}

From source file:com.rackspacecloud.blueflood.http.QueryStringDecoderAndRouter.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {

    // for POST requests, check Content-Type header
    if (request.getMethod() == HttpMethod.POST) {
        if (!mediaTypeChecker.isContentTypeValid(request.headers())) {
            DefaultHandler.sendErrorResponse(ctx, request,
                    String.format("Unsupported media type for Content-Type: %s",
                            request.headers().get(HttpHeaders.Names.CONTENT_TYPE)),
                    HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
            return;
        }/*from w  ww .  ja v a2  s.  c o  m*/
    }

    // for GET or POST requests, check Accept header
    if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.POST) {
        if (!mediaTypeChecker.isAcceptValid(request.headers())) {
            DefaultHandler.sendErrorResponse(ctx, request,
                    String.format("Unsupported media type for Accept: %s",
                            request.headers().get(HttpHeaders.Names.ACCEPT)),
                    HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
            return;
        }
    }
    router.route(ctx, HttpRequestWithDecodedQueryParams.create(request));
}

From source file:com.spotify.ffwd.http.HttpDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, FullHttpRequest in, List<Object> out) throws Exception {
    switch (in.uri()) {
    case "/ping":
        if (in.method() == GET) {
            getPing(ctx, in, out);//from w  w w . j av  a  2 s. com
            return;
        }

        throw new HttpException(HttpResponseStatus.METHOD_NOT_ALLOWED);
    case "/v1/batch":
        if (in.method() == POST) {
            if (matchContentType(in, "application/json")) {
                postBatch(ctx, in, out);
                return;
            }
            log.error("Unsupported Media Type");
            throw new HttpException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
        }
        log.error("HTTP Method Not Allowed");
        throw new HttpException(HttpResponseStatus.METHOD_NOT_ALLOWED);
    default:
        /* do nothing */
        break;
    }

    throw new HttpException(HttpResponseStatus.NOT_FOUND);
}

From source file:io.soliton.protobuf.json.JsonRpcServerHandler.java

License:Apache License

/**
 * In charge of validating all the transport-related aspects of the incoming
 * HTTP request./*from ww w .j a  v a2s. c  o m*/
 * <p/>
 * <p>The checks include:</p>
 * <p/>
 * <ul>
 * <li>that the request's path matches that of this handler;</li>
 * <li>that the request's method is {@code POST};</li>
 * <li>that the request's content-type is {@code application/json};</li>
 * </ul>
 *
 * @param request the received HTTP request
 * @return {@code null} if the request passes the transport checks, an error
 *         to return to the client otherwise.
 * @throws URISyntaxException if the URI of the request cannot be parsed
 */
private JsonRpcError validateTransport(HttpRequest request) throws URISyntaxException, JsonRpcError {
    URI uri = new URI(request.getUri());
    JsonRpcError error = null;

    if (!uri.getPath().equals(rpcPath)) {
        error = new JsonRpcError(HttpResponseStatus.NOT_FOUND, "Not Found");
    }

    if (!request.getMethod().equals(HttpMethod.POST)) {
        error = new JsonRpcError(HttpResponseStatus.METHOD_NOT_ALLOWED, "Method not allowed");
    }

    if (!request.headers().get(HttpHeaders.Names.CONTENT_TYPE).equals(JsonRpcProtocol.CONTENT_TYPE)) {
        error = new JsonRpcError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE, "Unsupported media type");
    }

    return error;
}

From source file:org.iotivity.cloud.base.protocols.http.HCProxyProcessor.java

License:Open Source License

private HttpResponseStatus getHttpResponseStatus(ResponseStatus coapResponseStatus, boolean isPayload) {

    HttpResponseStatus httpStatusCode = HttpResponseStatus.NOT_IMPLEMENTED;

    if (coapResponseStatus == ResponseStatus.CREATED) {

        httpStatusCode = HttpResponseStatus.CREATED;

    } else if (coapResponseStatus == ResponseStatus.DELETED || coapResponseStatus == ResponseStatus.CHANGED
            || coapResponseStatus == ResponseStatus.CONTENT) {

        if (isPayload) {
            httpStatusCode = HttpResponseStatus.OK;
        } else {//w ww.  ja va 2  s. c  o  m
            httpStatusCode = HttpResponseStatus.NO_CONTENT;
        }

    } else if (coapResponseStatus == ResponseStatus.VALID) {

        if (isPayload) {
            httpStatusCode = HttpResponseStatus.OK;
        } else {
            httpStatusCode = HttpResponseStatus.NOT_MODIFIED;
        }

    } else if (coapResponseStatus == ResponseStatus.UNAUTHORIZED
            || coapResponseStatus == ResponseStatus.FORBIDDEN) {

        httpStatusCode = HttpResponseStatus.FORBIDDEN;

    } else if (coapResponseStatus == ResponseStatus.BAD_REQUEST
            || coapResponseStatus == ResponseStatus.BAD_OPTION) {

        httpStatusCode = HttpResponseStatus.BAD_REQUEST;

    } else if (coapResponseStatus == ResponseStatus.METHOD_NOT_ALLOWED) {

        // The HC Proxy should return a HTTP reason-phrase
        // in the HTTP status line that starts with the string
        // "CoAP server returned 4.05"
        // in order to facilitate troubleshooting.
        httpStatusCode = new HttpResponseStatus(400, "CoAP server returned 4.05");

    } else if (coapResponseStatus == ResponseStatus.NOT_ACCEPTABLE) {

        httpStatusCode = HttpResponseStatus.NOT_ACCEPTABLE;

    } else if (coapResponseStatus == ResponseStatus.PRECONDITION_FAILED) {

        httpStatusCode = HttpResponseStatus.PRECONDITION_FAILED;

    } else if (coapResponseStatus == ResponseStatus.UNSUPPORTED_CONTENT_FORMAT) {

        httpStatusCode = HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;

    } else if (coapResponseStatus == ResponseStatus.BAD_GATEWAY
            || coapResponseStatus == ResponseStatus.PROXY_NOT_SUPPORTED) {

        httpStatusCode = HttpResponseStatus.BAD_GATEWAY;

    } else if (coapResponseStatus == ResponseStatus.SERVICE_UNAVAILABLE) {

        httpStatusCode = HttpResponseStatus.SERVICE_UNAVAILABLE;

    } else if (coapResponseStatus == ResponseStatus.GATEWAY_TIMEOUT) {

        httpStatusCode = HttpResponseStatus.GATEWAY_TIMEOUT;

    } else if (coapResponseStatus == ResponseStatus.NOT_FOUND) {

        httpStatusCode = HttpResponseStatus.NOT_FOUND;

    } else if (coapResponseStatus == ResponseStatus.INTERNAL_SERVER_ERROR) {

        httpStatusCode = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    }

    return httpStatusCode;
}

From source file:org.nosceon.titanite.Response.java

License:Apache License

public static Response unsupportedMediaType() {
    return new Response(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE);
}

From source file:org.restnext.server.ServerHandler.java

License:Apache License

private HttpResponseStatus fromStatus(Response.Status status) {
    switch (status) {
    case OK://from   w w  w  . j  a v a  2  s  .c  o  m
        return HttpResponseStatus.OK;
    case CREATED:
        return HttpResponseStatus.CREATED;
    case ACCEPTED:
        return HttpResponseStatus.ACCEPTED;
    case NO_CONTENT:
        return HttpResponseStatus.NO_CONTENT;
    case RESET_CONTENT:
        return HttpResponseStatus.RESET_CONTENT;
    case PARTIAL_CONTENT:
        return HttpResponseStatus.PARTIAL_CONTENT;
    case MOVED_PERMANENTLY:
        return HttpResponseStatus.MOVED_PERMANENTLY;
    case FOUND:
        return HttpResponseStatus.FOUND;
    case SEE_OTHER:
        return HttpResponseStatus.SEE_OTHER;
    case NOT_MODIFIED:
        return HttpResponseStatus.NOT_MODIFIED;
    case USE_PROXY:
        return HttpResponseStatus.USE_PROXY;
    case TEMPORARY_REDIRECT:
        return HttpResponseStatus.TEMPORARY_REDIRECT;
    case BAD_REQUEST:
        return HttpResponseStatus.BAD_REQUEST;
    case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
    case PAYMENT_REQUIRED:
        return HttpResponseStatus.PAYMENT_REQUIRED;
    case FORBIDDEN:
        return HttpResponseStatus.FORBIDDEN;
    case NOT_FOUND:
        return HttpResponseStatus.NOT_FOUND;
    case METHOD_NOT_ALLOWED:
        return HttpResponseStatus.METHOD_NOT_ALLOWED;
    case NOT_ACCEPTABLE:
        return HttpResponseStatus.NOT_ACCEPTABLE;
    case PROXY_AUTHENTICATION_REQUIRED:
        return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
    case REQUEST_TIMEOUT:
        return HttpResponseStatus.REQUEST_TIMEOUT;
    case CONFLICT:
        return HttpResponseStatus.CONFLICT;
    case GONE:
        return HttpResponseStatus.GONE;
    case LENGTH_REQUIRED:
        return HttpResponseStatus.LENGTH_REQUIRED;
    case PRECONDITION_FAILED:
        return HttpResponseStatus.PRECONDITION_FAILED;
    case REQUEST_ENTITY_TOO_LARGE:
        return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
    case REQUEST_URI_TOO_LONG:
        return HttpResponseStatus.REQUEST_URI_TOO_LONG;
    case UNSUPPORTED_MEDIA_TYPE:
        return HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE;
    case REQUESTED_RANGE_NOT_SATISFIABLE:
        return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
    case EXPECTATION_FAILED:
        return HttpResponseStatus.EXPECTATION_FAILED;
    case INTERNAL_SERVER_ERROR:
        return HttpResponseStatus.INTERNAL_SERVER_ERROR;
    case NOT_IMPLEMENTED:
        return HttpResponseStatus.NOT_IMPLEMENTED;
    case BAD_GATEWAY:
        return HttpResponseStatus.BAD_GATEWAY;
    case SERVICE_UNAVAILABLE:
        return HttpResponseStatus.SERVICE_UNAVAILABLE;
    case GATEWAY_TIMEOUT:
        return HttpResponseStatus.GATEWAY_TIMEOUT;
    case HTTP_VERSION_NOT_SUPPORTED:
        return HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
    case CONTINUE:
        return HttpResponseStatus.CONTINUE;
    default:
        throw new RuntimeException(String.format("Status: %s not supported", status));
    }
}

From source file:org.wso2.carbon.mss.internal.router.HttpResourceHandler.java

License:Open Source License

/**
 * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but
 * httpMethod does not match what's configured.
 *
 * @param request   instance of {@code HttpRequest}
 * @param responder instance of {@code HttpResponder} to handle the request.
 * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked.
 * @throws HandlerException If URL rewriting fails
 *///  w w  w .j  a  v  a2 s .com
public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder)
        throws HandlerException {
    if (urlRewriter != null) {
        try {
            request.setUri(URI.create(request.getUri()).normalize().toString());
            if (!urlRewriter.rewrite(request, responder)) {
                return null;
            }
        } catch (Throwable t) {
            log.error("Exception thrown during rewriting of uri {}", request.getUri(), t);
            throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    String.format("Caught exception processing request. Reason: %s", t.getMessage()));
        }
    }

    String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT);
    List<String> acceptHeader = (acceptHeaderStr != null)
            ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream()
                    .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList())
            : null;

    String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);
    //Trim specified charset since UTF-8 is assumed
    String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0]
            : null;

    try {
        String path = URI.create(request.getUri()).normalize().getPath();

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter
                .getDestinations(path);

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination(
                routableDestinations, request.getMethod(), path);

        if (!matchedDestinations.isEmpty()) {
            PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations
                    .stream().filter(matchedDestination1 -> {
                        return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader)
                                && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader);
                    }).findFirst().get();
            HttpResourceModel httpResourceModel = matchedDestination.getDestination();

            // Call preCall method of handler interceptors.
            boolean terminated = false;
            HandlerInfo handlerInfo = new HandlerInfo(
                    httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod());
            for (Interceptor interceptor : interceptors) {
                if (!interceptor.preCall(request, responder, handlerInfo)) {
                    // Terminate further request processing if preCall returns false.
                    terminated = true;
                    break;
                }
            }

            // Call httpresource handle method, return the HttpMethodInfo Object.
            if (!terminated) {
                // Wrap responder to make post hook calls.
                responder = new WrappedHttpResponder(responder, interceptors, request, handlerInfo);
                return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel)
                        .httpRequest(request).httpResponder(responder)
                        .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader);
            }
        } else if (!routableDestinations.isEmpty()) {
            //Found a matching resource but could not find the right HttpMethod so return 405
            throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri());
        } else {
            throw new HandlerException(HttpResponseStatus.NOT_FOUND,
                    String.format("Problem accessing: %s. Reason: Not Found", request.getUri()));
        }
    } catch (NoSuchElementException ex) {
        throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex);
    }
    return null;
}

From source file:org.wso2.carbon.mss.internal.router.MicroserviceMetadata.java

License:Open Source License

/**
 * Call the appropriate handler for handling the httprequest. 404 if path is not found. 405 if path is found but
 * httpMethod does not match what's configured.
 *
 * @param request   instance of {@code HttpRequest}
 * @param responder instance of {@code HttpResponder} to handle the request.
 * @return HttpMethodInfo object, null if urlRewriter rewrite returns false, also when method cannot be invoked.
 * @throws HandlerException If URL rewriting fails
 *///from  w  w w.j  av a 2  s. c  o  m
public HttpMethodInfoBuilder getDestinationMethod(HttpRequest request, HttpResponder responder)
        throws HandlerException {
    if (urlRewriter != null) {
        try {
            request.setUri(URI.create(request.getUri()).normalize().toString());
            if (!urlRewriter.rewrite(request, responder)) {
                return null;
            }
        } catch (Throwable t) {
            log.error("Exception thrown during rewriting of uri {}", request.getUri(), t);
            throw new HandlerException(HttpResponseStatus.INTERNAL_SERVER_ERROR,
                    String.format("Caught exception processing request. Reason: %s", t.getMessage()));
        }
    }

    String acceptHeaderStr = request.headers().get(HttpHeaders.Names.ACCEPT);
    List<String> acceptHeader = (acceptHeaderStr != null)
            ? Arrays.asList(acceptHeaderStr.split("\\s*,\\s*")).stream()
                    .map(mediaType -> mediaType.split("\\s*;\\s*")[0]).collect(Collectors.toList())
            : null;

    String contentTypeHeaderStr = request.headers().get(HttpHeaders.Names.CONTENT_TYPE);
    //Trim specified charset since UTF-8 is assumed
    String contentTypeHeader = (contentTypeHeaderStr != null) ? contentTypeHeaderStr.split("\\s*;\\s*")[0]
            : null;

    try {
        String path = URI.create(request.getUri()).normalize().getPath();

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations = patternRouter
                .getDestinations(path);

        List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations = getMatchedDestination(
                routableDestinations, request.getMethod(), path);

        if (!matchedDestinations.isEmpty()) {
            PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination = matchedDestinations
                    .stream().filter(matchedDestination1 -> {
                        return matchedDestination1.getDestination().matchConsumeMediaType(contentTypeHeader)
                                && matchedDestination1.getDestination().matchProduceMediaType(acceptHeader);
                    }).findFirst().get();
            HttpResourceModel httpResourceModel = matchedDestination.getDestination();

            // Call preCall method of handler interceptors.
            boolean terminated = false;
            ServiceMethodInfo serviceMethodInfo = new ServiceMethodInfo(
                    httpResourceModel.getMethod().getDeclaringClass().getName(), httpResourceModel.getMethod());
            for (Interceptor interceptor : interceptors) {
                if (!interceptor.preCall(request, responder, serviceMethodInfo)) {
                    // Terminate further request processing if preCall returns false.
                    terminated = true;
                    break;
                }
            }

            // Call httpresource handle method, return the HttpMethodInfo Object.
            if (!terminated) {
                // Wrap responder to make post hook calls.
                responder = new WrappedHttpResponder(responder, interceptors, request, serviceMethodInfo);
                return HttpMethodInfoBuilder.getInstance().httpResourceModel(httpResourceModel)
                        .httpRequest(request).httpResponder(responder)
                        .requestInfo(matchedDestination.getGroupNameValues(), contentTypeHeader, acceptHeader);
            }
        } else if (!routableDestinations.isEmpty()) {
            //Found a matching resource but could not find the right HttpMethod so return 405
            throw new HandlerException(HttpResponseStatus.METHOD_NOT_ALLOWED, request.getUri());
        } else {
            throw new HandlerException(HttpResponseStatus.NOT_FOUND,
                    String.format("Problem accessing: %s. Reason: Not Found", request.getUri()));
        }
    } catch (NoSuchElementException ex) {
        throw new HandlerException(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE,
                String.format("Problem accessing: %s. Reason: Unsupported Media Type", request.getUri()), ex);
    }
    return null;
}

From source file:ratpack.handling.internal.ContentTypeHandler.java

License:Apache License

@Override
public void handle(Context context) throws Exception {
    boolean accepted = false;
    String requestType = context.getRequest().getContentType().getType();
    if (requestType != null) {
        for (String contentType : contentTypes) {
            if (requestType.equals(contentType)) {
                accepted = true;/*from w  ww .  j a v a2s. c  o  m*/
                break;
            }
        }
    }

    if (accepted) {
        context.next();
    } else {
        context.clientError(HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE.code());
    }
}