List of usage examples for io.netty.util Attribute get
T get();
From source file:net.hasor.rsf.console.TelnetHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { request = request.trim();/*from w ww. j a v a2 s .c om*/ rxdLogger.info("RXD({})-> {}", ctx.channel().remoteAddress(), request); // Attribute<RsfCommandRequest> attr = ctx.attr(RequestKEY); boolean close = false; String result = ""; boolean doRequest = false; if (StringUtils.isBlank(request)) { if (attr != null && attr.get() != null) { doRequest = true; } } else { doRequest = true; } // if (!doRequest) { logger.info("rsfConsole -> receive RXD :" + request); } // if (doRequest) { RsfCommandResponse response = this.doRequest(attr, ctx, request); if (response != null) { close = response.isCloseConnection(); logger.info("rsfConsole -> receive RXD, response isComplete = {}, isCloseConnection = {}", response.isComplete(), response.isCloseConnection()); if (response.isComplete()) { result = response.getResult() + "\r\n" + CMD; } else { result = response.getResult() + "\r\n"; } } } else { result = CMD; } // if (StringUtils.isNotBlank(result)) { rxdLogger.info("TXD({})-> {}", ctx.channel().remoteAddress(), result); ChannelFuture future = ctx.writeAndFlush(result); if (close) { logger.info("rsfConsole -> close connection."); future.addListener(ChannelFutureListener.CLOSE); } } }
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. jav a 2s. co 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 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Attribute<HttpServerChannelHandler> attr = ctx.attr(SERVER_HANDLER_KEY); HttpServerChannelHandler handler = attr.get(); if (handler != null) { handler.exceptionCaught(ctx, cause); } else {/*from ww w . j a v a 2s .co m*/ if (cause instanceof ClosedChannelException) { // The channel is closed so we do nothing here LOG.debug("Channel already closed. Ignoring this exception."); return; } else { // we cannot throw the exception here LOG.warn( "HttpServerChannelHandler is not found as attachment to handle exception, send 404 back to the client.", cause); // Now we just send 404 back to the client 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 {//from w ww.j a va 2s . c o 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.asynchttpclient.netty.channel.Channels.java
License:Open Source License
public static Object getAttribute(Channel channel) { Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE); return attr != null ? attr.get() : null; }
From source file:org.asynchttpclient.netty.channel.Channels.java
License:Open Source License
public static ChannelId getChannelId(Channel channel) { Attribute<ChannelId> attr = channel.attr(CHANNEL_ID_ATTRIBUTE); return attr != null ? attr.get() : null; }
From source file:org.asynchttpclient.providers.netty.channel.Channels.java
License:Apache License
public static Object getDefaultAttribute(Channel channel) { Attribute<Object> attr = channel.attr(DEFAULT_ATTRIBUTE); return attr != null ? attr.get() : null; }
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();//ww w .j a va 2s . c om //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
/** * Process response debug// w w w . ja v a2 s . c o m * * @param response Response Object * @param m_ctx Netty Context * @return Return indicator shows if the response requires handling for debugging. If true, the caller needs to stop handling response */ public boolean debugResponse(FullHttpResponse response, ChannelHandlerContext m_ctx) { boolean consume = false; if (debugEnabled()) { Attribute<CacheResultVerifier> debugResult = m_ctx.attr(DEBUG_RESULT); if (debugResult.get() != null) { try { CacheVerifiedResult result = debugResult.get().fetchResult(response); m_cacheManager.getStats().addCacheVerifiedResult(result); } catch (Exception e) { LOGGER.error(e.getMessage()); } finally { consume = true; } } } return consume; }
From source file:org.ebayopensource.scc.debug.DebugManagerTest.java
License:Apache License
@Test @SuppressWarnings("unchecked") public void testDebugResponse_consume() { Mockito.when(m_appConfiguration.getBoolean("debugManager.debugEnabled")).thenReturn(true); FullHttpResponse actualResponse = Mockito.mock(FullHttpResponse.class); ChannelHandlerContext ctx = Mockito.mock(ChannelHandlerContext.class); Attribute<CacheResultVerifier> debugging = Mockito.mock(Attribute.class); Mockito.when(ctx.attr(DebugManager.DEBUG_RESULT)).thenReturn(debugging); CacheResultVerifier verifier = Mockito.mock(CacheResultVerifier.class); CacheVerifiedResult result = new CacheVerifiedResult(); result.key = "test_req"; Mockito.when(verifier.fetchResult(actualResponse)).thenReturn(result); Mockito.when(debugging.get()).thenReturn(verifier); CacheStats cacheStats = Mockito.mock(CacheStats.class); Mockito.when(m_cacheManager.getStats()).thenReturn(cacheStats); debugManager.debugResponse(actualResponse, ctx); Mockito.verify(cacheStats, Mockito.times(1)).addCacheVerifiedResult(verifier.fetchResult(actualResponse)); }