List of usage examples for io.netty.channel ChannelHandlerContext attr
@Deprecated @Override <T> Attribute<T> attr(AttributeKey<T> key);
From source file:io.netlibs.bgp.netty.handlers.ValidateServerIdentifier.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, OpenPacket openPacket) throws Exception { PeerConnectionInformation peerConnInfo = ctx.attr(BGPv4ClientEndpoint.PEER_CONNECTION_INFO).get(); if (openPacket.getBgpIdentifier() != peerConnInfo.getRemoteBgpIdentifier()) { log.error("expected remote BGP identifier {}, received BGP identifier {}", peerConnInfo.getRemoteBgpIdentifier(), openPacket.getBgpIdentifier()); NotificationHelper.sendNotification(ctx, new BadBgpIdentifierNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return;// w w w. ja va 2s. c o m } if (peerConnInfo.getRemoteAS() > 65535) { // we must have an AutonomousSystem4 capability at this point in the OPEN packet and a AS_TRANS 2-octet AS number if (openPacket.getAutonomousSystem() != BGPv4Constants.BGP_AS_TRANS) { log.error("expected remote autonomous system {}, received autonomous system {}", BGPv4Constants.BGP_AS_TRANS, openPacket.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } AutonomousSystem4Capability as4cap = openPacket.findCapability(AutonomousSystem4Capability.class); if (as4cap == null) { log.error("missing Autonomous system 4-octet capability"); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } if (as4cap.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), as4cap.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } } else { if (openPacket.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), openPacket.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } // we may have an optional AS4 capability but if we have it it must carry the same AS number as the 2-octet AS number AutonomousSystem4Capability as4cap = openPacket.findCapability(AutonomousSystem4Capability.class); if (as4cap != null) { if (as4cap.getAutonomousSystem() != peerConnInfo.getRemoteAS()) { log.error("expected remote autonomous system {}, received autonomous system {}", peerConnInfo.getRemoteAS(), as4cap.getAutonomousSystem()); NotificationHelper.sendNotification(ctx, new BadPeerASNotificationPacket(), new BgpEventFireChannelFutureListener(ctx)); return; } } } ctx.fireChannelRead(openPacket); }
From source file:io.urmia.job.handler.JobHandler.java
License:Open Source License
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { JobRequest jobRequest = ctx.attr(jobAttributeKey).getAndRemove(); log.info("channelInactive jobRequest: {} in ctx: {}", jobRequest, ctx); //if(jobRequest == null) // return; //log.info("publishing EOT as channel inactive for job: {}", jobRequest); //input(new JobInputRequest(jobRequest, JobInput.end())); }
From source file:io.urmia.job.handler.JobHandler.java
License:Open Source License
@Override protected void channelRead0(final ChannelHandlerContext ctx, final JobRequest msg) throws Exception { log.info("channelRead0 received: {}", msg); String location = msg.objectName.owner + '/' + msg.objectName.ns.path + '/' + msg.getId(); if (StringUtils.isBlank(location)) { final HttpResponse httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); ctx.writeAndFlush(httpResp);/*from w w w. ja va 2s . co m*/ ctx.channel().close(); return; } if (msg instanceof JobQueryRequest) { JobQueryRequest queryRequest = (JobQueryRequest) msg; Optional<String> status = query(queryRequest); final HttpResponse httpResp; if (status.isPresent()) { byte[] statusByes = status.get().getBytes(); httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(statusByes)); httpResp.headers().set("Content-Type", "application/json"); httpResp.headers().set("Content-Length", statusByes.length); httpResp.headers().set("Connection", "close"); } else { String err = String.format("{\"code\":\"ResourceNotFound\",\"message\":\"%s was not found\"}", location); httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, Unpooled.wrappedBuffer(err.getBytes())); httpResp.headers().set("Content-Length", err.length()); httpResp.headers().set("Connection", "close"); } ctx.writeAndFlush(httpResp); return; } if (msg instanceof JobCancelRequest) { JobCancelRequest cancelRequest = (JobCancelRequest) msg; cancel(cancelRequest); final HttpResponse httpResp; httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, ACCEPTED); httpResp.headers().set("Content-Type", "application/json"); httpResp.headers().set("Content-Length", 0); httpResp.headers().set("Connection", "close"); ctx.writeAndFlush(httpResp); return; } if (msg instanceof JobCreateRequest) { JobCreateRequest createRequest = (JobCreateRequest) msg; register(createRequest); ctx.attr(jobAttributeKey).setIfAbsent(msg); log.info("added jobReq {} to ctx: {}", msg, ctx); DefaultFullHttpResponse httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, CREATED); httpResp.headers().add("location", msg.getId()); httpResp.headers().add("Content-Length", 0); ctx.writeAndFlush(httpResp); return; } if (msg instanceof JobInputRequest) { JobInputRequest inputRequest = (JobInputRequest) msg; input(inputRequest); boolean end = inputRequest.input.isEod(); final HttpResponse httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, CREATED); httpResp.headers().add("Content-Length", 0); ctx.writeAndFlush(httpResp); if (end) ctx.channel().close(); return; } if (msg instanceof JobGetRequest) { JobGetRequest getRequest = (JobGetRequest) msg; setupProxyGet(ctx, getRequest); return; } log.error("invalid input"); final HttpResponse httpResp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST); ctx.writeAndFlush(httpResp); ctx.channel().close(); }
From source file:io.urmia.job.handler.JobIdleStateHandler.java
License:Open Source License
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { log.info("userEventTriggered ctx: {} evt: {}", ctx, evt); if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; JobRequest jobRequest = ctx.attr(JobHandler.jobAttributeKey).getAndRemove(); log.info("userEventTriggered jobRequest: {}", jobRequest); /*//from www . j a v a 2s. c o m if (e.state() == IdleState.READER_IDLE) { ctx.close(); } else if (e.state() == IdleState.WRITER_IDLE) { ctx.writeAndFlush(new PingMessage()); } */ } }
From source file:net.bafeimao.umbrella.support.network.netty.handler.DefaultServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Packet packet) throws Exception { LOGGER.info("RECEIVED: {} [type:{}]", packet, packet.getType()); ctx.attr(key).setIfAbsent(new NettyChannelHandlerContext(ctx)); HandlerContext context = ctx.attr(key).get(); try {/*w w w . j a va2 s. co m*/ messageDispatcher.dispatch(context, packet); } catch (Exception e) { LOGGER.error("????:{}", e); // ctx.write(packet.toBuilder().setError(ErrorCode.SERVER_INTERNAL_ERROR_VALUE)); Errors.sendError(context, packet, ErrorCode.SERVER_INTERNAL_ERROR); } }
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 a va 2s . 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
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { request = request.trim();/*from ww w.j av a 2s .co m*/ 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 void clearAttr(ChannelHandlerContext ctx) { Attribute<RsfCommandSession> sessionAttr = ctx.attr(SessionKEY); Attribute<RsfCommandRequest> attr = ctx.attr(RequestKEY); if (sessionAttr != null) { logger.info("rsfConsole -> clearAttr ,remove sessionAttr."); sessionAttr.remove();/*from w ww . ja va 2s . c o m*/ } if (attr != null) { logger.info("rsfConsole -> clearAttr ,remove requestAttr."); attr.remove(); } }
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 ww .j av a 2s .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:net.pms.network.RequestHandlerV2.java
License:Open Source License
private void writeResponse(ChannelHandlerContext ctx, FullHttpRequest e, RequestV2 request, InetAddress ia) { // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE .equalsIgnoreCase(nettyRequest.headers().get(HttpHeaders.Names.CONNECTION)) || nettyRequest.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE .equalsIgnoreCase(nettyRequest.headers().get(HttpHeaders.Names.CONNECTION)); // Build the response object. HttpResponse response;// ww w .j a v a 2s. c o m if (request.getLowRange() != 0 || request.getHighRange() != 0) { response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PARTIAL_CONTENT); } else { String soapAction = nettyRequest.headers().get("SOAPACTION"); if (soapAction != null && soapAction.contains("X_GetFeatureList")) { LOGGER.debug("Invalid action in SOAPACTION: " + soapAction); response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } else { response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } } StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(ia.getHostAddress()); // Attach it to the context so it can be invoked if connection is reset unexpectedly ctx.attr(startStop).set(startStopListenerDelegate); try { request.answer(ctx, response, e, close, startStopListenerDelegate); } catch (IOException e1) { LOGGER.trace("HTTP request V2 IO error: " + e1.getMessage()); // note: we don't call stop() here in a finally block as // answer() is non-blocking. we only (may) need to call it // here in the case of an exception. it's a no-op if it's // already been called startStopListenerDelegate.stop(); } }