List of usage examples for io.netty.channel ChannelHandlerContext pipeline
ChannelPipeline pipeline();
From source file:com.couchbase.client.core.endpoint.kv.KeyValueFeatureHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception { List<ServerFeatures> supported = new ArrayList<ServerFeatures>(); ResponseStatus responseStatus = ResponseStatusConverter.fromBinary(msg.getStatus()); if (responseStatus.isSuccess()) { while (msg.content().isReadable()) { supported.add(ServerFeatures.fromValue(msg.content().readShort())); }/*from w w w.j a v a 2s . co m*/ } else { LOGGER.debug("HELLO Negotiation did not succeed ({}).", responseStatus); } LOGGER.debug("Negotiated supported features: {}", supported); ctx.fireUserEventTriggered(new ServerFeaturesEvent(supported)); originalPromise.setSuccess(); ctx.pipeline().remove(this); ctx.fireChannelActive(); }
From source file:com.curlymaple.server.ServerHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.pipeline().channel(); MemoryData md = new MemoryData(channel); ctx.attr(key).set(md);//from w w w .j av a 2 s.co m }
From source file:com.curlymaple.server.ServerHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception { try {//from w w w . ja va 2 s .c om // logger.info(msg); if (null == msg || "".equals(msg)) { return; } JSONObject json = JSONObject.fromObject(msg); IC2SCommand command = MessageDispatcher.dispatcher(json); if (null == command) { return; } MemoryData md = ctx.attr(key).get(); JSONObject param = JSONObject.fromObject(json.get("p")); command.execute(param, md); } catch (Exception e) { ctx.pipeline().channel().close(); ctx.pipeline().channel().disconnect(); logger.error("messageReceived", e); } }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java
License:Apache License
private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) { logger.debug("Received Acknowledge message on channel={}.", ctx.channel()); buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer); long remoteProtocolVersion = acknowledge.getProtocolVersion(); long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize(); long remoteSendBufferSize = acknowledge.getSendBufferSize(); long remoteMaxMessageSize = acknowledge.getMaxMessageSize(); long remoteMaxChunkCount = acknowledge.getMaxChunkCount(); if (PROTOCOL_VERSION > remoteProtocolVersion) { logger.warn("Client protocol version ({}) does not match server protocol version ({}).", PROTOCOL_VERSION, remoteProtocolVersion); }//ww w. ja va 2s. c o m ChannelConfig config = client.getChannelConfig(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize()); /* Max message size the remote can send us; not influenced by remote configuration. */ long localMaxMessageSize = config.getMaxMessageSize(); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = config.getMaxChunkCount(); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake); ctx.executor().execute(() -> { int maxArrayLength = client.getChannelConfig().getMaxArrayLength(); int maxStringLength = client.getChannelConfig().getMaxStringLength(); SerializationQueue serializationQueue = new SerializationQueue(client.getConfig().getExecutor(), parameters, maxArrayLength, maxStringLength); UaTcpClientAsymmetricHandler handler = new UaTcpClientAsymmetricHandler(client, serializationQueue, secureChannel, handshakeFuture); ctx.pipeline().addLast(handler); }); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientAsymmetricHandler.java
License:Apache License
private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) { ChannelSecurity.SecuritySecrets newKeys = null; if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) { throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion()); }/* ww w.j av a2 s . com*/ ChannelSecurityToken newToken = response.getSecurityToken(); if (secureChannel.isSymmetricSigningEnabled()) { secureChannel.setRemoteNonce(response.getServerNonce()); newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce()); } ChannelSecurity oldSecrets = secureChannel.getChannelSecurity(); ChannelSecurity.SecuritySecrets oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null; ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null; secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken)); DateTime createdAt = response.getSecurityToken().getCreatedAt(); long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue(); if (revisedLifetime > 0) { long renewAt = (long) (revisedLifetime * 0.75); renewFuture = ctx.executor().schedule(() -> renewSecureChannel(ctx), renewAt, TimeUnit.MILLISECONDS); } else { logger.warn("Server revised secure channel lifetime to 0; renewal will not occur."); } ctx.executor().execute(() -> { // SecureChannel is ready; remove the acknowledge handler and add the symmetric handler. if (ctx.pipeline().get(UaTcpClientAcknowledgeHandler.class) != null) { ctx.pipeline().remove(UaTcpClientAcknowledgeHandler.class); ctx.pipeline().addFirst(new UaTcpClientSymmetricHandler(client, serializationQueue, secureChannel, handshakeFuture)); } }); ChannelSecurity channelSecurity = secureChannel.getChannelSecurity(); long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue(); long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L); logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}", secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientMessageHandler.java
License:Apache License
private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) { ChannelSecurity.SecuritySecrets newKeys = null; if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) { throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion()); }//from ww w. j av a2 s. c o m ChannelSecurityToken newToken = response.getSecurityToken(); if (secureChannel.isSymmetricSigningEnabled()) { secureChannel.setRemoteNonce(response.getServerNonce()); newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce()); } ChannelSecurity oldSecrets = secureChannel.getChannelSecurity(); ChannelSecurity.SecuritySecrets oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null; ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null; secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken)); DateTime createdAt = response.getSecurityToken().getCreatedAt(); long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue(); if (revisedLifetime > 0) { long renewAt = (long) (revisedLifetime * 0.75); renewFuture = ctx.executor().schedule( () -> sendOpenSecureChannelRequest(ctx, SecurityTokenRequestType.Renew), renewAt, TimeUnit.MILLISECONDS); } else { logger.warn("Server revised secure channel lifetime to 0; renewal will not occur."); } ctx.executor().execute(() -> { // SecureChannel is ready; remove the acknowledge handler. if (ctx.pipeline().get(UaTcpClientAcknowledgeHandler.class) != null) { ctx.pipeline().remove(UaTcpClientAcknowledgeHandler.class); } }); ChannelSecurity channelSecurity = secureChannel.getChannelSecurity(); long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue(); long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L); logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}", secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt); }
From source file:com.digitalpetri.opcua.stack.client.handlers.UaTcpClientSymmetricHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { List<UaMessage> awaitingHandshake = ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE) .get();/*from w w w . j av a 2 s .c om*/ if (awaitingHandshake != null) { logger.debug("{} message(s) queued before handshake completed; sending now.", awaitingHandshake.size()); awaitingHandshake.forEach(m -> ctx.pipeline().write(m)); ctx.flush(); ctx.channel().attr(UaTcpClientAcknowledgeHandler.KEY_AWAITING_HANDSHAKE).remove(); } client.getExecutorService().execute(() -> handshakeFuture.complete(secureChannel)); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerAsymmetricHandler.java
License:Apache License
private void sendOpenSecureChannelResponse(ChannelHandlerContext ctx, long requestId, OpenSecureChannelResponse response) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.buffer(); try {/*from ww w . ja va2 s .c o m*/ binaryEncoder.setBuffer(messageBuffer); binaryEncoder.encodeMessage(null, response); List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric(secureChannel, MessageType.OpenSecureChannel, messageBuffer, requestId); if (!symmetricHandlerAdded) { ctx.pipeline() .addFirst(new UaTcpServerSymmetricHandler(server, serializationQueue, secureChannel)); symmetricHandlerAdded = true; } chunks.forEach(c -> ctx.write(c, ctx.voidPromise())); ctx.flush(); long lifetime = response.getSecurityToken().getRevisedLifetime().longValue(); server.secureChannelIssuedOrRenewed(secureChannel, lifetime); logger.debug("Sent OpenSecureChannelResponse."); } catch (UaException e) { logger.error("Error encoding OpenSecureChannelResponse: {}", e.getMessage(), e); ctx.close(); } finally { messageBuffer.release(); } }); }
From source file:com.digitalpetri.opcua.stack.server.handlers.UaTcpServerHelloHandler.java
License:Apache License
private void onHello(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { logger.debug("[remote={}] Received Hello message.", ctx.channel().remoteAddress()); HelloMessage hello = TcpMessageDecoder.decodeHello(buffer); UaTcpStackServer server = socketServer.getServer(hello.getEndpointUrl()); if (server == null) { throw new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid, "unrecognized endpoint url: " + hello.getEndpointUrl()); }/*from w w w . j a v a2s. com*/ ctx.channel().attr(ENDPOINT_URL_KEY).set(hello.getEndpointUrl()); long remoteProtocolVersion = hello.getProtocolVersion(); long remoteReceiveBufferSize = hello.getReceiveBufferSize(); long remoteSendBufferSize = hello.getSendBufferSize(); long remoteMaxMessageSize = hello.getMaxMessageSize(); long remoteMaxChunkCount = hello.getMaxChunkCount(); if (remoteProtocolVersion < PROTOCOL_VERSION) { throw new UaException(StatusCodes.Bad_ProtocolVersionUnsupported, "unsupported protocol version: " + remoteProtocolVersion); } ChannelConfig config = server.getChannelConfig(); /* Our receive buffer size is determined by the remote send buffer size. */ long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize()); /* Our send buffer size is determined by the remote receive buffer size. */ long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize()); /* Max chunk count the remote can send us; not influenced by remote configuration. */ long localMaxChunkCount = config.getMaxChunkCount(); /* Max message size the remote can send us. Determined by our max chunk count and receive buffer size. */ long localMaxMessageSize = Math.min(localReceiveBufferSize * localMaxChunkCount, config.getMaxMessageSize()); ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize), Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize), Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize), Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize), Ints.saturatedCast(remoteMaxChunkCount)); int maxArrayLength = config.getMaxArrayLength(); int maxStringLength = config.getMaxStringLength(); SerializationQueue serializationQueue = new SerializationQueue(server.getConfig().getExecutor(), parameters, maxArrayLength, maxStringLength); ctx.pipeline().addLast(new UaTcpServerAsymmetricHandler(server, serializationQueue)); ctx.pipeline().remove(this); logger.debug("[remote={}] Removed HelloHandler, added AsymmetricHandler.", ctx.channel().remoteAddress()); AcknowledgeMessage acknowledge = new AcknowledgeMessage(PROTOCOL_VERSION, localReceiveBufferSize, localSendBufferSize, localMaxMessageSize, localMaxChunkCount); ByteBuf messageBuffer = TcpMessageEncoder.encode(acknowledge); ctx.executor().execute(() -> ctx.writeAndFlush(messageBuffer)); logger.debug("[remote={}] Sent Acknowledge message.", ctx.channel().remoteAddress()); }
From source file:com.e2e.management.HttpSocketHandler.java
License:Apache License
public void handleHttpFileRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);//from www .j a va 2 s. c om return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } String uri = request.getUri(); if (uri == null) { sendError(ctx, FORBIDDEN); return; } if ((uri.equals("")) || (uri.equals("/"))) { uri = "/index.html"; } final String path = sanitizeUri(uri); File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { sendListing(ctx, file); } else { sendRedirect(ctx, uri + '/'); } return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); // Only compare up to the second because the datetime format we send to the client // does not have milliseconds long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000; long fileLastModifiedSeconds = file.lastModified() / 1000; if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, Values.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }