List of usage examples for io.netty.handler.codec.http HttpHeaders isKeepAlive
@Deprecated public static boolean isKeepAlive(HttpMessage message)
From source file:adalightserver.http.HttpServer.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // res.headers().set("Access-Control-Allow-Methods", "POST, OPTIONS, GET"); // res.headers().set("Access-Control-Allow-Origin", "*"); // res.headers().set("Access-Control-Allow-Headers", "*"); // 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);// ww w . java2 s . c o m buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:baseFrame.netty.atest.HttpHelloWorldServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }/*w w w . java2s .c o m*/ boolean keepAlive = HttpHeaders.isKeepAlive(request); // Encode the cookie. String cookieString = request.headers().get(Names.COOKIE); if (cookieString != null) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { // Browser sent no cookie. Add some. /* response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.encode("key2", "value2"));*/ } if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } responseContent.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); //responseContent.append("HOSTNAME: ").append(request.headers().).append("\r\n"); responseContent.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Entry<String, String> h : headers) { CharSequence key = h.getKey(); CharSequence value = h.getValue(); responseContent.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } responseContent.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) { responseContent.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } responseContent.append("\r\n"); } response = setResponse(response, responseContent); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(Names.CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; if (msg instanceof LastHttpContent) { } } }
From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpHeaders.isKeepAlive(request); // Build the response object. FullHttpResponse response;/*from w w w. jav a2 s .c om*/ if (currentAction.equals("Add")) response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? CREATED : BAD_REQUEST); else if (currentAction.equals("Latest")) { response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "application/json; charset=utf-8"); } else response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); // response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the response. ctx.write(response); return keepAlive; }
From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java
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 va 2 s . co m*/ buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:ch07.handlers.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpHeaders.isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }/* w w w . j a v a 2 s . co m*/ // Encode the cookie. String cookieString = request.headers().get(COOKIE); if (cookieString != null) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:co.paralleluniverse.comsat.webactors.netty.WebActorHandler.java
License:Open Source License
private static void writeHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res, boolean close) { if (!omitDateHeader && !res.headers().contains(DefaultHttpHeaders.Names.DATE)) DefaultHttpHeaders.addDateHeader(res, DefaultHttpHeaders.Names.DATE, new Date()); // Reply the response and close the connection if necessary. if (!HttpHeaders.isKeepAlive(req) || close) { res.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE); } else {/*www. j a v a 2 s . c o m*/ res.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); write(ctx, res); } }
From source file:com.addthis.hydra.query.tracker.DetailedStatusHandler.java
License:Apache License
private void onSuccess(QueryEntryInfo queryEntryInfo) { try {// w w w. j a v a2s. c om JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo); writer.write(entryJSON.toString()); 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); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable t) { onFailure(t); } }
From source file:com.addthis.hydra.query.web.DetailedStatusHandler.java
License:Apache License
private void onSuccess(QueryEntryInfo queryEntryInfo) throws Exception { JSONObject entryJSON = CodecJSON.encodeJSON(queryEntryInfo); writer.write(entryJSON.toString());/*from w w w . j av a 2 s .co m*/ 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); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
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 w w . j a v a 2s . co m*/ 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.addthis.hydra.query.web.LegacyHandler.java
License:Apache License
public static Query handleQuery(Query query, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx) throws IOException, QueryException { String async = kv.getValue("async"); if (async == null) { return query; } else if (async.equals("new")) { StringBuilderWriter writer = new StringBuilderWriter(50); HttpResponse response = HttpUtils.startResponse(writer); String asyncUuid = genAsyncUuid(); asyncCache.put(asyncUuid, query); if (query.isTraced()) { Query.emitTrace("async create " + asyncUuid + " from " + query); }/*from ww w . j a v a 2 s . c om*/ writer.write("{\"id\":\"" + asyncUuid + "\"}"); 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); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return null; } else { Query asyncQuery = asyncCache.getIfPresent(async); asyncCache.invalidate(async); if (query.isTraced()) { Query.emitTrace("async restore " + async + " as " + asyncQuery); } if (asyncQuery != null) { return asyncQuery; } else { throw new QueryException("Missing Async Id"); } } }