List of usage examples for javax.servlet.http Cookie getSecure
public boolean getSecure()
true
if the browser is sending cookies only over a secure protocol, or false
if the browser can send cookies using any protocol. From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {//from w ww. ja v a 2s . co m 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.jasig.portal.portlet.container.services.SessionOnlyPortletCookieImpl.java
SessionOnlyPortletCookieImpl(Cookie cookie) { this.name = cookie.getName(); this.value = cookie.getValue(); this.comment = cookie.getComment(); this.domain = cookie.getDomain(); this.path = cookie.getPath(); this.version = cookie.getVersion(); this.secure = cookie.getSecure(); setMaxAge(cookie.getMaxAge());//www . j a va2 s. c o m }
From source file:org.jasig.portal.portlet.container.services.SessionOnlyPortletCookieImpl.java
@Override public void updateFromCookie(Cookie cookie) { this.setComment(cookie.getComment()); this.setDomain(cookie.getDomain()); this.setExpires(DateUtils.addSeconds(new Date(), cookie.getMaxAge())); this.setPath(cookie.getPath()); this.setSecure(cookie.getSecure()); this.setValue(cookie.getValue()); }
From source file:org.jboss.web.loadbalancer.Loadbalancer.java
protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response, HttpMethod method) {/*from ww w.j a v a 2 s . c o m*/ // clear state HttpClient client = new HttpClient(connectionManager); client.setStrictMode(false); client.setTimeout(connectionTimeout); method.setFollowRedirects(false); method.setDoAuthentication(false); client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY); Enumeration reqHeaders = request.getHeaderNames(); while (reqHeaders.hasMoreElements()) { String headerName = (String) reqHeaders.nextElement(); String headerValue = request.getHeader(headerName); if (!ignorableHeader.contains(headerName.toLowerCase())) { method.setRequestHeader(headerName, headerValue); } } //Cookies Cookie[] cookies = request.getCookies(); HttpState state = client.getState(); for (int i = 0; cookies != null && i < cookies.length; ++i) { Cookie cookie = cookies[i]; org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie(); reqCookie.setName(cookie.getName()); reqCookie.setValue(cookie.getValue()); if (cookie.getPath() != null) { reqCookie.setPath(cookie.getPath()); } else { reqCookie.setPath("/"); } reqCookie.setSecure(cookie.getSecure()); reqCookie.setDomain(method.getHostConfiguration().getHost()); state.addCookie(reqCookie); } return client; }
From source file:org.opencms.flex.CmsFlexResponse.java
/** * Method overloaded from the standard HttpServletRequest API.<p> * * Cookies must be set directly as a header, otherwise they might not be set * in the super class.<p>//from ww w.j a v a 2 s .c o m * * @see javax.servlet.http.HttpServletResponseWrapper#addCookie(javax.servlet.http.Cookie) */ @Override public void addCookie(Cookie cookie) { if (cookie == null) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_ADD_COOKIE_0)); } StringBuffer header = new StringBuffer(128); // name and value header.append(cookie.getName()); header.append('='); header.append(cookie.getValue()); // add version 1 / RFC 2109 specific information if (cookie.getVersion() == 1) { header.append("; Version=1"); // comment if (cookie.getComment() != null) { header.append("; Comment="); header.append(cookie.getComment()); } } // domain if (cookie.getDomain() != null) { header.append("; Domain="); header.append(cookie.getDomain()); } // max-age / expires if (cookie.getMaxAge() >= 0) { if (cookie.getVersion() == 0) { // old Netscape format header.append("; Expires="); long time; if (cookie.getMaxAge() == 0) { time = 10000L; } else { time = System.currentTimeMillis() + (cookie.getMaxAge() * 1000L); } header.append(CmsDateUtil.getOldCookieDate(time)); } else { // new RFC 2109 format header.append("; Max-Age="); header.append(cookie.getMaxAge()); } } // path if (cookie.getPath() != null) { header.append("; Path="); header.append(cookie.getPath()); } // secure if (cookie.getSecure()) { header.append("; Secure"); } addHeader("Set-Cookie", header.toString()); }
From source file:org.opensubsystems.core.util.servlet.WebUtils.java
/** * Create debug string containing all parameter names and their values from * the request, all attributes, all cookies and other data characterizing the * request.//from www .ja v a 2 s .c o m * * @param hsrqRequest - the servlet request. * @return String - debug string containing all parameter names and their * values from the request */ public static String debug(HttpServletRequest hsrqRequest) { Enumeration enumNames; Enumeration enumValues; Iterator iterValues; String strName; String[] arValues; Cookie[] arCookies; int iIndex; Map<String, String[]> mpParamMap; StringBuilder sbfReturn = new StringBuilder(); sbfReturn.append("HttpServletRequest=["); sbfReturn.append("\nRemoteAddress="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr())); sbfReturn.append(";"); sbfReturn.append("\nRemotePort="); sbfReturn.append(hsrqRequest.getRemotePort()); sbfReturn.append(";"); sbfReturn.append("\nRemoteHost="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost())); sbfReturn.append(";"); sbfReturn.append("\nRemoteUser="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser())); sbfReturn.append(";"); sbfReturn.append("\nFullURL="); sbfReturn.append(getFullRequestURL(hsrqRequest)); sbfReturn.append(";"); sbfReturn.append("\nContextPath="); sbfReturn.append(hsrqRequest.getContextPath()); sbfReturn.append(";"); sbfReturn.append("\nServletPath="); sbfReturn.append(hsrqRequest.getServletPath()); sbfReturn.append(";"); sbfReturn.append("\nPathInfo ="); sbfReturn.append(hsrqRequest.getPathInfo()); sbfReturn.append(";"); sbfReturn.append("\nRequestURI="); sbfReturn.append(hsrqRequest.getRequestURI()); sbfReturn.append(";"); sbfReturn.append("\nRequestURL="); sbfReturn.append(hsrqRequest.getRequestURL()); sbfReturn.append(";"); sbfReturn.append("\nMethod="); sbfReturn.append(hsrqRequest.getMethod()); sbfReturn.append(";"); sbfReturn.append("\nAuthenticationType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType())); sbfReturn.append(";"); sbfReturn.append("\nCharacterEncoding="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding())); sbfReturn.append(";"); sbfReturn.append("\nContentType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType())); sbfReturn.append(";"); sbfReturn.append("\nMultiPart="); sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest)); sbfReturn.append(";"); // Parameters //////////////////////////////////////////////////////////// try { Map.Entry<String, String[]> entry; // Use getParameterMap rather than request.getParameterNames since it // correctly handles multipart requests mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest); for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) { entry = (Map.Entry<String, String[]>) iterValues.next(); strName = entry.getKey(); arValues = entry.getValue(); sbfReturn.append("\nParam="); sbfReturn.append(strName); sbfReturn.append(" values="); for (iIndex = 0; iIndex < arValues.length; iIndex++) { sbfReturn.append(arValues[iIndex]); if (iIndex < (arValues.length - 1)) { sbfReturn.append(";"); } } if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access parameter map of the request>"); s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex); } // Uploaded files //////////////////////////////////////////////////////// if (ServletFileUpload.isMultipartContent(hsrqRequest)) { try { FileItem item; Map<String, FileItem> mpFiles; TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params; params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest); mpFiles = params.getSecond(); for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) { item = (FileItem) iterValues.next(); sbfReturn.append("\nUpload="); sbfReturn.append(item.getName()); sbfReturn.append(" field="); sbfReturn.append(item.getFieldName()); sbfReturn.append(" contentType="); sbfReturn.append(item.getContentType()); sbfReturn.append(" isInMemory="); sbfReturn.append(item.isInMemory()); sbfReturn.append(" sizeInBytes="); sbfReturn.append(item.getSize()); if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access list of multipart parameters>"); s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex); } } // Headers /////////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nHeader="); sbfReturn.append(strName); sbfReturn.append(" values="); for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) { sbfReturn.append(enumValues.nextElement()); if (enumValues.hasMoreElements()) { sbfReturn.append(";"); } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Cookies /////////////////////////////////////////////////////////////// arCookies = hsrqRequest.getCookies(); if (arCookies != null) { Cookie cookie; for (iIndex = 0; iIndex < arCookies.length; iIndex++) { cookie = arCookies[iIndex]; sbfReturn.append("\nCookie="); sbfReturn.append(cookie.getName()); sbfReturn.append(" path="); sbfReturn.append(cookie.getPath()); sbfReturn.append(" path="); sbfReturn.append(cookie.getDomain()); sbfReturn.append(" maxage="); sbfReturn.append(cookie.getMaxAge()); sbfReturn.append(" version="); sbfReturn.append(cookie.getVersion()); sbfReturn.append(" secure="); sbfReturn.append(cookie.getSecure()); sbfReturn.append(" value="); sbfReturn.append(cookie.getValue()); sbfReturn.append(" comment="); sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment())); if (iIndex < (arCookies.length - 1)) { sbfReturn.append(";"); } } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } // Attributes //////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nAttribute="); sbfReturn.append(strName); sbfReturn.append(" value="); sbfReturn.append(hsrqRequest.getAttribute(strName)); if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Content /////////////////////////////////////////////////////////////// sbfReturn.append("\nContent="); try { sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true)); } catch (IOException ex) { sbfReturn.append("<Cannot access input stream of the request>"); s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex); } sbfReturn.append(";"); return sbfReturn.toString(); }
From source file:org.owasp.esapi.reference.DefaultHTTPUtilities.java
/** * {@inheritDoc}/*from www . ja v a2 s. co m*/ * This implementation uses a custom "set-cookie" header rather than Java's * cookie interface which doesn't allow the use of HttpOnly. Configure the * HttpOnly and Secure settings in ESAPI.properties. */ public void addCookie(HttpServletResponse response, Cookie cookie) { String name = cookie.getName(); String value = cookie.getValue(); int maxAge = cookie.getMaxAge(); String domain = cookie.getDomain(); String path = cookie.getPath(); boolean secure = cookie.getSecure(); // validate the name and value ValidationErrorList errors = new ValidationErrorList(); String cookieName = ESAPI.validator().getValidInput("cookie name", name, "HTTPCookieName", 50, false, errors); String cookieValue = ESAPI.validator().getValidInput("cookie value", value, "HTTPCookieValue", 5000, false, errors); // if there are no errors, then set the cookie either with a header or normally if (errors.size() == 0) { if (ESAPI.securityConfiguration().getForceHttpOnlyCookies()) { String header = createCookieHeader(cookieName, cookieValue, maxAge, domain, path, secure); addHeader(response, "Set-Cookie", header); } else { // Issue 23 - If the ESAPI Configuration is set to force secure cookies, force the secure flag on the cookie before setting it cookie.setSecure(secure || ESAPI.securityConfiguration().getForceSecureCookies()); response.addCookie(cookie); } return; } logger.warning(Logger.SECURITY_FAILURE, "Attempt to add unsafe data to cookie (skip mode). Skipping cookie and continuing."); }
From source file:org.piraso.web.base.WebEntryUtils.java
public static CookieEntry toEntry(Cookie cookie) { CookieEntry entry = new CookieEntry(); entry.setName(cookie.getName());// w w w.jav a 2 s .c o m entry.setValue(cookie.getValue()); entry.setComment(cookie.getComment()); entry.setDomain(cookie.getDomain()); entry.setMaxAge(cookie.getMaxAge()); entry.setPath(cookie.getPath()); entry.setSecure(cookie.getSecure()); entry.setVersion(cookie.getVersion()); return entry; }
From source file:org.projectforge.web.UserFilter.java
/** * User is not logged. Checks a stay-logged-in-cookie. * @return user if valid cookie found, otherwise null. *///from w w w . j a v a 2s . c om private PFUserDO checkStayLoggedIn(final HttpServletRequest request, final HttpServletResponse response) { final Cookie sessionIdCookie = getCookie(request, "JSESSIONID"); if (sessionIdCookie != null && sessionIdCookie.getSecure() == false && request.isSecure() == true) { // Hack for developers: Safari (may-be also other browsers) don't update unsecure cookies for secure connections. This seems to be // occurring // if you use ProjectForge on localhost with http and https (e. g. for testing). You have to delete this cookie normally in your // browser. final Cookie cookie = new Cookie("JSESSIONID", "to be deleted"); cookie.setMaxAge(0); cookie.setPath(sessionIdCookie.getPath()); // Doesn't work for Safari: getPath() returns always null! response.addCookie(cookie); } final Cookie stayLoggedInCookie = getStayLoggedInCookie(request); if (stayLoggedInCookie != null) { final String value = stayLoggedInCookie.getValue(); if (StringUtils.isBlank(value) == true) { return null; } final String[] values = value.split(":"); if (values == null || values.length != 3) { log.warn("Invalid cookie found: " + value); return null; } final Integer userId = NumberHelper.parseInteger(values[0]); final PFUserDO user = userDao.internalGetById(userId); if (user == null) { log.warn("Invalid cookie found (user not found): " + value); return null; } if (user.getUsername().equals(values[1]) == false) { log.warn("Invalid cookie found (user name wrong, maybe changed): " + value); return null; } if (values[2] == null || values[2].equals(user.getStayLoggedInKey()) == false) { log.warn("Invalid cookie found (stay-logged-in key, maybe renewed and/or user password changed): " + value); return null; } if (Login.getInstance().checkStayLoggedIn(user) == false) { log.warn("Stay-logged-in wasn't accepted by the login handler: " + user.getUserDisplayname()); return null; } addStayLoggedInCookie(request, response, stayLoggedInCookie); log.info("User successfully logged in using stay-logged-in method: " + user.getUserDisplayname()); return user; } return null; }
From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java
/** * Generates a reusable http client wrapper which can be given to {@link #fireRequest(HttpClientWrapper, String, Method, Map, Object, boolean)} * as an efficiency mechanism/*from w ww. j a v a2s .co m*/ * * @param multiThreaded true if you want to allow the client to run in multiple threads * @param idleConnectionTimeout if this is 0 then it will use the defaults, otherwise connections will be timed out after this long (ms) * @param cookies to send along with every request from this client * @return the reusable http client wrapper */ public static HttpClientWrapper makeReusableHttpClient(boolean multiThreaded, int idleConnectionTimeout, Cookie[] cookies) { HttpClientWrapper wrapper; HttpClient client; MultiThreadedHttpConnectionManager connectionManager = null; if (multiThreaded) { connectionManager = new MultiThreadedHttpConnectionManager(); client = new HttpClient(connectionManager); } else { client = new HttpClient(); } if (idleConnectionTimeout <= 0) { idleConnectionTimeout = 5000; } client.getHttpConnectionManager().closeIdleConnections(idleConnectionTimeout); client.getHttpConnectionManager().getParams().setConnectionTimeout(idleConnectionTimeout); // create the initial state HttpState initialState = new HttpState(); if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; org.apache.commons.httpclient.Cookie mycookie = new org.apache.commons.httpclient.Cookie( c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure()); initialState.addCookie(mycookie); } client.setState(initialState); } // set some defaults client.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"); client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true); wrapper = new HttpClientWrapper(client, connectionManager, initialState); return wrapper; }