private static HttpResponse addEtag( HttpRequest nettyRequest, HttpResponse httpResponse, File file) { if (Play.mode == Play.Mode.DEV) { httpResponse.setHeader(CACHE_CONTROL, "no-cache"); } else { String maxAge = Play.configuration.getProperty("http.cacheControl", "3600"); if (maxAge.equals("0")) { httpResponse.setHeader(CACHE_CONTROL, "no-cache"); } else { httpResponse.setHeader(CACHE_CONTROL, "max-age=" + maxAge); } } boolean useEtag = Play.configuration.getProperty("http.useETag", "true").equals("true"); long last = file.lastModified(); final String etag = "\"" + last + "-" + file.hashCode() + "\""; if (!isModified(etag, last, nettyRequest)) { if (nettyRequest.getMethod().equals(HttpMethod.GET)) { httpResponse.setStatus(HttpResponseStatus.NOT_MODIFIED); } if (useEtag) { httpResponse.setHeader(ETAG, etag); } } else { httpResponse.setHeader(LAST_MODIFIED, Utils.getHttpDateFormatter().format(new Date(last))); if (useEtag) { httpResponse.setHeader(ETAG, etag); } } return httpResponse; }
public static boolean isModified(String etag, long last, HttpRequest nettyRequest) { if (nettyRequest.containsHeader(IF_NONE_MATCH)) { final String browserEtag = nettyRequest.getHeader(IF_NONE_MATCH); if (browserEtag.equals(etag)) { return false; } return true; } if (nettyRequest.containsHeader(IF_MODIFIED_SINCE)) { final String ifModifiedSince = nettyRequest.getHeader(IF_MODIFIED_SINCE); if (!StringUtils.isEmpty(ifModifiedSince)) { try { Date browserDate = Utils.getHttpDateFormatter().parse(ifModifiedSince); if (browserDate.getTime() >= last) { return false; } } catch (ParseException ex) { Logger.warn("Can't parse HTTP date", ex); } return true; } } return true; }
protected static void addToRequest(HttpRequest nettyRequest, Request request) { for (String key : nettyRequest.getHeaderNames()) { Http.Header hd = new Http.Header(); hd.name = key.toLowerCase(); hd.values = new ArrayList<String>(); for (String next : nettyRequest.getHeaders(key)) { hd.values.add(next); } request.headers.put(hd.name, hd); } String value = nettyRequest.getHeader(COOKIE); if (value != null) { Set<Cookie> cookies = new CookieDecoder().decode(value); if (cookies != null) { for (Cookie cookie : cookies) { Http.Cookie playCookie = new Http.Cookie(); playCookie.name = cookie.getName(); playCookie.path = cookie.getPath(); playCookie.domain = cookie.getDomain(); playCookie.secure = cookie.isSecure(); playCookie.value = cookie.getValue(); playCookie.httpOnly = cookie.isHttpOnly(); request.cookies.put(playCookie.name, playCookie); } } } }
private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception { // Allow only GET methods. if (req.getMethod() != GET) { sendHttpResponse(ctx, req, new DefaultHttpResponse(HTTP_1_1, FORBIDDEN)); return; } // Send the demo page and favicon.ico if (req.getUri().equals("/")) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, OK); ChannelBuffer content = WebSocketServerIndexPage.getContent(getWebSocketLocation(req)); res.setHeader(CONTENT_TYPE, "text/html; charset=UTF-8"); setContentLength(res, content.readableBytes()); res.setContent(content); sendHttpResponse(ctx, req, res); return; } else if (req.getUri().equals("/favicon.ico")) { HttpResponse res = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); sendHttpResponse(ctx, req, res); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(this.getWebSocketLocation(req), null, false); this.handshaker = wsFactory.newHandshaker(ctx, req); if (this.handshaker == null) { wsFactory.sendUnsupportedWebSocketVersionResponse(ctx); } else { this.handshaker.executeOpeningHandshake(ctx, req); } }
private boolean addRequest(HttpRequest request) { URI uri = null; try { uri = new URI(request.getUri()); } catch (URISyntaxException ex) { logger.error( "Can't create URI from request uri (" + request.getUri() + ")" + ex.getStackTrace()); // FIXME error handling return false; } if (configuration.getFilterStrategy() != FilterStrategy.NONE) { String p = EMPTY; boolean add = true; if (configuration.getFilterStrategy() == FilterStrategy.ONLY) add = true; else if (configuration.getFilterStrategy() == FilterStrategy.EXCEPT) add = false; for (Pattern pattern : configuration.getPatterns()) { switch (pattern.getPatternType()) { case ANT: p = SelectorUtils.ANT_HANDLER_PREFIX; break; case JAVA: p = SelectorUtils.REGEX_HANDLER_PREFIX; break; } p += pattern.getPattern() + SelectorUtils.PATTERN_HANDLER_SUFFIX; if (SelectorUtils.matchPath(p, uri.getPath())) return add; } return !add; } return true; }
@Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { if (!chunked) { final HttpRequest request = (HttpRequest) e.getMessage(); final ChannelBuffer buffer = request.getContent(); receivedData.write(buffer.array()); // System.out.println("received "+buffer.array() ); // System.out.println(buffer.array().length); if (!request.isChunked()) { processRequest(e); } else { chunked = true; } // final boolean keepAlive = isKeepAlive(request); } else { final HttpChunk chunk = (HttpChunk) e.getMessage(); final ChannelBuffer buffer = chunk.getContent(); receivedData.write(buffer.array()); if (chunk.isLast()) { processRequest(e); } } }
private String getUri() { String uri = null; if (HttpMethod.POST == request.getMethod()) { uri = request.getUri() + "?" + request.getContent().toString("ISO-8859-1"); } else { uri = request.getUri(); } return uri; }
public static HttpRequest create(HttpMethod method, String action) throws URISyntaxException { URI uri = new URI(action); HttpRequest request = new DefaultHttpRequest(new HttpVersion("STREST", 0, 1, true), method, uri.toASCIIString()); // request.setHeader(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP); request.setHeader("Strest-Txn-Id", generateTxnId()); request.setProtocolVersion(new HttpVersion("STREST", 0, 1, true)); return request; }
private HttpRequest rewriteRequest(HttpRequest request, boolean isStreaming) { if (!isStreaming) { return request; } if (!request.isChunked() || request.getContent().readable()) { request.setChunked(true); request.setContent(ChannelBuffers.EMPTY_BUFFER); } return request; }
@Override public boolean checkAccepts(final HttpRequest message) { if (message instanceof MappingHttpRequest) { final MappingHttpRequest httpRequest = (MappingHttpRequest) message; final boolean usesServicePath = Iterables.any(servicePathPrefixes, Strings.isPrefixOf(message.getUri())); final boolean noPath = message.getUri().isEmpty() || message.getUri().equals("/") || message.getUri().startsWith("/?"); if (!usesServicePath && !(noPath && resolvesByHost(message.getHeader(HttpHeaders.Names.HOST)))) { return false; } if (httpRequest.getMethod().equals(HttpMethod.POST) && !message.getHeaderNames().contains("SOAPAction")) { Map<String, String> parameters = new HashMap<String, String>(httpRequest.getParameters()); Set<String> nonQueryParameters = Sets.newHashSet(); final String query = httpRequest.getContentAsString(); for (String p : query.split("&")) { String[] splitParam = p.split("=", 2); String lhs = splitParam[0]; String rhs = splitParam.length == 2 ? splitParam[1] : null; try { if (lhs != null) lhs = new URLCodec().decode(lhs); } catch (DecoderException e) { } try { if (rhs != null) rhs = new URLCodec().decode(rhs); } catch (DecoderException e) { } parameters.put(lhs, rhs); nonQueryParameters.add(lhs); } for (RequiredQueryParams p : requiredQueryParams) { if (!parameters.containsKey(p.toString())) { return false; } } httpRequest.getParameters().putAll(parameters); httpRequest.addNonQueryParameterKeys(nonQueryParameters); } else { for (RequiredQueryParams p : requiredQueryParams) { if (!httpRequest.getParameters().containsKey(p.toString())) { return false; } } } return true; } return false; }
private void writeHead() { request.setChunked(chunked); if (!raw) { request.setHeader(HttpHeaders.Names.HOST, conn.hostHeader); if (chunked) { request.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); } else if (contentLength == 0) { // request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, "0"); } } conn.write(request); }
@Test public void shouldAddXContentTypeOptionsHeader() { HttpRequest httpRequest = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, "/foo?param1=bar¶m2=baz&quux"); httpRequest.addHeader("Host", "testing-host"); Response response = new Response(); postprocessor.process(new Request(httpRequest, null), response); assertTrue(response.hasHeaders()); String result = response.getHeader(XCONTENTTYPEOPTIONS); assertNotNull(result); assertEquals(NOSNIFF, result); }
/** * adds params to the uri * * @param params * @return */ public static HttpRequest addParams(HttpRequest request, DynMap params) { String encodedParams = params.toURLString(); if (encodedParams == null || encodedParams.isEmpty()) { return request; } String uri = request.getUri(); if (!uri.contains("?")) { uri = uri + "?"; } else { uri = uri + "&"; } request.setUri(uri + encodedParams); return request; }
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception { if (!(me.getMessage() instanceof HttpRequest)) { ctx.sendUpstream(me); return; } HttpRequest request = (HttpRequest) me.getMessage(); Object response; // Look up resource String path = request.getUri(); String host = request.getHeader("host"); log.debug("Received request for path:" + path); boolean showHtml = false; if (path.endsWith("?html")) { showHtml = true; path = path.replace("?html", ""); } for (String service : resources.keySet()) { log.debug("Available Service: " + service); } Model model = resources.get(path); if (model != null) { if (request.getMethod() == HttpMethod.GET) { if (showHtml) { String html = HtmlCreator.createModelPage(model, new URI(path), host); response = ChannelBuffers.wrappedBuffer(html.getBytes(Charset.forName("UTF-8"))); log.debug("Returned html page for resource: " + path); } else { response = new SelfDescription(model, new URI(request.getUri())); log.debug("Resource found: " + path); } } else { response = new DefaultHttpResponse( request.getProtocolVersion(), HttpResponseStatus.METHOD_NOT_ALLOWED); log.debug("Method not allowed: " + request.getMethod()); } } else { response = HttpResponseFactory.createHttpResponse( request.getProtocolVersion(), HttpResponseStatus.NOT_FOUND); log.debug("Resource not found: " + path); } // Send response ChannelFuture future = Channels.write(ctx.getChannel(), response); future.addListener(ChannelFutureListener.CLOSE); }
protected void sendRequest( HttpRequest request, SendRequestResultListener listener, HttpResponseProcessor responseProcessor) { if (isClosingOrClosed()) { listener.onSendRequestFailure(request, new ClosedChannelException()); } else if (!isConnected()) { listener.onSendRequestFailure(request, new RuntimeException("unable to send request")); } else { try { setResponseProcessor(responseProcessor, listener); } catch (DatabusException e) { listener.onSendRequestFailure(request, e.getCause()); _channel.close(); return; } // Send the HTTP request. if (_channel.isConnected()) { // ChannelFuture future = _channel.write(request); // future.addListener(new MySendRequestListener(request, listener)); _channel.write(request); } else { _log.error("disconnect on request: " + request.getUri()); listener.onSendRequestFailure(request, new ClosedChannelException()); } } }
protected static void writeResponse( ChannelHandlerContext ctx, Response response, HttpResponse nettyResponse, HttpRequest nettyRequest) { Logger.trace("writeResponse: begin"); byte[] content = null; final boolean keepAlive = isKeepAlive(nettyRequest); if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) { content = new byte[0]; } else { content = response.out.toByteArray(); } ChannelBuffer buf = ChannelBuffers.copiedBuffer(content); nettyResponse.setContent(buf); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. Logger.trace("writeResponse: content length [" + response.out.size() + "]"); setContentLength(nettyResponse, response.out.size()); } ChannelFuture f = ctx.getChannel().write(nettyResponse); // Decide whether to close the connection or not. if (!keepAlive) { // Close the connection when the whole content is written out. f.addListener(ChannelFutureListener.CLOSE); } Logger.trace("writeResponse: end"); }
@Override public void messageReceived(ChannelHandlerContext context, MessageEvent e) throws Exception { if (e.getMessage() instanceof HttpRequest) { HttpRequest message = (HttpRequest) e.getMessage(); HttpResponse response; if (new QueryStringDecoder(message.getUri()).getPath().equals(START_TIME_PATH)) { response = new DefaultHttpResponse(HTTP_1_1, OK); response.setHeader("Access-Control-Allow-Origin", "*"); response.setContent( ChannelBuffers.copiedBuffer(getApplicationStartTime(), CharsetUtil.US_ASCII)); } else { response = new DefaultHttpResponse(HTTP_1_1, NOT_FOUND); } context.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } }
/** * Sends a 400 error page to the client. * * @param explain The string describing why the request is bad. */ public void badRequest(final String explain) { if (hasQueryStringParam("json")) { final StringBuilder buf = new StringBuilder(10 + explain.length()); buf.append("{\"err\":\""); HttpQuery.escapeJson(explain, buf); buf.append("\"}"); sendReply(HttpResponseStatus.BAD_REQUEST, buf); } else if (hasQueryStringParam("png")) { sendAsPNG(HttpResponseStatus.BAD_REQUEST, explain, 3600); } else { sendReply( HttpResponseStatus.BAD_REQUEST, makePage( "Bad Request", "Looks like it's your fault this time", "<blockquote>" + "<h1>Bad Request</h1>" + "Sorry but your request was rejected as being" + " invalid.<br/><br/>" + "The reason provided was:<blockquote>" + explain + "</blockquote></blockquote>")); } logWarn("Bad Request on " + request.getUri() + ": " + explain); }
private static HashMap<String, String> getParams(HttpRequest request) { HashMap<String, String> headers = new HashMap<String, String>(); String uri = request.getUri(); int index = uri.indexOf('?'); if (index == -1) { return headers; } String queryString = uri.substring(index + 1); String[] parts = queryString.split("&|="); if ((parts.length % 2) != 0) { return headers; } for (int i = 0; i != parts.length; ) { String name = parts[i]; String value = parts[i + 1]; i += 2; headers.put(name, value); } return headers; }
private static void sendStatus( HttpResponse response, @Nullable HttpRequest request, Channel channel, @Nullable String description) { response.setHeader(CONTENT_TYPE, "text/html"); if (request == null || request.getMethod() != HttpMethod.HEAD) { String message = response.getStatus().toString(); StringBuilder builder = new StringBuilder(); builder .append("<!doctype html><title>") .append(message) .append("</title>") .append("<h1 style=\"text-align: center\">") .append(message) .append("</h1>"); if (description != null) { builder.append("<p>").append(description).append("</p>"); } builder .append("<hr/><p style=\"text-align: center\">") .append(StringUtil.notNullize(getServerHeaderValue(), "")) .append("</p>"); response.setContent(ChannelBuffers.copiedBuffer(builder, CharsetUtil.UTF_8)); } send(response, channel, request); }
/** * @param factory the factory used to create InterfaceHttpData * @param request the request to encode * @param multipart True if the FORM is a ENCTYPE="multipart/form-data" * @param charset the charset to use as default * @throws NullPointerException for request or charset or factory * @throws ErrorDataEncoderException if the request is not a POST */ public HttpPostRequestEncoder( HttpDataFactory factory, HttpRequest request, boolean multipart, Charset charset) throws ErrorDataEncoderException { if (factory == null) { throw new NullPointerException("factory"); } if (request == null) { throw new NullPointerException("request"); } if (charset == null) { throw new NullPointerException("charset"); } if (request.getMethod() != HttpMethod.POST) { throw new ErrorDataEncoderException("Cannot create a Encoder if not a POST"); } this.request = request; this.charset = charset; this.factory = factory; // Fill default values bodyListDatas = new ArrayList<InterfaceHttpData>(); // default mode isLastChunk = false; isLastChunkSent = false; isMultipart = multipart; multipartHttpDatas = new ArrayList<InterfaceHttpData>(); if (isMultipart) { initDataMultipart(); } }
private void executeBatchQueries(HttpRequest request, HttpResponder responder) { if (HttpHeaders.getContentLength(request) > 0) { try { String json = request.getContent().toString(Charsets.UTF_8); Map<String, QueryRequestFormat> queries = GSON.fromJson(json, new TypeToken<Map<String, QueryRequestFormat>>() {}.getType()); LOG.trace("Received Queries {}", queries); Map<String, MetricQueryResult> queryFinalResponse = Maps.newHashMap(); for (Map.Entry<String, QueryRequestFormat> query : queries.entrySet()) { MetricQueryRequest queryRequest = getQueryRequestFromFormat(query.getValue()); queryFinalResponse.put(query.getKey(), executeQuery(queryRequest)); } responder.sendJson(HttpResponseStatus.OK, queryFinalResponse); } catch (IllegalArgumentException e) { LOG.warn("Invalid request", e); responder.sendString(HttpResponseStatus.BAD_REQUEST, e.getMessage()); } catch (Exception e) { LOG.error("Exception querying metrics ", e); responder.sendString( HttpResponseStatus.INTERNAL_SERVER_ERROR, "Internal error while querying for metrics"); } } else { responder.sendJson(HttpResponseStatus.BAD_REQUEST, "Batch request with empty content"); } }
/** * Sends a 500 error page to the client. * * @param cause The unexpected exception that caused this error. */ public void internalError(final Exception cause) { ThrowableProxy tp = new ThrowableProxy(cause); tp.calculatePackagingData(); final String pretty_exc = ThrowableProxyUtil.asString(tp); tp = null; if (hasQueryStringParam("json")) { // 32 = 10 + some extra space as exceptions always have \t's to escape. final StringBuilder buf = new StringBuilder(32 + pretty_exc.length()); buf.append("{\"err\":\""); HttpQuery.escapeJson(pretty_exc, buf); buf.append("\"}"); sendReply(HttpResponseStatus.INTERNAL_SERVER_ERROR, buf); } else if (hasQueryStringParam("png")) { sendAsPNG(HttpResponseStatus.INTERNAL_SERVER_ERROR, pretty_exc, 30); } else { sendReply( HttpResponseStatus.INTERNAL_SERVER_ERROR, makePage( "Internal Server Error", "Houston, we have a problem", "<blockquote>" + "<h1>Internal Server Error</h1>" + "Oops, sorry but your request failed due to a" + " server error.<br/><br/>" + "Please try again in 30 seconds.<pre>" + pretty_exc + "</pre></blockquote>")); } logError("Internal Server Error on " + request.getUri(), cause); }
/** * Same as {@link #end()} but writes some data to the request body before ending. If the request * is not chunked and no other data has been written then the Content-Length header will be * automatically set */ public void end(Buffer chunk) { if (!chunked && contentLength == 0) { contentLength = chunk.length(); request.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(contentLength)); } write(chunk); end(); }
/** * Inserts all the specified headers into the request. The {@link Object#toString()} method will * be called on the header values {@code value} to determine the String value to actually use for * the header value. * * <p> * * @return A reference to this, so multiple method calls can be chained. */ public HttpClientRequest putAllHeaders(Map<String, ? extends Object> m) { check(); for (Map.Entry<String, ? extends Object> entry : m.entrySet()) { request.setHeader(entry.getKey(), entry.getValue().toString()); checkContentLengthChunked(entry.getKey(), entry.getValue()); } return this; }
@Override public boolean checkAccepts(HttpRequest message) { return (super.checkAccepts(message) && message .getMethod() .getName() .equals(ObjectStorageProperties.HTTPVerb.OPTIONS.toString())); }
@Override public boolean checkAccepts(final HttpRequest message) { if (message instanceof MappingHttpRequest) { final MappingHttpRequest httpRequest = (MappingHttpRequest) message; if (httpRequest.getMethod().equals(HttpMethod.POST)) { final Map<String, String> parameters = new HashMap<String, String>(httpRequest.getParameters()); final ChannelBuffer buffer = httpRequest.getContent(); buffer.markReaderIndex(); final byte[] read = new byte[buffer.readableBytes()]; buffer.readBytes(read); final String query = new String(read); buffer.resetReaderIndex(); for (final String p : query.split("&")) { final String[] splitParam = p.split("="); String lhs = splitParam[0]; String rhs = splitParam.length == 2 ? splitParam[1] : null; try { if (lhs != null) lhs = new URLCodec().decode(lhs); } catch (final DecoderException e) { } try { if (rhs != null) rhs = new URLCodec().decode(rhs); } catch (final DecoderException e) { } parameters.put(lhs, rhs); } for (final RequiredQueryParams p : RequiredQueryParams.values()) { if (!parameters.containsKey(p.toString())) { return false; } } httpRequest.getParameters().putAll(parameters); } else { for (final RequiredQueryParams p : RequiredQueryParams.values()) { if (!httpRequest.getParameters().containsKey(p.toString())) { return false; } } } return (message.getUri().startsWith(this.servicePath) || message.getUri().startsWith(this.internalServicePath)); } return false; }
/* * 获取POST请求中的请求参数 * @param [req] 一个POST请求 */ static HashMap<String, String> getPostParameter(HttpRequest req) { HashMap<String, String> postParameterList = new HashMap<String, String>(); ChannelBuffer buf = req.getContent(); for (String parameterEquation : buf.toString(CharsetUtil.UTF_8).split("&")) { String[] parameterList = parameterEquation.split("="); postParameterList.put(parameterList[0], parameterList[1]); } return postParameterList; }
@Path("/queue") @POST public void getPing(HttpRequest request, HttpResponder responder) { String dataPacket = request.getContent().toString(Charsets.UTF_8); LOG.info("/ping Got Data {}", dataPacket); queue.add(dataPacket); latch.countDown(); responder.sendStatus(HttpResponseStatus.OK); }
private static URI getEffectiveURI(HttpRequest httpRequest) { URI requestURI = URI.create(httpRequest.getUri()); if (requestURI.isAbsolute()) { return requestURI; } String host = getHost(httpRequest); return (host != null) ? URI.create(format("http://%s%s", host, requestURI)) : null; }