List of usage examples for io.netty.handler.codec.http Cookie setPath
void setPath(String path);
From source file:com.ejisto.modules.vertx.handler.SecurityEnforcer.java
License:Open Source License
@Override public void handle(HttpServerRequest request) { final MultiMap headers = request.headers(); Optional<String> xRequestedWith = Optional.ofNullable(headers.get(X_REQUESTED_WITH)) .filter("XMLHttpRequest"::equals); if (xRequestedWith.isPresent()) { if (!isDevModeActive()) { request.response().write(SECURITY_TOKEN); }/* w ww. j a v a2 s. c o m*/ Optional<String> header = Optional.ofNullable(headers.get(XSRF_TOKEN_HEADER)).filter(token::equals); if (!header.isPresent()) { Boilerplate.writeError(request, HttpResponseStatus.FORBIDDEN.code(), HttpResponseStatus.FORBIDDEN.reasonPhrase()); return; } } if ("/index.html".equals(request.path())) { Cookie cookie = new DefaultCookie(XSRF_TOKEN, token); cookie.setPath("/"); request.response().headers().set(HttpHeaders.SET_COOKIE, ServerCookieEncoder.encode(cookie)); } super.handle(request); }
From source file:com.ejisto.modules.vertx.handler.SecurityEnforcerTest.java
License:Open Source License
@Test public void testTokenCreation() throws Exception { MultiMap headers = new CaseInsensitiveMultiMap(); when(serverRequest.path()).thenReturn("/index.html"); when(serverResponse.headers()).thenReturn(headers); System.setProperty(StringConstants.DEV_MODE.getValue(), "true"); enforcer.handle(serverRequest);//from ww w . ja v a 2 s .com verify(serverResponse, never()).write(SecurityEnforcer.SECURITY_TOKEN); assertTrue(headers.contains(HttpHeaders.SET_COOKIE)); assertNotNull(headers.get(HttpHeaders.SET_COOKIE)); Cookie cookie = new DefaultCookie(SecurityEnforcer.XSRF_TOKEN, NSA_PROOF_TOKEN); cookie.setPath("/"); assertEquals(ServerCookieEncoder.encode(cookie), headers.get(HttpHeaders.SET_COOKIE)); }
From source file:com.titilink.camel.rest.common.AdapterRestletUtil.java
License:LGPL
/** * ?Cookie/*from ww w .jav a 2 s . c om*/ * * @param cookie * @return */ public static org.restlet.data.Cookie parseToRestletCookie(Cookie cookie) { if (null == cookie) { LOGGER.error("cookie=null"); return null; } org.restlet.data.Cookie restletCookie = new org.restlet.data.Cookie(); restletCookie.setDomain(cookie.getDomain()); restletCookie.setVersion(cookie.getVersion()); restletCookie.setName(cookie.getName()); restletCookie.setValue(cookie.getValue()); restletCookie.setPath(cookie.getPath()); return restletCookie; }
From source file:divconq.web.http.ServerHandler.java
License:Open Source License
public void handleHttpRequest(ChannelHandlerContext ctx, HttpObject httpobj) throws Exception { if (httpobj instanceof HttpContent) { this.context.offerContent((HttpContent) httpobj); return;//from www. j a v a 2s .c o m } if (!(httpobj instanceof HttpRequest)) { this.context.sendRequestBad(); return; } HttpRequest httpreq = (HttpRequest) httpobj; this.context.load(ctx, httpreq); // Handle a bad request. if (!httpreq.getDecoderResult().isSuccess()) { this.context.sendRequestBad(); return; } Request req = this.context.getRequest(); Response resp = this.context.getResponse(); // to avoid lots of unused sessions if (req.pathEquals("/favicon.ico") || req.pathEquals("/robots.txt")) { this.context.sendNotFound(); return; } // make sure we don't have a leftover task context OperationContext.clear(); String origin = "http:" + NetUtil.formatIpAddress((InetSocketAddress) ctx.channel().remoteAddress()); // TODO use X-Forwarded-For if available, maybe a plug in approach to getting client's IP? DomainInfo dinfo = this.context.getSiteman().resolveDomainInfo(req.getHeader("Host")); if (dinfo == null) { this.context.sendForbidden(); return; } WebDomain wdomain = this.context.getSiteman().getDomain(dinfo.getId()); // check into url re-routing String reroute = wdomain.route(req, (SslHandler) ctx.channel().pipeline().get("ssl")); if (StringUtil.isNotEmpty(reroute)) { this.context.getResponse().setStatus(HttpResponseStatus.FOUND); this.context.getResponse().setHeader("Location", reroute); this.context.send(); return; } Cookie sesscookie = req.getCookie("SessionId"); Session sess = null; if (sesscookie != null) { String v = sesscookie.getValue(); String sessionid = v.substring(0, v.lastIndexOf('_')); String accesscode = v.substring(v.lastIndexOf('_') + 1); sess = Hub.instance.getSessions().lookupAuth(sessionid, accesscode); } if (sess == null) { sess = Hub.instance.getSessions().create(origin, dinfo.getId()); Logger.info("Started new session: " + sess.getId() + " on " + req.getPath() + " for " + origin); // TODO if ssl set client key on user context //req.getSecuritySession().getPeerCertificates(); sess.setAdatper(new ISessionAdapter() { protected volatile ListStruct msgs = new ListStruct(); @Override public void stop() { ServerHandler.this.context.close(); } @Override public ListStruct popMessages() { ListStruct ret = this.msgs; this.msgs = new ListStruct(); return ret; } @Override public void deliver(Message msg) { // keep no more than 100 messages - this is not a "reliable" approach, just basic comm help while (this.msgs.getSize() > 99) this.msgs.removeItem(0); this.msgs.addItem(msg); } }); Cookie sk = new DefaultCookie("SessionId", sess.getId() + "_" + sess.getKey()); sk.setPath("/"); sk.setHttpOnly(true); resp.setCookie(sk); } this.context.setSession(sess); sess.touch(); OperationContext tc = sess.setContext(origin); tc.info("Web request for host: " + req.getHeader("Host") + " url: " + req.getPath() + " by: " + origin + " session: " + sess.getId()); /* System.out.println("sess proto: " + ((SslHandler)ctx.channel().pipeline().get("ssl")).engine().getSession().getProtocol()); System.out.println("sess suite: " + ((SslHandler)ctx.channel().pipeline().get("ssl")).engine().getSession().getCipherSuite()); */ try { if (req.pathEquals(ServerHandler.BUS_PATH)) { // Allow only GET methods. if (req.getMethod() != HttpMethod.GET) { this.context.sendForbidden(); return; } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory( ServerHandler.getWebSocketLocation( "True".equals(this.context.getConfig().getAttribute("Secure")), httpreq), null, false); this.handshaker = wsFactory.newHandshaker(httpreq); if (this.handshaker == null) WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); else { DefaultFullHttpRequest freq = new DefaultFullHttpRequest(httpreq.getProtocolVersion(), httpreq.getMethod(), httpreq.getUri()); freq.headers().add(httpreq.headers()); this.handshaker.handshake(ctx.channel(), freq); return; } this.context.sendForbidden(); return; } // "upload" is it's own built-in extension. if ((req.getPath().getNameCount() == 3) && req.getPath().getName(0).equals(ServerHandler.UPLOAD_PATH)) { if (!Hub.instance.isRunning()) { // only allow uploads when running this.context.sendRequestBad(); return; } // currently only supporting POST/PUT of pure binary - though support for form uploads can be restored, see below // we cannot rely on content type being meaningful //if (!"application/octet-stream".equals(req.getContentType().getPrimary())) { // this.context.sendRequestBad(); // return; //} // TODO add CORS support if needed if ((req.getMethod() != HttpMethod.PUT) && (req.getMethod() != HttpMethod.POST)) { this.context.sendRequestBad(); return; } final String cid = req.getPath().getName(1); final String op = req.getPath().getName(2); final DataStreamChannel dsc = sess.getChannel(cid); if (dsc == null) { this.context.sendRequestBad(); return; } dsc.setDriver(new IStreamDriver() { @Override public void cancel() { Logger.error("Transfer canceled on channel: " + cid); dsc.complete(); ServerHandler.this.context.sendRequestBad(); // TODO headers? } @Override public void nextChunk() { Logger.debug("Continue on channel: " + cid); ServerHandler.this.context.sendRequestOk(); } @Override public void message(StreamMessage msg) { if (msg.isFinal()) { Logger.debug("Final on channel: " + cid); dsc.complete(); ServerHandler.this.context.sendRequestOk(); } } }); //if (req.getMethod() == HttpMethod.PUT) { this.context.setDecoder(new IContentDecoder() { protected boolean completed = false; protected int seq = 0; @Override public void release() { // trust that http connection is closing or what ever needs to happen, we just need to deal with datastream Logger.debug("Releasing data stream"); // if not done with request then something went wrong, kill data channel if (!this.completed) dsc.abort(); } @Override public void offer(HttpContent chunk) { boolean finalchunk = (chunk instanceof LastHttpContent); //System.out.println("Chunk: " + finalchunk); ByteBuf buffer = chunk.content(); if (!dsc.isClosed()) { int size = buffer.readableBytes(); //System.out.println("Chunk size: " + size); dsc.touch(); // TODO try to set progress on dsc // TODO set hint in netty as to where this buffer was handled and sent if (size > 0) { buffer.retain(); // we will be using a reference up during send StreamMessage b = new StreamMessage("Block", buffer); b.setField("Sequence", this.seq); //System.out.println("Buffer ref cnt a: " + buffer.refCnt()); OperationResult or = dsc.send(b); //System.out.println("Buffer ref cnt b: " + buffer.refCnt()); // indicate we have read the buffer? buffer.readerIndex(buffer.writerIndex()); if (or.hasErrors()) { dsc.close(); return; } this.seq++; } // if last buffer of last block then mark the upload as completed if (finalchunk) { if ("Final".equals(op)) dsc.send(MessageUtil.streamFinal()); else dsc.getDriver().nextChunk(); } } // means this block is completed, not necessarily entire file uploaded if (finalchunk) this.completed = true; } }); //return; //} /* old approach that supported multipart posts TODO review/remove if (req.getMethod() == HttpMethod.POST) { StreamingDataFactory sdf = new StreamingDataFactory(dsc, op); // TODO consider supporting non-multipart? final HttpPostMultipartRequestDecoder prd = new HttpPostMultipartRequestDecoder(sdf, httpreq); this.context.setDecoder(new IContentDecoder() { @Override public void release() { // trust that http connection is closing or what ever needs to happen, we just need to deal with datastream // if not done with request then something went wrong, kill data channel if ((prd.getStatus() != MultiPartStatus.EPILOGUE) && (prd.getStatus() != MultiPartStatus.PREEPILOGUE)) dsc.kill(); } @Override public void offer(HttpContent chunk) { //the only thing we care about is the file, the file will stream to dsc - the rest can disappear prd.offer(chunk); } }); return; } */ //this.context.sendRequestBad(); return; } // "download" is it's own built-in extension. if ((req.getPath().getNameCount() == 2) && req.getPath().getName(0).equals(ServerHandler.DOWNLOAD_PATH)) { if (!Hub.instance.isRunning()) { // only allow downloads when running this.context.sendRequestBad(); return; } if (req.getMethod() != HttpMethod.GET) { this.context.sendRequestBad(); return; } String cid = req.getPath().getName(1); final DataStreamChannel dsc = sess.getChannel(cid); if (dsc == null) { this.context.sendRequestBad(); return; } dsc.setDriver(new IStreamDriver() { //protected long amt = 0; protected long seq = 0; @Override public void cancel() { dsc.complete(); ServerHandler.this.context.close(); } @Override public void nextChunk() { // meaningless in download } @Override public void message(StreamMessage msg) { int seqnum = (int) msg.getFieldAsInteger("Sequence", 0); if (seqnum != this.seq) { this.error(1, "Bad sequence number: " + seqnum); return; } if (msg.hasData()) { //this.amt += msg.getData().readableBytes(); HttpContent b = new DefaultHttpContent(Unpooled.copiedBuffer(msg.getData())); // TODO not copied ServerHandler.this.context.sendDownload(b); } this.seq++; // TODO update progress if (msg.isFinal()) { ServerHandler.this.context.sendDownload(new DefaultLastHttpContent()); ServerHandler.this.context.close(); dsc.complete(); } } public void error(int code, String msg) { dsc.send(MessageUtil.streamError(code, msg)); ServerHandler.this.context.close(); } }); // for some reason HyperSession is sending content. this.context.setDecoder(new IContentDecoder() { @Override public void release() { } @Override public void offer(HttpContent chunk) { if (!(chunk instanceof LastHttpContent)) Logger.error("Unexplained and unwanted content during download: " + chunk); } }); // tell the client that chunked content is coming this.context.sendDownloadHeaders(dsc.getPath() != null ? dsc.getPath().getFileName() : null, dsc.getMime()); // get the data flowing dsc.send(new StreamMessage("Start")); return; } if ((req.getPath().getNameCount() == 1) && req.getPath().getName(0).equals(ServerHandler.STATUS_PATH)) { if (Hub.instance.getState() == HubState.Running) this.context.sendRequestOk(); else this.context.sendRequestBad(); return; } // "rpc" is it's own built-in extension. all requests to rpc are routed through // DivConq bus, if the request is valid if (req.pathEquals(ServerHandler.RPC_PATH)) { if (req.getMethod() != HttpMethod.POST) { this.context.sendRequestBad(); return; } //System.out.println("looks like we have a rpc message"); // max 4MB of json? -- TODO is that max chunk size or max total? we don't need 4MB chunk... this.context.setDecoder(new HttpBodyRequestDecoder(4096 * 1024, new RpcHandler(this.context))); return; } // otherwise we need to figure out which extension is being called // "local" is also used to mean default extension String ext = req.pathEquals("/") ? "local" : req.getPath().getName(0); IWebExtension ex = "local".equals(ext) ? this.context.getSiteman().getDefaultExtension() : this.context.getSiteman().getExtension(ext); // still cannot figure it out, use default if (ex == null) ex = this.context.getSiteman().getDefaultExtension(); // then have extension handle it if (ex != null) { //OperationResult res = new OperationResult(); OperationResult res = ex.handle(sess, this.context); //resp.addBody("Hello"); //this.context.send(); // no errors starting page processing, return if (!res.hasErrors()) return; resp.setHeader("X-dcResultCode", res.getCode() + ""); resp.setHeader("X-dcResultMesage", res.getMessage()); this.context.sendNotFound(); return; } } catch (Exception x) { this.context.sendInternalError(); return; } this.context.sendNotFound(); }
From source file:divconq.web.Response.java
License:Open Source License
public void writeDownloadHeaders(Channel ch, String name, String mime) { // Build the response object. HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, this.status); response.headers().set(Names.CONTENT_TYPE, StringUtil.isNotEmpty(mime) ? mime : MimeUtil.getMimeTypeForFile(name)); if (StringUtil.isEmpty(name)) name = FileUtil.randomFilename("bin"); response.headers().set("Content-Disposition", "attachment; filename=\"" + NetUtil.urlEncodeUTF8(name) + "\""); Cookie dl = new DefaultCookie("fileDownload", "true"); dl.setPath("/"); response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(dl)); // Encode the cookies for (Cookie c : this.cookies.values()) response.headers().add(Names.SET_COOKIE, ServerCookieEncoder.encode(c)); for (Entry<CharSequence, String> h : this.headers.entrySet()) response.headers().set(h.getKey(), h.getValue()); response.headers().set(Names.TRANSFER_ENCODING, Values.CHUNKED); // Write the response. ch.writeAndFlush(response);//from w ww .j a v a 2s .co m }
From source file:fr.wseduc.webutils.request.CookieHelper.java
License:Apache License
public static void set(String name, String value, long timeout, String path, HttpServerRequest request) { Cookie cookie = new DefaultCookie(name, value); cookie.setMaxAge(timeout);//from ww w . j a v a2 s. co m cookie.setSecure("https".equals(Renders.getScheme(request))); if (path != null && !path.trim().isEmpty()) { cookie.setPath(path); } request.response().headers().set("Set-Cookie", ServerCookieEncoder.encode(cookie)); }
From source file:fr.wseduc.webutils.request.CookieHelper.java
License:Apache License
public void setSigned(String name, String value, long timeout, String path, HttpServerRequest request) { Cookie cookie = new DefaultCookie(name, value); cookie.setMaxAge(timeout);/*from ww w . j a va2s .c om*/ cookie.setSecure("https".equals(Renders.getScheme(request))); if (path != null && !path.trim().isEmpty()) { cookie.setPath(path); } if (signKey != null) { try { signCookie(cookie); } catch (InvalidKeyException | NoSuchAlgorithmException | IllegalStateException | UnsupportedEncodingException e) { log.error(e); return; } request.response().headers().set("Set-Cookie", ServerCookieEncoder.encode(cookie)); } }
From source file:io.nebo.container.NettyHttpServletRequest.java
License:Apache License
@Override public Cookie[] getCookies() { String cookieString = this.request.headers().get(COOKIE); if (cookieString != null) { Set<io.netty.handler.codec.http.Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { Cookie[] cookiesArray = new Cookie[cookies.size()]; int index = 0; for (io.netty.handler.codec.http.Cookie c : cookies) { Cookie cookie = new Cookie(c.getName(), c.getValue()); cookie.setComment(c.getComment()); if (c.getDomain() != null) cookie.setDomain(c.getDomain()); cookie.setMaxAge((int) c.getMaxAge()); cookie.setPath(c.getPath()); cookie.setSecure(c.isSecure()); cookie.setVersion(c.getVersion()); cookiesArray[index] = cookie; index++;// w w w . ja v a 2s . c om } return cookiesArray; } } return new Cookie[0]; }
From source file:io.reactivex.netty.protocol.http.client.CookieTest.java
License:Apache License
@Test public void testSetCookie() throws Exception { DefaultHttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); String cookie1Name = "PREF"; String cookie1Value = "ID=a95756377b78e75e:FF=0:TM=1392709628:LM=1392709628:S=a5mOVvTB7DBkexgi"; String cookie1Domain = ".google.com"; String cookie1Path = "/"; Cookie cookie = new DefaultCookie(cookie1Name, cookie1Value); cookie.setPath(cookie1Path); cookie.setDomain(cookie1Domain);//from w w w . jav a2 s. co m new HttpClientRequest<ByteBuf>(nettyRequest).withCookie(cookie); String cookieHeader = nettyRequest.headers().get(HttpHeaders.Names.COOKIE); Assert.assertNotNull("No cookie header found.", cookieHeader); Set<Cookie> decodeCookies = CookieDecoder.decode(cookieHeader); Assert.assertNotNull("No cookie found with name.", decodeCookies); Assert.assertEquals("Unexpected number of cookies.", 1, decodeCookies.size()); Cookie decodedCookie = decodeCookies.iterator().next(); Assert.assertEquals("Unexpected cookie name.", cookie1Name, decodedCookie.getName()); Assert.assertEquals("Unexpected cookie path.", cookie1Path, decodedCookie.getPath()); Assert.assertEquals("Unexpected cookie domain.", cookie1Domain, decodedCookie.getDomain()); }
From source file:org.glowroot.local.ui.HttpSessionManager.java
License:Apache License
void createSession(HttpResponse response, boolean admin) { String sessionId = new BigInteger(130, secureRandom).toString(32); updateSessionExpiration(sessionId, admin); Cookie cookie = new DefaultCookie("GLOWROOT_SESSION_ID", sessionId); cookie.setHttpOnly(true);// www .j a va 2 s.c o m cookie.setPath("/"); response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); purgeExpiredSessions(); }