List of usage examples for io.netty.util Attribute set
void set(T value);
From source file:org.ebayopensource.scc.filter.NettyRequestProxyFilter.java
License:Apache License
@Override public HttpResponse filterRequest(HttpObject reqObject, ChannelHandlerContext reqCtx) { if (reqObject instanceof HttpRequest) { String uri = ((HttpRequest) reqObject).getUri(); LOGGER.info("Received a request: " + uri); reqCtx.attr(REQUEST_URI).setIfAbsent(uri); }// w ww .j a v a2 s . c o m if (reqObject instanceof FullHttpRequest) { FullHttpRequest req = (FullHttpRequest) reqObject; if (!isProxyRequest(req)) { return handleNonProxyRequest(req); } boolean isCachable = m_policyManager .cacheIsNeededFor(new CacheDecisionObject(req.getUri(), req.getMethod().name())); reqCtx.attr(IS_CACHABLE).setIfAbsent(isCachable); if (isCachable) { String key = m_policyManager.generateCacheKey(req); FullHttpResponse response = m_policyManager.getCacheManager().get(key); Attribute<String> attr = reqCtx.attr(CACHE_KEY); attr.set(key); debugRequestInfo(reqObject, key); if (response != null) { long bSize = 0; if (response.headers().contains(HttpHeaders.Names.CONTENT_LENGTH)) { bSize = HttpHeaders.getContentLength(response); } else { bSize = response.content().readableBytes(); } if (bSize != 0) { setBufferSizeIfConfigIsSocketChannelConfig(reqCtx.channel().config(), bSize); } LOGGER.info("HIT CACHE: " + key); } return response; } } debugRequestInfo(reqObject, null); return null; }
From source file:org.eclipse.moquette.server.netty.NettyUtils.java
License:Open Source License
public static void setAttribute(ChannelHandlerContext channel, AttributeKey<Object> key, Object value) { Attribute<Object> attr = channel.attr(key); attr.set(value); }
From source file:org.hawkular.metrics.clients.ptrans.MetricBatcher.java
License:Apache License
/** * Batch up incoming SingleMetric messages. If the #minimumBatchSize is not yet reached, the messages are stored * locally. Otherwise the list of messages will be forwarded to the next handler. * This method will be called for each written message that can be handled * by this encoder./* w w w . j a v a 2 s . c o m*/ * * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to * @param msg the SingleMetric to be batched up * @param out the {@link List} to which decoded messages should be added if the batch size is reached * @throws Exception is thrown if an error occurs */ @Override protected void decode(ChannelHandlerContext ctx, SingleMetric msg, List<Object> out) throws Exception { LOG.trace("Incoming metric for key '{}'", cacheKey.name()); Attribute<List<SingleMetric>> cache = ctx.attr(cacheKey); List<SingleMetric> batchList = cache.get(); if (batchList == null) { LOG.trace("Creating new batch list for key '{}'", cacheKey.name()); batchList = new ArrayList<>(minimumBatchSize); cache.set(batchList); } batchList.add(msg); if (batchList.size() >= minimumBatchSize) { LOG.trace("Batch size limit '{}' reached for key '{}'", minimumBatchSize, cacheKey.name()); cache.remove(); out.add(batchList); } }
From source file:org.jmqtt.core.codec.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex();// www . java2 s . c o m //Common decoding part ConnectPacket message = new ConnectPacket(); if (!decodeCommonHeader(message, 0x00, in)) { in.resetReaderIndex(); return; } int remainingLength = message.getRemainingLength(); int start = in.readerIndex(); int protocolNameLen = in.readUnsignedShort(); byte[] encProtoName; String protoName; Attribute<Integer> versionAttr = ctx.attr(MQTTDecoder.PROTOCOL_VERSION); switch (protocolNameLen) { case 6: //MQTT version 3.1 "MQIsdp" //ProtocolName 8 bytes or 6 bytes if (in.readableBytes() < 10) { in.resetReaderIndex(); return; } encProtoName = new byte[6]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQIsdp".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) MqttUtils.VERSION_3_1); break; case 4: //MQTT version 3.1.1 "MQTT" //ProtocolName 6 bytes if (in.readableBytes() < 8) { in.resetReaderIndex(); return; } encProtoName = new byte[4]; in.readBytes(encProtoName); protoName = new String(encProtoName, "UTF-8"); if (!"MQTT".equals(protoName)) { in.resetReaderIndex(); throw new CorruptedFrameException("Invalid protoName: " + protoName); } message.setProtocolName(protoName); versionAttr.set((int) MqttUtils.VERSION_3_1_1); break; default: //protocol broken throw new CorruptedFrameException("Invalid protoName size: " + protocolNameLen); } //ProtocolVersion 1 byte (value 0x03 for 3.1, 0x04 for 3.1.1) message.setProtocolVersion(in.readByte()); if (message.getProtocolVersion() == MqttUtils.VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != QosType.MOST_ONE) { throw new CorruptedFrameException("Received a CONNECT with fixed header flags != 0"); } //check if this is another connect from the same client on the same session Attribute<Boolean> connectAttr = ctx.attr(ConnectDecoder.CONNECT_STATUS); Boolean alreadyConnected = connectAttr.get(); if (alreadyConnected == null) { //never set connectAttr.set(true); } else if (alreadyConnected) { throw new CorruptedFrameException("Received a second CONNECT on the same network connection"); } } //Connection flag byte connFlags = in.readByte(); if (message.getProtocolVersion() == MqttUtils.VERSION_3_1_1) { if ((connFlags & 0x01) != 0) { //bit(0) of connection flags is != 0 throw new CorruptedFrameException("Received a CONNECT with connectionFlags[0(bit)] != 0"); } } boolean cleanSession = ((connFlags & 0x02) >> 1) == 1; boolean willFlag = ((connFlags & 0x04) >> 2) == 1; byte willQos = (byte) ((connFlags & 0x18) >> 3); if (willQos > 2) { in.resetReaderIndex(); throw new CorruptedFrameException("Expected will QoS in range 0..2 but found: " + willQos); } boolean willRetain = ((connFlags & 0x20) >> 5) == 1; boolean passwordFlag = ((connFlags & 0x40) >> 6) == 1; boolean userFlag = ((connFlags & 0x80) >> 7) == 1; //a password is true iff user is true. if (!userFlag && passwordFlag) { in.resetReaderIndex(); throw new CorruptedFrameException( "Expected password flag to true if the user flag is true but was: " + passwordFlag); } message.setCleanSession(cleanSession); message.setWillFlag(willFlag); message.setWillQos(willQos); message.setWillRetain(willRetain); message.setPasswordFlag(passwordFlag); message.setUserFlag(userFlag); //Keep Alive timer 2 bytes //int keepAlive = MqttUtils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProtocolVersion() == MqttUtils.VERSION_3_1) || (remainingLength == 10 && message.getProtocolVersion() == MqttUtils.VERSION_3_1_1)) { out.add(message); return; } //Decode the ClientID String clientID = MqttUtils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = MqttUtils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { byte[] willMessage = MqttUtils.readFixedLengthContent(in); if (willMessage == null) { in.resetReaderIndex(); return; } message.setWillMessage(willMessage); } //Compatibility check with v3.0, remaining length has precedence over //the user and password flags int readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode username if (userFlag) { String userName = MqttUtils.decodeString(in); if (userName == null) { in.resetReaderIndex(); return; } message.setUsername(userName); } readed = in.readerIndex() - start; if (readed == remainingLength) { out.add(message); return; } //Decode password if (passwordFlag) { byte[] password = MqttUtils.readFixedLengthContent(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:org.jooby.internal.netty.NettyWebSocket.java
License:Apache License
@Override public void close(final int status, final String reason) { handshaker.close(ctx.channel(), new CloseWebSocketFrame(status, reason)).addListener(CLOSE); Attribute<NettyWebSocket> ws = ctx.channel().attr(KEY); if (ws != null) { ws.set(null); }//from w w w . j av a 2 s . co m }
From source file:org.kaaproject.kaa.server.transports.http.transport.netty.DefaultHttpServerInitializer.java
License:Apache License
@Override protected void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); final UUID uuid = UUID.randomUUID(); LOG.info("DefaultServerInitializer Initializing Channel {} connection from {}:{}", uuid, ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort()); Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY); uuidAttr.set(uuid); p.addLast("httpDecoder", new HttpRequestDecoder()); p.addLast("httpAggregator", new HttpObjectAggregator(getClientMaxBodySize())); p.addLast("httpDecoderAux", getRequestDecoder()); p.addLast("httpEncoder", new HttpResponseEncoder()); p.addLast("httpEncoderAux", new ResponseEncoder()); p.addLast("handler", getMainHandler(uuid)); p.addLast("httpExceptionHandler", new DefaultExceptionHandler()); }
From source file:org.kaaproject.kaa.server.transports.tcp.transport.netty.AbstractKaaTcpServerInitializer.java
License:Apache License
@Override protected void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); final UUID uuid = UUID.randomUUID(); LOG.debug("KaaTcpServerInitializer Initializing Channel {} connection from {}:{}", uuid, ch.remoteAddress().getAddress().toString(), ch.remoteAddress().getPort()); Attribute<UUID> uuidAttr = ch.attr(AbstractNettyServer.UUID_KEY); uuidAttr.set(uuid); p.addLast("binaryDecoder", new ByteArrayDecoder()); p.addLast("kaaTcpDecoder", getDecoder()); p.addLast("binaryEncoder", new ByteArrayEncoder()); p.addLast("kaaTcpEncoder", new KaaTcpEncoder()); p.addLast("mainHandler", getMainHandler(uuid)); p.addLast("kaaTcpExceptionHandler", new KaaTcpExceptionHandler()); }
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 {//from w w w. ja v a2 s .com 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.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 w w . j a v a 2s. c o m*/ } // 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;/*from w ww .j a v a2 s. c om*/ } 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(); } }