List of usage examples for io.netty.util Attribute set
void set(T value);
From source file:io.moquette.server.netty.metrics.MessageMetricsHandler.java
License:Open Source License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { Attribute<MessageMetrics> attr = ctx.attr(ATTR_KEY_METRICS); attr.set(new MessageMetrics()); super.channelActive(ctx); }
From source file:io.moquette.server.netty.NettyChannel.java
License:Open Source License
public void setAttribute(AttributeKey<Object> key, Object value) { Attribute<Object> attr = m_channel.attr(key); attr.set(value); }
From source file:io.vertx.core.net.impl.SslHandshakeCompletionHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof SniCompletionEvent) { // Shall we care ? SniCompletionEvent completion = (SniCompletionEvent) evt; Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR); val.set(completion.hostname()); } else if (evt instanceof SslHandshakeCompletionEvent) { SslHandshakeCompletionEvent completion = (SslHandshakeCompletionEvent) evt; if (completion.isSuccess()) { ctx.pipeline().remove(this); handler.handle(Future.succeededFuture(ctx.channel())); } else {/*w ww.ja va 2s . co m*/ handler.handle(Future.failedFuture(completion.cause())); } } else { ctx.fireUserEventTriggered(evt); } }
From source file:io.vertx.core.net.impl.VertxSniHandler.java
License:Open Source License
@Override protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception { SslHandler sslHandler = null;/*ww w .j a v a 2s .c o m*/ try { SSLEngine engine = helper.createEngine(sslContext); sslHandler = new SslHandler(engine); ctx.pipeline().replace(this, "ssl", sslHandler); Future<Channel> fut = sslHandler.handshakeFuture(); fut.addListener(future -> { if (future.isSuccess()) { Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR); val.set(hostname); handshakeFuture.setSuccess(ctx.channel()); } else { handshakeFuture.setFailure(future.cause()); } }); sslHandler = null; } finally { // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not // transferred to the SslHandler. // See https://github.com/netty/netty/issues/5678 if (sslHandler != null) { ReferenceCountUtil.safeRelease(sslHandler.engine()); } } }
From source file:net.hasor.rsf.console.TelnetHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { InetSocketAddress inetAddress = (InetSocketAddress) ctx.channel().remoteAddress(); String remoteAddress = inetAddress.getAddress().getHostAddress(); ///*from w w w . j av a2 s .c o m*/ boolean contains = false; for (String addr : this.inBoundAddress) { if (addr.equals(remoteAddress)) contains = true; } // if (!contains) { logger.warn("rsfConsole -> reject inBound socket ,remoteAddress = {}.", remoteAddress); ctx.write("--------------------------------------------\r\n\r\n"); ctx.write("I'm sorry you are not allowed to connect RSF Console.\r\n\r\n"); ctx.write(" your address is :" + remoteAddress + "\r\n"); ctx.write("--------------------------------------------\r\n"); ctx.flush(); ctx.close(); return; } else { logger.info("rsfConsole -> accept inBound socket ,remoteAddress = {}.", remoteAddress); } // RsfSettings settings = this.rsfContext.getSettings(); List<String> rsfAddressList = getStrings(settings.getBindAddressSet()); // Attribute<RsfCommandSession> attr = ctx.attr(SessionKEY); if (attr.get() == null) { logger.info("rsfConsole -> new RsfCommandSession."); attr.set(new RsfCommandSession(this.rsfContext, ctx)); } logger.info("rsfConsole -> send Welcome info."); // Send greeting for a new connection. ctx.write("--------------------------------------------\r\n\r\n"); ctx.write("Welcome to RSF Console!\r\n"); ctx.write("\r\n"); ctx.write(" login : " + new Date() + " now. form " + ctx.channel().remoteAddress() + "\r\n"); ctx.write(" workAt : " + ctx.channel().localAddress() + "\r\n"); for (int i = 0; i < rsfAddressList.size(); i++) { if (i == 0) { ctx.write("rsfAddress : " + rsfAddressList.get(i) + "\r\n"); } else { ctx.write(" : " + rsfAddressList.get(i) + "\r\n"); } } ctx.write(" unitName : " + this.rsfContext.getSettings().getUnitName() + "\r\n\r\n"); ctx.write("Tips: You can enter a 'help' or 'help -a' for more information.\r\n"); ctx.write("use the 'exit' or 'quit' out of the console.\r\n"); ctx.write("--------------------------------------------\r\n"); ctx.write(CMD); ctx.flush(); }
From source file:net.hasor.rsf.console.TelnetHandler.java
License:Apache License
private RsfCommandResponse doRequest(final Attribute<RsfCommandRequest> cmdAttr, final ChannelHandlerContext ctx, final String inputString) { // .//from w w w .j a v a 2 s . c o m logger.info("rsfConsole -> doRequest, pre environment."); RsfCommandRequest requestCmd = cmdAttr.get(); Attribute<RsfCommandSession> sessionAttr = ctx.attr(SessionKEY); boolean newCommand = (requestCmd == null); // // .? if (requestCmd == null) { String requestCMD = inputString; String requestArgs = ""; int cmdIndex = inputString.indexOf(" "); if (inputString.indexOf(" ") > 0) { requestCMD = inputString.substring(0, cmdIndex); requestArgs = inputString.substring(cmdIndex + 1); } RsfInstruct rsfInstruct = this.commandManager.findCommand(requestCMD); if (rsfInstruct == null) { String msgStr = "'" + requestCMD + "' is bad command."; logger.info("rsfConsole -> " + msgStr); return new RsfCommandResponse(msgStr, true, false); } // logger.info("rsfConsole -> doRequest, RsfCommandRequest in ctx exist. -> command = {} , args = {}", requestCMD, requestArgs); requestCmd = new RsfCommandRequest(requestCMD, sessionAttr.get(), rsfInstruct, requestArgs); cmdAttr.set(requestCmd); } // // .???? if (requestCmd.inputMultiLine()) { /*?*/ if (requestCmd.getStatus() == CommandRequestStatus.Prepare) { if (!newCommand) { requestCmd.appendRequestBody(inputString); } if (StringUtils.isBlank(inputString)) { requestCmd.inReady();// } } else if (requestCmd.getStatus() == CommandRequestStatus.Ready) { if (StringUtils.isBlank(inputString)) { requestCmd.inStandBy();// } else { requestCmd.appendRequestBody(inputString); } } } else { /*??*/ requestCmd.inStandBy(); } // //3. if (requestCmd.getStatus() == CommandRequestStatus.StandBy) { logger.info("rsfConsole -> doRequest, doRunning."); requestCmd.doCommand(executor, new Runnable() { public void run() { cmdAttr.remove(); ctx.writeAndFlush("\r\n" + CMD); } }); //? return requestCmd.getResponse(); } else if (requestCmd.getStatus() == CommandRequestStatus.Running) { return new RsfCommandResponse("command is running, please wait a moment.", false, false); } // return null; }
From source file:org.apache.camel.component.netty4.http.handlers.HttpServerMultiplexChannelHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { // store request, as this channel handler is created per pipeline HttpRequest request = (HttpRequest) msg; LOG.debug("Message received: {}", request); HttpServerChannelHandler handler = getHandler(request); if (handler != null) { Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY); // store handler as attachment attr.set(handler); if (msg instanceof HttpContent) { // need to hold the reference of content HttpContent httpContent = (HttpContent) msg; httpContent.content().retain(); }/*w ww .j av a2s.c om*/ handler.channelRead(ctx, request); } else { // this resource is not found, so send empty response back HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); response.headers().set(Exchange.CONTENT_TYPE, "text/plain"); response.headers().set(Exchange.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); ctx.close(); } }
From source file:org.apache.tinkerpop.gremlin.server.handler.SaslAuthenticationHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception { if (msg instanceof RequestMessage) { final RequestMessage requestMessage = (RequestMessage) msg; final Attribute<Authenticator.SaslNegotiator> negotiator = ctx.attr(StateKey.NEGOTIATOR); final Attribute<RequestMessage> request = ctx.attr(StateKey.REQUEST_MESSAGE); if (negotiator.get() == null) { // First time through so save the request and send an AUTHENTICATE challenge with no data negotiator.set(authenticator.newSaslNegotiator(getRemoteInetAddress(ctx))); request.set(requestMessage); final ResponseMessage authenticate = ResponseMessage.build(requestMessage) .code(ResponseStatusCode.AUTHENTICATE).create(); ctx.writeAndFlush(authenticate); } else {/* w w w . ja v a 2s.co m*/ if (requestMessage.getOp().equals(Tokens.OPS_AUTHENTICATION) && requestMessage.getArgs().containsKey(Tokens.ARGS_SASL)) { final Object saslObject = requestMessage.getArgs().get(Tokens.ARGS_SASL); final byte[] saslResponse; if (saslObject instanceof byte[]) { saslResponse = (byte[]) saslObject; } else if (saslObject instanceof String) { saslResponse = BASE64_DECODER.decode((String) saslObject); } else { final ResponseMessage error = ResponseMessage.build(request.get()) .statusMessage("Incorrect type for : " + Tokens.ARGS_SASL + " - byte[] or base64 encoded String is expected") .code(ResponseStatusCode.REQUEST_ERROR_MALFORMED_REQUEST).create(); ctx.writeAndFlush(error); return; } try { final byte[] saslMessage = negotiator.get().evaluateResponse(saslResponse); if (negotiator.get().isComplete()) { // todo: do something with this user final AuthenticatedUser user = negotiator.get().getAuthenticatedUser(); // If we have got here we are authenticated so remove the handler and pass // the original message down the pipeline for processing ctx.pipeline().remove(this); final RequestMessage original = request.get(); ctx.fireChannelRead(original); } else { // not done here - send back the sasl message for next challenge. note that we send back // the base64 encoded sasl as well as the byte array. the byte array will eventually be // phased out, but is present now for backward compatibility in 3.2.x final Map<String, Object> metadata = new HashMap<>(); metadata.put(Tokens.ARGS_SASL, BASE64_ENCODER.encodeToString(saslMessage)); final ResponseMessage authenticate = ResponseMessage.build(requestMessage) .statusAttributes(metadata).code(ResponseStatusCode.AUTHENTICATE) .result(saslMessage).create(); ctx.writeAndFlush(authenticate); } } catch (AuthenticationException ae) { final ResponseMessage error = ResponseMessage.build(request.get()) .statusMessage(ae.getMessage()).code(ResponseStatusCode.UNAUTHORIZED).create(); ctx.writeAndFlush(error); } } else { final ResponseMessage error = ResponseMessage.build(requestMessage) .statusMessage("Failed to authenticate").code(ResponseStatusCode.UNAUTHORIZED).create(); ctx.writeAndFlush(error); } } } else { logger.warn("{} only processes RequestMessage instances - received {} - channel closing", this.getClass().getSimpleName(), msg.getClass()); ctx.close(); } }
From source file:org.dna.mqtt.moquette.parser.netty.ConnectDecoder.java
License:Open Source License
@Override void decode(AttributeMap ctx, ByteBuf in, List<Object> out) throws UnsupportedEncodingException { in.resetReaderIndex();//from w ww . j av a2 s . c o m //Common decoding part ConnectMessage message = new ConnectMessage(); 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) 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) 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.setProcotolVersion(in.readByte()); if (message.getProcotolVersion() == VERSION_3_1_1) { //if 3.1.1, check the flags (dup, retain and qos == 0) if (message.isDupFlag() || message.isRetainFlag() || message.getQos() != AbstractMessage.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.getProcotolVersion() == 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 = Utils.readWord(in); int keepAlive = in.readUnsignedShort(); message.setKeepAlive(keepAlive); if ((remainingLength == 12 && message.getProcotolVersion() == VERSION_3_1) || (remainingLength == 10 && message.getProcotolVersion() == VERSION_3_1_1)) { out.add(message); return; } //Decode the ClientID String clientID = Utils.decodeString(in); if (clientID == null) { in.resetReaderIndex(); return; } message.setClientID(clientID); //Decode willTopic if (willFlag) { String willTopic = Utils.decodeString(in); if (willTopic == null) { in.resetReaderIndex(); return; } message.setWillTopic(willTopic); } //Decode willMessage if (willFlag) { String willMessage = Utils.decodeString(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 = Utils.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) { String password = Utils.decodeString(in); if (password == null) { in.resetReaderIndex(); return; } message.setPassword(password); } out.add(message); }
From source file:org.ebayopensource.scc.debug.DebugManager.java
License:Apache License
/** * Issue a debug request when debugging is enabled. * * @param httpObject Http request of client * @param m_ctx Netty context//from w ww . j a v a 2s .c o m * @param fromDebugFilter Indicator shows if the request require to be forwarded * @return An indicator showing if debug manager consumes the request. If true, the caller needs to stop handling request. */ public void issueDebugRequest(FullHttpRequest httpObject, final ChannelHandlerContext m_ctx, boolean fromDebugFilter) { if (debugEnabled()) { final FullHttpRequest request = httpObject.copy(); if (fromDebugFilter) { try { if (ssl(request)) { Field field = ClientToProxyConnection.class.getDeclaredField("mitming"); field.setAccessible(true); field.set(m_ctx.handler(), true); } } catch (Exception e) { LOGGER.error(e.getMessage()); } String key = m_policyManager.generateCacheKey(request); FullHttpResponse cacheResponse = m_policyManager.getCacheManager().get(key); CacheResultVerifier verifier = new CacheResultVerifier(key, request, cacheResponse); Attribute<CacheResultVerifier> debugging = m_ctx.attr(DEBUG_RESULT); debugging.set(verifier); } else { executor.execute(new Runnable() { @Override public void run() { forwardDebugRequest(request); } }); } } }