List of usage examples for io.netty.handler.codec.http HttpMethod GET
HttpMethod GET
To view the source code for io.netty.handler.codec.http HttpMethod GET.
Click Source Link
From source file:com.buildria.mocking.builder.action.StatusCodeActionTest.java
License:Open Source License
@Test public void testApplyResponse() throws Exception { int code = 404; StatusCodeAction action = new StatusCodeAction(code); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/api/p"); HttpResponse res = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpResponse out = action.apply(req, res); assertThat(out, notNullValue());/*from w w w . j a v a 2 s .c om*/ assertThat(out.getStatus().code(), is(code)); }
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 {//w w w .j ava 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.chiorichan.http.HttpHandler.java
License:Mozilla Public License
/** * Handles the HTTP request. Each HTTP subsystem will be explicitly activated until a resolve is determined. * * @throws IOException/*from w w w.j av a 2 s. com*/ * Universal exception for all Input/Output errors * @throws HttpError * for HTTP Errors * @throws PermissionException * for permission problems, like access denied * @throws MultipleException * for multiple Scripting Factory Evaluation Exceptions * @throws ScriptingException * for Scripting Factory Evaluation Exception * @throws SessionException * for problems initializing a new or used session */ private void handleHttp() throws Exception // IOException, HttpError, SiteException, PermissionException, MultipleException, ScriptingException, SessionException { log.log(Level.INFO, request.methodString() + " " + request.getFullUrl()); Session sess = request.startSession(); log.log(Level.FINE, "Session {id=%s,timeout=%s,new=%s}", sess.getSessId(), sess.getTimeout(), sess.isNew()); if (response.getStage() == HttpResponseStage.CLOSED) throw new IOException("Connection reset by peer"); // This is not the only place 'Connection reset by peer' is thrown RequestEvent requestEvent = new RequestEvent(request); try { EventBus.instance().callEventWithException(requestEvent); } catch (EventException ex) { throw new IOException( "Exception encountered during request event call, most likely the fault of a plugin.", ex); } response.setStatus(requestEvent.getStatus()); if (requestEvent.isCancelled()) { int status = requestEvent.getStatus(); String reason = requestEvent.getReason(); if (status == 200) { status = 502; reason = "Navigation Cancelled by Plugin Event"; } NetworkManager.getLogger().warning("Navigation was cancelled by a Plugin Event"); throw new HttpError(status, reason); } if (response.isCommitted()) return; // Throws IOException and HttpError fi = new WebInterpreter(request); response.annotations.putAll(fi.getAnnotations()); currentSite = request.getLocation(); sess.setSite(currentSite); if (request.getSubdomain().length() > 0 && !currentSite.getSubdomain(request.getSubdomain()).isMaped(request.getDomain())) { if ("www".equalsIgnoreCase(request.getSubdomain()) || AppConfig.get().getBoolean("sites.redirectMissingSubDomains")) { log.log(Level.SEVERE, "Redirecting non-existent subdomain '%s' to root domain '%s'", request.getSubdomain(), request.getFullUrl("")); response.sendRedirect(request.getFullUrl("")); } else { log.log(Level.SEVERE, "The requested subdomain '%s' is non-existent.", request.getSubdomain(), request.getFullDomain("")); response.sendError(HttpResponseStatus.NOT_FOUND, "Subdomain not found"); } return; } File docRoot = currentSite.getSubdomain(request.getSubdomain()).directory(); Validate.notNull(docRoot); if (sess.isLoginPresent()) log.log(Level.FINE, "Account {id=%s,displayName=%s}", sess.getId(), sess.getDisplayName()); /* * Start: SSL enforcer * * Acts on the value of annotation 'SSL'. * REQUIRED means a forbidden error will be thrown is it can not be accomplished * * Options include: * Preferred: If SSL is available, we preferred to be switched to it * PostOnly: SSL is REQUIRED is this is a POST request * GetOnly: SSL is REQUIRED if this is a GET request * Required: SSL is REQUIRED, no exceptions! * Deny: SSL is DENIED, no exceptions! * Ignore: We don't care one way or other, do nothing! DEFAULT */ SslLevel sslLevel = SslLevel.parse(fi.get("ssl")); boolean required = false; switch (sslLevel) { case Preferred: if (NetworkManager.isHttpsRunning()) required = true; break; case PostOnly: if (request.method() == HttpMethod.POST) required = true; break; case GetOnly: if (request.method() == HttpMethod.GET) required = true; break; case Required: required = true; break; case Deny: if (ssl) { if (!response.switchToUnsecure()) response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires an unsecure connection."); return; } break; case Ignore: break; } if (required && !ssl) { if (!response.switchToSecure()) response.sendError(HttpCode.HTTP_FORBIDDEN, "This page requires a secure connection."); return; } /* * End: SSL enforcer */ if (fi.getStatus() != HttpResponseStatus.OK) throw new HttpError(fi.getStatus()); /* * Start: Apache Configuration Section * * Loads a Apache configuration and .htaccess files into a common handler, then parsed for directives like access restrictions and basic auth * TODO Load server-wide Apache Configuration then merge with Site Configuration */ ApacheHandler htaccess = new ApacheHandler(); response.setApacheParser(htaccess); try { boolean result = htaccess.handleDirectives(currentSite.getApacheConfig(), this); if (htaccess.overrideNone() || htaccess.overrideListNone()) // Ignore .htaccess files { if (fi.hasFile()) if (!htaccess.handleDirectives(new ApacheConfiguration(fi.getFile().getParentFile()), this)) result = false; if (!htaccess.handleDirectives(new ApacheConfiguration(docRoot), this)) result = false; } if (!result) { if (!response.isCommitted()) response.sendError(500, "Your request was blocked by an internal configuration directive, exact details are unknown."); return; } } catch (ApacheDirectiveException e) { log.log(Level.SEVERE, "Caught Apache directive exception: " + e.getMessage()); // TODO Throw 500 unless told not to } /* * End: Apache Configuration Section */ if (!fi.hasFile() && !fi.hasHTML()) response.setStatus(HttpResponseStatus.NO_CONTENT); sess.setGlobal("__FILE__", fi.getFile()); request.putRewriteParams(fi.getRewriteParams()); response.setContentType(fi.getContentType()); response.setEncoding(fi.getEncoding()); request.getServer().put(ServerVars.DOCUMENT_ROOT, docRoot); request.setGlobal("_SERVER", request.getServer()); request.setGlobal("_POST", request.getPostMap()); request.setGlobal("_GET", request.getGetMap()); request.setGlobal("_REWRITE", request.getRewriteMap()); request.setGlobal("_FILES", request.getUploadedFiles()); // TODO Implement NONCE requirement for login page NonceLevel level = NonceLevel.parse(fi.get("nonce")); boolean nonceProvided = sess.nonce() == null ? false : request.getRequestMap().get(sess.nonce().key()) != null; boolean processNonce = false; switch (level) { case Required: processNonce = true; break; case GetOnly: processNonce = request.method() == HttpMethod.GET || nonceProvided; break; case PostOnly: processNonce = request.method() == HttpMethod.POST || nonceProvided; break; case Flexible: processNonce = nonceProvided; break; case Disabled: default: // Do Nothing } Map<String, String> nonceMap = Maps.newHashMap(); if (processNonce) { if (!nonceProvided) { log.log(Level.SEVERE, "The request has failed NONCE validation, because the nonce key was not present!"); response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!"); return; } Nonce nonce = sess.nonce(); if (level == NonceLevel.Required) // Required NonceLevels are of the highest protected state sess.destroyNonce(); try { if (!(request.getRequestMap().get(nonce.key()) instanceof String)) throw new NonceException("Nonce token is not a string"); nonce.validateWithException((String) request.getRequestMap().get(nonce.key())); } catch (NonceException e) { log.log(Level.SEVERE, "The request has failed NONCE validation, because " + e.getMessage().toLowerCase() + "!"); response.sendError(HttpResponseStatus.FORBIDDEN, "Your request has failed NONCE validation!"); sess.destroyNonce(); return; } finally { log.log(Level.INFO, "The request has passed the NONCE validation!"); request.nonceProcessed(true); nonceMap = nonce.mapValues(); } } if (request.validateLogins()) return; if (level != NonceLevel.Disabled) request.setGlobal("_NONCE", nonceMap); try { if (request.getUploadedFiles().size() > 0) log.log(Level.INFO, "Uploads {" + StringFunc.limitLength( Joiner.on(",").skipNulls().join(request.getUploadedFiles().values()), 255) + "}"); if (request.getGetMap().size() > 0) log.log(Level.INFO, "Params GET {" + StringFunc.limitLength( Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getGetMap()), 255) + "}"); if (request.getPostMap().size() > 0) log.log(Level.INFO, "Params POST {" + StringFunc.limitLength( Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getPostMap()), 255) + "}"); if (request.getRewriteMap().size() > 0) log.log(Level.INFO, "Params REWRITE {" + StringFunc.limitLength( Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(request.getRewriteMap()), 255) + "}"); if (fi.getAnnotations().size() > 0) log.log(Level.INFO, "Params ANNOTATIONS {" + StringFunc.limitLength( Joiner.on(",").withKeyValueSeparator("=").useForNull("null").join(fi.getAnnotations()), 255) + "}"); } catch (Throwable t) { t.printStackTrace(); } if (AppConfig.get().getBoolean("advanced.security.requestMapEnabled", true)) request.setGlobal("_REQUEST", request.getRequestMap()); ByteBuf rendered = Unpooled.buffer(); ScriptingFactory factory = request.getEvalFactory(); factory.setEncoding(fi.getEncoding()); NetworkSecurity.isForbidden(htaccess, currentSite, fi); String req = fi.get("reqperm"); if (req == null) req = "-1"; sess.requirePermission(req, currentSite.getId()); // Enhancement: Allow HTML to be ran under different shells. Default is embedded. if (fi.hasHTML()) { ScriptingResult result = factory.eval( ScriptingContext.fromSource(fi.getHTML(), "<embedded>").request(request).site(currentSite)); if (result.hasExceptions()) // TODO Print notices to output like PHP does for (ScriptingException e : result.getExceptions()) { ExceptionReport.throwExceptions(e); log.exceptions(e); if (e.reportingLevel().isEnabled()) rendered.writeBytes(e.getMessage().getBytes()); } if (result.isSuccessful()) { rendered.writeBytes(result.content()); if (result.getObject() != null && !(result.getObject() instanceof NullObject)) try { rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes()); } catch (Exception e) { log.log(Level.SEVERE, "Exception Excountered: %s", e.getMessage()); if (Versioning.isDevelopment()) log.log(Level.SEVERE, e.getStackTrace()[0].toString()); } } log.log(Level.INFO, "EvalHtml {timing=%sms,success=%s}", Timings.mark(this), result.isSuccessful()); } if (fi.hasFile()) { if (fi.isDirectoryRequest()) { processDirectoryListing(); return; } ScriptingResult result = factory.eval(ScriptingContext.fromFile(fi).request(request).site(currentSite)); if (result.hasExceptions()) // TODO Print notices to output like PHP does for (ScriptingException e : result.getExceptions()) { ExceptionReport.throwExceptions(e); log.exceptions(e); if (e.reportingLevel().isEnabled() && e.getMessage() != null) rendered.writeBytes(e.getMessage().getBytes()); } if (result.isSuccessful()) { rendered.writeBytes(result.content()); if (result.getObject() != null && !(result.getObject() instanceof NullObject)) try { rendered.writeBytes(ObjectFunc.castToStringWithException(result.getObject()).getBytes()); } catch (Exception e) { rendered.writeBytes(result.getObject().toString().getBytes()); log.log(Level.SEVERE, "Exception encountered while writing returned object to output. %s", e.getMessage()); if (Versioning.isDevelopment()) log.log(Level.SEVERE, e.getStackTrace()[0].toString()); } } log.log(Level.INFO, "EvalFile {file=%s,timing=%sms,success=%s}", fi.getFilePath(), Timings.mark(this), result.isSuccessful()); } // if the connection was in a MultiPart mode, wait for the mode to change then return gracefully. if (response.stage == HttpResponseStage.MULTIPART) { while (response.stage == HttpResponseStage.MULTIPART) // I wonder if there is a better way to handle multipart responses. try { Thread.sleep(100); } catch (InterruptedException e) { throw new HttpError(500, "Internal Server Error encountered during multipart execution."); } return; } // If the connection was closed from page redirect, return gracefully. else if (response.stage == HttpResponseStage.CLOSED || response.stage == HttpResponseStage.WRITTEN) return; // Allows scripts to directly override interpreter values. For example: Themes, Views, Titles for (Entry<String, String> kv : response.annotations.entrySet()) fi.put(kv.getKey(), kv.getValue()); RenderEvent renderEvent = new RenderEvent(this, rendered, fi.getEncoding(), fi.getAnnotations()); try { EventBus.instance().callEventWithException(renderEvent); if (renderEvent.getSource() != null) rendered = renderEvent.getSource(); } catch (EventException ex) { throw new ScriptingException(ReportingLevel.E_ERROR, "Caught EventException while trying to fire the RenderEvent", ex.getCause()); } log.log(Level.INFO, "Written {bytes=%s,total_timing=%sms}", rendered.readableBytes(), Timings.finish(this)); try { response.write(rendered); } catch (IllegalReferenceCountException e) { log.log(Level.SEVERE, "Exception encountered while writting script object to output, %s", e.getMessage()); } }
From source file:com.chiorichan.http.HttpHandler.java
License:Mozilla Public License
@Override protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception { Timings.start(this); if (msg instanceof FullHttpRequest) { if (AppLoader.instances().get(0).runLevel() != RunLevel.RUNNING) { // Outputs a very crude raw message if we are running in a low level mode a.k.a. Startup or Reload. // While in the mode, much of the server API is potentially unavailable, that is why we do this. StringBuilder sb = new StringBuilder(); sb.append("<h1>503 - Service Unavailable</h1>\n"); sb.append(// w w w. ja v a 2 s .c o m "<p>I'm sorry to have to be the one to tell you this but the server is currently unavailable.</p>\n"); sb.append( "<p>This is most likely due to many possibilities, most commonly being it's currently booting up. Which would be great news because it means your request should succeed if you try again.</p>\n"); sb.append( "<p>But it is also possible that the server is actually running in a low level mode or could be offline for some other reason. If you feel this is a mistake, might I suggest you talk with the server admin.</p>\n"); sb.append("<p><i>You have a good day now and we will see you again soon. :)</i></p>\n"); sb.append("<hr>\n"); sb.append("<small>Running <a href=\"https://github.com/ChioriGreene/ChioriWebServer\">" + Versioning.getProduct() + "</a> Version " + Versioning.getVersion() + " (Build #" + Versioning.getBuildNumber() + ")<br />" + Versioning.getCopyright() + "</small>"); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(503), Unpooled.wrappedBuffer(sb.toString().getBytes())); ctx.write(response); return; } requestFinished = false; requestOrig = (FullHttpRequest) msg; request = new HttpRequestWrapper(ctx.channel(), requestOrig, this, ssl, log); response = request.getResponse(); String threadName = Thread.currentThread().getName(); if (threadName.length() > 10) threadName = threadName.substring(0, 2) + ".." + threadName.substring(threadName.length() - 6); else if (threadName.length() < 10) threadName = threadName + Strings.repeat(" ", 10 - threadName.length()); log.header("&7[&d%s&7] %s %s [&9%s:%s&7] -> [&a%s:%s&7]", threadName, dateFormat.format(Timings.millis()), timeFormat.format(Timings.millis()), request.getIpAddr(), request.getRemotePort(), request.getLocalIpAddr(), request.getLocalPort()); if (HttpHeaderUtil.is100ContinueExpected((HttpRequest) msg)) send100Continue(ctx); if (NetworkSecurity.isIpBanned(request.getIpAddr())) { response.sendError(403); return; } Site currentSite = request.getLocation(); File tmpFileDirectory = currentSite != null ? currentSite.directoryTemp() : AppConfig.get().getDirectoryCache(); setTempDirectory(tmpFileDirectory); if (request.isWebsocketRequest()) { try { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( request.getWebSocketLocation(requestOrig), null, true); handshaker = wsFactory.newHandshaker(requestOrig); if (handshaker == null) WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); else handshaker.handshake(ctx.channel(), requestOrig); } catch (WebSocketHandshakeException e) { NetworkManager.getLogger().severe( "A request was made on the websocket uri '/fw/websocket' but it failed to handshake for reason '" + e.getMessage() + "'."); response.sendError(500, null, "This URI is for websocket requests only<br />" + e.getMessage()); } return; } if (request.method() != HttpMethod.GET) try { decoder = new HttpPostRequestDecoder(factory, requestOrig); } catch (ErrorDataDecoderException e) { e.printStackTrace(); response.sendException(e); return; } request.contentSize += requestOrig.content().readableBytes(); if (decoder != null) { try { decoder.offer(requestOrig); } catch (ErrorDataDecoderException e) { e.printStackTrace(); response.sendError(e); // ctx.channel().close(); return; } catch (IllegalArgumentException e) { // TODO Handle this further? maybe? // java.lang.IllegalArgumentException: empty name } readHttpDataChunkByChunk(); } handleHttp(); finish(); } else if (msg instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) msg; // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) throw new UnsupportedOperationException( String.format("%s frame types are not supported", frame.getClass().getName())); String request = ((TextWebSocketFrame) frame).text(); NetworkManager.getLogger() .fine("Received '" + request + "' over WebSocket connection '" + ctx.channel() + "'"); ctx.channel().write(new TextWebSocketFrame(request.toUpperCase())); } else if (msg instanceof DefaultHttpRequest) { // Do Nothing! } else NetworkManager.getLogger().warning( "Received Object '" + msg.getClass() + "' and had nothing to do with it, is this a bug?"); }
From source file:com.cmz.http.snoop.HttpSnoopClient.java
License:Apache License
public static void main(String[] args) throws Exception { URI uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;/* w ww.java 2 s.co m*/ } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. Channel ch = b.connect(host, port).sync().channel(); // Prepare the HTTP request. HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath()); request.headers().set(HttpHeaderNames.HOST, host); request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); // Set some example cookies. request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar"))); // Send the HTTP request. ch.writeAndFlush(request); // Wait for the server to close the connection. ch.closeFuture().sync(); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); } }
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 v a 2s. 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.corundumstudio.socketio.handler.AuthorizeHandlerTest.java
License:Apache License
@Test public void shouldAuthorizeRequest() throws Exception { prepareAuthorizationListener(true, null); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TEST_URI)); // then// ww w.java2 s . c o m Object in = channel.readInbound(); assertTrue(in instanceof DefaultFullHttpRequest); DefaultFullHttpRequest req = (DefaultFullHttpRequest) in; assertEquals(1, req.refCnt()); }
From source file:com.corundumstudio.socketio.handler.AuthorizeHandlerTest.java
License:Apache License
@Test public void shouldNotAuthorizeRequest() throws Exception { prepareAuthorizationListener(false, null); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TEST_URI)); // then/*from w w w .j a v a 2s . c o m*/ Object out = channel.readOutbound(); assertTrue(out instanceof DefaultHttpResponse); DefaultHttpResponse res = (DefaultHttpResponse) out; assertEquals(HttpResponseStatus.UNAUTHORIZED, res.getStatus()); }
From source file:com.corundumstudio.socketio.transport.PollingTransport.java
License:Apache License
private void handleMessage(FullHttpRequest req, UUID sessionId, QueryStringDecoder queryDecoder, ChannelHandlerContext ctx) throws IOException { String origin = req.headers().get(HttpHeaders.Names.ORIGIN); if (queryDecoder.parameters().containsKey("disconnect")) { ClientHead client = clientsBox.get(sessionId); client.onChannelDisconnect();// w ww . j av a2 s.com ctx.channel().writeAndFlush(new XHRPostMessage(origin, sessionId)); } else if (HttpMethod.POST.equals(req.getMethod())) { onPost(sessionId, ctx, origin, req.content()); } else if (HttpMethod.GET.equals(req.getMethod())) { onGet(sessionId, ctx, origin); } else if (HttpMethod.OPTIONS.equals(req.getMethod())) { onOptions(sessionId, ctx, origin); } else { log.error("Wrong {} method invocation for {}", req.getMethod(), sessionId); sendError(ctx); } }
From source file:com.corundumstudio.socketio.transport.XHRPollingTransport.java
License:Apache License
private void handleMessage(FullHttpRequest req, QueryStringDecoder queryDecoder, ChannelHandlerContext ctx) throws IOException { String[] parts = queryDecoder.path().split("/"); if (parts.length > 3) { UUID sessionId = UUID.fromString(parts[4]); String origin = req.headers().get(HttpHeaders.Names.ORIGIN); if (queryDecoder.parameters().containsKey("disconnect")) { MainBaseClient client = sessionId2Client.get(sessionId); client.onChannelDisconnect(); ctx.channel().writeAndFlush(new XHROutMessage(origin, sessionId)); } else if (HttpMethod.POST.equals(req.getMethod())) { onPost(sessionId, ctx, origin, req.content()); } else if (HttpMethod.GET.equals(req.getMethod())) { onGet(sessionId, ctx, origin); }//from w w w. j a v a2s . c o m } else { log.warn("Wrong {} method request path: {}, from ip: {}. Channel closed!", req.getMethod(), path, ctx.channel().remoteAddress()); ctx.channel().close(); } }