Example usage for io.netty.channel ChannelHandlerContext pipeline

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

Introduction

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

Prototype

ChannelPipeline pipeline();

Source Link

Document

Return the assigned ChannelPipeline

Usage

From source file:org.apache.hadoop.hdfs.server.datanode.web.URLDispatcher.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
    String uri = req.getUri();//from ww  w  .  j a  v  a  2  s. com
    ChannelPipeline p = ctx.pipeline();
    if (uri.startsWith(WEBHDFS_PREFIX)) {
        WebHdfsHandler h = new WebHdfsHandler(conf, confForCreate);
        p.replace(this, WebHdfsHandler.class.getSimpleName(), h);
        h.channelRead0(ctx, req);
    } else {
        SimpleHttpProxyHandler h = new SimpleHttpProxyHandler(proxyHost);
        p.replace(this, SimpleHttpProxyHandler.class.getSimpleName(), h);
        h.channelRead0(ctx, req);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.webhdfs.WebHdfsHandler.java

License:Apache License

private void onCreate(ChannelHandlerContext ctx) throws IOException, URISyntaxException {
    writeContinueHeader(ctx);//  w w  w.  j a  va  2  s  .co m

    final String nnId = params.namenodeId();
    final int bufferSize = params.bufferSize();
    final short replication = params.replication();
    final long blockSize = params.blockSize();
    final FsPermission permission = params.permission();

    EnumSet<CreateFlag> flags = params.overwrite() ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
            : EnumSet.of(CreateFlag.CREATE);

    final DFSClient dfsClient = newDfsClient(nnId, confForCreate);
    OutputStream out = dfsClient.createWrappedOutputStream(
            dfsClient.create(path, permission, flags, replication, blockSize, null, bufferSize, null, null),
            null);
    DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, CREATED);

    final URI uri = new URI(HDFS_URI_SCHEME, nnId, path, null, null);
    resp.headers().set(LOCATION, uri.toString());
    resp.headers().set(CONTENT_LENGTH, 0);
    ctx.pipeline().replace(this, HdfsWriter.class.getSimpleName(), new HdfsWriter(dfsClient, out, resp));
}

From source file:org.apache.hadoop.hdfs.server.datanode.web.webhdfs.WebHdfsHandler.java

License:Apache License

private void onAppend(ChannelHandlerContext ctx) throws IOException {
    writeContinueHeader(ctx);//from  ww  w. j av  a  2 s .  c  om
    final String nnId = params.namenodeId();
    final int bufferSize = params.bufferSize();

    DFSClient dfsClient = newDfsClient(nnId, conf);
    OutputStream out = dfsClient.append(path, bufferSize, EnumSet.of(CreateFlag.APPEND), null, null);
    DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, OK);
    resp.headers().set(CONTENT_LENGTH, 0);
    ctx.pipeline().replace(this, HdfsWriter.class.getSimpleName(), new HdfsWriter(dfsClient, out, resp));
}

From source file:org.apache.jackrabbit.oak.plugins.segment.standby.client.StandbyClientHandler.java

License:Apache License

synchronized void setHead(ChannelHandlerContext ctx, RecordId head) {
    if (store.getHead().getRecordId().equals(head)) {
        // all sync'ed up
        log.debug("no changes on sync.");
        return;/*from   w  w  w. j a  v a2 s  .  c o m*/
    }

    log.debug("updating current head to " + head);
    ctx.pipeline().remove(ReadTimeoutHandler.class);
    ctx.pipeline().remove(RecordIdDecoder.class);
    ctx.pipeline().remove(this);
    ctx.pipeline().addLast(new ReplyDecoder(store));

    ctx.pipeline().addLast(
            new SegmentLoaderHandler(store, head, this.observer.getID(), running, readTimeoutMs, autoClean));
    ctx.pipeline().fireUserEventTriggered("sync");
}

From source file:org.apache.tajo.HttpFileServerHandler.java

License:Apache License

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

    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;/*from  ww w  .  jav a2s.  c  om*/
    }

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

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

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

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response);

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

    // Write the content.
    ChannelFuture writeFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ctx.write(region);
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        writeFuture.addListener(new ChannelProgressiveFutureListener() {
            @Override
            public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                    throws Exception {
                LOG.trace(String.format("%s: %d / %d", path, progress, total));
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                region.release();
            }
        });
    }

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

From source file:org.apache.tajo.pullserver.HttpDataServerHandler.java

License:Apache License

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

    if (request.getMethod() != HttpMethod.GET) {
        sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;//from w  w w  .ja va  2s. c  om
    }

    String base = ContainerLocalizer.USERCACHE + "/" + userName + "/" + ContainerLocalizer.APPCACHE + "/"
            + appId + "/output" + "/";

    final Map<String, List<String>> params = new QueryStringDecoder(request.getUri()).parameters();

    List<FileChunk> chunks = Lists.newArrayList();
    List<String> taskIds = splitMaps(params.get("ta"));
    int sid = Integer.valueOf(params.get("sid").get(0));
    int partitionId = Integer.valueOf(params.get("p").get(0));
    for (String ta : taskIds) {

        File file = new File(base + "/" + sid + "/" + ta + "/output/" + partitionId);
        FileChunk chunk = new FileChunk(file, 0, file.length());
        chunks.add(chunk);
    }

    FileChunk[] file = chunks.toArray(new FileChunk[chunks.size()]);

    // Write the content.
    if (file == null) {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        if (!HttpHeaders.isKeepAlive(request)) {
            ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            ctx.writeAndFlush(response);
        }
    } else {
        HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        ChannelFuture writeFuture = null;
        long totalSize = 0;
        for (FileChunk chunk : file) {
            totalSize += chunk.length();
        }
        HttpHeaders.setContentLength(response, totalSize);

        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        // Write the initial line and the header.
        writeFuture = ctx.write(response);

        for (FileChunk chunk : file) {
            writeFuture = sendFile(ctx, chunk);
            if (writeFuture == null) {
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }
        }
        if (ctx.pipeline().get(SslHandler.class) == null) {
            writeFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            ctx.flush();
        }

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

}

From source file:org.apache.tajo.pullserver.HttpDataServerHandler.java

License:Apache License

private ChannelFuture sendFile(ChannelHandlerContext ctx, FileChunk file) throws IOException {
    RandomAccessFile raf;//  w w w.j  a va 2  s .c o  m
    try {
        raf = new RandomAccessFile(file.getFile(), "r");
    } catch (FileNotFoundException fnfe) {
        return null;
    }

    ChannelFuture writeFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) != null) {
        // Cannot use zero-copy with HTTPS.
        lastContentFuture = ctx
                .write(new HttpChunkedInput(new ChunkedFile(raf, file.startOffset(), file.length(), 8192)));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length());
        writeFuture = ctx.write(region);
        lastContentFuture = ctx.write(LastHttpContent.EMPTY_LAST_CONTENT);
        writeFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (region.refCnt() > 0) {
                    region.release();
                }
            }
        });
    }

    return lastContentFuture;
}

From source file:org.apache.tajo.rpc.MonitorClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // Initialize the message.
    ping = ctx.alloc().buffer(RpcConstants.PING_PACKET.length())
            .writeBytes(RpcConstants.PING_PACKET.getBytes(Charset.defaultCharset()));
    IdleStateHandler handler = ctx.pipeline().get(IdleStateHandler.class);
    if (handler != null && handler.getWriterIdleTimeInMillis() > 0) {
        enableMonitor = true;//  ww w .j a  v a  2  s  . c  om
    }
    super.channelActive(ctx);
}

From source file:org.apache.tajo.ws.rs.netty.NettyRestHandlerContainer.java

License:Apache License

private URI getBaseUri(ChannelHandlerContext ctx, FullHttpRequest request) {
    URI baseUri;//from w  w  w  .  j a v a  2 s . c om
    String scheme;

    if (ctx.pipeline().get(SslHandler.class) == null) {
        scheme = "http";
    } else {
        scheme = "https";
    }

    List<String> hosts = request.headers().getAll(HttpHeaders.Names.HOST);
    try {
        if (hosts != null && hosts.size() > 0) {
            baseUri = new URI(scheme + "://" + hosts.get(0) + rootPath);
        } else {
            InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
            baseUri = new URI(scheme, null, localAddress.getHostName(), localAddress.getPort(), rootPath, null,
                    null);
        }
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }

    return baseUri;
}

From source file:org.apache.tinkerpop.gremlin.server.handler.SaslAndHttpBasicAuthenticationHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object obj) throws Exception {
    if (obj instanceof HttpMessage && !WebSocketHandlerUtil.isWebSocket((HttpMessage) obj)) {
        if (null == ctx.pipeline().get(HTTP_AUTH)) {
            ctx.pipeline().addAfter(PIPELINE_AUTHENTICATOR, HTTP_AUTH,
                    new HttpBasicAuthenticationHandler(authenticator, this.authenticationSettings));
        }/* w  w w . j  av a2  s  . c om*/
        ctx.fireChannelRead(obj);
    } else {
        super.channelRead(ctx, obj);
    }
}