List of usage examples for io.netty.channel ChannelHandlerContext fireChannelRead
@Override ChannelHandlerContext fireChannelRead(Object msg);
From source file:cn.david.socks.SocksServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, SocksRequest socksRequest) throws Exception { switch (socksRequest.requestType()) { case INIT: {/*from w w w.j ava 2 s . c o m*/ // auth support example //ctx.pipeline().addFirst(new SocksAuthRequestDecoder()); //ctx.write(new SocksInitResponse(SocksAuthScheme.AUTH_PASSWORD)); ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksInitResponse(SocksAuthScheme.NO_AUTH)); break; } case AUTH: ctx.pipeline().addFirst(new SocksCmdRequestDecoder()); ctx.write(new SocksAuthResponse(SocksAuthStatus.SUCCESS)); break; case CMD: SocksCmdRequest req = (SocksCmdRequest) socksRequest; if (req.cmdType() == SocksCmdType.CONNECT) { ctx.pipeline().addLast(new SocksServerConnectHandler()); ctx.pipeline().remove(this); ctx.fireChannelRead(socksRequest); } else { ctx.close(); } break; case UNKNOWN: ctx.close(); break; } }
From source file:cn.dennishucd.nettyhttpserver.HttpServerHandler.java
License:Apache License
@SuppressWarnings("deprecation") @Override/*from w ww . j ava2 s .c o m*/ public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { request = (HttpRequest) msg; if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } if (!request.uri().equalsIgnoreCase(URL)) { sendError(ctx, NOT_FOUND); return; } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); UserToken ut = CTools.JSONStr2Object(buf.toString(io.netty.util.CharsetUtil.UTF_8), UserToken.class); logger.info("request body: " + buf.toString(io.netty.util.CharsetUtil.UTF_8)); buf.release(); boolean keepAlive = HttpUtil.isKeepAlive(request); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT.getBytes())); response.headers().set(CONTENT_TYPE, "application/json"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); logger.info("response body: " + CONTENT); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } else { ctx.fireChannelRead(msg); } }
From source file:co.rsk.rpc.netty.JsonRpcWeb3ServerHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder request) throws Exception { ByteBuf responseContent = Unpooled.buffer(); int responseCode; try (ByteBufOutputStream os = new ByteBufOutputStream(responseContent); ByteBufInputStream is = new ByteBufInputStream(request.content().retain())) { responseCode = jsonRpcServer.handleRequest(is, os); } catch (Exception e) { String unexpectedErrorMsg = "Unexpected error"; LOGGER.error(unexpectedErrorMsg, e); int errorCode = ErrorResolver.JsonError.CUSTOM_SERVER_ERROR_LOWER; responseContent = buildErrorContent(errorCode, unexpectedErrorMsg); responseCode = errorCode;// w ww. j a v a 2 s .co m } ctx.fireChannelRead(new Web3Result(responseContent, responseCode)); }
From source file:co.rsk.rpc.netty.RskJsonRpcHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, ByteBufHolder msg) { try {/*w ww. j a va 2 s .c o m*/ RskJsonRpcRequest request = serializer.deserializeRequest(new ByteBufInputStream(msg.copy().content())); // TODO(mc) we should support the ModuleDescription method filters JsonRpcResultOrError resultOrError = request.accept(this, ctx); JsonRpcIdentifiableMessage response = resultOrError.responseFor(request.getId()); ctx.writeAndFlush(new TextWebSocketFrame(serializer.serializeMessage(response))); return; } catch (IOException e) { LOGGER.trace("Not a known or valid JsonRpcRequest", e); } // delegate to the next handler if the message can't be matched to a known JSON-RPC request ctx.fireChannelRead(msg.retain()); }
From source file:co.rsk.rpc.netty.Web3HttpMethodFilterHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) { HttpMethod httpMethod = request.getMethod(); if (HttpMethod.POST.equals(httpMethod)) { // retain the request so it isn't released automatically by SimpleChannelInboundHandler ctx.fireChannelRead(request.retain()); } else {/*from ww w . j av a 2 s .com*/ HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_IMPLEMENTED); ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { RecyclableArrayList out = RecyclableArrayList.newInstance(); try {/*from w w w . j a v a 2 s .c om*/ if (msg instanceof ByteBuf) { ByteBuf data = (ByteBuf) msg; if (cumulation == null) { cumulation = data; try { callDecode(ctx, cumulation, out); } finally { if (cumulation != null && !cumulation.isReadable()) { cumulation.release(); cumulation = null; } } } else { try { if (cumulation.writerIndex() > cumulation.maxCapacity() - data.readableBytes()) { ByteBuf oldCumulation = cumulation; cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + data.readableBytes()); cumulation.writeBytes(oldCumulation); oldCumulation.release(); } cumulation.writeBytes(data); callDecode(ctx, cumulation, out); } finally { if (cumulation != null) { if (!cumulation.isReadable()) { cumulation.release(); cumulation = null; } else { cumulation.discardSomeReadBytes(); } } data.release(); } } } else { out.add(msg); } } catch (DecoderException e) { throw e; } catch (Throwable t) { throw new DecoderException(t); } finally { if (out.isEmpty()) { decodeWasNull = true; } List<Object> results = new ArrayList<Object>(); for (Object result : out) { results.add(result); } ctx.fireChannelRead(results); out.recycle(); } }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { RecyclableArrayList out = RecyclableArrayList.newInstance(); try {/* ww w.j a va2 s .co m*/ if (cumulation != null) { callDecode(ctx, cumulation, out); decodeLast(ctx, cumulation, out); } else { decodeLast(ctx, Unpooled.EMPTY_BUFFER, out); } } catch (DecoderException e) { throw e; } catch (Exception e) { throw new DecoderException(e); } finally { if (cumulation != null) { cumulation.release(); cumulation = null; } for (int i = 0; i < out.size(); i++) { ctx.fireChannelRead(out.get(i)); } ctx.fireChannelInactive(); } }
From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java
License:Apache License
@Override public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { ByteBuf buf = internalBuffer();/* w w w . j a v a 2s. c o m*/ int readable = buf.readableBytes(); if (buf.isReadable()) { ByteBuf bytes = buf.readBytes(readable); buf.release(); ctx.fireChannelRead(bytes); } cumulation = null; ctx.fireChannelReadComplete(); handlerRemoved0(ctx); }
From source file:com.addthis.hydra.query.web.HttpQueryHandler.java
License:Apache License
private void fastHandle(ChannelHandlerContext ctx, FullHttpRequest request, String target, KVPairs kv) throws Exception { StringBuilderWriter writer = new StringBuilderWriter(50); HttpResponse response = HttpUtils.startResponse(writer); response.headers().add("Access-Control-Allow-Origin", "*"); switch (target) { case "/metrics": fakeMetricsServlet.writeMetrics(writer, kv); break;// w ww. j ava2 s . com case "/query/list": writer.write("[\n"); for (QueryEntryInfo stat : tracker.getRunning()) { writer.write(CodecJSON.encodeString(stat).concat(",\n")); } writer.write("]"); break; case "/completed/list": writer.write("[\n"); for (QueryEntryInfo stat : tracker.getCompleted()) { writer.write(CodecJSON.encodeString(stat).concat(",\n")); } writer.write("]"); break; case "/v2/host/list": case "/host/list": String queryStatusUuid = kv.getValue("uuid"); QueryEntry queryEntry = tracker.getQueryEntry(queryStatusUuid); if (queryEntry != null) { DetailedStatusHandler hostDetailsHandler = new DetailedStatusHandler(writer, response, ctx, request, queryEntry); hostDetailsHandler.handle(); return; } else { QueryEntryInfo queryEntryInfo = tracker.getCompletedQueryInfo(queryStatusUuid); if (queryEntryInfo != null) { JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo); writer.write(entryJSON.toString()); } else { throw new RuntimeException("could not find query"); } break; } case "/query/cancel": if (tracker.cancelRunning(kv.getValue("uuid"))) { writer.write("canceled " + kv.getValue("uuid")); } else { writer.write("canceled failed for " + kv.getValue("uuid")); response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); } break; case "/query/encode": { Query q = new Query(null, kv.getValue("query", kv.getValue("path", "")), null); JSONArray path = CodecJSON.encodeJSON(q).getJSONArray("path"); writer.write(path.toString()); break; } case "/query/decode": { String qo = "{path:" + kv.getValue("query", kv.getValue("path", "")) + "}"; Query q = CodecJSON.decodeString(new Query(), qo); writer.write(q.getPaths()[0]); break; } case "/v2/queries/finished.list": { JSONArray runningEntries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getCompleted()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); //TODO: replace this with some high level summary entryJSON.put("hostInfoSet", ""); runningEntries.put(entryJSON); } writer.write(runningEntries.toString()); break; } case "/v2/queries/running.list": { JSONArray runningEntries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getRunning()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); //TODO: replace this with some high level summary entryJSON.put("hostInfoSet", ""); runningEntries.put(entryJSON); } writer.write(runningEntries.toString()); break; } case "/v2/queries/workers": { JSONObject jsonObject = new JSONObject(); for (WorkerData workerData : meshQueryMaster.worky().values()) { jsonObject.put(workerData.hostName, workerData.queryLeases.availablePermits()); } writer.write(jsonObject.toString()); break; } case "/v2/queries/list": JSONArray queries = new JSONArray(); for (QueryEntryInfo entryInfo : tracker.getCompleted()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); entryJSON.put("state", 0); queries.put(entryJSON); } for (QueryEntryInfo entryInfo : tracker.getRunning()) { JSONObject entryJSON = CodecJSON.encodeJSON(entryInfo); entryJSON.put("state", 3); queries.put(entryJSON); } writer.write(queries.toString()); break; case "/v2/job/list": { StringWriter swriter = new StringWriter(); final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter); json.writeStartArray(); for (IJob job : meshQueryMaster.keepy().getJobs()) { if (job.getQueryConfig() != null && job.getQueryConfig().getCanQuery()) { List<JobTask> tasks = job.getCopyOfTasks(); String uuid = job.getId(); json.writeStartObject(); json.writeStringField("id", uuid); json.writeStringField("description", Optional.fromNullable(job.getDescription()).or("")); json.writeNumberField("state", job.getState().ordinal()); json.writeStringField("creator", job.getCreator()); json.writeNumberField("submitTime", Optional.fromNullable(job.getSubmitTime()).or(-1L)); json.writeNumberField("startTime", Optional.fromNullable(job.getStartTime()).or(-1L)); json.writeNumberField("endTime", Optional.fromNullable(job.getStartTime()).or(-1L)); json.writeNumberField("replicas", Optional.fromNullable(job.getReplicas()).or(0)); json.writeNumberField("backups", Optional.fromNullable(job.getBackups()).or(0)); json.writeNumberField("nodes", tasks.size()); json.writeEndObject(); } } json.writeEndArray(); json.close(); writer.write(swriter.toString()); break; } case "/v2/settings/git.properties": { StringWriter swriter = new StringWriter(); final JsonGenerator json = QueryServer.factory.createJsonGenerator(swriter); Properties gitProperties = new Properties(); json.writeStartObject(); try { InputStream in = queryServer.getClass().getResourceAsStream("/git.properties"); gitProperties.load(in); in.close(); json.writeStringField("commitIdAbbrev", gitProperties.getProperty("git.commit.id.abbrev")); json.writeStringField("commitUserEmail", gitProperties.getProperty("git.commit.user.email")); json.writeStringField("commitMessageFull", gitProperties.getProperty("git.commit.message.full")); json.writeStringField("commitId", gitProperties.getProperty("git.commit.id")); json.writeStringField("commitUserName", gitProperties.getProperty("git.commit.user.name")); json.writeStringField("buildUserName", gitProperties.getProperty("git.build.user.name")); json.writeStringField("commitIdDescribe", gitProperties.getProperty("git.commit.id.describe")); json.writeStringField("buildUserEmail", gitProperties.getProperty("git.build.user.email")); json.writeStringField("branch", gitProperties.getProperty("git.branch")); json.writeStringField("commitTime", gitProperties.getProperty("git.commit.time")); json.writeStringField("buildTime", gitProperties.getProperty("git.build.time")); } catch (Exception ex) { log.warn("Error loading git.properties, possibly jar was not compiled with maven."); } json.writeEndObject(); json.close(); writer.write(swriter.toString()); break; } default: // forward to static file server ctx.pipeline().addLast(staticFileHandler); request.retain(); ctx.fireChannelRead(request); return; // don't do text response clean up } log.trace("response being sent {}", writer); ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()), CharsetUtil.UTF_8); HttpContent content = new DefaultHttpContent(textResponse); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes()); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ctx.write(content); ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); log.trace("response pending"); if (!HttpHeaders.isKeepAlive(request)) { log.trace("Setting close listener"); lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.baidu.jprotobuf.pbrpc.transport.handler.RpcServiceHandler.java
License:Apache License
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { LOG.log(Level.SEVERE, cause.getCause().getMessage(), cause.getCause()); RpcDataPackage data = null;//from w ww .j ava 2 s . c om if (cause instanceof ErrorDataException) { ErrorDataException error = (ErrorDataException) cause; RpcDataPackage dataPackage = error.getRpcDataPackage(); if (dataPackage != null) { int errorCode = ErrorCodes.ST_ERROR; if (error.getErrorCode() > 0) { errorCode = error.getErrorCode(); } data = dataPackage.getErrorResponseRpcDataPackage(errorCode, cause.getCause().getMessage()); } } if (data == null) { data = new RpcDataPackage(); data = data.magicCode(ProtocolConstant.MAGIC_CODE).getErrorResponseRpcDataPackage(ErrorCodes.ST_ERROR, cause.getCause().getMessage()); } ctx.fireChannelRead(data); }