List of usage examples for io.netty.handler.codec.http HttpResponse setStatus
HttpResponse setStatus(HttpResponseStatus status);
From source file:appium.android.server.http.ServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof FullHttpRequest)) { return;/*from w w w . j a v a 2s . co m*/ } FullHttpRequest request = (FullHttpRequest) msg; FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().add("Connection", "close"); HttpRequest httpRequest = new NettyHttpRequest(request); HttpResponse httpResponse = new NettyHttpResponse(response); for (HttpServlet handler : httpHandlers) { handler.handleHttpRequest(httpRequest, httpResponse); if (httpResponse.isClosed()) { break; } } if (!httpResponse.isClosed()) { httpResponse.setStatus(404); httpResponse.end(); } ctx.write(response).addListener(ChannelFutureListener.CLOSE); super.channelRead(ctx, msg); }
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;/*from w w w . j a va 2 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.buildria.mocking.builder.action.StatusCodeAction.java
License:Open Source License
@Nonnull @Override//from w w w . j ava 2 s . c o m public HttpResponse apply(@Nonnull HttpRequest req, @Nonnull HttpResponse res) { Objects.requireNonNull(req); Objects.requireNonNull(res); res.setStatus(HttpResponseStatus.valueOf(code)); return res; }
From source file:com.creamsugardonut.HttpStaticFileServerHandler2.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);//from w w w . j a v a 2 s. c om return; } final String uri = request.getUri(); final String path = sanitizeUri(uri); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentTypeHeader(response, file); if (HttpHeaders.isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; // Tell clients that Partial Requests are available. response.headers().add(HttpHeaders.Names.ACCEPT_RANGES, HttpHeaders.Values.BYTES); String rangeHeader = request.headers().get(HttpHeaders.Names.RANGE); System.out.println(HttpHeaders.Names.RANGE + " = " + rangeHeader); if (rangeHeader != null && rangeHeader.length() > 0) { // Partial Request PartialRequestInfo partialRequestInfo = getPartialRequestInfo(rangeHeader, fileLength); // Set Response Header response.headers().add(HttpHeaders.Names.CONTENT_RANGE, HttpHeaders.Values.BYTES + " " + partialRequestInfo.startOffset + "-" + partialRequestInfo.endOffset + "/" + fileLength); System.out.println(HttpHeaders.Names.CONTENT_RANGE + " : " + response.headers().get(HttpHeaders.Names.CONTENT_RANGE)); HttpHeaders.setContentLength(response, partialRequestInfo.getChunkSize()); System.out.println(HttpHeaders.Names.CONTENT_LENGTH + " : " + partialRequestInfo.getChunkSize()); response.setStatus(HttpResponseStatus.PARTIAL_CONTENT); // Write Response ctx.write(response); sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), partialRequestInfo.getStartOffset(), partialRequestInfo.getChunkSize()), ctx.newProgressivePromise()); } else { // Set Response Header HttpHeaders.setContentLength(response, fileLength); // Write Response ctx.write(response); sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown System.err.println(future.channel() + " Transfer progress: " + progress); } else { System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { System.err.println(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.yeetor.server.HttpServer.java
License:Open Source License
public void writeErrorHttpResponse(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response, HttpResponseStatus status) {//from ww w. j av a2s. c o m response.setStatus(status); response.headers().set(CONTENT_LENGTH, 0); writeResponse(ctx, request, response); }
From source file:io.termd.core.http.netty.HttpRequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (wsUri.equalsIgnoreCase(request.getUri())) { ctx.fireChannelRead(request.retain()); } else {// w w w .ja v a 2s . co m if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR); String path = request.getUri(); if ("/".equals(path)) { path = "/index.html"; } URL res = HttpTtyConnection.class.getResource("/io/termd/core/http" + path); try { if (res != null) { DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK); InputStream in = res.openStream(); byte[] tmp = new byte[256]; for (int l = 0; l != -1; l = in.read(tmp)) { fullResp.content().writeBytes(tmp, 0, l); } int li = path.lastIndexOf('.'); if (li != -1 && li != path.length() - 1) { String ext = path.substring(li + 1, path.length()); String contentType; switch (ext) { case "html": contentType = "text/html"; break; case "js": contentType = "application/javascript"; break; default: contentType = null; break; } if (contentType != null) { fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); } } response = fullResp; } else { response.setStatus(HttpResponseStatus.NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); } finally { ctx.write(response); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); } } }
From source file:net.anyflow.menton.http.HttpRequestRouter.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (HttpHeaderValues.WEBSOCKET.toString().equalsIgnoreCase(request.headers().get(HttpHeaderNames.UPGRADE)) && HttpHeaderValues.UPGRADE.toString() .equalsIgnoreCase(request.headers().get(HttpHeaderNames.CONNECTION))) { if (ctx.pipeline().get(WebsocketFrameHandler.class) == null) { logger.error("No WebSocket Handler available."); ctx.channel()//from w w w . jav a 2 s. c o m .writeAndFlush( new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN)) .addListener(ChannelFutureListener.CLOSE); return; } ctx.fireChannelRead(request.retain()); return; } if (HttpUtil.is100ContinueExpected(request)) { ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE)); return; } HttpResponse response = HttpResponse.createServerDefault(request.headers().get(HttpHeaderNames.COOKIE)); String requestPath = new URI(request.uri()).getPath(); if (isWebResourcePath(requestPath)) { handleWebResourceRequest(ctx, request, response, requestPath); } else { try { processRequest(ctx, request, response); } catch (URISyntaxException e) { response.setStatus(HttpResponseStatus.NOT_FOUND); logger.info("unexcepted URI : {}", request.uri()); } catch (Exception e) { response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR); logger.error("Unknown exception was thrown in business logic handler.\r\n" + e.getMessage(), e); } } }
From source file:net.anyflow.menton.http.HttpRequestRouter.java
License:Apache License
/** * @param response// w w w . ja v a 2s.c o m * @param webResourceRequestPath * @throws IOException */ private void handleWebResourceRequest(ChannelHandlerContext ctx, FullHttpRequest rawRequest, HttpResponse response, String webResourceRequestPath) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(webResourceRequestPath); if (is == null) { String rootPath = (new File(Settings.SELF.webResourcePhysicalRootPath(), webResourceRequestPath)) .getPath(); try { is = new FileInputStream(rootPath); } catch (FileNotFoundException e) { is = null; } } if (is == null) { response.setStatus(HttpResponseStatus.NOT_FOUND); } else { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); response.content().writeBytes(buffer.toByteArray()); String ext = Files.getFileExtension(webResourceRequestPath); response.headers().set(HttpHeaderNames.CONTENT_TYPE, Settings.SELF.webResourceExtensionToMimes().get(ext)); is.close(); } setDefaultHeaders(rawRequest, response); if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writeHttpResponse"))) { logger.info(response.toString()); } ctx.write(response); }
From source file:net.anyflow.menton.http.HttpRequestRouter.java
License:Apache License
private void processRequest(ChannelHandlerContext ctx, FullHttpRequest rawRequest, HttpResponse response) throws InstantiationException, IllegalAccessException, IOException, URISyntaxException { HttpRequestHandler.MatchedCriterion mc = HttpRequestHandler .findRequestHandler((new URI(rawRequest.uri())).getPath(), rawRequest.method().toString()); if (mc.requestHandlerClass() == null) { response.setStatus(HttpResponseStatus.NOT_FOUND); logger.info("unexcepted URI : {}", rawRequest.uri()); response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/html"); response.setContent(response.toString()); } else {//from ww w. j ava 2s . com HttpRequest request = new HttpRequest(rawRequest, mc.pathParameters()); HttpRequestHandler handler = mc.requestHandlerClass().newInstance(); String webResourcePath = handler.getClass().getAnnotation(HttpRequestHandler.Handles.class) .webResourcePath(); if ("none".equals(webResourcePath) == false) { handleWebResourceRequest(ctx, rawRequest, response, webResourcePath); return; } handler.initialize(request, response); if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writeHttpRequest"))) { logger.info(request.toString()); } response.setContent(handler.service()); } setDefaultHeaders(rawRequest, response); if ("true".equalsIgnoreCase(Settings.SELF.getProperty("menton.logging.writeHttpResponse"))) { logger.info(response.toString()); } ctx.write(response); }
From source file:org.aesh.terminal.http.netty.HttpRequestHandler.java
License:Open Source License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (wsUri.equalsIgnoreCase(request.getUri())) { ctx.fireChannelRead(request.retain()); } else {/* w ww .ja v a 2 s. co m*/ if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx); } HttpResponse response = new DefaultHttpResponse(request.getProtocolVersion(), HttpResponseStatus.INTERNAL_SERVER_ERROR); String path = request.getUri(); if ("/".equals(path)) { path = "/index.html"; } URL res = HttpTtyConnection.class.getResource("/org/aesh/terminal/http" + path); try { if (res != null) { DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(request.getProtocolVersion(), HttpResponseStatus.OK); InputStream in = res.openStream(); byte[] tmp = new byte[256]; for (int l = 0; l != -1; l = in.read(tmp)) { fullResp.content().writeBytes(tmp, 0, l); } int li = path.lastIndexOf('.'); if (li != -1 && li != path.length() - 1) { String ext = path.substring(li + 1, path.length()); String contentType; switch (ext) { case "html": contentType = "text/html"; break; case "js": contentType = "application/javascript"; break; default: contentType = null; break; } if (contentType != null) { fullResp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType); } } response = fullResp; } else { response.setStatus(HttpResponseStatus.NOT_FOUND); } } catch (Exception e) { e.printStackTrace(); } finally { ctx.write(response); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); } } }