List of usage examples for javax.servlet.http Cookie getVersion
public int getVersion()
From source file:ed.net.CookieJar.java
/** * Performs RFC 2109 {@link Cookie} validation * /*from www. ja v a 2 s . com*/ * @param url the source of the cookie * @param cookie The cookie to validate. * @throws IllegalArgumentException if an exception occurs during validation */ private void validate(URL url, Cookie cookie) { String host = url.getHost(); int port = url.getPort(); String path = url.getPath(); // based on org.apache.commons.httpclient.cookie.CookieSpecBase if (host == null) { throw new IllegalArgumentException("Host of origin may not be null"); } if (host.trim().equals("")) { throw new IllegalArgumentException("Host of origin may not be blank"); } if (port < 0) port = 80; if (path == null) { throw new IllegalArgumentException("Path of origin may not be null."); } if (path.trim().equals("")) { path = "/"; } host = host.toLowerCase(); // check version if (cookie.getVersion() < 0) { throw new MalformedCookieException("Illegal version number " + cookie.getValue()); } // security check... we musn't allow the server to give us an // invalid domain scope // Validate the cookies domain attribute. NOTE: Domains without // any dots are allowed to support hosts on private LANs that don't // have DNS names. Since they have no dots, to domain-match the // request-host and domain must be identical for the cookie to sent // back to the origin-server. if (host.indexOf(".") >= 0) { // Not required to have at least two dots. RFC 2965. // A Set-Cookie2 with Domain=ajax.com will be accepted. // domain must match host if (!host.endsWith(cookie.getDomain())) { String s = cookie.getDomain(); if (s.startsWith(".")) { s = s.substring(1, s.length()); } if (!host.equals(s)) { throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } } } else { if (!host.equals(cookie.getDomain())) { throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } } // another security check... we musn't allow the server to give us a // cookie that doesn't match this path if (!path.startsWith(cookie.getPath())) { throw new MalformedCookieException( "Illegal path attribute \"" + cookie.getPath() + "\". Path of origin: \"" + path + "\""); } // Validate using RFC 2109 // -------------------------------------------------------- if (cookie.getName().indexOf(' ') != -1) { throw new MalformedCookieException("Cookie name may not contain blanks"); } if (cookie.getName().startsWith("$")) { throw new MalformedCookieException("Cookie name may not start with $"); } if (cookie.getDomain() != null && (!cookie.getDomain().equals(host))) { // domain must start with dot if (!cookie.getDomain().startsWith(".")) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot"); } // domain must have at least one embedded dot int dotIndex = cookie.getDomain().indexOf('.', 1); if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: domain must contain an embedded dot"); } host = host.toLowerCase(); if (!host.endsWith(cookie.getDomain())) { throw new MalformedCookieException("Illegal domain attribute \"" + cookie.getDomain() + "\". Domain of origin: \"" + host + "\""); } // host minus domain may not contain any dots String hostWithoutDomain = host.substring(0, host.length() - cookie.getDomain().length()); if (hostWithoutDomain.indexOf('.') != -1) { throw new MalformedCookieException("Domain attribute \"" + cookie.getDomain() + "\" violates RFC 2109: host minus domain may not contain any dots"); } } }
From source file:com.liferay.portal.util.HttpImpl.java
protected org.apache.commons.httpclient.Cookie toCommonsCookie(Cookie cookie) { org.apache.commons.httpclient.Cookie commonsCookie = new org.apache.commons.httpclient.Cookie( cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getMaxAge(), cookie.getSecure());//w ww . j a v a2s.com commonsCookie.setVersion(cookie.getVersion()); return commonsCookie; }
From source file:net.lightbody.bmp.proxy.jetty.http.HttpFields.java
/** Format a set cookie value * @param cookie The cookie.//w ww .j ava 2s . c om */ public void addSetCookie(Cookie cookie) { String name = cookie.getName(); String value = cookie.getValue(); int version = cookie.getVersion(); // Check arguments if (name == null || name.length() == 0) throw new IllegalArgumentException("Bad cookie name"); // Format value and params StringBuffer buf = new StringBuffer(128); String name_value_params = null; synchronized (buf) { buf.append(name); buf.append('='); if (value != null && value.length() > 0) { if (version == 0) URI.encodeString(buf, value, "\";, '"); else buf.append(QuotedStringTokenizer.quote(value, "\";, '")); } if (version > 0) { buf.append(";Version="); buf.append(version); String comment = cookie.getComment(); if (comment != null && comment.length() > 0) { buf.append(";Comment="); QuotedStringTokenizer.quote(buf, comment); } } String path = cookie.getPath(); if (path != null && path.length() > 0) { buf.append(";Path="); buf.append(path); } String domain = cookie.getDomain(); if (domain != null && domain.length() > 0) { buf.append(";Domain="); buf.append(domain.toLowerCase());// lowercase for IE } long maxAge = cookie.getMaxAge(); if (maxAge >= 0) { if (version == 0) { buf.append(";Expires="); if (maxAge == 0) buf.append(__01Jan1970); else formatDate(buf, System.currentTimeMillis() + 1000L * maxAge, true); } else { buf.append(";Max-Age="); buf.append(cookie.getMaxAge()); } } else if (version > 0) { buf.append(";Discard"); } if (cookie.getSecure()) { buf.append(";Secure"); } if (cookie instanceof HttpOnlyCookie) buf.append(";HttpOnly"); name_value_params = buf.toString(); } put(__Expires, __01Jan1970); add(__SetCookie, name_value_params); }
From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
private Cookies convertCookies(javax.servlet.http.Cookie[] servletCookies) { List<Cookie> cookies = new ArrayList<Cookie>(); for (javax.servlet.http.Cookie servletCookie : servletCookies) { Cookie.Builder cookieBuilder = new Cookie.Builder(servletCookie.getName(), servletCookie.getValue()); if (servletCookie.getComment() != null) { cookieBuilder.setComment(servletCookie.getComment()); }/*from w ww . j av a 2 s. c om*/ if (servletCookie.getDomain() != null) { cookieBuilder.setDomain(servletCookie.getDomain()); } if (servletCookie.getPath() != null) { cookieBuilder.setPath(servletCookie.getPath()); } cookieBuilder.setMaxAge(servletCookie.getMaxAge()); cookieBuilder.setVersion(servletCookie.getVersion()); cookieBuilder.setSecured(servletCookie.getSecure()); cookies.add(cookieBuilder.build()); } return new Cookies(cookies); }
From source file:com.liferay.portal.util.HttpImpl.java
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain);/*from w w w . j av a 2s . co m*/ } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }
From source file:com.twelve.capital.external.feed.util.HttpImpl.java
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); if (!PropsValues.SESSION_COOKIE_USE_FULL_HOSTNAME) { String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain);//w w w .j av a 2s. com } } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }
From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java
private void serializeCookies() throws Exception { Cookie[] cookies = req.getCookies(); if (cookies != null && cookies.length > 0) { xsw.writeStartElement(URI, "cookies"); for (Cookie cookie : cookies) { xsw.writeStartElement(URI, "cookie"); dataElement(xsw, URI, "comment", cookie.getComment()); dataElement(xsw, URI, "domain", cookie.getDomain()); dataElement(xsw, URI, "max-age", Integer.toString(cookie.getMaxAge())); dataElement(xsw, URI, "name", cookie.getName()); dataElement(xsw, URI, "path", cookie.getPath()); dataElement(xsw, URI, "is-secure", Boolean.toString(cookie.getSecure())); dataElement(xsw, URI, "value", cookie.getValue()); dataElement(xsw, URI, "version", Integer.toString(cookie.getVersion())); xsw.writeEndElement();/* w ww . jav a 2 s . c o m*/ } xsw.writeEndElement(); } }
From source file:org.apache.hive.service.cli.thrift.ThriftHttpServlet.java
/** * Generate httponly cookie from HS2 cookie * @param cookie HS2 generated cookie/*w w w . j a v a 2 s . c o m*/ * @return The httponly cookie */ private static String getHttpOnlyCookieHeader(Cookie cookie) { NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getVersion(), cookie.getComment(), cookie.getMaxAge(), cookie.getSecure()); return newCookie + "; HttpOnly"; }
From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {/* ww w . j a v a 2s .com*/ if (!initialized.get()) { initializeServer(context); } } catch (Exception e) { context.yield(); throw new ProcessException("Failed to initialize the server", e); } final HttpRequestContainer container = containerQueue.poll(); if (container == null) { return; } final long start = System.nanoTime(); final HttpServletRequest request = container.getRequest(); FlowFile flowFile = session.create(); try { flowFile = session.importFrom(request.getInputStream(), flowFile); } catch (final IOException e) { getLogger().error("Failed to receive content from HTTP Request from {} due to {}", new Object[] { request.getRemoteAddr(), e }); session.remove(flowFile); return; } final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding(); final String contextIdentifier = UUID.randomUUID().toString(); final Map<String, String> attributes = new HashMap<>(); try { putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier); putAttribute(attributes, "mime.type", request.getContentType()); putAttribute(attributes, "http.servlet.path", request.getServletPath()); putAttribute(attributes, "http.context.path", request.getContextPath()); putAttribute(attributes, "http.method", request.getMethod()); putAttribute(attributes, "http.local.addr", request.getLocalAddr()); putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName()); final String queryString = request.getQueryString(); if (queryString != null) { putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset)); } putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost()); putAttribute(attributes, "http.remote.addr", request.getRemoteAddr()); putAttribute(attributes, "http.remote.user", request.getRemoteUser()); putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI()); putAttribute(attributes, "http.request.url", request.getRequestURL().toString()); putAttribute(attributes, "http.auth.type", request.getAuthType()); putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId()); final DispatcherType dispatcherType = request.getDispatcherType(); if (dispatcherType != null) { putAttribute(attributes, "http.dispatcher.type", dispatcherType.name()); } putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding()); putAttribute(attributes, "http.locale", request.getLocale()); putAttribute(attributes, "http.server.name", request.getServerName()); putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort()); final Enumeration<String> paramEnumeration = request.getParameterNames(); while (paramEnumeration.hasMoreElements()) { final String paramName = paramEnumeration.nextElement(); final String value = request.getParameter(paramName); attributes.put("http.param." + paramName, value); } final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String cookiePrefix = "http.cookie." + name + "."; attributes.put(cookiePrefix + "value", cookie.getValue()); attributes.put(cookiePrefix + "domain", cookie.getDomain()); attributes.put(cookiePrefix + "path", cookie.getPath()); attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge())); attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion())); attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure())); } } if (queryString != null) { final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString); for (final String keyValueString : params) { final int indexOf = keyValueString.indexOf("="); if (indexOf < 0) { // no =, then it's just a key with no value attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), ""); } else { final String key = keyValueString.substring(0, indexOf); final String value; if (indexOf == keyValueString.length() - 1) { value = ""; } else { value = keyValueString.substring(indexOf + 1); } attributes.put("http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset)); } } } } catch (final UnsupportedEncodingException uee) { throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated } final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final String headerValue = request.getHeader(headerName); putAttribute(attributes, "http.headers." + headerName, headerValue); } final Principal principal = request.getUserPrincipal(); if (principal != null) { putAttribute(attributes, "http.principal.name", principal.getName()); } final X509Certificate certs[] = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); final String subjectDn; if (certs != null && certs.length > 0) { final X509Certificate cert = certs[0]; subjectDn = cert.getSubjectDN().getName(); final String issuerDn = cert.getIssuerDN().getName(); putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn); putAttribute(attributes, "http.issuer.dn", issuerDn); } else { subjectDn = null; } flowFile = session.putAllAttributes(flowFile, attributes); final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP) .asControllerService(HttpContextMap.class); final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(), container.getContext()); if (!registered) { getLogger().warn( "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] { request.getRemoteAddr() }); try { container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); container.getResponse().flushBuffer(); container.getContext().complete(); } catch (final Exception e) { getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] { request.getRemoteAddr(), e }); } session.remove(flowFile); return; } final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis); session.transfer(flowFile, REL_SUCCESS); getLogger().info("Transferring {} to 'success'; received from {}", new Object[] { flowFile, request.getRemoteAddr() }); }
From source file:org.ireland.jnetty.http.HttpServletRequestImpl.java
/** * Extracte cookies.//from w ww .j a v a2s . c om */ protected void extracteCookie() { _cookiesExtracted = true; // Decode the cookie. String cookieString = headers.get(HttpHeaders.Names.COOKIE); if (cookieString != null) { Set<io.netty.handler.codec.http.Cookie> _cookies = CookieDecoder.decode(cookieString); this.cookies = new Cookie[_cookies.size()]; int i = 0; // Convent netty's Cookie to Servlet's Cookie 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.setHttpOnly(c.isHttpOnly()); cookie.setMaxAge((int) c.getMaxAge()); cookie.setPath(c.getPath()); cookie.setSecure(c.isSecure()); cookie.setVersion(c.getVersion()); this.cookies[i] = cookie; i++; } } }