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

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

Introduction

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

Prototype

HttpResponseStatus NOT_FOUND

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

Click Source Link

Document

404 Not Found

Usage

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/*  w  w  w.j  a  v a 2s.c  o  m*/
                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:cn.wantedonline.puppy.exception.ResourceNotFoundError.java

License:Apache License

@Override
public HttpResponseStatus getStatus() {
    return HttpResponseStatus.NOT_FOUND;
}

From source file:co.cask.cdap.app.stream.DefaultStreamBatchWriter.java

License:Apache License

@Override
public void close() throws IOException {
    int responseCode;
    try {/*  ww  w.  j  av  a  2  s. com*/
        open = false;
        outputStream.close();
        responseCode = connection.getResponseCode();
    } finally {
        connection.disconnect();
    }

    if (responseCode == HttpResponseStatus.NOT_FOUND.code()) {
        throw new IOException(String.format("Stream %s not found", stream));
    }

    if (responseCode < 200 || responseCode >= 300) {
        throw new IOException(
                String.format("Writing to Stream %s did not succeed. Stream Service ResponseCode : %d", stream,
                        responseCode));
    }
}

From source file:co.cask.cdap.app.stream.DefaultStreamWriter.java

License:Apache License

private void writeToStream(Id.Stream stream, HttpRequest request) throws IOException {
    HttpResponse response = HttpRequests.execute(request);
    int responseCode = response.getResponseCode();
    if (responseCode == HttpResponseStatus.NOT_FOUND.code()) {
        throw new IOException(String.format("Stream %s not found", stream));
    }//from  w  ww  . ja va  2 s.co m

    // prone being entered multiple times, but OK since usageRegistry.register is not an expensive operation
    if (!isStreamRegistered.containsKey(stream)) {
        usageRegistry.registerAll(owners, stream);
        isStreamRegistered.put(stream, true);
    }

    if (responseCode < 200 || responseCode >= 300) {
        throw new IOException(
                String.format("Writing to Stream %s did not succeed. Stream Service ResponseCode : %d", stream,
                        responseCode));
    }
}

From source file:co.cask.cdap.guides.PageRankHandler.java

License:Apache License

@Path("pagerank")
@POST/*from w w w.j  a va  2 s.c om*/
public void handleBackLink(HttpServiceRequest request, HttpServiceResponder responder) {

    ByteBuffer requestContents = request.getContent();
    if (requestContents == null) {
        responder.sendError(HttpResponseStatus.NO_CONTENT.code(), "No URL provided.");
        return;
    }

    String urlParam = Charsets.UTF_8.decode(requestContents).toString();

    Double rank = pageRanks.read(urlParam);
    if (rank == null) {
        responder.sendError(HttpResponseStatus.NOT_FOUND.code(),
                "The following URL was not found: " + urlParam);
        return;
    }

    responder.sendJson(String.valueOf(rank));
}

From source file:co.cask.cdap.internal.app.runtime.adapter.AdapterServiceTest.java

License:Apache License

@Test
public void checkForbiddenOperations() throws Exception {
    String adapterName = "myAdp";
    DummyBatchTemplate.Config config = new DummyBatchTemplate.Config("some", "0 0 1 1 *");
    AdapterConfig adapterConfig = new AdapterConfig("desc", DummyBatchTemplate.NAME, GSON.toJsonTree(config));

    // Create an adapter to deploy template application.
    adapterService.createAdapter(NAMESPACE, adapterName, adapterConfig);
    AdapterDefinition adapterSpec = adapterService.getAdapter(NAMESPACE, adapterName);
    Assert.assertNotNull(adapterSpec);/*  ww  w . j  a  v  a 2s .c  o  m*/

    // We should not be able to delete the application since we have created an adapter.
    Assert.assertFalse(adapterService.canDeleteApp(Id.Application.from(NAMESPACE, DummyBatchTemplate.NAME)));

    // Remove adapter but this does not delete the template app automatically.
    adapterService.removeAdapter(NAMESPACE, adapterName);

    // We should be able to delete the application since no adapters exist.
    Assert.assertTrue(adapterService.canDeleteApp(Id.Application.from(NAMESPACE, DummyBatchTemplate.NAME)));

    // This request should fail since the application is a template application.
    HttpResponse response = doPost(
            String.format("%s/namespaces/%s/apps/%s/workflows/%s/start", Constants.Gateway.API_VERSION_3,
                    TEST_NAMESPACE1, adapterConfig.getTemplate(), DummyBatchTemplate.AdapterWorkflow.NAME));
    Assert.assertEquals(HttpResponseStatus.FORBIDDEN.code(), response.getStatusLine().getStatusCode());

    // the deletion of the only adapter using the application should have deleted the app and an attempt to delete the
    // application should reutrn not found
    response = doDelete(String.format("%s/namespaces/%s/apps/%s", Constants.Gateway.API_VERSION_3,
            TEST_NAMESPACE1, adapterConfig.getTemplate()));
    Assert.assertEquals(HttpResponseStatus.NOT_FOUND.code(), response.getStatusLine().getStatusCode());

    String workerAdapter = "workAdapter";
    DummyWorkerTemplate.Config config1 = new DummyWorkerTemplate.Config(2);
    AdapterConfig adapterConfig1 = new AdapterConfig("desc1", DummyWorkerTemplate.NAME,
            GSON.toJsonTree(config1));
    adapterService.createAdapter(NAMESPACE, workerAdapter, adapterConfig1);
    adapterSpec = adapterService.getAdapter(NAMESPACE, workerAdapter);
    Assert.assertNotNull(adapterSpec);

    // This request should fail since the application is a template application.
    response = doPost(String.format("%s/namespaces/%s/apps/%s/workers/%s/stop", Constants.Gateway.API_VERSION_3,
            TEST_NAMESPACE1, adapterConfig1.getTemplate(), DummyWorkerTemplate.TWorker.NAME));
    Assert.assertEquals(HttpResponseStatus.FORBIDDEN.code(), response.getStatusLine().getStatusCode());
    adapterService.removeAdapter(NAMESPACE, workerAdapter);
}

From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java

License:Apache License

private static final FullHttpResponse http_404() {
    FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    HttpHeaders httpHeaders = response.headers();
    httpHeaders.set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
    httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
    return response;
}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

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

    final RequestHandlerMapping mapping = config.getRequestMapping(msg.getUri());

    String relativePath = msg.getUri();

    if (mapping != null) {
        relativePath = relativePath.substring(mapping.path().length());
    }//from  w w  w. j  a  v  a  2s  .  co  m

    // Create request/response
    final PooledServerRequest request = messagePool.getRequest();

    // Handle 503 - sanity check, should be caught in acceptor
    if (request == null) {
        sendServerError(ctx, new ServerTooBusyException("Maximum concurrent connections reached"));
        return;
    }

    request.init(ctx.channel(), msg, relativePath);

    final RequestHandler handler = mapping == null ? null : mapping.handler(request);

    final PooledServerResponse response = messagePool.getResponse();
    response.init(ctx, this, handler, request, config.logger());

    if (mapping == null) {
        // No handler found, 404
        response.setStatus(HttpResponseStatus.NOT_FOUND);
    }

    // Store in ChannelHandlerContext for future reference
    ctx.attr(ATTR_RESPONSE).set(response);

    try {

        // MJS: Dispatch an error if not found or authorized
        if (response.getStatus() == HttpResponseStatus.UNAUTHORIZED
                || response.getStatus() == HttpResponseStatus.NOT_FOUND) {
            config.errorHandler().onError(request, response, null);
        } else {
            handler.onRequest(request, response);
        }

    } catch (final Throwable t) {

        // Catch server errors
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

        try {
            config.errorHandler().onError(request, response, t);
        } catch (final Throwable t2) {
            response.write(t.getClass() + " was thrown while processing this request.  Additionally, "
                    + t2.getClass() + " was thrown while handling this exception.");
        }

        config.logger().error(request, response, t);

        // Force request to end on exception, async handlers cannot allow
        // unchecked exceptions and still expect to return data
        if (!response.isFinished()) {
            response.finish();
        }

    } finally {

        // If handler did not request async response, finish request
        if (!response.isFinished() && !response.isSuspended()) {
            response.finish();
        }

    }

}

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

License:BSD License

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

    try {//w  w w  .  j av  a2s . c  om
        route(request).handle();
    } catch (final RestException e) {
        request.response().setStatus(HttpResponseStatus.NOT_FOUND);
        request.response().write("404 Not Found");
        request.response().finish();
    }

}

From source file:com.barchart.netty.server.http.handlers.StaticResourceHandler.java

License:BSD License

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

    try {//www. j av a 2 s .  co  m

        final Resource resource = resolver.resolve(request.getPathInfo());

        if (resource.contentType() != null)
            request.response().setContentType(resource.contentType());

        // Set Cache-Control: public
        request.response().headers().add(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.PUBLIC);

        if (!handleCache(request, resource)) {

            // Set modification time
            HttpHeaders.setDateHeader(request.response(), HttpHeaders.Names.LAST_MODIFIED,
                    new Date(resource.modified()));

            request.response().setContentLength((int) resource.size());

            // Chunked response for (potentially) large files
            if (resource.size() == 0 || resource.size() > 8192)
                request.response().setChunkSize(8192);

            IOUtils.copy(resource.stream(), request.response().getOutputStream());

        }

    } catch (final IOException e) {

        request.response().setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        request.response().write("500 Server Error");

    } catch (final ResourceNotFoundException e) {

        request.response().setStatus(HttpResponseStatus.NOT_FOUND);
        request.response().write("404 Not Found");

    } finally {

        request.response().finish();

    }

}