List of usage examples for io.netty.handler.codec.http.cookie ServerCookieDecoder STRICT
ServerCookieDecoder STRICT
To view the source code for io.netty.handler.codec.http.cookie ServerCookieDecoder STRICT.
Click Source Link
From source file:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpRequest) { this.httprequest = (HttpRequest) msg; requestBuilder = new Request.Builder(); requestBuilder.requestMethod(RequestMethod.valueOf(httprequest.method().name())).uri(httprequest.uri()); try {//from ww w.j a v a 2 s .c o m // Decode URI GET query parameters QueryStringDecoder queryStringDecoder = new QueryStringDecoder(httprequest.uri()); requestBuilder.path(queryStringDecoder.path()).query(queryStringDecoder.parameters()); // Process cookies List<Cookie> cookies = new ArrayList<>(); String cookieString = httprequest.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { ServerCookieDecoder.STRICT.decode(cookieString).stream().forEach((cookie) -> { cookies.add(NettyCookieConverter.convertToFuga(cookie)); }); } requestBuilder.cookies(cookies); // Process headers Map<String, String> headers = new HashMap<>(); httprequest.headers().entries().stream().forEach((e) -> { headers.put(e.getKey(), e.getValue()); }); requestBuilder.headers(headers); // Get real parameters from frontend HTTP server boolean isSecure = false; SocketAddress remoteAddress = ctx.channel().remoteAddress(); if (forwarded == 1) { // RFC7239 if (headers.containsKey("Forwarded")) { String fwdStr = headers.get("Forwarded"); List<String> fwdparams = Stream.of(fwdStr.split("; ")).map((s) -> s.trim()) .collect(Collectors.toList()); for (String f : fwdparams) { String p[] = f.split("="); switch (p[0]) { case "for": remoteAddress = parseAddress(p[1]); break; case "proto": isSecure = p[1].equals("https"); break; } } } } else if (forwarded == 0) { // X-Forwarded if (headers.containsKey("X-Forwarded-Proto")) { if (headers.get("X-Forwarded-Proto").equalsIgnoreCase("https")) { isSecure = true; } } if (headers.containsKey("X-Forwarded-For")) { String fwdfor = headers.get("X-Forwarded-For"); remoteAddress = parseAddress( fwdfor.contains(",") ? fwdfor.substring(0, fwdfor.indexOf(',')) : fwdfor); } else if (headers.containsKey("X-Real-IP")) { remoteAddress = parseAddress(headers.get("X-Real-IP")); } } requestBuilder.remoteAddress(remoteAddress).isSecure(isSecure); if (headers.containsKey("Accept-Language")) { String acceptLanguage = headers.get("Accept-Language"); List<Locale> acceptLocales = Stream.of(acceptLanguage.split(",")) .map((s) -> s.contains(";") ? s.substring(0, s.indexOf(";")).trim() : s.trim()) .map((s) -> s.contains("-") ? new Locale(s.split("-")[0], s.split("-")[0]) : new Locale(s)) .collect(Collectors.toList()); requestBuilder.acceptLocales(acceptLocales); } // if (httprequest.method().equals(HttpMethod.GET)) { processResponse(ctx); return; } decoder = true; } catch (Exception e) { processClientError(ctx, requestBuilder.build(), 400); return; } } if (msg instanceof HttpContent && decoder) { HttpContent httpContent = (HttpContent) msg; contentBuffer.writeBytes(httpContent.content()); if (httpContent instanceof LastHttpContent) { requestBuilder.content(new BufferedContent(contentBuffer.nioBuffer())); processResponse(ctx); } } }
From source file:com.cmz.http.snoop.HttpSnoopServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpUtil.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(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().setInt(HttpHeaderNames.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(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); }/*from ww w.ja va2 s. com*/ // Encode the cookie. String cookieString = request.headers().get(HttpHeaderNames.COOKIE); if (cookieString != null) { Set<Cookie> cookies = ServerCookieDecoder.STRICT.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key1", "value1")); response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);/*from w w w. ja va 2 s . co m*/ return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.cmz.http.upload.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);// w w w. j a va2s . c o m // Decide whether to close the connection or not. boolean close = request.headers().contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE, true) || request.protocolVersion().equals(HttpVersion.HTTP_1_0) && !request.headers() .contains(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE, true); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.look.netty.demo.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);//from w w w . j a va 2s . c o m return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); System.err.println(new String(responseContent.toString().getBytes(), "UTF-8")); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.netty.file.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);// w w w . ja va 2 s . com return; } responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); System.out.println("Helllllllllllllllllloooooooooooooo"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.nextcont.ecm.fileengine.http.nettyServer.HttpUploadServerHandler.java
License:Apache License
private void writeResponse(Channel channel) { logger.info("writeResponse ..."); // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(responseContent.toString(), CharsetUtil.UTF_8); responseContent.setLength(0);//from www. j a v a 2 s. c o m // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); } Set<Cookie> cookies; String value = request.headers().get(COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { // cookies = CookieDecoder.decode(value); cookies = ServerCookieDecoder.STRICT.decode(value); } if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { // response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); response.headers().add(HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT.encode(cookie)); } } // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.shiyq.netty.http.HttpUploadServerHandler1.java
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); if (!uri.getPath().startsWith("/upload")) { // Write Menu //writeMenu(ctx); responseContent.append("{code:-1,message:''}"); writeResponse(ctx.channel()); return; }/* www . j a v a 2 s . c om*/ // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { map.put(attr.getKey(), attrVal); } } // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("{code:-2,message:'??get'}"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append("{code:-3,message:'" + e1.getMessage() + "'}"); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); if (readingChunks) { // Chunk version //responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append("{code:-4,message:'" + e1.getMessage() + "'}"); writeResponse(ctx.channel()); ctx.channel().close(); return; } //responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { writeResponse(ctx.channel()); } }
From source file:com.tongtech.tis.fsc.upload.HttpUploadServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; URI uri = new URI(request.uri()); System.out.println("uri upload: " + uri); if (!uri.getPath().startsWith("/form")) { // Write Menu writeMenu(ctx);// w w w. ja va 2 s . c o m return; } logger.info("write last reponse."); responseContent.setLength(0); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.protocolVersion().text() + "\r\n"); responseContent.append("REQUEST_URI: " + request.uri() + "\r\n\r\n"); responseContent.append("\r\n\r\n"); // new getMethod for (Entry<String, String> entry : request.headers()) { responseContent.append("HEADER: " + entry.getKey() + '=' + entry.getValue() + "\r\n"); } responseContent.append("\r\n\r\n"); // new getMethod Set<Cookie> cookies; String value = request.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { responseContent.append("COOKIE: " + cookie + "\r\n"); } responseContent.append("\r\n\r\n"); QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri()); Map<String, List<String>> uriAttributes = decoderQuery.parameters(); for (Entry<String, List<String>> attr : uriAttributes.entrySet()) { for (String attrVal : attr.getValue()) { responseContent.append("URI: " + attr.getKey() + '=' + attrVal + "\r\n"); } } responseContent.append("\r\n\r\n"); // if GET Method: should not try to create a HttpPostRequestDecoder if (request.method().equals(HttpMethod.GET)) { // GET Method: should not try to create a HttpPostRequestDecoder // So stop here responseContent.append("\r\n\r\nEND OF GET CONTENT\r\n"); // Not now: LastHttpContent will be sent writeResponse(ctx.channel()); return; } try { decoder = new HttpPostRequestDecoder(factory, request); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } readingChunks = HttpUtil.isTransferEncodingChunked(request); responseContent.append("Is Chunked: " + readingChunks + "\r\n"); responseContent.append("IsMultipart: " + decoder.isMultipart() + "\r\n"); if (readingChunks) { // Chunk version responseContent.append("Chunks: "); readingChunks = true; } } // check if the decoder was constructed before // if not it handles the form get if (decoder != null) { logger.info("upload, decoder!= null" + msg); if (msg instanceof HttpContent) { // New chunk is received HttpContent chunk = (HttpContent) msg; try { decoder.offer(chunk); } catch (ErrorDataDecoderException e1) { e1.printStackTrace(); responseContent.append(e1.getMessage()); writeResponse(ctx.channel()); ctx.channel().close(); return; } responseContent.append('o'); // example of reading chunk by chunk (minimize memory usage due to // Factory) readHttpDataChunkByChunk(); // example of reading only if at the end if (chunk instanceof LastHttpContent) { writeResponse(ctx.channel()); readingChunks = false; reset(); } } } else { logger.info("upload, decoder == null, writeResponse."); writeResponse(ctx.channel()); } }
From source file:gribbit.http.request.Request.java
License:Open Source License
public Request(ChannelHandlerContext ctx, HttpRequest httpReq) throws ResponseException { this.reqReceivedTimeEpochMillis = System.currentTimeMillis(); this.httpRequest = httpReq; HttpHeaders headers = httpReq.headers(); // Netty changes the URI of the request to "/bad-request" if the HTTP request was malformed this.rawURL = httpReq.uri(); if (rawURL.equals("/bad-request")) { throw new BadRequestException(); } else if (rawURL.isEmpty()) { rawURL = "/"; }//from w w w .ja v a2s . com // Decode the URL RequestURL requestURL = new RequestURL(rawURL); this.normalizedURL = requestURL.getNormalizedPath(); this.queryParamToVals = requestURL.getQueryParams(); // TODO: figure out how to detect HTTP/2 connections this.httpVersion = httpReq.protocolVersion().toString(); // Get HTTP2 stream ID this.streamId = headers.getAsString(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text()); this.isSecure = ctx.pipeline().get(SslHandler.class) != null; // TODO: is this correct for HTTP2? // Decode cookies try { for (CharSequence cookieHeader : headers.getAll(COOKIE)) { for (Cookie cookie : ServerCookieDecoder.STRICT.decode(cookieHeader.toString())) { // Log.fine("Cookie in request: " + nettyCookie); if (cookieNameToCookies == null) { cookieNameToCookies = new HashMap<>(); } String cookieName = cookie.name(); // Multiple cookies may be present in the request with the same name but with different paths ArrayList<Cookie> cookiesWithThisName = cookieNameToCookies.get(cookieName); if (cookiesWithThisName == null) { cookieNameToCookies.put(cookieName, cookiesWithThisName = new ArrayList<>()); } cookiesWithThisName.add(cookie); } } } catch (IllegalArgumentException e) { // Malformed cookies cause ServerCookieDecoder to throw IllegalArgumentException // Log.info("Malformed cookie in request"); throw new BadRequestException(); } // Sort cookies into decreasing order of path length, in case client doesn't conform to RFC6295, // delivering the cookies in this order itself. This allows us to get the most likely single // cookie for a given cookie name by reading the first cookie in a list for a given name. if (cookieNameToCookies != null) { for (Entry<String, ArrayList<Cookie>> ent : cookieNameToCookies.entrySet()) { Collections.sort(ent.getValue(), COOKIE_COMPARATOR); } } this.method = httpReq.method(); // Force the GET method if HEAD is requested this.isHEADRequest = this.method == HttpMethod.HEAD; if (this.isHEADRequest) { this.method = HttpMethod.GET; } this.isKeepAlive = HttpUtil.isKeepAlive(httpReq) && httpReq.protocolVersion().equals(HttpVersion.HTTP_1_0); CharSequence host = headers.get(HOST); this.host = host == null ? null : host.toString(); this.xRequestedWith = headers.get("X-Requested-With"); this.accept = headers.get(ACCEPT); this.acceptCharset = headers.get(ACCEPT_CHARSET); this.acceptLanguage = headers.get(ACCEPT_LANGUAGE); this.origin = headers.get(ORIGIN); this.referer = headers.get(REFERER); this.userAgent = headers.get(USER_AGENT); InetSocketAddress requestorSocketAddr = (InetSocketAddress) ctx.channel().remoteAddress(); if (requestorSocketAddr != null) { InetAddress address = requestorSocketAddr.getAddress(); if (address != null) { this.requestor = address.getHostAddress(); } } CharSequence acceptEncoding = headers.get(ACCEPT_ENCODING); this.acceptEncodingGzip = acceptEncoding != null && acceptEncoding.toString().toLowerCase().contains("gzip"); this.ifModifiedSince = headers.get(IF_MODIFIED_SINCE); if (this.ifModifiedSince != null && this.ifModifiedSince.length() > 0) { this.ifModifiedSinceEpochSecond = ZonedDateTime .parse(this.ifModifiedSince, DateTimeFormatter.RFC_1123_DATE_TIME).toEpochSecond(); } // // If this is a hash URL, look up original URL whose served resource was hashed to give this hash URL. // // We only need to serve the resource at a hash URL once per resource per client, since resources served // // from hash URLs are indefinitely cached in the browser. // // TODO: Move cache-busting out of http package // this.urlHashKey = CacheExtension.getHashKey(this.urlPath); // this.urlPathUnhashed = this.urlHashKey != null ? CacheExtension.getOrigURL(this.urlPath) : this.urlPath; // // Get flash messages from cookie, if any // this.flashMessages = FlashMessage.fromCookieString(getCookieValue(Cookie.FLASH_COOKIE_NAME)); }