List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:com.alibaba.dubbo.qos.server.handler.HttpProcessHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception { CommandContext commandContext = HttpCommandDecoder.decode(msg); // return 404 when fail to construct command context if (commandContext == null) { log.warn("can not found commandContext url: " + msg.getUri()); FullHttpResponse response = http_404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else {// ww w . j a v a 2 s. c o m commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); FullHttpResponse response = http_200(result); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (NoSuchCommandException ex) { log.error("can not find commandContext: " + commandContext, ex); FullHttpResponse response = http_404(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } catch (Exception qosEx) { log.error("execute commandContext: " + commandContext + " got exception", qosEx); FullHttpResponse response = http_500(qosEx.getMessage()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } } }
From source file:com.alibaba.dubbo.qos.server.handler.LocalHostPermitHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { if (!acceptForeignIp) { if (!((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().isLoopbackAddress()) { ByteBuf cb = Unpooled.wrappedBuffer( (QosConstants.BR_STR + "Foreign Ip Not Permitted." + QosConstants.BR_STR).getBytes()); ctx.writeAndFlush(cb).addListener(ChannelFutureListener.CLOSE); }/*from w w w . j a v a2 s. c om*/ } }
From source file:com.alibaba.dubbo.qos.server.handler.TelnetProcessHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { if (StringUtils.isBlank(msg)) { ctx.writeAndFlush(QosProcessHandler.prompt); } else {// w ww. j a v a 2s . co m CommandContext commandContext = TelnetCommandDecoder.decode(msg); commandContext.setRemote(ctx.channel()); try { String result = commandExecutor.execute(commandContext); if (StringUtils.equals(QosConstants.CLOSE, result)) { ctx.writeAndFlush(getByeLabel()).addListener(ChannelFutureListener.CLOSE); } else { ctx.writeAndFlush(result + QosConstants.BR_STR + QosProcessHandler.prompt); } } catch (NoSuchCommandException ex) { ctx.writeAndFlush(msg + " :no such command"); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.prompt); log.error("can not found command " + commandContext, ex); } catch (Exception ex) { ctx.writeAndFlush(msg + " :fail to execute commandContext by " + ex.getMessage()); ctx.writeAndFlush(QosConstants.BR_STR + QosProcessHandler.prompt); log.error("execute commandContext got exception " + commandContext, ex); } } }
From source file:com.android.tools.idea.diagnostics.crash.LocalTestServer.java
License:Apache License
public void start() throws Exception { ServerBootstrap b = new ServerBootstrap(); myEventLoopGroup = new OioEventLoopGroup(); b.group(myEventLoopGroup).channel(OioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override// w ww .ja v a 2s . co m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpServerCodec()); // Note: Netty's decompressor uses jcraft jzlib, which is not exported as a library // p.addLast(new HttpContentDecompressor()); p.addLast(new HttpObjectAggregator(32 * 1024)); // big enough to collect a full thread dump p.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.flush(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { return; } FullHttpResponse response = myResponseSupplier.apply((FullHttpRequest) msg); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes()); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.write(cause.toString()).addListener(ChannelFutureListener.CLOSE); } }); } }); myChannel = b.bind(myPort).sync().channel(); }
From source file:com.artigile.homestats.HomeStatsHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; byte responseBody[]; final String uri = req.uri(); if (uri.startsWith("/getCurrentHumidity")) { responseBody = getHumidity(); } else if (uri.startsWith("/getCurrentTemp")) { responseBody = getTemperature(); } else if (uri.startsWith("/getCurrentPressure")) { responseBody = getPressure(); } else if (uri.startsWith("/getData")) { responseBody = readDataFromDb(); } else {//from w ww. java2s . c o m responseBody = "404".getBytes(); } if (HttpHeaderUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } boolean keepAlive = HttpHeaderUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(responseBody)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } } }
From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/*from w ww .j a v a 2 s .c o m*/ buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/*w ww . ja v a 2 s.co m*/ buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().write(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.athena.peacock.controller.netty.PeacockServerHandler.java
License:Open Source License
@SuppressWarnings("unchecked") @Override/*from www . j a v a2 s . co m*/ protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("channelRead0() has invoked."); logger.debug("[Server] IP Address => " + ctx.channel().remoteAddress().toString()); logger.debug("[Server] Object => " + msg.getClass().getName()); //logger.debug("[Server] Contents => " + msg.toString()); if ("bye".equals(msg.toString())) { // Response and exit. ChannelFuture future = ctx.write("This channel will be closed."); future.addListener(ChannelFutureListener.CLOSE); } else { if (msg instanceof PeacockDatagram) { MessageType messageType = ((PeacockDatagram<?>) msg).getMessageType(); switch (messageType) { case COMMAND: break; case RESPONSE: ProvisioningResponseMessage responseMsg = ((PeacockDatagram<ProvisioningResponseMessage>) msg) .getMessage(); if (responseMsg.isBlocking()) { CallbackManagement.poll().handle(responseMsg); } break; case SYSTEM_STATUS: AgentSystemStatusMessage statusMsg = ((PeacockDatagram<AgentSystemStatusMessage>) msg) .getMessage(); //ThreadLocal cannot use. //List<MonFactorDto> monFactorList = (List<MonFactorDto>) ThreadLocalUtil.get(PeacockConstant.MON_FACTOR_LIST); List<MonFactorDto> monFactorList = AppContext.getBean(MonFactorHandler.class) .getMonFactorList(); List<MonDataDto> monDataList = new ArrayList<MonDataDto>(); MonDataDto monData = null; for (MonFactorDto monFactor : monFactorList) { monData = new MonDataDto(); monData.setMachineId(statusMsg.getAgentId()); monData.setMonFactorId(monFactor.getMonFactorId()); monData.setMonDataValue(getMonDataValue(monFactor, statusMsg)); monData.setRegUserId(1); monData.setUpdUserId(1); monDataList.add(monData); } if (this.monitorService == null) { monitorService = AppContext.getBean(MonitorService.class); } monitorService.insertMonDataList(monDataList); break; case INITIAL_INFO: AgentInitialInfoMessage infoMsg = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage(); if (infoMsg.getMachineId() != null) { // register a new channel ChannelManagement.registerChannel(infoMsg.getMachineId(), ctx.channel()); break; } String ipAddr = ctx.channel().remoteAddress().toString(); ipAddr = ipAddr.substring(1, ipAddr.indexOf(":")); // ipAddr? rhev_id RHEV Manager . String machineId = infoMsg.getAgentId(); Integer hypervisorId = null; String displayName = null; String clusterName = null; String isPrd = "N"; String isVm = "N"; String description = null; boolean isMatch = false; try { List<RHEVMRestTemplate> templates = RHEVMRestTemplateManager.getAllTemplates(); if (templates == null || templates.size() == 0) { List<HypervisorDto> hypervisorList = AppContext.getBean(HypervisorService.class) .getHypervisorList(); RHEVMRestTemplateManager.resetRHEVMRestTemplate(hypervisorList); templates = RHEVMRestTemplateManager.getAllTemplates(); } logger.debug("[PeacockServerHandler] templates.size() : {}", templates.size()); for (RHEVMRestTemplate restTemplate : templates) { VMs vms = restTemplate.submit("/api/vms?search=" + ipAddr, HttpMethod.GET, VMs.class); if (vms.getVMs().size() > 0) { isVm = "Y"; List<VM> vmList = vms.getVMs(); List<IP> ipList = null; for (VM vm : vmList) { // ip ? ? getIps() null? . ipList = vm.getGuestInfo().getIps().getIPs(); for (IP ip : ipList) { if (ip.getAddress().equals(ipAddr)) { isMatch = true; machineId = vm.getId(); hypervisorId = restTemplate.getHypervisorId(); displayName = vm.getName(); description = vm.getDescription(); Cluster cluster = restTemplate.submit(vm.getCluster().getHref(), HttpMethod.GET, Cluster.class); clusterName = cluster.getName(); break; } } if (isMatch) { break; } } } if (isMatch) { break; } } } catch (Exception e) { // ignore logger.error("Unhandled Exception has occurred.", e); } // register a new channel ChannelManagement.registerChannel(machineId, ctx.channel()); // Agent? RHEV Manager? ?? ID ??? AgentID // Agent? Software ?? ? Software ? ? AgentInitialInfoMessage returnMsg = new AgentInitialInfoMessage(); returnMsg.setAgentId(machineId); PeacockDatagram<AbstractMessage> datagram = new PeacockDatagram<AbstractMessage>(returnMsg); ctx.channel().writeAndFlush(datagram); if (this.machineService == null) { machineService = AppContext.getBean(MachineService.class); } // Instance DB? . MachineDto machine = new MachineDto(); machine.setMachineId(machineId); machine.setHypervisorId(hypervisorId); machine.setDisplayName(displayName); machine.setDescription(description); if (StringUtils.isNotEmpty(displayName)) { if (displayName.toLowerCase().startsWith("hhilws") && !displayName.toLowerCase().startsWith("hhilwsd")) { isPrd = "Y"; } } machine.setIsPrd(isPrd); machine.setMachineMacAddr(infoMsg.getMacAddrMap().get(ipAddr)); machine.setIsVm(isVm); machine.setCluster(clusterName); machine.setOsName(infoMsg.getOsName()); machine.setOsVer(infoMsg.getOsVersion()); machine.setOsArch(infoMsg.getOsArch()); machine.setCpuClock(Integer.toString(infoMsg.getCpuClock())); machine.setCpuNum(Integer.toString(infoMsg.getCpuNum())); machine.setMemSize(Long.toString(infoMsg.getMemSize())); machine.setIpAddr(ipAddr); machine.setHostName(infoMsg.getHostName()); machine.setRegUserId(1); machine.setUpdUserId(1); machineService.insertMachine(machine); // machine_additional_info_tbl? hostname ? IP ? .( ? IP applyYn ?) machine = machineService.getAdditionalInfo(machineId); boolean hostnameChanged = false; // hostname chhost.sh . if (machine != null && StringUtils.isNotEmpty(machine.getHostName()) && !machine.getHostName().equals(infoMsg.getHostName())) { try { // /etc/hosts ?? ? ipAddress Machine? IP? ? IP? ?. String ipAddress = null; if (StringUtils.isNotEmpty(machine.getIpAddress())) { ipAddress = machine.getIpAddress(); } else { ipAddress = ipAddr; } ProvisioningCommandMessage cmdMsg = new ProvisioningCommandMessage(); cmdMsg.setAgentId(machine.getMachineId()); //cmdMsg.setBlocking(true); int sequence = 0; Command command = new Command("SET_HOSTNAME"); ShellAction action = new ShellAction(sequence++); action.setCommand("sh"); action.addArguments("chhost.sh"); action.addArguments(ipAddress); action.addArguments(machine.getHostName()); command.addAction(action); cmdMsg.addCommand(command); datagram = new PeacockDatagram<AbstractMessage>(cmdMsg); ctx.channel().writeAndFlush(datagram); hostnameChanged = true; } catch (Exception e) { // HostName ? ?? IP ? ?? . logger.error("Unhandled exception has occurred while change hostname.", e); } } boolean resetIp = false; if (machine != null && StringUtils.isNotEmpty(machine.getIpAddress())) { if (machine.getApplyYn().equals("N") && !machine.getIpAddress().equals(ipAddr)) { // IP ? Agent ? ? ? ? ??? . machine.setIpAddr(ipAddr); machineService.applyStaticIp(machine); resetIp = true; } } if (!resetIp) { if (hostnameChanged) { // IP ? hostname ? peacock-agent restart . machineService.agentRestart(machineId); } else { // Package ? Software ? ?? . if (this.softwareService == null) { softwareService = AppContext.getBean(SoftwareService.class); } List<SoftwareDto> softwareList = softwareService.getSoftwareInstallListAll(machineId); PackageService packageService = AppContext.getBean(PackageService.class); PackageDto ospackage = new PackageDto(); ospackage.setMachineId(machineId); int packageCnt = packageService.getPackageListCnt(ospackage); returnMsg = new AgentInitialInfoMessage(); returnMsg.setAgentId(machineId); if (softwareList != null && softwareList.size() > 0) { returnMsg.setSoftwareInstalled("Y"); } else { returnMsg.setSoftwareInstalled("N"); } if (packageCnt > 0) { returnMsg.setPackageCollected("Y"); } else { returnMsg.setPackageCollected("N"); } datagram = new PeacockDatagram<AbstractMessage>(returnMsg); ctx.channel().writeAndFlush(datagram); } } break; case PACKAGE_INFO: OSPackageInfoMessage packageMsg = ((PeacockDatagram<OSPackageInfoMessage>) msg).getMessage(); List<PackageInfo> packageInfoList = packageMsg.getPackageInfoList(); PackageInfo packageInfo = null; List<PackageDto> packageList = new ArrayList<PackageDto>(); PackageDto ospackage = null; for (int i = 0; i < packageInfoList.size(); i++) { packageInfo = packageInfoList.get(i); ospackage = new PackageDto(); ospackage.setPkgId(i + 1); ospackage.setMachineId(packageMsg.getAgentId()); ospackage.setName(packageInfo.getName()); ospackage.setArch(packageInfo.getArch()); ospackage.setSize(packageInfo.getSize()); ospackage.setVersion(packageInfo.getVersion()); ospackage.setReleaseInfo(packageInfo.getRelease()); ospackage.setInstallDate(packageInfo.getInstallDate()); ospackage.setSummary(packageInfo.getSummary()); ospackage.setDescription(packageInfo.getDescription()); packageList.add(ospackage); } if (packageList.size() > 0) { if (packageService == null) { packageService = AppContext.getBean(PackageService.class); } packageService.insertPackageList(packageList); } break; case SOFTWARE_INFO: SoftwareInfoMessage softwareMsg = ((PeacockDatagram<SoftwareInfoMessage>) msg).getMessage(); List<SoftwareInfo> softwareInfoList = softwareMsg.getSoftwareInfoList(); SoftwareInfo softwareInfo = null; if (softwareRepoService == null) { softwareRepoService = AppContext.getBean(SoftwareRepoService.class); } SoftwareRepoDto softwareRepo = new SoftwareRepoDto(); softwareRepo.setStart(0); softwareRepo.setLimit(100); List<SoftwareRepoDto> softwareRepoList = softwareRepoService.getSoftwareRepoList(softwareRepo); List<ConfigDto> configList = null; List<ConfigInfo> configInfoList = null; SoftwareDto software = null; ConfigDto config = null; int softwareId = 0; StringBuilder stopCmd = null; StringBuilder startCmd = null; for (int i = 0; i < softwareInfoList.size(); i++) { softwareInfo = softwareInfoList.get(i); for (SoftwareRepoDto repo : softwareRepoList) { softwareId = 0; if (repo.getSoftwareName().toLowerCase() .indexOf(softwareInfo.getName().toLowerCase()) > 0) { // ? ? ?? ? softwareId . softwareId = repo.getSoftwareId(); if (repo.getSoftwareVersion().startsWith(softwareInfo.getVersion())) { softwareId = repo.getSoftwareId(); break; } } } //software.setInstallLocation(apacheHome + "," + serverHome + "/bin," + serverHome + "/conf," + serverHome + "/log," + serverHome + "/run," + serverHome + "/www"); //software.setInstallLocation(serverHome + "/apps," + serverHome + "/bin," + serverHome + "/Servers," + serverHome + "/svrlogs," + serverHome + "/wily," + serverHome + "/jboss-ews-2.1"); //software.setInstallLocation(jbossHome + "," + serverBase + ", " + serverHome + "/apps," + serverHome + "/svrlogs," + serverHome + "/wily"); stopCmd = new StringBuilder(); startCmd = new StringBuilder(); stopCmd.append("WORKING_DIR:").append(softwareInfo.getStopWorkingDir()).append(",") .append("CMD:").append(softwareInfo.getStopCommand()).append(",").append("ARGS:") .append(softwareInfo.getStopArgs()); startCmd.append("WORKING_DIR:").append(softwareInfo.getStartWorkingDir()).append(",") .append("CMD:").append(softwareInfo.getStartCommand()).append(",").append("ARGS:") .append(softwareInfo.getStartArgs()); software = new SoftwareDto(); software.setMachineId(softwareMsg.getAgentId()); software.setSoftwareId(softwareId); software.setInstallLocation(StringUtils.join(softwareInfo.getInstallLocations(), ",")); software.setInstallStat("COMPLETED"); software.setInstallLog("Software installed manually."); software.setServiceStopCmd(stopCmd.toString()); software.setServiceStartCmd(startCmd.toString()); software.setDescription(""); software.setDeleteYn("N"); configInfoList = softwareInfo.getConfigInfoList(); configList = new ArrayList<ConfigDto>(); for (ConfigInfo configInfo : configInfoList) { config = new ConfigDto(); config.setMachineId(softwareMsg.getAgentId()); config.setSoftwareId(softwareId); config.setConfigFileLocation(configInfo.getConfigFileLocation()); config.setConfigFileName(configInfo.getConfigFileName()); config.setConfigFileContents(configInfo.getConfigFileContents()); config.setDeleteYn("N"); configList.add(config); } if (softwareService == null) { softwareService = AppContext.getBean(SoftwareService.class); } softwareService.insertSoftware(software, configList); } break; } } } }
From source file:com.bala.learning.learning.netty.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/*from w w w .java2s.c om*/ } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.barchart.http.server.HttpRequestChannelHandler.java
License:BSD License
private void sendServerError(final ChannelHandlerContext ctx, final ServerException cause) throws Exception { if (ctx.channel().isActive()) { final ByteBuf content = Unpooled.buffer(); content.writeBytes(// w ww .jav a 2 s . c o m (cause.getStatus().code() + " " + cause.getStatus().reasonPhrase() + " - " + cause.getMessage()) .getBytes()); final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, cause.getStatus()); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes()); response.content().writeBytes(content); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } }