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:diskCacheV111.doors.NettyLineBasedDoor.java

License:Open Source License

@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    ChannelPipeline pipeline = ctx.pipeline();
    String self = ctx.name();//from  ww  w. j  a v a2s.c o  m

    if (expectProxyProtocol) {
        pipeline.addBefore("door", "haproxy", new HAProxyMessageDecoder());
    }

    // Decoders
    pipeline.addBefore(self, "frameDecoder", new LineBasedFrameDecoder(KiB.toBytes(64)));
    pipeline.addBefore(self, "stringDecoder", new StringDecoder(charset));

    // Encoder
    pipeline.addBefore(self, "lineEncoder", new LineEncoder(lineSeparator, charset));

    pipeline.addBefore(self, "logger", new LoggingHandler());
}

From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandlerServerTCP.java

License:Apache License

/**
 * STEP 3-XXXXX: We pass registration messages around until we the registration handshake is complete!
 *///from   w w w  .j av a  2 s  . com
@SuppressWarnings("Duplicates")
@Override
public void channelRead(ChannelHandlerContext context, Object message) throws Exception {
    Channel channel = context.channel();

    if (message instanceof Registration) {
        Registration registration = (Registration) message;

        MetaChannel metaChannel;
        int sessionId = registration.sessionID;
        if (sessionId == 0) {
            metaChannel = registrationWrapper.createSessionServer();
            metaChannel.tcpChannel = channel;
            // TODO: use this: channel.voidPromise();
            logger.debug("New TCP connection. Saving meta-channel id: {}", metaChannel.sessionId);
        } else {
            metaChannel = registrationWrapper.getSession(sessionId);

            if (metaChannel == null) {
                logger.error("Error getting invalid TCP channel session ID {}! MetaChannel is null!",
                        sessionId);
                shutdown(channel, sessionId);
                return;
            }
        }

        readServer(context, channel, registration, "TCP server", metaChannel);
    } else {
        logger.error("Error registering TCP with remote client!");

        // this is what happens when the registration happens too quickly...
        Object connection = context.pipeline().last();
        if (connection instanceof ConnectionImpl) {
            ((ConnectionImpl) connection).channelRead(context, message);
        } else {
            shutdown(channel, 0);
        }
    }
}

From source file:dorkbox.network.connection.registration.remote.RegistrationRemoteHandlerServerUDP.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext context, Object message) throws Exception {
    Channel channel = context.channel();

    if (message instanceof Registration) {
        Registration registration = (Registration) message;

        MetaChannel metaChannel;/*from www .j ava 2s . com*/
        int sessionId = 0;
        sessionId = registration.sessionID;
        if (sessionId == 0) {
            metaChannel = registrationWrapper.createSessionServer();
            metaChannel.udpChannel = channel;
            logger.debug("New UDP connection. Saving meta-channel id: {}", metaChannel.sessionId);
        } else {
            metaChannel = registrationWrapper.getSession(sessionId);

            if (metaChannel == null) {
                logger.error("Error getting invalid UDP channel session ID {}! MetaChannel is null!",
                        sessionId);
                shutdown(channel, sessionId);
                return;
            }

            // in the event that we start with a TCP channel first, we still have to set the UDP channel
            metaChannel.udpChannel = channel;
        }

        readServer(context, channel, registration, "UDP server", metaChannel);
    } else {
        logger.error("Error registering UDP with remote client!");

        // this is what happens when the registration happens too quickly...
        Object connection = context.pipeline().last();
        if (connection instanceof ConnectionImpl) {
            ((ConnectionImpl) connection).channelRead(context, message);
        } else {
            shutdown(channel, 0);
        }
    }
}

From source file:dorkbox.network.pipeline.tcp.KryoDecoderCrypto.java

License:Apache License

@Override
protected Object readObject(final NetworkSerializationManager serializationManager,
        final ChannelHandlerContext context, final ByteBuf in, final int length) throws Exception {

    try {/*ww w .j  a  v  a 2s  .c o  m*/
        Connection_ connection = (Connection_) context.pipeline().last();
        return serializationManager.readWithCrypto(connection, in, length);
    } catch (Exception e) {
        throw e;
    }
}

From source file:dorkbox.network.pipeline.tcp.KryoEncoderCrypto.java

License:Apache License

@Override
protected void writeObject(final NetworkSerializationManager serializationManager,
        final ChannelHandlerContext context, final Object msg, final ByteBuf buffer) throws IOException {

    Connection_ connection = (Connection_) context.pipeline().last();
    serializationManager.writeWithCrypto(connection, buffer, msg);
}

From source file:dorkbox.network.pipeline.udp.KryoDecoderUdpCrypto.java

License:Apache License

@Override
public void decode(ChannelHandlerContext context, DatagramPacket in, List<Object> out) throws Exception {
    try {//from   w w w  .jav  a  2  s  .  c  o m
        Connection_ last = (Connection_) context.pipeline().last();
        ByteBuf data = in.content();
        Object object = serializationManager.readWithCrypto(last, data, data.readableBytes());
        out.add(object);
    } catch (IOException e) {
        String message = "Unable to deserialize object";
        LoggerFactory.getLogger(this.getClass()).error(message, e);
        throw new IOException(message, e);
    }
}

From source file:dorkbox.network.pipeline.udp.KryoEncoderUdpCrypto.java

License:Apache License

@Override
void writeObject(NetworkSerializationManager serializationManager, ChannelHandlerContext ctx, Object msg,
        ByteBuf buffer) throws IOException {

    Connection_ last = (Connection_) ctx.pipeline().last();
    serializationManager.writeWithCrypto(last, buffer, msg);
}

From source file:dpfmanager.shell.modules.server.core.HttpServerHandler.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // Will use the first five bytes to detect a protocol.
    if (in.readableBytes() < 5) {
        in.clear();//from w  w  w .j a  v  a 2  s  .  co m
        ctx.close();
        return;
    }

    final int magic1 = in.getUnsignedByte(in.readerIndex());
    final int magic2 = in.getUnsignedByte(in.readerIndex() + 1);
    if (isPost(magic1, magic2) || isOptions(magic1, magic2)) {
        // POST
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.addLast(new HttpRequestDecoder());
        pipeline.addLast(new HttpResponseEncoder());
        pipeline.addLast(new HttpPostHandler(context));
        pipeline.remove(this);
    } else if (isGet(magic1, magic2)) {
        // GET
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(65536));
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpGetHandler(context));
        pipeline.remove(this);
    } else {
        in.clear();
        ctx.close();
    }
}

From source file:dpfmanager.shell.modules.server.get.HttpGetHandler.java

License:Open Source License

/**
 * Main functions/*from  w w w.j a v  a 2s.c  o  m*/
 */

private void tractReadGet(ChannelHandlerContext ctx, String zipPath) {
    // Parse params
    String path = DPFManagerProperties.getReportsDir() + zipPath;
    if (!zipPath.endsWith(".zip")) {
        String hash = zipPath.substring(1, zipPath.length());
        StatusMessage sm = (StatusMessage) context.sendAndWaitResponse(BasicConfig.MODULE_DATABASE,
                new PostMessage(PostMessage.Type.ASK, hash));
        path = sm.getFolder().substring(0, sm.getFolder().length() - 1) + ".zip";
    }

    // Send the zip report
    File file = new File(path);
    if (file.exists()) {
        try {
            RandomAccessFile raf = new RandomAccessFile(file, "r");

            long fileLength = raf.length();

            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            HttpUtil.setContentLength(response, fileLength);
            setContentTypeHeader(response, file);
            setDateAndCacheHeaders(response, file);
            response.headers().remove(HttpHeaderNames.CONNECTION);

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

            // Write the content.
            ChannelFuture lastContentFuture;
            if (ctx.pipeline().get(SslHandler.class) == null) {
                ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
                // Write the end marker.
                lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            } else {
                lastContentFuture = ctx.writeAndFlush(
                        new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                        ctx.newProgressivePromise());
            }

            // Delete the zip after download?
            lastContentFuture.addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    //            file.delete();
                }
            });
            // Decide whether to close the connection or not.
            if (!HttpUtil.isKeepAlive(request)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (Exception ignore) {
            sendError(ctx, NOT_FOUND);
        }
    } else {
        // No exists
        sendError(ctx, NOT_FOUND);
    }
}

From source file:eu.jangos.realm.network.handler.CharacterHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    // Let's refuse any packed for non-authed clients.
    if (ctx.channel().attr(AUTH).get() != AuthStep.STEP_AUTHED) {
        return;/*from  w w  w. j  a  v a 2 s.  c om*/
    }

    AbstractRealmClientPacket request = (AbstractRealmClientPacket) msg;

    AbstractRealmServerPacket response = null;

    logger.info(msg.toString());

    switch (request.getOpcode()) {
    case CMSG_PING:
        response = new SMSG_PING(Opcodes.SMSG_PING);

        int ping = ((CMSG_PING) request).getPing();

        ((SMSG_PING) response).setPing(ping);

        break;
    case CMSG_CHAR_ENUM:
        response = new SMSG_CHAR_ENUM(Opcodes.SMSG_CHAR_ENUM);

        // Adding character list.
        ((SMSG_CHAR_ENUM) response)
                .addCharacters(characterService.getCharactersForAccount(ctx.channel().attr(ACCOUNT).get()));

        break;
    case CMSG_CHAR_CREATE:
        response = new SMSG_CHAR_CREATE(Opcodes.SMSG_CHAR_CREATE);

        ((SMSG_CHAR_CREATE) response).setResult(characterService.createChar(
                ((CMSG_CHAR_CREATE) request).getName(), ((CMSG_CHAR_CREATE) request).getRace(),
                ((CMSG_CHAR_CREATE) request).getCharClass(), ((CMSG_CHAR_CREATE) request).getGender(),
                ((CMSG_CHAR_CREATE) request).getSkin(), ((CMSG_CHAR_CREATE) request).getFace(),
                ((CMSG_CHAR_CREATE) request).getHairStyle(), ((CMSG_CHAR_CREATE) request).getHairColor(),
                ((CMSG_CHAR_CREATE) request).getFacialHair(),
                ctx.pipeline().get(RealmAuthHandler.class).getAccount()));

        break;
    case CMSG_CHAR_DELETE:
        response = new SMSG_CHAR_DELETE(Opcodes.SMSG_CHAR_DELETE);

        ((SMSG_CHAR_DELETE) response)
                .setResult(characterService.deleteChar(((CMSG_CHAR_DELETE) request).getId(),
                        ctx.pipeline().get(RealmAuthHandler.class).getAccount(), false));

        break;

    case CMSG_PLAYER_LOGIN:
        if (characterService.loginChar(((CMSG_PLAYER_LOGIN) request).getId(),
                ctx.pipeline().get(RealmAuthHandler.class).getAccount())) {
            SMSG_LOGIN_VERIFY_WORLD packet = new SMSG_LOGIN_VERIFY_WORLD();

            /**packet.setMap(characterService.getLoggedCharacter().getFkDbcMap());
            packet.setPosX(characterService.getLoggedCharacter().getPositionX());
            packet.setPosY(characterService.getLoggedCharacter().getPositionY());
            packet.setPosZ(characterService.getLoggedCharacter().getPositionZ());
            packet.setOrientation(characterService.getLoggedCharacter().getOrientation());*/

            ctx.write(packet);

            SMSG_ACCOUNT_DATA_TIMES data = new SMSG_ACCOUNT_DATA_TIMES();

            ctx.write(data);

        } else {
            // Kick unknown client.                    
            ctx.close();
        }

        break;

    default:
        logger.error("Packet received, opcode not handled: " + request.getOpcode());
        break;
    }

    if (response != null) {
        ctx.writeAndFlush(response);
    } else {
        // Let pass this to other handlers.
        ctx.fireChannelRead(msg);
    }
}