Example usage for io.netty.util Attribute get

List of usage examples for io.netty.util Attribute get

Introduction

In this page you can find the example usage for io.netty.util Attribute get.

Prototype

T get();

Source Link

Document

Returns the current value, which may be null

Usage

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoder.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {

    DecoderResult result = httpObject.getDecoderResult();
    if (!result.isSuccess()) {
        throw new BadRequestException(result.cause());
    }/*from  w w  w  . ja va 2 s.com*/

    Attribute<UUID> sessionUuidAttr = ctx.channel().attr(AbstractNettyServer.UUID_KEY);

    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;
        LOG.trace("Session: {} got valid HTTP request:\n{}", sessionUuidAttr.get().toString(),
                httpRequest.headers().toString());
        if (httpRequest.getMethod().equals(HttpMethod.POST)) {
            String uri = httpRequest.getUri();
            AbstractCommand cp = (AbstractCommand) commandFactory.getCommandProcessor(uri);
            cp.setSessionUuid(sessionUuidAttr.get());
            cp.setRequest(httpRequest);
            cp.parse();
            ctx.fireChannelRead(cp);
        } else {
            LOG.error("Got invalid HTTP method: expecting only POST");
            throw new BadRequestException(
                    "Incorrect method " + httpRequest.getMethod().toString() + ", expected POST");
        }
    } else {
        LOG.warn("Session: {} got invalid HTTP object:\n{}", sessionUuidAttr.get().toString(), httpObject);
    }
}

From source file:org.kaaproject.kaa.server.transports.http.transport.netty.RequestDecoderTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Before/*from w ww  .  j  a v a  2 s . c om*/
public void setUp() {
    channelHandlerContext = mock(ChannelHandlerContext.class);
    Channel channel = mock(Channel.class);
    Attribute attribute = mock(Attribute.class);
    UUID uuid = new UUID(234L, 1234L);
    when(attribute.get()).thenReturn(uuid);
    when(channel.attr(AbstractNettyServer.UUID_KEY)).thenReturn(attribute);
    when(channelHandlerContext.channel()).thenReturn(channel);
}

From source file:org.lanternpowered.server.network.forge.message.handler.handshake.HandlerForgeHandshakeInAck.java

License:MIT License

@Override
public void handle(NetworkContext context, MessageForgeHandshakeInOutAck message) {
    final NetworkSession session = context.getSession();
    final Attribute<ForgeServerHandshakePhase> phase = context.getChannel().attr(ForgeHandshakePhase.PHASE);
    switch (phase.get()) {
    case WAITING_ACK:
        if (!message.getPhase().equals(ForgeClientHandshakePhase.WAITING_SERVER_DATA)) {
            session.disconnect(t("Retrieved unexpected forge handshake ack message. (Got %s, expected %s)",
                    message.getPhase(), ForgeClientHandshakePhase.WAITING_SERVER_DATA));
        } else {/*  ww  w  .  java  2 s.  c om*/
            final List<MessageForgeHandshakeOutRegistryData.Entry> entries = new ArrayList<>();
            entries.add(new MessageForgeHandshakeOutRegistryData.Entry("minecraft:items", new HashMap<>(),
                    new ArrayList<>()));
            entries.add(new MessageForgeHandshakeOutRegistryData.Entry("minecraft:blocks", new HashMap<>(),
                    new ArrayList<>()));
            session.send(new MessageForgeHandshakeOutRegistryData(entries));
            session.send(new MessageForgeHandshakeInOutAck(ForgeServerHandshakePhase.WAITING_ACK));
            phase.set(ForgeServerHandshakePhase.COMPLETE);
        }
        Lantern.getLogger().info("{}: Forge handshake -> Received ack (waitingServerData) message.",
                session.getGameProfile().getName().get());
        break;
    case COMPLETE:
        if (!message.getPhase().equals(ForgeClientHandshakePhase.WAITING_SERVER_COMPLETE)) {
            session.disconnect(t("Retrieved unexpected forge handshake ack message. (Got %s, expected %s)",
                    message.getPhase(), ForgeClientHandshakePhase.WAITING_SERVER_COMPLETE));
        } else {
            session.send(new MessageForgeHandshakeInOutAck(ForgeServerHandshakePhase.COMPLETE));
            phase.set(ForgeServerHandshakePhase.DONE);
        }
        Lantern.getLogger().info("{}: Forge handshake -> Received ack (waitingServerComplete) message.",
                session.getGameProfile().getName().get());
        break;
    case DONE:
        if (!message.getPhase().equals(ForgeClientHandshakePhase.PENDING_COMPLETE)
                && !message.getPhase().equals(ForgeClientHandshakePhase.COMPLETE)) {
            session.disconnect(
                    t("Retrieved unexpected forge handshake ack message. (Got %s, expected %s or %s)",
                            message.getPhase(), ForgeClientHandshakePhase.PENDING_COMPLETE,
                            ForgeClientHandshakePhase.COMPLETE));
        } else {
            if (message.getPhase().equals(ForgeClientHandshakePhase.PENDING_COMPLETE)) {
                session.send(new MessageForgeHandshakeInOutAck(ForgeServerHandshakePhase.DONE));
                Lantern.getLogger().info("{}: Forge handshake -> Received ack (pendingComplete) message.",
                        session.getGameProfile().getName().get());
            } else {
                session.setProtocolState(ProtocolState.PLAY);
                session.initPlayer();
                Lantern.getLogger().info("{}: Forge handshake -> Received ack (complete) message.",
                        session.getGameProfile().getName().get());
            }
        }
        break;
    case ERROR:
        break;
    default:
        session.disconnect(t("Retrieved unexpected forge handshake ack message. (Got %s)", message.getPhase()));
    }
}

From source file:org.lanternpowered.server.network.forge.message.handler.handshake.HandlerForgeHandshakeInHello.java

License:MIT License

@Override
public void handle(NetworkContext context, MessageForgeHandshakeInOutHello message) {
    final NetworkSession session = context.getSession();
    final Attribute<ForgeServerHandshakePhase> phase = session.getChannel().attr(ForgeHandshakePhase.PHASE);
    if (phase.get() != ForgeServerHandshakePhase.HELLO) {
        session.disconnect(t("Retrieved unexpected forge handshake hello message."));
        return;/*from  w  w  w . j  a va 2s. c om*/
    }
    Lantern.getLogger().info("{}: Forge handshake -> Received hello message.",
            session.getGameProfile().getName().get());
}

From source file:org.lanternpowered.server.network.forge.message.handler.handshake.HandlerForgeHandshakeInModList.java

License:MIT License

@Override
public void handle(NetworkContext context, MessageForgeHandshakeInOutModList message) {
    final NetworkSession session = context.getSession();
    final Attribute<ForgeServerHandshakePhase> phase = context.getChannel().attr(ForgeHandshakePhase.PHASE);
    if (phase.get() != ForgeServerHandshakePhase.HELLO) {
        session.disconnect(t("Retrieved unexpected forge handshake modList message."));
        return;//from   w ww.j  a  v  a2 s .com
    }
    // We don't need to validate the mods for now, maybe in the future, just poke back
    session.getInstalledMods().addAll(message.getEntries().keySet());
    // Just use a empty map for now
    session.send(new MessageForgeHandshakeInOutModList(new HashMap<>()));
    phase.set(ForgeServerHandshakePhase.WAITING_ACK);
    Lantern.getLogger().info("{}: Forge handshake -> Received modList message.",
            session.getGameProfile().getName().get());
}

From source file:org.lanternpowered.server.network.forge.message.handler.handshake.HandlerForgeHandshakeInStart.java

License:MIT License

@Override
public void handle(NetworkContext context, MessageForgeHandshakeInStart message) {
    final Attribute<ForgeServerHandshakePhase> phase = context.getChannel().attr(ForgeHandshakePhase.PHASE);
    final NetworkSession session = context.getSession();
    if (phase.get() != null && phase.get() != ForgeServerHandshakePhase.START) {
        session.disconnect(t("Retrieved unexpected forge handshake start message."));
        return;//  w w  w. j a  v a  2  s .co  m
    }
    final boolean fml = session.getChannel().attr(NetworkSession.FML_MARKER).get();

    final Set<String> channels = new HashSet<>(
            Sponge.getChannelRegistrar().getRegisteredChannels(Platform.Type.SERVER));
    if (fml) {
        channels.add("FML");
        channels.add("FML|HS");
        channels.add("FML|MP");
    }
    if (!channels.isEmpty()) {
        session.send(new MessagePlayInOutRegisterChannels(channels));
    }
    // Disable Forge for now, we need to send the registries and stuff,
    // which isn't actually used. We may also remove the protocol in the
    // future if sponge uses completely it's own protocol.
    if (false && fml) {
        phase.set(ForgeServerHandshakePhase.HELLO);
        session.send(new MessageForgeHandshakeInOutHello());
        Lantern.getLogger().info("{}: Start forge handshake.", session.getGameProfile().getName().get());
    } else {
        Lantern.getLogger().info("{}: Skip forge handshake.", session.getGameProfile().getName().get());
        phase.set(ForgeServerHandshakePhase.DONE);
        session.setProtocolState(ProtocolState.PLAY);
        session.initPlayer();
    }
}

From source file:org.lanternpowered.server.network.vanilla.message.codec.play.AbstractCodecPlayInOutCustomPayload.java

License:MIT License

private Message decode0(CodecContext context, ByteBuffer content, String channel) {
    if ("REGISTER".equals(channel)) {
        Set<String> channels = decodeChannels(content);
        Iterator<String> it = channels.iterator();
        while (it.hasNext()) {
            String channel0 = it.next();
            if (channel0.startsWith("FML")) {
                it.remove();/*  w w w. jav a 2  s.  c o m*/
            }
        }
        if (!channels.isEmpty()) {
            return new MessagePlayInOutRegisterChannels(channels);
        }
    } else if ("UNREGISTER".equals(channel)) {
        Set<String> channels = decodeChannels(content);
        Iterator<String> it = channels.iterator();
        while (it.hasNext()) {
            String channel0 = it.next();
            if (channel0.startsWith("FML")) {
                it.remove();
            }
        }
        if (!channels.isEmpty()) {
            return new MessagePlayInOutUnregisterChannels(channels);
        }
    } else if ("FML|MP".equals(channel)) {
        Attribute<MultiPartMessage> attribute = context.getChannel().attr(FML_MULTI_PART_MESSAGE);
        MultiPartMessage message0 = attribute.get();
        if (message0 == null) {
            String channel0 = content.readString();
            int parts = content.readByte() & 0xff;
            int size = content.readInteger();
            if (size <= 0 || size >= -16797616) {
                throw new CodecException(
                        "Received FML MultiPart packet outside of valid length bounds, Max: -16797616, Received: "
                                + size);
            }
            attribute.set(new MultiPartMessage(channel0, context.byteBufAlloc().buffer(size), parts));
        } else {
            int part = content.readByte() & 0xff;
            if (part != message0.index) {
                throw new CodecException("Received FML MultiPart packet out of order, Expected: "
                        + message0.index + ", Got: " + part);
            }
            int len = content.available() - 1;
            content.readBytes(message0.buffer, message0.offset, len);
            message0.offset += len;
            message0.index++;
            if (message0.index >= message0.parts) {
                final Message message = decode0(context, message0.channel, message0.buffer);
                attribute.set(null);
                return message;
            }
        }
    } else {
        return decode0(context, channel, content);
    }
    return NullMessage.INSTANCE;
}

From source file:org.lanternpowered.server.network.vanilla.message.handler.play.HandlerPlayInChatMessage.java

License:MIT License

@Override
public void handle(NetworkContext context, MessagePlayInChatMessage message) {
    final NetworkSession session = context.getSession();
    final LanternPlayer player = session.getPlayer();
    player.resetIdleTimeoutCounter();/*  w w w. j av a2s .c  om*/
    final String message0 = message.getMessage();

    // Check for a valid click action callback
    final Matcher matcher = LanternClickActionCallbacks.COMMAND_PATTERN.matcher(message0);
    if (matcher.matches()) {
        final UUID uniqueId = UUID.fromString(matcher.group(1));
        final Optional<Consumer<CommandSource>> callback = LanternClickActionCallbacks.get()
                .getCallbackForUUID(uniqueId);
        if (callback.isPresent()) {
            callback.get().accept(player);
        } else {
            player.sendMessage(
                    error(t("The callback you provided was not valid. Keep in mind that callbacks will expire "
                            + "after 10 minutes, so you might want to consider clicking faster next time!")));
        }
        return;
    }

    String message1 = StringUtils.normalizeSpace(message0);
    if (!isAllowedString(message0)) {
        session.disconnect(t("multiplayer.disconnect.illegal_characters"));
        return;
    }
    if (message1.startsWith("/")) {
        Lantern.getSyncExecutorService()
                .submit(() -> Sponge.getCommandManager().process(player, message1.substring(1)));
    } else {
        final Text nameText = player.get(Keys.DISPLAY_NAME).get();
        final Text rawMessageText = Text.of(message0);
        final GlobalConfig.Chat.Urls urls = Lantern.getGame().getGlobalConfig().getChat().getUrls();
        final Text messageText;
        if (urls.isEnabled() && player.hasPermission(Permissions.Chat.FORMAT_URLS)) {
            messageText = newTextWithLinks(message0, urls.getTemplate(), false);
        } else {
            messageText = rawMessageText;
        }
        final MessageChannel channel = player.getMessageChannel();
        final MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(
                Cause.of(NamedCause.source(player)), channel, Optional.of(channel),
                new MessageEvent.MessageFormatter(nameText, messageText), rawMessageText, false);
        if (!Sponge.getEventManager().post(event) && !event.isMessageCancelled()) {
            event.getChannel().ifPresent(c -> c.send(player, event.getMessage(), ChatTypes.CHAT));
        }
    }
    final Attribute<ChatData> attr = context.getChannel().attr(CHAT_DATA);
    ChatData chatData = attr.get();
    if (chatData == null) {
        chatData = new ChatData();
        final ChatData chatData1 = attr.setIfAbsent(chatData);
        if (chatData1 != null) {
            chatData = chatData1;
        }
    }
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (chatData) {
        final long currentTime = LanternGame.currentTimeTicks();
        if (chatData.lastChatTime != -1L) {
            chatData.chatThrottle = (int) Math.max(0,
                    chatData.chatThrottle - (currentTime - chatData.lastChatTime));
        }
        chatData.lastChatTime = currentTime;
        chatData.chatThrottle += 20;
        if (chatData.chatThrottle > Lantern.getGame().getGlobalConfig().getChatSpamThreshold()) {
            session.disconnect(t("disconnect.spam"));
        }
    }
}

From source file:org.quartzpowered.network.session.SessionManager.java

License:Open Source License

public Session get(Channel channel) {
    Attribute<Session> attribute = channel.attr(ATTRIBUTE_KEY);
    Session session = attribute.get();
    if (session == null) {
        attribute.setIfAbsent(factory.create(channel));
        session = attribute.get();/* www  .ja v a  2  s . c  om*/
    }
    return session;
}

From source file:qunar.tc.qmq.util.ChannelUtil.java

License:Apache License

public static Object getAttribute(Channel channel) {
    synchronized (channel) {
        Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE);
        return attr != null ? attr.get() : null;
    }//from   w  ww  .j a v  a2  s . c  om
}