Example usage for io.netty.handler.codec.http FullHttpRequest retain

List of usage examples for io.netty.handler.codec.http FullHttpRequest retain

Introduction

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

Prototype

@Override
    FullHttpRequest retain();

Source Link

Usage

From source file:co.rsk.rpc.netty.Web3HttpMethodFilterHandler.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) {
    HttpMethod httpMethod = request.getMethod();
    if (HttpMethod.POST.equals(httpMethod)) {
        // retain the request so it isn't released automatically by SimpleChannelInboundHandler
        ctx.fireChannelRead(request.retain());
    } else {//www .  ja  v a  2s  . c  o m
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.NOT_IMPLEMENTED);
        ctx.write(response).addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.addthis.hydra.query.web.HttpQueryHandler.java

License:Apache License

private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv)
        throws Exception {
    StringBuilderWriter writer = new StringBuilderWriter(50);
    HttpResponse response = HttpUtils.startResponse(writer);
    response.headers().add("Access-Control-Allow-Origin", "*");

    switch (target) {
    case "/metrics":
        fakeMetricsServlet.writeMetrics(writer, kv);
        break;/*from ww  w  .ja v  a 2  s  .c  o  m*/
    case "/query/list":
        writer.write("[\n");
        for (QueryEntryInfo stat : tracker.getRunning()) {
            writer.write(CodecJSON.encodeString(stat).concat(",\n"));
        }
        writer.write("]");
        break;
    case "/completed/list":
        writer.write("[\n");
        for (QueryEntryInfo stat : tracker.getCompleted()) {
            writer.write(CodecJSON.encodeString(stat).concat(",\n"));
        }
        writer.write("]");
        break;
    case "/v2/host/list":
    case "/host/list":
        String queryStatusUuid = kv.getValue("uuid");
        QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid);
        if (queryEntry != null) {
            DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request,
                    queryEntry);
            hostDetailsHandler.handle();
            return;
        } else {
            QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid);
            if (queryEntryInfo != null) {
                JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo);
                writer.write(entryJSON.toString());
            } else {
                throw new RuntimeException("could not find query");
            }
            break;
        }
    case "/query/cancel":
        if (tracker.cancelRunning(kv.getValue("uuid"))) {
            writer.write("canceled " + kv.getValue("uuid"));
        } else {
            writer.write("canceled failed for " + kv.getValue("uuid"));
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
        break;
    case "/query/encode": {
        Query q = new Query(null, kv.getValue("query", kv.getValue("path", "")), null);
        JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path");
        writer.write(path.toString());
        break;
    }
    case "/query/decode": {
        String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}";
        Query q = CodecJSON.decodeString(new Query(), qo);
        writer.write(q.getPaths()[0]);
        break;
    }
    case "/v2/queries/finished.list": {
        JSONArray runningEntries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getCompleted()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            //TODO: replace this with some high level summary
            entryJSON.put("hostInfoSet", "");
            runningEntries.put(entryJSON);
        }
        writer.write(runningEntries.toString());
        break;
    }
    case "/v2/queries/running.list": {
        JSONArray runningEntries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getRunning()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            //TODO: replace this with some high level summary
            entryJSON.put("hostInfoSet", "");
            runningEntries.put(entryJSON);
        }
        writer.write(runningEntries.toString());
        break;
    }
    case "/v2/queries/workers": {
        JSONObject jsonObject = new JSONObject();
        for (WorkerData workerData : meshQueryMaster.worky().values()) {
            jsonObject.put(workerData.hostName, workerData.queryLeases.availablePermits());
        }
        writer.write(jsonObject.toString());
        break;
    }
    case "/v2/queries/list":
        JSONArray queries = new JSONArray();
        for (QueryEntryInfo entryInfo : tracker.getCompleted()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            entryJSON.put("state", 0);
            queries.put(entryJSON);
        }
        for (QueryEntryInfo entryInfo : tracker.getRunning()) {
            JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo);
            entryJSON.put("state", 3);
            queries.put(entryJSON);
        }
        writer.write(queries.toString());
        break;
    case "/v2/job/list": {
        StringWriter swriter = new StringWriter();
        final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter);
        json.writeStartArray();
        for (IJob job : meshQueryMaster.keepy().getJobs()) {
            if (job.getQueryConfig() != null && job.getQueryConfig().getCanQuery()) {
                List<JobTask> tasks = job.getCopyOfTasks();
                String uuid = job.getId();
                json.writeStartObject();
                json.writeStringField("id", uuid);
                json.writeStringField("description", Optional.fromNullable(job.getDescription()).or(""));
                json.writeNumberField("state", job.getState().ordinal());
                json.writeStringField("creator", job.getCreator());
                json.writeNumberField("submitTime", Optional.fromNullable(job.getSubmitTime()).or(-1L));
                json.writeNumberField("startTime", Optional.fromNullable(job.getStartTime()).or(-1L));
                json.writeNumberField("endTime", Optional.fromNullable(job.getStartTime()).or(-1L));
                json.writeNumberField("replicas", Optional.fromNullable(job.getReplicas()).or(0));
                json.writeNumberField("backups", Optional.fromNullable(job.getBackups()).or(0));
                json.writeNumberField("nodes", tasks.size());
                json.writeEndObject();
            }
        }
        json.writeEndArray();
        json.close();
        writer.write(swriter.toString());
        break;
    }
    case "/v2/settings/git.properties": {
        StringWriter swriter = new StringWriter();
        final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter);
        Properties gitProperties = new Properties();
        json.writeStartObject();
        try {
            InputStream in = queryServer.getClass().getResourceAsStream("/git.properties");
            gitProperties.load(in);
            in.close();
            json.writeStringField("commitIdAbbrev", gitProperties.getProperty("git.commit.id.abbrev"));
            json.writeStringField("commitUserEmail", gitProperties.getProperty("git.commit.user.email"));
            json.writeStringField("commitMessageFull", gitProperties.getProperty("git.commit.message.full"));
            json.writeStringField("commitId", gitProperties.getProperty("git.commit.id"));
            json.writeStringField("commitUserName", gitProperties.getProperty("git.commit.user.name"));
            json.writeStringField("buildUserName", gitProperties.getProperty("git.build.user.name"));
            json.writeStringField("commitIdDescribe", gitProperties.getProperty("git.commit.id.describe"));
            json.writeStringField("buildUserEmail", gitProperties.getProperty("git.build.user.email"));
            json.writeStringField("branch", gitProperties.getProperty("git.branch"));
            json.writeStringField("commitTime", gitProperties.getProperty("git.commit.time"));
            json.writeStringField("buildTime", gitProperties.getProperty("git.build.time"));
        } catch (Exception ex) {
            log.warn("Error loading git.properties, possibly jar was not compiled with maven.");
        }
        json.writeEndObject();
        json.close();
        writer.write(swriter.toString());
        break;
    }
    default:
        // forward to static file server
        ctx.pipeline().addLast(staticFileHandler);
        request.retain();
        ctx.fireChannelRead(request);
        return; // don't do text response clean up
    }
    log.trace("response being sent {}", writer);
    ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()),
            CharsetUtil.UTF_8);
    HttpContent content = new DefaultHttpContent(textResponse);
    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }
    ctx.write(response);
    ctx.write(content);
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    log.trace("response pending");
    if (!HttpHeaders.isKeepAlive(request)) {
        log.trace("Setting close listener");
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.jansegre.jwar.webapi.FileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    request.retain();
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from  www.  j  a  va  2 s. c  o  m*/
        ctx.fireChannelRead(request);
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        ctx.fireChannelRead(request);
        return;
    }

    final String uri = request.getUri();
    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        ctx.fireChannelRead(request);
        return;
    }

    //XXX: notice hardcoded socket.io namespace
    if (uri.startsWith("/socket.io")) {
        ctx.fireChannelRead(request);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            File index_file = new File(sanitizeUri(uri + INDEX_FILE));
            if (index_file.exists()) {
                file = index_file;
            } else {
                sendListing(ctx, file);
                return;
            }
        } else {
            sendRedirect(ctx, uri + '/');
            return;
        }
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // Only compare up to the second because the datetime format we send to the client
        // does not have milliseconds
        long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
        long fileLastModifiedSeconds = file.lastModified() / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.lufs.preresearch.nettyrouter.playground.HttpHelloWorldServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
    msg.retain();
    String uri = msg.uri();/*from   w  w  w.j a  va  2s .  com*/
    HttpMethod method = msg.method();
    try {
        router.route(method, uri).target().invokeExact(ctx, msg);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
    }

}

From source file:com.whizzosoftware.hobson.hub.websockets.Authorizer.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest message) throws Exception {
    logger.trace("channelRead0: {}", message);

    // attempt to get token from header and then from cookie
    String token = null;/*from   w w w  . j  a  va2 s. co  m*/
    String h = HttpHeaders.getHeader(message, "Authorization");
    if (h != null && h.startsWith("Bearer ") && h.length() > 7) {
        token = h.substring(7, h.length()).trim();
    } else {
        h = HttpHeaders.getHeader(message, "Cookie");
        if (h != null) {
            Set<Cookie> cookies = CookieDecoder.decode(h);
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if ("Token".equalsIgnoreCase(c.getName())) {
                        token = c.getValue();
                    }
                }
            }
        }
    }

    // if we found a token, process the message
    if (token != null) {
        try {
            HobsonUser user = accessManager.authenticate(token);
            accessManager.authorize(user, AuthorizationAction.HUB_READ, null);
            if (user != null) {
                logger.trace("Found token, passing message along");
                ctx.fireChannelRead(message.retain());
            }
        } catch (Exception e) {
            logger.debug("Token decryption error", e);
        }
    } else {
        logger.debug("No token found; closing connection");
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.UNAUTHORIZED);
        response.headers().add("Content-Length", 0);
        ctx.writeAndFlush(response);
        ctx.close();
    }
}

From source file:etcd.client.HttpClient.java

License:Open Source License

private void send(Iterator<ServerList.Server> serverIterator, FullHttpRequest request,
        Consumer<Response> completionHandler) {
    final ServerList.Server server = serverIterator.next();
    final URI address = server.getAddress();
    final ChannelFuture connectFuture = bootstrap.connect(address.getHost(), address.getPort());
    final FullHttpRequest requestCopy = request.copy();
    requestCopy.retain();
    final Channel channel = connectFuture.channel();
    channel.attr(REQUEST_KEY).set(requestCopy);
    channel.attr(ATTRIBUTE_KEY).set(completionHandler);
    connectFuture.addListener((future) -> {
        if (future.isSuccess()) {
            channel.writeAndFlush(request);
        } else {//  w ww  .  ja va2  s.  c o  m
            server.connectionFailed();
            if (autoReconnect && serverIterator.hasNext()) {
                send(serverIterator, request, completionHandler);
            } else {
                invokeCompletionHandler(completionHandler,
                        new Response(null, new EtcdException(future.cause())));
            }
        }
    });
}

From source file:io.termd.core.http.netty.HttpRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (wsUri.equalsIgnoreCase(request.getUri())) {
        ctx.fireChannelRead(request.retain());
    } else {//from www . j  av a  2s .c  o m
        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);
        }

        HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(),
                HttpResponseStatus.INTERNAL_SERVER_ERROR);

        String path = request.getUri();
        if ("/".equals(path)) {
            path = "/index.html";
        }
        URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path);
        try {
            if (res != null) {
                DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(),
                        HttpResponseStatus.OK);
                InputStream in = res.openStream();
                byte[] tmp = new byte[256];
                for (int l = 0; l != -1; l = in.read(tmp)) {
                    fullResp.content().writeBytes(tmp, 0, l);
                }
                int li = path.lastIndexOf('.');
                if (li != -1 && li != path.length() - 1) {
                    String ext = path.substring(li + 1, path.length());
                    String contentType;
                    switch (ext) {
                    case "html":
                        contentType = "text/html";
                        break;
                    case "js":
                        contentType = "application/javascript";
                        break;
                    default:
                        contentType = null;
                        break;
                    }
                    if (contentType != null) {
                        fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
                    }
                }
                response = fullResp;
            } else {
                response.setStatus(HttpResponseStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.write(response);
            ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }
}

From source file:io.urmia.job.codec.JobDecoder.java

License:Open Source License

public void decode(final ChannelHandlerContext ctx, HttpObject msg, List out) {

    log.debug("decoding: {} on ctx: {}", msg, ctx);

    if (!(msg instanceof FullHttpRequest)) {
        log.warn("input to JobDecoder is not FullHttpReq: {}", msg);
        return;//from www. j  av  a2  s  .c  om
    }

    final FullHttpRequest httpReq = (FullHttpRequest) msg;

    final JobRequest jobRequest = decode(httpReq);

    log.info("returning {} -> {}", httpReq.getUri(), jobRequest);

    //noinspection unchecked
    out.add(jobRequest);

    httpReq.retain(); // need the content
}

From source file:net.anyflow.menton.http.HttpRequestRouter.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE))
            && HttpHeaderValues.UPGRADE.toString()
                    .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) {

        if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) {
            logger.error("No WebSocket Handler available.");

            ctx.channel()/*from  w w  w .  j ava  2  s  . c om*/
                    .writeAndFlush(
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN))
                    .addListener(ChannelFutureListener.CLOSE);
            return;
        }

        ctx.fireChannelRead(request.retain());
        return;
    }

    if (HttpUtil.is100ContinueExpected(request)) {
        ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        return;
    }

    HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE));

    String requestPath = new URI(request.uri()).getPath();

    if (isWebResourcePath(requestPath)) {
        handleWebResourceRequest(ctx, request, response, requestPath);
    } else {
        try {
            processRequest(ctx, request, response);
        } catch (URISyntaxException e) {
            response.setStatus(HttpResponseStatus.NOT_FOUND);
            logger.info("unexcepted URI : {}", request.uri());
        } catch (Exception e) {
            response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
            logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e);
        }
    }
}

From source file:net.holmes.core.service.http.HttpFileRequestDecoder.java

License:Open Source License

/**
 * {@inheritDoc}/*  www . ja v  a2 s.  com*/
 */
@Override
protected void decode(ChannelHandlerContext context, FullHttpRequest request, List<Object> out) {
    HttpFileRequest fileRequest = null;
    if (request.getMethod().equals(GET)) {
        QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
        if (decoder.path().startsWith(HTTP_CONTENT_REQUEST_PATH.toString())
                && decoder.parameters().get(HTTP_CONTENT_ID.toString()) != null) {
            // Request for a content file is valid if content is found in media index
            AbstractNode node = mediaManager
                    .getNode(decoder.parameters().get(HTTP_CONTENT_ID.toString()).get(0));
            if (node instanceof ContentNode) {
                ContentNode contentNode = (ContentNode) node;
                fileRequest = new HttpFileRequest(request, new File(contentNode.getPath()),
                        contentNode.getMimeType(), false);
            }
        } else {
            // Request for UI static file is valid if requested file name has a correct mime type
            String fileName = getFileName(decoder);
            MimeType mimeType = mimeTypeManager.getMimeType(fileName);
            if (mimeType != null) {
                fileRequest = new HttpFileRequest(request, new File(uiDirectory, fileName), mimeType, true);
            }
        }
    }

    if (fileRequest != null) {
        // Add file request to message list
        out.add(fileRequest);
    } else {
        // Forward request to pipeline
        request.retain();
        out.add(request);
    }
}