private void sendReq(String btyimei) { Battery battery = batteryService.fetchBtyByIMEI(btyimei); if (battery == null) { logger.error("电池不存在, " + btyimei); return; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接的imei:" + imei); if (imei != null && imei.equals(battery.getImei())) { c.writeAndFlush("tellme" + imei + "\n"); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, " + btyimei); } }
@Override public boolean chat(String deviceImei, String chatType) { Battery battery = batteryService.fetchBtyByIMEI(deviceImei); if (battery == null) { logger.error("数据库中设备不存在, 设备Imei卡号:{}", deviceImei); return false; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接设备的imei:{}", imei); if (imei != null && imei.equals(battery.getImei())) { String msg = chatType + imei + "\n"; c.writeAndFlush(msg); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, 设备Imei卡号:{}", deviceImei); } return hasConn; }
@Override public HttpResponse clientToProxyRequest(HttpObject httpObject) { if (httpObject instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) httpObject; if (ProxyUtils.isCONNECT(httpRequest)) { Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME)); String hostAndPort = httpRequest.getUri(); // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example) // would be unexpected. String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443); hostname.set(hostNoDefaultPort); } } return null; }
private void onIdeled(Channel channel) { Long lastTime = (Long) channel.attr(AttributeKey.valueOf("heart")).get(); if (lastTime != null && System.currentTimeMillis() - lastTime >= 30 * 1000) { LOG.info("wait for heart timeout close the channel {}", channel); channel.attr(AttributeKey.valueOf("heart")).set(null); channel.close(); } else { LOG.info("send heart .. {}", channel); if (lastTime == null) channel.attr(AttributeKey.valueOf("heart")).set(System.currentTimeMillis()); channel.writeAndFlush(heartMsg.msg()); } }
/** * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is * {@code null}, the attribute of the specified {@code key} is removed. */ @SuppressWarnings("unchecked") public <T> B attr(AttributeKey<T> key, T value) { if (key == null) { throw new NullPointerException("key"); } if (value == null) { synchronized (attrs) { attrs.remove(key); } } else { synchronized (attrs) { attrs.put(key, value); } } return (B) this; }
@Test public void testGetSetString() { AttributeKey<String> key = AttributeKey.valueOf("Nothing"); Attribute<String> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent("Whoohoo"); assertSame("Whoohoo", one.get()); one.setIfAbsent("What"); assertNotSame("What", one.get()); one.remove(); assertNull(one.get()); }
@Test public void testGetSetInt() { AttributeKey<Integer> key = AttributeKey.valueOf("Nada"); Attribute<Integer> one = map.attr(key); assertSame(one, map.attr(key)); one.setIfAbsent(3653); assertEquals(Integer.valueOf(3653), one.get()); one.setIfAbsent(1); assertNotSame(1, one.get()); one.remove(); assertNull(one.get()); }
/** * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is * {@code null}, the attribute of the specified {@code key} is removed. */ /* 对this.attrs进行负值。 * 如果对应的key的value为null,则从attrs删除该属性 * 否则直接put */ public <T> B attr(AttributeKey<T> key, T value) { if (key == null) { throw new NullPointerException("key"); } if (value == null) { synchronized (attrs) { attrs.remove(key); } } else { synchronized (attrs) { attrs.put(key, value); } } @SuppressWarnings("unchecked") B b = (B) this; return b; }
/** * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is * {@code null}, the attribute of the specified {@code key} is removed. */ public <T> B attr(AttributeKey<T> key, T value) { if (key == null) { throw new NullPointerException("key"); } if (value == null) { synchronized (attrs) { attrs.remove(key); } } else { synchronized (attrs) { attrs.put(key, value); } } @SuppressWarnings("unchecked") B b = (B) this; return b; }
public NPCNetworkManager() { super(EnumProtocolDirection.SERVERBOUND); try { Field channel = NetworkManager.class.getDeclaredField("i"); Field address = NetworkManager.class.getDeclaredField("j"); channel.setAccessible(true); address.setAccessible(true); Channel parent = new NPCChannel(null); try { Field protocolVersion = NetworkManager.class.getDeclaredField("protocolVersion"); parent.attr(((AttributeKey<Integer>) protocolVersion.get(null))).set(5); } catch(NoSuchFieldException ignored) { // This server isn't spigot, we're good. } channel.set(this, parent); address.set(this, new SocketAddress() { private static final long serialVersionUID = 6994835504305404545L; }); } catch(Exception e) { e.printStackTrace(); } }
/** * Mock Nettys ChannelHandlerContext with the minimal functions. * * @param buf * The buffer to use for decoding * @param m2 * The message reference to store the result * @return The mocked ChannelHandlerContext */ @SuppressWarnings("unchecked") private ChannelHandlerContext mockChannelHandlerContext(final ByteBuf buf, final AtomicReference<Message2> m2) { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); ByteBufAllocator alloc = mock(ByteBufAllocator.class); when(ctx.alloc()).thenReturn(alloc); when(alloc.ioBuffer()).thenReturn(buf); DatagramChannel dc = mock(DatagramChannel.class); when(ctx.channel()).thenReturn(dc); when(ctx.writeAndFlush(any(), any(ChannelPromise.class))).thenReturn(null); Attribute<InetSocketAddress> attr = mock(Attribute.class); when(ctx.attr(any(AttributeKey.class))).thenReturn(attr); when(ctx.fireChannelRead(any())).then(new Answer<Void>() { @Override public Void answer(final InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); m2.set((Message2) args[0]); return null; } }); return ctx; }
/** * 连接被关闭 * @param ctx * @throws Exception */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { AttributeKey<Session> attrKeySession = AttributeKey.valueOf("Session"); Attribute<Session> attrSession = ctx.attr(attrKeySession); Session session = attrSession.get(); logger.warn("client diconnect!"); super.channelInactive(ctx); }
/** * 「内部使用」将 TCP 帧解码并转换为消息对象,而后传递至 Server * * @param head TCP 帧头 * @param subMsgId TCP 子帧功能位 * @param data TCP 子帧数据体 * @param channel 该消息帧的容器 Channel */ public void decodeAndHuntMessage(FrameMajorHeader head, int subMsgId, byte[] data, Channel channel) { BaseMsg msg = msgProcessor.decode(head, subMsgId, data); if (msg == null) { logger.warn("帧解析出错"); return; } logger.info("收到正常消息对象:「" + msg.getMsgDetail() + "」"); switch (msg.getJointMsgFlag()) { case JointMsgType.HeartBeat: Attribute<Integer> key = channel.attr(AttributeKey.valueOf("ID")); MsgReplyNormal replyHeartbeat = MsgCodecReplyNormal.createByBaseMsg(MsgCodecHeartbeat.create(key.get())); logger.info("已生成并发送正常回复消息对象:「" + replyHeartbeat.getMsgDetail() + "」"); sendMessageToTcp(replyHeartbeat); break; default: //剩下的均为正常需回复消息 server.huntMessage(msg); MsgReplyNormal replyNormal = MsgCodecReplyNormal.createByBaseMsg(msg); if (replyNormal == null) { logger.warn("生成正常回复消息对象出错"); return; } logger.info("已生成并发送正常回复消息对象:「" + replyNormal.getMsgDetail() + "」"); sendMessageToTcp(replyNormal); } }
/** * 保存已激活的 Channel * * @param channel 已激活的 Channel */ public void activeChannel(Channel channel) { Attribute<Integer> key = channel.attr(AttributeKey.valueOf("ID")); int id = key.get(); CHANNEL_ARRAY.set(id, channel); SENDING_MESSAGE_QUEUE.get(id).clear(); }
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); Attribute<Integer> key = ctx.channel().attr(AttributeKey.valueOf("ID")); logger.info("Channel「" + key.get() + "」建立连接成功"); tcpPresenter.channelActive(ctx.channel()); }
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); Attribute<Integer> key = ctx.channel().attr(AttributeKey.valueOf("ID")); logger.info("Channel「" + key.get() + "」已经断开连接"); tcpPresenter.channelInactive(key.get()); }
/** * Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is * {@code null} the {@link AttributeKey} is removed */ public <T> UkcpServerBootstrap childAttr(AttributeKey<T> childKey, T value) { if (childKey == null) { throw new NullPointerException("childKey"); } if (value == null) { childAttrs.remove(childKey); } else { childAttrs.put(childKey, value); } return this; }
ServerUkcpBootstrapAcceptor( final Channel channel, ChannelHandler childHandler, Map.Entry<ChannelOption<?>, Object>[] childOptions, Map.Entry<AttributeKey<?>, Object>[] childAttrs) { this.childHandler = childHandler; this.childOptions = childOptions; this.childAttrs = childAttrs; }
@Override @SuppressWarnings("unchecked") public void channelRead(ChannelHandlerContext ctx, Object msg) { Channel parent = ctx.channel(); final Channel child = (Channel) msg; child.pipeline().addLast(childHandler); setChannelOptions(child, childOptions, logger); for (Map.Entry<AttributeKey<?>, Object> e : childAttrs) { child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue()); } try { parent.eventLoop().register(child).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { forceClose(child, future.cause()); } } }); } catch (Throwable t) { forceClose(child, t); } }
@Override public String toString() { StringBuilder buf = new StringBuilder(super.toString()); buf.setLength(buf.length() - 1); buf.append(", "); Map<ChannelOption<?>, Object> childOptions = childOptions(); if (!childOptions.isEmpty()) { buf.append("childOptions: "); buf.append(childOptions); buf.append(", "); } Map<AttributeKey<?>, Object> childAttrs = childAttrs(); if (!childAttrs.isEmpty()) { buf.append("childAttrs: "); buf.append(childAttrs); buf.append(", "); } ChannelHandler childHandler = childHandler(); if (childHandler != null) { buf.append("childHandler: "); buf.append(childHandler); buf.append(", "); } if (buf.charAt(buf.length() - 1) == '(') { buf.append(')'); } else { buf.setCharAt(buf.length() - 2, ')'); buf.setLength(buf.length() - 1); } return buf.toString(); }
@SuppressWarnings("unchecked") public HandshakeMessageHandler(Class<S> stateType) { fmlHandshakeState = (AttributeKey<S>) ((Object)STATE); initialState = Enum.valueOf(stateType, "START"); this.stateType = stateType; }
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { try { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); } catch (WebSocketHandshakeException e) { System.out.println("WebSocket Client failed to connect"); handshakeFuture.setFailure(e); } return; } //发生未知错误 if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException( "Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); //已收到回复,标记后不再发送音频 ch.attr(AttributeKey.valueOf("response")).set(true); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
@Test public void testFilterChunkeResponses() throws InterruptedException{ PolicyManager policyManager = mock(PolicyManager.class); AppConfiguration appConfig = mock(AppConfiguration.class); when(appConfig.getBoolean(AppConfiguration.KEY_DEBUG_INFO)).thenReturn(true); ExecutorService tp = Executors.newCachedThreadPool(); NettyResponseProxyFilter filter = new NettyResponseProxyFilter( policyManager, tp); ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.attr(any(AttributeKey.class))).thenReturn( mock(Attribute.class)); Attribute cachable = mock(Attribute.class); when(ctx.attr(NettyRequestProxyFilter.IS_CACHABLE)) .thenReturn(cachable); when(cachable.get()).thenReturn(Boolean.TRUE); Attribute cacheKey = mock(Attribute.class); when(ctx.attr(NettyRequestProxyFilter.CACHE_KEY)).thenReturn(cacheKey); when(cacheKey.get()).thenReturn("key"); HttpResponse resp = mock(HttpResponse.class); when(resp.getStatus()).thenReturn(HttpResponseStatus.OK); filter.filterResponse(resp, ctx); HttpContent httpContent = mock(HttpContent.class); when(httpContent.duplicate()).thenReturn(mock(HttpContent.class)); filter.filterResponse(httpContent, ctx); LastHttpContent lastHttpContent = mock(LastHttpContent.class); when(lastHttpContent.duplicate()).thenReturn(mock(LastHttpContent.class)); filter.filterResponse(lastHttpContent, ctx); filter.filterResponse(resp, ctx); filter.filterResponse(lastHttpContent, ctx); tp.awaitTermination(10, TimeUnit.SECONDS); }
private void sendReq(String Imei) { Battery battery = batteryService.fetchBtyByIMEI(Imei); if (battery == null) { logger.error("电池不存在, " + Imei); return; } boolean hasConn = false; ChannelGroup channelGroup = SamBtyDataHandler.getChannels(); for (Channel c : channelGroup) { String imei = (String) c.attr(AttributeKey.valueOf("IMEI")).get(); logger.info("已经连接的imei:" + imei); if (imei != null && imei.equals(battery.getImei())) { c.writeAndFlush("tellme" + imei + "\n"); hasConn = true; } } if (!hasConn) { logger.error("未获取到长连接, " + Imei); } // ConcurrentHashMap<String, Channel> map = // SamBtyDataHandler.getChannelMap(); // Channel channel = map.get(battery.getImei()); // if (channel == null) { // logger.error("未获取到长连接, " + simNo); // } // // channel.writeAndFlush("tellme\r\n"); }
@Before public void beforeMethod() { channelMock = mock(Channel.class); ctxMock = mock(ChannelHandlerContext.class); doReturn(channelMock).when(ctxMock).channel(); doReturn(mock(Attribute.class)).when(channelMock).attr(any(AttributeKey.class)); }
@Test public void processingStateClassAndKeyPair_setValue_throws_UnsupportedOperationException() { // given ChannelAttributes.ProcessingStateClassAndKeyPair instance = new ChannelAttributes.ProcessingStateClassAndKeyPair(null, null); // when Throwable ex = catchThrowable(() -> instance.setValue(AttributeKey.newInstance("someattr"))); // then Assertions.assertThat(ex).isInstanceOf(UnsupportedOperationException.class); }
protected void encode(final ChannelHandlerContext ctx, final ImaginePacket packet, final List<Object> out) throws Exception { final WritableBuf buffer = new WritableBuf(Unpooled.buffer()); final ImaginePacketRegistry packetRegistry = (ImaginePacketRegistry)ctx.attr((AttributeKey)ImaginePacketCodec.PACKET_REGISTRY).get(); final Class<? extends ImaginePacket> packetClass = packet.getClass(); final int packetClassId = packetRegistry.id(packetClass); if (packetRegistry.missing(packetClass)) { packetRegistry.register(packetClassId, packetClass); buffer.writeBoolean(true); buffer.writeInt(packetClassId); final byte[] classNameBytes = packetClass.getName().getBytes(ImaginePacketCodec.UTF_8); final int classNameLength = classNameBytes.length; buffer.writeInt(classNameLength); buffer.writeBytes(classNameBytes, 0, classNameLength); } else { buffer.writeBoolean(false); buffer.writeInt(packetClassId); } packet.writePacket(ctx, buffer); final FMLProxyPacket proxy = new FMLProxyPacket((ByteBuf)buffer, (String)ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get()); final WeakReference<FMLProxyPacket> ref = ((ThreadLocal)ctx.attr((AttributeKey)ImaginePacketCodec.PACKET_TRACKER).get()).get(); final FMLProxyPacket old = (ref == null) ? null : ref.get(); if (old != null) { proxy.setDispatcher(old.getDispatcher()); } out.add(proxy); }
protected void decode(final ChannelHandlerContext ctx, final FMLProxyPacket msg, final List<Object> out) throws Exception { ((ThreadLocal)ctx.attr((AttributeKey)ImaginePacketCodec.PACKET_TRACKER).get()).set(new WeakReference<FMLProxyPacket>(msg)); final ImaginePacketRegistry packetRegistry = (ImaginePacketRegistry)ctx.attr((AttributeKey)ImaginePacketCodec.PACKET_REGISTRY).get(); final ByteBuf payload = msg.payload(); final boolean newPacketClass = payload.readBoolean(); final int packetClassId = payload.readInt(); Class<? extends ImaginePacket> packetClass; if (newPacketClass) { final int classNameLength = payload.readInt(); if (classNameLength <= 0) { new IllegalArgumentException("Too short class name: " + classNameLength).printStackTrace(); ctx.close(); } if (classNameLength > 1024) { new IllegalArgumentException("Too long class name: " + classNameLength).printStackTrace(); ctx.close(); } final byte[] classNameBytes = new byte[classNameLength]; payload.readBytes(classNameBytes, 0, classNameLength); final String className = new String(classNameBytes, 0, classNameLength, ImaginePacketCodec.UTF_8); packetClass = (Class<? extends ImaginePacket>)Class.forName(className); if (!ImaginePacket.class.isAssignableFrom(packetClass)) { new IllegalArgumentException("Provided class isn't imagine packet: " + packetClass).printStackTrace(); ctx.close(); } packetRegistry.register(packetClassId, packetClass); } else { packetClass = packetRegistry.get(packetClassId); } if (packetClass == null) { new NullPointerException("Undefined message in channel " + msg.channel()).printStackTrace(); ctx.close(); } final ImaginePacket packet = ImagineNetwork.obtainPacket(packetClass); packet.readPacket(ctx, new WritableBuf(payload.slice())); out.add(packet); }
/** * Returns the host and port of this HTTPS request, including any modifications by other filters. * * @return host and port of this HTTPS request * @throws IllegalStateException if this is not an HTTPS request */ private String getHttpsRequestHostAndPort() throws IllegalStateException { if (!isHttps()) { throw new IllegalStateException("Request is not HTTPS. Cannot get host and port on non-HTTPS request using this method."); } Attribute<String> hostnameAttr = ctx.attr(AttributeKey.<String>valueOf(HOST_ATTRIBUTE_NAME)); return hostnameAttr.get(); }
/** * Returns the original host and port of this HTTPS request, as sent by the client. Does not reflect any modifications * by other filters. * TODO: evaluate this (unused) method and its capture mechanism in HttpsOriginalHostCaptureFilter; remove if not useful. * * @return host and port of this HTTPS request * @throws IllegalStateException if this is not an HTTPS request */ private String getHttpsOriginalRequestHostAndPort() throws IllegalStateException { if (!isHttps()) { throw new IllegalStateException("Request is not HTTPS. Cannot get original host and port on non-HTTPS request using this method."); } Attribute<String> hostnameAttr = ctx.attr(AttributeKey.<String>valueOf(ORIGINAL_HOST_ATTRIBUTE_NAME)); return hostnameAttr.get(); }
public HttpsOriginalHostCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx) { super(originalRequest, ctx); // if this is an HTTP CONNECT, set the isHttps attribute on the ChannelHandlerConect and capture the hostname from the original request. // capturing the original host (and the remapped/modified host in clientToProxyRequest() below) guarantees that we will // have the "true" host, rather than relying on the Host header in subsequent requests (which may be absent or spoofed by malicious clients). if (ProxyUtils.isCONNECT(originalRequest)) { Attribute<String> originalHostAttr = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.ORIGINAL_HOST_ATTRIBUTE_NAME)); String hostAndPort = originalRequest.getUri(); originalHostAttr.set(hostAndPort); Attribute<Boolean> isHttpsAttr = ctx.attr(AttributeKey.<Boolean>valueOf(HttpsAwareFiltersAdapter.IS_HTTPS_ATTRIBUTE_NAME)); isHttpsAttr.set(true); } }
@Override public void onError(ContextWrapper conn, Exception ex) { LOG.log(Level.FINE,"***DominoWebSocketServer.onError***"); if(conn!=null){ Attribute<Object> att = conn.attr(AttributeKey.newInstance("resourceDescriptor")); LOG.log(Level.SEVERE,null,att.get().toString()); } LOG.log(Level.SEVERE,null, ex); this.notifyEventObservers(Const.ON_ERROR, ex); }
/** * Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is * {@code null} the {@link AttributeKey} is removed */ public <T> ServerBootstrap childAttr(AttributeKey<T> childKey, T value) { if (childKey == null) { throw new NullPointerException("childKey"); } if (value == null) { childAttrs.remove(childKey); } else { childAttrs.put(childKey, value); } return this; }
@Override void init(Channel channel) throws Exception { final Map<ChannelOption<?>, Object> options = options(); synchronized (options) { channel.config().setOptions(options); } final Map<AttributeKey<?>, Object> attrs = attrs(); synchronized (attrs) { for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) { @SuppressWarnings("unchecked") AttributeKey<Object> key = (AttributeKey<Object>) e.getKey(); channel.attr(key).set(e.getValue()); } } ChannelPipeline p = channel.pipeline(); if (handler() != null) { p.addLast(handler()); } final EventLoopGroup currentChildGroup = childGroup; final ChannelHandler currentChildHandler = childHandler; final Entry<ChannelOption<?>, Object>[] currentChildOptions; final Entry<AttributeKey<?>, Object>[] currentChildAttrs; synchronized (childOptions) { currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size())); } synchronized (childAttrs) { currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size())); } p.addLast(new ChannelInitializer<Channel>() { @Override public void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new ServerBootstrapAcceptor( currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); } }); }
ServerBootstrapAcceptor( EventLoopGroup childGroup, ChannelHandler childHandler, Entry<ChannelOption<?>, Object>[] childOptions, Entry<AttributeKey<?>, Object>[] childAttrs) { this.childGroup = childGroup; this.childHandler = childHandler; this.childOptions = childOptions; this.childAttrs = childAttrs; }