Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext channel.

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:code.google.nfs.rpc.netty4.client.Netty4ClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ResponseWrapper) {
        ResponseWrapper response = (ResponseWrapper) msg;
        if (isDebugEnabled) {
            // for performance trace
            LOGGER.debug("receive response list from server: " + ctx.channel().remoteAddress() + ",request is:"
                    + response.getRequestId());
        }//from  w w  w . j a v a2 s .co m
        client.putResponse(response);
    } else {
        LOGGER.error("receive message error,only support List || ResponseWrapper");
        throw new Exception("receive message error,only support List || ResponseWrapper");
    }

}

From source file:code.google.nfs.rpc.netty4.server.Netty4ServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    RequestWrapper request = (RequestWrapper) msg;
    long beginTime = System.currentTimeMillis();
    ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType())
            .handleRequest(request);//from w  ww. ja  v a  2s  .  c o m
    final int id = request.getId();
    // already timeout,so not return
    if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
        LOGGER.warn("timeout,so give up send response to client,requestId is:" + id + ",client is:"
                + ctx.channel().remoteAddress() + ",consumetime is:" + (System.currentTimeMillis() - beginTime)
                + ",timeout is:" + request.getTimeout());
        return;
    }
    ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
    wf.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("server write response error,request id is: " + id);
            }
        }
    });
}

From source file:com.addthis.hydra.query.aggregate.MeshSourceAggregator.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    if (msg instanceof DataChannelOutput) {
        queryPromise = (ChannelProgressivePromise) promise;
        consumer = (DataChannelOutput) msg;
        AggregateConfig.totalQueries.inc();
        queryPromise.addListener(this);
        meshQueryMaster.allocators().allocateQueryTasks(query, taskSources, meshy, queryOptions);
        queryTask = new QueryTask(this);
        if (ctx.channel().isWritable()) {
            channelWritable = true;/*from w  w w  . j  a  v  a2  s . co  m*/
            executor.execute(queryTask);
        }
        maybeScheduleStragglerChecks();
    } else if (msg instanceof DetailedStatusTask) {
        DetailedStatusTask task = (DetailedStatusTask) msg;
        task.run(this);
    } else {
        super.write(ctx, msg, promise);
    }
}

From source file:com.addthis.hydra.query.aggregate.MeshSourceAggregator.java

License:Apache License

@Override
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
    channelWritable = ctx.channel().isWritable();
    if (channelWritable && needScheduling) {
        executor.execute(queryTask);/*from  w  w  w.  j a va 2  s.  c  om*/
    }
}

From source file:com.addthis.hydra.query.loadbalance.HttpQueryCallHandler.java

License:Apache License

/**
 * special handler for query// w w w.jav a 2  s .  c o  m
 */
public static ChannelFuture handleQuery(ChannelHandler queryToQueryResultsEncoder, KVPairs kv,
        HttpRequest request, ChannelHandlerContext ctx, EventExecutor executor) throws Exception {
    String job = kv.getValue("job");
    String path = kv.getValue("path", kv.getValue("q", ""));
    Query query = new Query(job, new String[] { path },
            new String[] { kv.getValue("ops"), kv.getValue("rops") });
    query.setTraced(kv.getIntValue("trace", 0) == 1);
    query.setParameterIfNotYetSet("hosts", kv.getValue("hosts"));
    query.setParameterIfNotYetSet("gate", kv.getValue("gate"));
    query.setParameterIfNotYetSet("originalrequest", kv.getValue("originalrequest"));
    SocketAddress remoteIP = ctx.channel().remoteAddress();
    if (remoteIP instanceof InetSocketAddress) { // only log implementations with known methods
        query.setParameterIfNotYetSet("remoteip", ((InetSocketAddress) remoteIP).getAddress().getHostAddress());
    }
    query.setParameterIfNotYetSet("allocator", kv.getValue("allocator"));
    query.setParameterIfNotYetSet("allowPartial", kv.getValue("allowPartial"));

    String filename = kv.getValue("filename", "query");
    String format = kv.getValue("format", "json");
    String gdriveAccessToken = kv.getValue("accesstoken");
    int timeout = Math.min(kv.getIntValue("timeout", maxQueryTime), maxQueryTime);
    query.setParameterIfNotYetSet("timeout", timeout);
    query.setParameter("sender", kv.getValue("sender"));

    if (log.isDebugEnabled()) {
        log.debug(new StringMapHelper().put("type", "query.starting").put("query.path", query.getPaths()[0])
                .put("query.hosts", query.getParameter("hosts")).put("query.ops", query.getOps())
                .put("trace", query.isTraced()).put("sources", query.getParameter("sources"))
                .put("time", System.currentTimeMillis()).put("job.id", query.getJob())
                .put("query.id", query.uuid()).put("sender", query.getParameter("sender")).put("format", format)
                .put("filename", filename).put("originalrequest", query.getParameter("originalrequest"))
                .put("timeout", query.getParameter("timeout")).put("requestIP", query.getParameter("remoteip"))
                .put("allocator", query.getParameter("allocator"))
                .put("allowPartial", query.getParameter("allowPartial")).createKVPairs().toString());
    }
    // support legacy async query semantics
    query = LegacyHandler.handleQuery(query, kv, request, ctx);
    if (query == null) {
        return ctx.newSucceededFuture();
    }

    if (query.getJob() == null) {
        sendError(ctx, new HttpResponseStatus(500, "missing job"));
        return ctx.newSucceededFuture();
    }
    switch (format) {
    case "json":
        ctx.pipeline().addLast(executor, "format", new JsonBundleEncoder());
        break;
    case "html":
        ctx.pipeline().addLast(executor, "format", new HtmlBundleEncoder());
        break;
    case "gdrive":
        ctx.pipeline().addLast(executor, "stringer", stringer);
        ctx.pipeline().addLast(executor, "format",
                GoogleDriveBundleEncoder.create(filename, gdriveAccessToken));
        break;
    default:
        ctx.pipeline().addLast(executor, "format", DelimitedBundleEncoder.create(filename, format));
        break;
    }
    ctx.pipeline().addLast(executor, "mqm", queryToQueryResultsEncoder);
    return ctx.pipeline().write(query, new DefaultChannelProgressivePromise(ctx.channel(), executor));
}

From source file:com.addthis.hydra.query.loadbalance.NextQueryTask.java

License:Apache License

private static void sendDetailedError(ChannelHandlerContext ctx, Throwable cause) {
    if (cause == null) {
        cause = new RuntimeException("query failed for unknown reasons");
    }//from w w  w.  j av a 2 s  . co m
    String reasonPhrase = cause.getMessage();
    HttpResponseStatus responseStatus;
    try {
        responseStatus = new HttpResponseStatus(500, reasonPhrase);
    } catch (NullPointerException | IllegalArgumentException ignored) {
        reasonPhrase = cause.getClass().getSimpleName();
        responseStatus = new HttpResponseStatus(500, reasonPhrase);
    }
    String detailPhrase = logAndFormatErrorDetail(cause);
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus,
            Unpooled.copiedBuffer(detailPhrase + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    log.trace("issuing error of {}", responseStatus);

    // Close the connection as soon as the error message is sent.
    ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

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

License:Apache License

/**
 * special handler for query// w  w w  . ja  v a  2s.  c om
 */
public static ChannelFuture handleQuery(ChannelHandler queryToQueryResultsEncoder, KVPairs kv,
        HttpRequest request, ChannelHandlerContext ctx, EventExecutor executor) throws Exception {
    String job = kv.getValue("job");
    // support either job=id/dir or job=id&dir=dir for convenience (and don't punish doing both)
    String dir = kv.getValue("dir");
    if ((dir != null) && !job.endsWith(dir)) {
        String[] jobs = job.split(",");
        String[] dirs = dir.split(",");
        job = Arrays.stream(jobs).flatMap(subJob -> Arrays.stream(dirs).map(subDir -> subJob + '/' + subDir))
                .collect(Collectors.joining(","));
    }
    String path = kv.getValue("path", kv.getValue("q", ""));
    Query query = new Query(job, new String[] { path },
            new String[] { kv.getValue("ops"), kv.getValue("rops") });
    query.setTraced(kv.getIntValue("trace", 0) == 1);
    query.setParameterIfNotYetSet("hosts", kv.getValue("hosts"));
    query.setParameterIfNotYetSet("gate", kv.getValue("gate"));
    query.setParameterIfNotYetSet("originalrequest", kv.getValue("originalrequest"));
    SocketAddress remoteIP = ctx.channel().remoteAddress();
    if (remoteIP instanceof InetSocketAddress) { // only log implementations with known methods
        query.setParameterIfNotYetSet("remoteip", ((InetSocketAddress) remoteIP).getAddress().getHostAddress());
    }
    query.setParameterIfNotYetSet("allocator", kv.getValue("allocator"));
    query.setParameterIfNotYetSet("allowPartial", kv.getValue("allowPartial"));
    query.setParameterIfNotYetSet("tasks", kv.getValue("tasks"));

    String filename = kv.getValue("filename", "query");
    String format = kv.getValue("format", "json");
    String gdriveAccessToken = kv.getValue("accesstoken");
    int timeout = Math.min(kv.getIntValue("timeout", maxQueryTime), maxQueryTime);
    query.setParameterIfNotYetSet("timeout", timeout);
    query.setParameter("sender", kv.getValue("sender"));
    query.setParameter("injectSource", kv.getValue("injectSource"));

    if (log.isDebugEnabled()) {
        log.debug(new StringMapHelper().put("type", "query.starting").put("query.path", query.getPaths()[0])
                .put("query.hosts", query.getParameter("hosts")).put("query.ops", query.getOps())
                .put("trace", query.isTraced()).put("sources", query.getParameter("sources"))
                .put("time", System.currentTimeMillis()).put("job.id", query.getJob())
                .put("query.id", query.uuid()).put("sender", query.getParameter("sender")).put("format", format)
                .put("filename", filename).put("originalrequest", query.getParameter("originalrequest"))
                .put("timeout", query.getParameter("timeout")).put("requestIP", query.getParameter("remoteip"))
                .put("allocator", query.getParameter("allocator"))
                .put("allowPartial", query.getParameter("allowPartial"))
                .put("tasks", query.getParameter("tasks")).createKVPairs().toString());
    }
    // support legacy async query semantics
    query = LegacyHandler.handleQuery(query, kv, request, ctx);
    if (query == null) {
        return ctx.newSucceededFuture();
    }

    if (query.getJob() == null) {
        sendError(ctx, new HttpResponseStatus(500, "missing job"));
        return ctx.newSucceededFuture();
    }
    switch (format) {
    case "json":
        ctx.pipeline().addLast(executor, "format", new JsonBundleEncoder());
        break;
    case "html":
        ctx.pipeline().addLast(executor, "format", new HtmlBundleEncoder());
        break;
    case "gdrive":
        ctx.pipeline().addLast(executor, "stringer", stringer);
        ctx.pipeline().addLast(executor, "format",
                GoogleDriveBundleEncoder.create(filename, gdriveAccessToken));
        break;
    case "csv2":
    case "psv2":
    case "tsv2":
        ctx.pipeline().addLast(executor, "format", DelimitedEscapedBundleEncoder.create(filename, format));
        break;
    default:
        ctx.pipeline().addLast(executor, "format", DelimitedBundleEncoder.create(filename, format));
        break;
    }
    ctx.pipeline().addLast(executor, "mqm", queryToQueryResultsEncoder);
    return ctx.pipeline().write(query, new DefaultChannelProgressivePromise(ctx.channel(), executor));
}

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

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    log.warn("Exception caught while serving http query endpoint", cause);
    if (ctx.channel().isActive()) {
        sendError(ctx, new HttpResponseStatus(500, cause.getMessage()));
    }/*from  w w w  .java2  s .co m*/
}

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

License:Apache License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    log.warn("Exception caught while serving static files", cause);
    if (ctx.channel().isActive()) {
        sendError(ctx, INTERNAL_SERVER_ERROR);
    }//w  w  w  . ja  v a 2s  . co  m
}

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

License:Apache License

public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status,
            Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
    response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
    log.trace("issuing error of {}", status);

    // Close the connection as soon as the error message is sent.
    ctx.channel().writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}