@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) { Channel ch = ctx.channel(); // Prevent recursion when the client close the connection during a write operation. In that // scenario the sendError will be invoked, but will fail since the channel has already been // closed // For an unknown reason, if (ch.attr(ATTACHMENT) != null && Error.class.isAssignableFrom(ch.attr(ATTACHMENT).get().getClass())) { return; } Throwable cause = t.getCause(); if (cause instanceof TooLongFrameException) { sendError(ctx, BAD_REQUEST, null); return; } ch.attr(ATTACHMENT).set(new Error()); if (ch.isOpen()) { sendError(ctx, INTERNAL_SERVER_ERROR, null); } if (ctx.channel().isActive()) { sendError(ctx, INTERNAL_SERVER_ERROR, null); } }
private void sentOfflineMessage(Channel channel) { log.trace("Channel was inactive for a long period."); Boolean isHard = channel.attr(ChannelState.IS_HARD_CHANNEL).get(); if (isHard != null && isHard) { User user = channel.attr(ChannelState.USER).get(); if (user != null) { Notification notification = user.getProfile().getActiveDashboardWidgetByType(Notification.class); if (notification == null || !notification.notifyWhenOffline) { Session session = sessionsHolder.userSession.get(user); if (session.appChannels.size() > 0) { session.sendMessageToApp(produce(0, DEVICE_WENT_OFFLINE)); } } else { String boardType = user.getProfile().getActiveDashBoard().getBoardType(); String dashName = user.getProfile().getActiveDashBoard().getName(); notificationsProcessor.push( user, notification, String.format( "Your %s went offline. \"%s\" project is disconnected.", boardType, dashName)); } } } }
public void channelRead(final ChannelHandlerContext remoteChannelCtx, final Object msg) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote msg", msg); remainMsgCount++; if (remainMsgCount <= 5) { remoteChannelCtx.read(); } HttpObject ho = (HttpObject) msg; if (ho instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) ho; LoggerUtil.info( forwardRestLogger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), httpResponse.getStatus(), httpResponse.getProtocolVersion()); httpResponse.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); httpResponse.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE); } if (uaChannel.isActive()) { uaChannel .writeAndFlush(ho) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Write to UA finished: " + future.isSuccess()); if (future.isSuccess()) { remainMsgCount--; remoteChannelCtx.read(); LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Fire read again"); } else { remoteChannelCtx.close(); } } }); } else { remoteChannelCtx.close(); } }
@Override public void channelInactive(final ChannelHandlerContext remoteChannelCtx) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote channel inactive"); final String remoteAddr = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote().getRemoteAddr(); remoteChannelInactiveCallback.remoteChannelInactive(uaChannel, remoteAddr); remoteChannelCtx.fireChannelInactive(); }
private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) throws IOException { Channel channel = ctx.channel(); Attribute<Boolean> attr = channel.attr(WRITE_ONCE); Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport()); if (!channel.isActive() || queue.isEmpty() || !attr.compareAndSet(null, true)) { promise.setSuccess(); return; } ByteBuf out = encoder.allocateBuffer(ctx.alloc()); Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get(); if (b64 != null && b64) { Integer jsonpIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get(); encoder.encodeJsonP(jsonpIndex, queue, out, ctx.alloc(), 50); String type = "application/javascript"; if (jsonpIndex == null) { type = "text/plain"; } sendMessage(msg, channel, out, type, promise); } else { encoder.encodePackets(queue, out, ctx.alloc(), 50); sendMessage(msg, channel, out, "application/octet-stream", promise); } }
public void onMessage(Message message) { if (message.getType() == MessageType.MSG && message.get(MessageProperty.ROOM).equals("#main")) { long userId = message.get(MessageProperty.USER_ID); String name = message.get(MessageProperty.NAME); UserCredentials userCredentials = null; if (needsFetchingConnectionData(userId)) { userCredentials = fetchConnectionDataForUser(name, userId); } if (userCredentials != null) { String id = userCredentials.getId(); Channel channel = connections.get(id.toLowerCase()); if (channel == null || !channel.isActive()) { try { channel = createConnection(id, userCredentials.getToken()); } catch (InterruptedException e) { logger.warn("", e); } } if (channel != null) { channel.attr(lastMessageAttrKey).set(System.currentTimeMillis()); channel.writeAndFlush( "PRIVMSG #" + this.channel + " :" + message.get(MessageProperty.TEXT) + "\r\n"); } } } }
@Override public void exceptionCaught(ChannelHandlerContext remoteChannelCtx, Throwable cause) throws Exception { logger.error( cause.getMessage() + uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), cause); remoteChannelCtx.close(); }
@Override public Channel fetch() { Channel ch = channels.fetch(); if (ch != null && ch.isActive()) { if (ch.attr(GlobalConstance.attributeKey).get() == SessionState.Connect) { return ch; } } return null; }
private void addOriginHeaders(Channel channel, HttpResponse res) { if (version != null) { res.headers().add(HttpHeaders.Names.SERVER, version); } if (configuration.getOrigin() != null) { HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_ORIGIN, configuration.getOrigin()); HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.TRUE); } else { String origin = channel.attr(ORIGIN).get(); if (origin != null) { HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_ORIGIN, origin); HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.TRUE); } else { HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_ORIGIN, "*"); } } }
private void sendMessage( HttpMessage msg, Channel channel, ByteBuf out, String type, ChannelPromise promise) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK); res.headers() .add(CONTENT_TYPE, type) .add("Set-Cookie", "io=" + msg.getSessionId()) .add(CONNECTION, KEEP_ALIVE); addOriginHeaders(channel, res); HttpHeaders.setContentLength(res, out.readableBytes()); // prevent XSS warnings on IE // https://github.com/LearnBoost/socket.io/pull/1333 String userAgent = channel.attr(EncoderHandler.USER_AGENT).get(); if (userAgent != null && (userAgent.contains(";MSIE") || userAgent.contains("Trident/"))) { res.headers().add("X-XSS-Protection", "0"); } sendMessage(msg, channel, out, res, promise); }
@Override public void run() { try { logger.debug("starting cleanup"); for (Map.Entry<String, Channel> entry : connections.entrySet()) { Channel channel = entry.getValue(); Long lastMessage = channel.attr(lastMessageAttrKey).get(); if (System.currentTimeMillis() - lastMessage > FIVE_MINUTES) { channel.disconnect(); connections.remove(entry.getKey()); logger.debug("connection released for {}", entry.getKey()); } else if (!channel.isActive()) { connections.remove(entry.getKey()); logger.debug("connection released for {}", entry.getKey()); } } logger.debug("cleanup complete"); } catch (Exception e) { logger.error("exception while clean up", e); } }
private void a(final Packet var1, final GenericFutureListener[] var2) { final EnumProtocol var3 = EnumProtocol.a(var1); final EnumProtocol var4 = (EnumProtocol) k.attr(c).get(); if (var4 != var3) { g.debug("Disabled auto read"); k.config().setAutoRead(false); } if (k.eventLoop().inEventLoop()) { if (var3 != var4) { this.a(var3); } ChannelFuture var5 = k.writeAndFlush(var1); if (var2 != null) { var5.addListeners(var2); } var5.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } else { k.eventLoop() .execute( new Runnable() { @Override public void run() { if (var3 != var4) { class_ek.this.a(var3); } ChannelFuture var1x = k.writeAndFlush(var1); if (var2 != null) { var1x.addListeners(var2); } var1x.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); } }); } }
@Override protected void channelRead0(ChannelHandlerContext ctx, UscException ex) throws Exception { log.trace("UscExceptionHandler channelRead0" + ex); final Throwable t = ex.getCause(); Channel channel = ctx.channel(); UscRouteIdentifier routeId = ctx.channel().attr(UscPlugin.ROUTE_IDENTIFIER).get(); if (routeId != null) { // this is a channel using remote channel if (broker == null) { broker = UscServiceUtils.getService(UscRouteBrokerService.class); } if (broker != null) { broker.removeLocalSession(routeId); } else { log.error( "Broker service is null! Can't check if it is remote channel message, failed to proccess this exception {}.", ex); } return; } SettableFuture<UscSessionImpl> tmp = channel.attr(UscPlugin.SESSION).get(); if (tmp != null) { UscSessionImpl session = tmp.get(); UscChannelImpl connection = session.getChannel(); // connection is down if (t instanceof UscConnectionException) { plugin.getConnectionManager().removeConnection(connection); } else if (t instanceof UscChannelException) { // TODO ; } else if (t instanceof UscSessionException) { connection.removeSession(session.getSessionId()); } } throw ex; }
@Override public void encode(ChannelHandlerContext ctx, Packet<PacketListener> packet, ByteBuf output) throws Exception { Channel channel = ctx.channel(); EnumProtocol currentProtocol = channel.attr(currentStateAttrKey).get(); final Integer packetId = currentProtocol.a(direction, packet); if (packetId == null) { throw new IOException("Can't serialize unregistered packet"); } ClientBoundMiddlePacket<RecyclableCollection<PacketData>> packetTransformer = dataRemapperRegistry.getTransformer(currentProtocol, packetId); if (packetTransformer != null) { serverdata.clear(); packet.b(serverdata); if (packetTransformer.needsPlayer()) { packetTransformer.setPlayer(ChannelUtils.getBukkitPlayer(channel)); } packetTransformer.readFromServerData(serverdata); packetTransformer.setLocalStorage(storage); packetTransformer.handle(); RecyclableCollection<PacketData> data = packetTransformer.toData(version); try { for (PacketData packetdata : data) { ByteBuf senddata = Allocator.allocateBuffer(); senddata.writeByte( packetIdRegistry.getNewPacketId(currentProtocol, packetdata.getPacketId())); senddata.writeBytes(packetdata); ctx.write(senddata); } ctx.flush(); } finally { for (PacketData packetdata : data) { packetdata.recycle(); } data.recycle(); } } }
public synchronized void addChannel(Channel ch) { // 标识连接已建立 ch.attr(GlobalConstance.attributeKey).set(SessionState.Connect); getChannels().add(ch); int cnt = incrementConn(); // 如果是CMPP端口 if (getEndpointEntity() instanceof CMPPEndpointEntity) { // 创建持久化Map用于存储发送的message Map<Long, Message> storedMap = BDBStoredMapFactoryImpl.INS.buildMap( getEndpointEntity().getId(), "Session_" + getEndpointEntity().getId()); Map<Long, Message> preSendMap = new HashMap<Long, Message>(); logger.debug( "Channel added To Endpoint {} .totalCnt:{} ,Channel.ID: {}", endpoint, cnt, ch.id()); if (cnt == 1) { // 如果是第一个连接。要把上次发送失败的消息取出,再次发送一次 if (storedMap != null && storedMap.size() > 0) { for (Map.Entry<Long, Message> entry : storedMap.entrySet()) { preSendMap.put(entry.getKey(), entry.getValue()); } } } CMPPEndpointEntity cmppentity = (CMPPEndpointEntity) getEndpointEntity(); // 将SessinManager放在messageHeaderCodec后边。因为要处理Submit 和 deliver消息的长短信分拆 ch.pipeline() .addBefore( CMPPCodecChannelInitializer.codecName, "sessionStateManager", new SessionStateManager(cmppentity, storedMap, preSendMap)); // 加载业务handler bindHandler(ch.pipeline(), cmppentity); } }
@Override public void postProcess(IOTMessage ioTMessage) { switch (ioTMessage.getMessageType()) { case ConnectAcknowledgeMessage.MESSAGE_TYPE: ConnectAcknowledgeMessage conMessage = (ConnectAcknowledgeMessage) ioTMessage; /** Use the connection acknowledgement message to store session id for persistance. */ Channel channel = getChannel(ioTMessage.getConnectionId()); if (Objects.nonNull(channel)) { if (MqttConnectReturnCode.CONNECTION_ACCEPTED.equals(conMessage.getReturnCode())) { channel.attr(ServerImpl.REQUEST_SESSION_ID).set(ioTMessage.getSessionId()); } else { closeClient(ioTMessage.getConnectionId()); } } break; default: super.postProcess(ioTMessage); } }
@Override public <X> X getAttribute(String key, Class<X> clz) { AttributeKey<X> attributeKey = AttributeKey.valueOf(key); Attribute<X> attribute = channel.attr(attributeKey); return attribute == null ? null : attribute.get(); }
@Override public <X, Y extends X> void setAttribute(String key, Class<X> clz, Y value) { AttributeKey<X> attributeKey = AttributeKey.valueOf(key); channel.attr(attributeKey).set(value); }
@Override public void channelActive(ChannelHandlerContext remoteChannelCtx) throws Exception { LoggerUtil.debug( logger, uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY), "Remote channel active"); remoteChannelCtx.read(); }
public synchronized void removeChannel(Channel ch) { ch.attr(GlobalConstance.attributeKey).set(SessionState.DisConnect); if (getChannels().remove(ch)) decrementConn(); }
public void a(EnumProtocol var1) { k.attr(c).set(var1); k.config().setAutoRead(true); g.debug("Enabled auto read"); }