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

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

Introduction

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

Prototype

HttpResponseStatus METHOD_NOT_ALLOWED

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

Click Source Link

Document

405 Method Not Allowed

Usage

From source file:cf.component.VcapComponent.java

License:Open Source License

public VcapComponent(CfNats nats, SimpleHttpServer httpServer, String type, List<VarzUpdater> varzUpdaters) {
    this.nats = nats;
    this.type = type;
    this.varzUpdaters = varzUpdaters;

    nats.subscribe(ComponentDiscover.class, new PublicationHandler<ComponentDiscover, ComponentAnnounce>() {
        @Override// w  w w.j av  a  2  s . c  o  m
        public void onMessage(Publication<ComponentDiscover, ComponentAnnounce> publication) {
            publication.reply(buildComponentAnnounce());
        }
    });

    nats.publish(buildComponentAnnounce());

    httpServer.addHandler(Pattern.compile("/healthz"), new AuthenticatedJsonTextResponseRequestHandler() {
        @Override
        public String handleAuthenticatedRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                throws RequestException {
            if (!request.getMethod().equals(HttpMethod.GET)) {
                throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
            }
            return "ok\n";
        }
    });

    httpServer.addHandler(Pattern.compile("/varz"), new AuthenticatedJsonTextResponseRequestHandler() {
        @Override
        protected String handleAuthenticatedRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                throws RequestException {
            if (!request.getMethod().equals(HttpMethod.GET)) {
                throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
            }
            final Varz varz = buildVarz();
            try {
                return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(varz);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:cf.service.NettyBrokerServer.java

License:Open Source License

public NettyBrokerServer(SimpleHttpServer server, Provisioner provisioner, String authToken) {
    super(provisioner, authToken);
    server.addHandler(Pattern.compile("/+gateway/v1/configurations/(.*?)/handles(/(.*))?"),
            new RequestHandler() {
                @Override/*from  w  ww .j  a v a  2s  . c  om*/
                public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                        throws RequestException {
                    validateAuthToken(request);
                    // Bind service
                    if (request.getMethod() == HttpMethod.POST) {
                        final BindRequest bindRequest = decode(BindRequest.class, body);
                        final BindResponse bindResponse = bindService(bindRequest);
                        return encodeResponse(bindResponse);
                    }
                    // Unbind service
                    if (request.getMethod() == HttpMethod.DELETE) {
                        if (uriMatcher.groupCount() != 3) {
                            throw new RequestException(HttpResponseStatus.NOT_FOUND);
                        }
                        final String serviceInstanceId = uriMatcher.group(1);
                        final String handleId = uriMatcher.group(3);
                        unbindService(serviceInstanceId, handleId);
                        return encodeResponse(EMPTY_JSON_OBJECT);
                    }
                    throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
                }
            });
    server.addHandler(Pattern.compile("/+gateway/v1/configurations(/(.*))?"), new RequestHandler() {
        @Override
        public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body)
                throws RequestException {
            validateAuthToken(request);
            // Create service
            if (request.getMethod() == HttpMethod.POST) {
                final CreateRequest createRequest = decode(CreateRequest.class, body);
                final CreateResponse createResponse = createService(createRequest);
                return encodeResponse(createResponse);
            }
            // Delete service
            if (request.getMethod() == HttpMethod.DELETE) {
                if (uriMatcher.groupCount() != 2) {
                    throw new RequestException(HttpResponseStatus.NOT_FOUND);
                }
                final String serviceInstanceId = uriMatcher.group(2);
                deleteService(serviceInstanceId);
                return encodeResponse(EMPTY_JSON_OBJECT);
            }
            throw new RequestException(HttpResponseStatus.METHOD_NOT_ALLOWED);
        }
    });
}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void get(final HttpServerRequest request) throws IOException {
    complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED, "GET not implemented");
}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void post(final HttpServerRequest request) throws IOException {
    complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED, "POST not implemented");
}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void put(final HttpServerRequest request) throws IOException {
    complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED, "PUT not implemented");
}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void delete(final HttpServerRequest request) throws IOException {
    complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED, "DELETE not implemented");
}

From source file:com.barchart.netty.rest.server.RestHandlerBase.java

License:BSD License

@Override
public void handle(final HttpServerRequest request) throws IOException {

    final HttpMethod method = request.getMethod();

    try {/* w  w  w  . j  a  va  2s.c om*/
        if (method == HttpMethod.GET) {
            get(request);
        } else if (method == HttpMethod.POST) {
            post(request);
        } else if (method == HttpMethod.PUT) {
            put(request);
        } else if (method == HttpMethod.DELETE) {
            delete(request);
        } else {
            complete(request.response(), HttpResponseStatus.METHOD_NOT_ALLOWED,
                    method.name() + " not implemented");
        }
    } catch (final Throwable t) {
        complete(request.response(), HttpResponseStatus.INTERNAL_SERVER_ERROR, t.getMessage());
    }

}

From source file:com.google.devtools.build.remote.worker.HttpCacheServerHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, request, HttpResponseStatus.BAD_REQUEST);
        return;//  w  w w.  j  av a2s.  co m
    }

    if (request.method() == HttpMethod.GET) {
        handleGet(ctx, request);
    } else if (request.method() == HttpMethod.PUT) {
        handlePut(ctx, request);
    } else {
        sendError(ctx, request, HttpResponseStatus.METHOD_NOT_ALLOWED);
    }
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceInvocationHandler.java

License:Apache License

@Override
public void invoke(ServiceInvocationContext ctx, Executor blockingTaskExecutor, Promise<Object> promise)
        throws Exception {

    final HttpRequest req = ctx.originalRequest();
    if (req.method() != HttpMethod.GET) {
        respond(ctx, promise, HttpResponseStatus.METHOD_NOT_ALLOWED, 0, ERROR_MIME_TYPE,
                Unpooled.wrappedBuffer(CONTENT_METHOD_NOT_ALLOWED));
        return;//from   www  .  ja va2s  .c o  m
    }

    final String path = normalizePath(ctx.mappedPath());
    if (path == null) {
        respond(ctx, promise, HttpResponseStatus.NOT_FOUND, 0, ERROR_MIME_TYPE,
                Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
        return;
    }

    Entry entry = getEntry(path);
    long lastModifiedMillis;
    if ((lastModifiedMillis = entry.lastModifiedMillis()) == 0) {
        boolean found = false;
        if (path.charAt(path.length() - 1) == '/') {
            // Try index.html if it was a directory access.
            entry = getEntry(path + "index.html");
            if ((lastModifiedMillis = entry.lastModifiedMillis()) != 0) {
                found = true;
            }
        }

        if (!found) {
            respond(ctx, promise, HttpResponseStatus.NOT_FOUND, 0, ERROR_MIME_TYPE,
                    Unpooled.wrappedBuffer(CONTENT_NOT_FOUND));
            return;
        }
    }

    long ifModifiedSinceMillis = Long.MIN_VALUE;
    try {
        ifModifiedSinceMillis = req.headers().getTimeMillis(HttpHeaderNames.IF_MODIFIED_SINCE, Long.MIN_VALUE);
    } catch (Exception e) {
        // Ignore the ParseException, which is raised on malformed date.
        //noinspection ConstantConditions
        if (!(e instanceof ParseException)) {
            throw e;
        }
    }

    // HTTP-date does not have subsecond-precision; add 999ms to it.
    if (ifModifiedSinceMillis > Long.MAX_VALUE - 999) {
        ifModifiedSinceMillis = Long.MAX_VALUE;
    } else {
        ifModifiedSinceMillis += 999;
    }

    if (lastModifiedMillis < ifModifiedSinceMillis) {
        respond(ctx, promise, HttpResponseStatus.NOT_MODIFIED, lastModifiedMillis, entry.mimeType(),
                Unpooled.EMPTY_BUFFER);
        return;
    }

    respond(ctx, promise, HttpResponseStatus.OK, lastModifiedMillis, entry.mimeType(),
            entry.readContent(ctx.alloc()));
}

From source file:com.linecorp.armeria.server.Http1RequestDecoder.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof HttpObject)) {
        ctx.fireChannelRead(msg);//from  w  ww .  j  a v a 2s.c  om
        return;
    }

    // this.req can be set to null by fail(), so we keep it in a local variable.
    DecodedHttpRequest req = this.req;
    try {
        if (discarding) {
            return;
        }

        if (req == null) {
            if (msg instanceof HttpRequest) {
                final HttpRequest nettyReq = (HttpRequest) msg;
                if (!nettyReq.decoderResult().isSuccess()) {
                    fail(ctx, HttpResponseStatus.BAD_REQUEST);
                    return;
                }

                final HttpHeaders nettyHeaders = nettyReq.headers();
                final int id = ++receivedRequests;

                // Validate the method.
                if (!HttpMethod.isSupported(nettyReq.method().name())) {
                    fail(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
                    return;
                }

                // Validate the 'content-length' header.
                final String contentLengthStr = nettyHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
                final boolean contentEmpty;
                if (contentLengthStr != null) {
                    final long contentLength;
                    try {
                        contentLength = Long.parseLong(contentLengthStr);
                    } catch (NumberFormatException ignored) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }
                    if (contentLength < 0) {
                        fail(ctx, HttpResponseStatus.BAD_REQUEST);
                        return;
                    }

                    contentEmpty = contentLength == 0;
                } else {
                    contentEmpty = true;
                }

                nettyHeaders.set(ExtensionHeaderNames.SCHEME.text(), scheme);

                this.req = req = new DecodedHttpRequest(ctx.channel().eventLoop(), id, 1,
                        ArmeriaHttpUtil.toArmeria(nettyReq), HttpUtil.isKeepAlive(nettyReq),
                        inboundTrafficController, cfg.defaultMaxRequestLength());

                // Close the request early when it is sure that there will be
                // neither content nor trailing headers.
                if (contentEmpty && !HttpUtil.isTransferEncodingChunked(nettyReq)) {
                    req.close();
                }

                ctx.fireChannelRead(req);
            } else {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                return;
            }
        }

        if (req != null && msg instanceof HttpContent) {
            final HttpContent content = (HttpContent) msg;
            final DecoderResult decoderResult = content.decoderResult();
            if (!decoderResult.isSuccess()) {
                fail(ctx, HttpResponseStatus.BAD_REQUEST);
                req.close(new ProtocolViolationException(decoderResult.cause()));
                return;
            }

            final ByteBuf data = content.content();
            final int dataLength = data.readableBytes();
            if (dataLength != 0) {
                req.increaseTransferredBytes(dataLength);
                final long maxContentLength = req.maxRequestLength();
                if (maxContentLength > 0 && req.transferredBytes() > maxContentLength) {
                    fail(ctx, HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE);
                    req.close(ContentTooLargeException.get());
                    return;
                }

                if (req.isOpen()) {
                    req.write(new ByteBufHttpData(data.retain(), false));
                }
            }

            if (msg instanceof LastHttpContent) {
                final HttpHeaders trailingHeaders = ((LastHttpContent) msg).trailingHeaders();
                if (!trailingHeaders.isEmpty()) {
                    req.write(ArmeriaHttpUtil.toArmeria(trailingHeaders));
                }

                req.close();
                this.req = req = null;
            }
        }
    } catch (URISyntaxException e) {
        fail(ctx, HttpResponseStatus.BAD_REQUEST);
        if (req != null) {
            req.close(e);
        }
    } catch (Throwable t) {
        fail(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        if (req != null) {
            req.close(t);
        } else {
            logger.warn("Unexpected exception:", t);
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}