List of usage examples for io.netty.channel Channel attr
<T> Attribute<T> attr(AttributeKey<T> key);
From source file:com.andrewkroh.cisco.xmlservices.ChannelConnectListener.java
License:Apache License
@Override public void operationComplete(ChannelFuture future) throws Exception { LOGGER.debug("connect() complete, status: " + future); if (responseFuture.isCancelled()) { future.channel().close();/*from w w w . j a v a2 s . c om*/ return; } if (future.isSuccess()) { final Channel channel = future.channel(); channel.attr(phoneAttributeKey).set(phone); channel.attr(responseFutureAttributeKey).set(responseFuture); // Timeout the task if it does not complete: eventLoopExecutor.schedule(new Runnable() { @Override public void run() { if (!responseFuture.isDone()) { responseFuture.cancel(false); channel.close(); } } }, responseTimeoutMs, TimeUnit.MILLISECONDS); channel.writeAndFlush(httpRequest).addListener(new ChannelWriteFuture<T>(responseFuture)); } else { responseFuture.setException(future.cause()); future.channel().close(); } }
From source file:com.caricah.iotracah.server.mqttserver.netty.MqttServerImpl.java
License:Apache License
@Override public void postProcess(IOTMessage ioTMessage) { switch (ioTMessage.getMessageType()) { case ConnectAcknowledgeMessage.MESSAGE_TYPE: ConnectAcknowledgeMessage conMessage = (ConnectAcknowledgeMessage) ioTMessage; /**//w w w. j ava 2 s . c o m * 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); } }
From source file:com.caricah.iotracah.server.netty.ServerImpl.java
License:Apache License
public void closeClient(String channelId) { Channel channel = getChannel(channelId); if (null != channel) { channel.attr(ServerImpl.REQUEST_SESSION_ID).set(null); channel.attr(ServerImpl.REQUEST_CONNECTION_ID).set(null); channel.close();//from w w w . ja v a2s . c o m } }
From source file:com.chenyang.proxy.http.HttpSchemaHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; String originalHost = HostNamePortUtil.getHostName(httpRequest); int originalPort = HostNamePortUtil.getPort(httpRequest); HttpRemote apnProxyRemote = new HttpRemote(originalHost, originalPort); if (!HostAuthenticationUtil.isValidAddress(apnProxyRemote.getInetSocketAddress())) { HttpErrorUtil.writeAndFlush(uaChannelCtx.channel(), HttpResponseStatus.FORBIDDEN); return; }/* w w w . j a v a 2 s . com*/ Channel uaChannel = uaChannelCtx.channel(); HttpConnectionAttribute apnProxyConnectionAttribute = HttpConnectionAttribute.build( uaChannel.remoteAddress().toString(), httpRequest.getMethod().name(), httpRequest.getUri(), httpRequest.getProtocolVersion().text(), httpRequest.headers().get(HttpHeaders.Names.USER_AGENT), apnProxyRemote); uaChannelCtx.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).set(apnProxyConnectionAttribute); if (httpRequest.getMethod().equals(HttpMethod.CONNECT)) { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) != null) { uaChannelCtx.pipeline().remove(HttpUserAgentForwardHandler.HANDLER_NAME); } if (uaChannelCtx.pipeline().get(HttpUserAgentTunnelHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentTunnelHandler.HANDLER_NAME, new HttpUserAgentTunnelHandler()); } } else { if (uaChannelCtx.pipeline().get(HttpUserAgentForwardHandler.HANDLER_NAME) == null) { uaChannelCtx.pipeline().addLast(HttpUserAgentForwardHandler.HANDLER_NAME, new HttpUserAgentForwardHandler()); } } } uaChannelCtx.fireChannelRead(msg); }
From source file:com.chenyang.proxy.http.HttpUserAgentForwardHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception { final Channel uaChannel = uaChannelCtx.channel(); final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote(); if (msg instanceof HttpRequest) { HttpRequest httpRequest = (HttpRequest) msg; Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); if (remoteChannel != null && remoteChannel.isActive()) { HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote); remoteChannel.writeAndFlush(request); } else {// ww w. j a va 2s. co m Bootstrap bootstrap = new Bootstrap(); bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.AUTO_READ, false) .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this)); ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(), new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0)); remoteChannel = remoteConnectFuture.channel(); remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel); remoteConnectFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote)); for (HttpContent hc : httpContentBuffer) { future.channel().writeAndFlush(hc); if (hc instanceof LastHttpContent) { future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } httpContentBuffer.clear(); } else { HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR); httpContentBuffer.clear(); future.channel().close(); } } }); } ReferenceCountUtil.release(msg); } else { Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr()); HttpContent hc = ((HttpContent) msg); if (remoteChannel != null && remoteChannel.isActive()) { remoteChannel.writeAndFlush(hc); if (hc instanceof LastHttpContent) { remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { future.channel().read(); } } }); } } else { httpContentBuffer.add(hc); } } }
From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java
License:Apache License
private boolean authorize(ChannelHandlerContext ctx, Channel channel, String origin, Map<String, List<String>> params, FullHttpRequest req) throws IOException { Map<String, List<String>> headers = new HashMap<String, List<String>>(req.headers().names().size()); for (String name : req.headers().names()) { List<String> values = req.headers().getAll(name); headers.put(name, values);/*from w w w . jav a 2 s. c o m*/ } HandshakeData data = new HandshakeData(headers, params, (InetSocketAddress) channel.remoteAddress(), req.getUri(), origin != null && !origin.equalsIgnoreCase("null")); boolean result = false; try { result = configuration.getAuthorizationListener().isAuthorized(data); } catch (Exception e) { log.error("Authorization error", e); } if (!result) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); log.debug("Handshake unauthorized, query params: {} headers: {}", params, headers); return false; } UUID sessionId = this.generateOrGetSessionIdFromRequest(headers); List<String> transportValue = params.get("transport"); if (transportValue == null) { log.warn("Got no transports for request {}", req.getUri()); HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); return false; } Transport transport = Transport.byName(transportValue.get(0)); ClientHead client = new ClientHead(sessionId, ackManager, disconnectable, storeFactory, data, clientsBox, transport, disconnectScheduler, configuration); channel.attr(ClientHead.CLIENT).set(client); clientsBox.addClient(client); String[] transports = {}; if (configuration.getTransports().contains(Transport.WEBSOCKET)) { transports = new String[] { "websocket" }; } AuthPacket authPacket = new AuthPacket(sessionId, transports, configuration.getPingInterval(), configuration.getPingTimeout()); Packet packet = new Packet(PacketType.OPEN); packet.setData(authPacket); client.send(packet); client.schedulePingTimeout(); log.debug("Handshake authorized for sessionId: {}, query params: {} headers: {}", sessionId, params, headers); return true; }
From source file:com.corundumstudio.socketio.handler.ClientHead.java
License:Apache License
public ChannelFuture send(Packet packet, Transport transport) { TransportState state = channels.get(transport); state.getPacketsQueue().add(packet); Channel channel = state.getChannel(); if (channel == null || (transport == Transport.POLLING && channel.attr(EncoderHandler.WRITE_ONCE).get() != null)) { return null; }/* w w w . java 2 s. co m*/ return sendPackets(transport, channel); }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void sendMessage(HttpMessage msg, Channel channel, ByteBuf out, String type) { 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);// w w w . j a v a2 s. c o m 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); }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void addOriginHeaders(Channel channel, HttpResponse res) { if (version != null) { res.headers().add(HttpHeaders.Names.SERVER, version); }//from w w w . j av a2 s. c o m 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, "*"); } } }
From source file:com.corundumstudio.socketio.handler.EncoderHandler.java
License:Apache License
private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx) 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)) { return;//from ww w . j a v a2 s . c o m } 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); } else { encoder.encodePackets(queue, out, ctx.alloc(), 50); sendMessage(msg, channel, out, "application/octet-stream"); } }