Java Code Examples for javax.servlet.http.Cookie#getDomain()

The following examples show how to use javax.servlet.http.Cookie#getDomain() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CookieUtil.java    From khan-session with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Create Cookie header
 *
 * @param cookie
 * @param isHttpOnly
 * @return
 */
public static String createCookieHeader(Cookie cookie, boolean isHttpOnly) {
    StringBuilder sb = new StringBuilder();
    sb = sb.append(cookie.getName()).append("=").append(cookie.getValue());

    if (cookie.getDomain() != null && !cookie.getDomain().equals("") ) {
        sb.append(";Domain=").append(cookie.getDomain());
    }
    if (cookie.getPath() != null && !cookie.getPath().equals("")) {
        sb.append(";Path=").append(cookie.getPath());
    }
    if (cookie.getComment() != null && !cookie.getComment().equals("")) {
        sb.append(";Comment=").append(cookie.getComment());
    }
    if (cookie.getMaxAge() > -1) {
        sb.append(";Max-Age=").append(cookie.getMaxAge());
    }
    if (cookie.getSecure()) {
        sb.append(";Secure");
    }
    if (isHttpOnly) {
        sb.append(";HttpOnly");
    }

    return sb.toString();
}
 
Example 2
Source File: SimpleCookieManager.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected Cookie createSnapshotCookie(Cookie src) {
    // not use close() to avoid dependency to ServletContainer
    final Cookie snapshot = new Cookie(src.getName(), src.getValue());
    snapshot.setPath(src.getPath());
    snapshot.setMaxAge(src.getMaxAge());
    final String domain = src.getDomain();
    if (domain != null) { // the setter has filter process
        snapshot.setDomain(domain);
    }
    snapshot.setSecure(src.getSecure());
    final String comment = src.getComment();
    if (comment != null) { // just in case
        snapshot.setComment(comment);
    }
    snapshot.setVersion(src.getVersion());
    snapshot.setHttpOnly(src.isHttpOnly());
    return snapshot;
}
 
Example 3
Source File: MockHttpClient.java    From karate with MIT License 6 votes vote down vote up
@Override
protected void buildCookie(com.intuit.karate.http.Cookie c) {
    Cookie cookie = new Cookie(c.getName(), c.getValue());
    requestBuilder.cookie(cookie);
    for (Map.Entry<String, String> entry : c.entrySet()) {
        if (entry.getValue() != null) {
            switch (entry.getKey()) {
                case DOMAIN:
                    cookie.setDomain(entry.getValue());
                    break;
                case PATH:
                    cookie.setPath(entry.getValue());
                    break;
            }
        }
    }
    if (cookie.getDomain() == null) {
        cookie.setDomain(uri.getHost());
    }
}
 
Example 4
Source File: CookieSerializer.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("RedundantIfStatement")
static boolean equals(final Cookie thisCookie, final Cookie thatCookie) {

   if (thisCookie.getMaxAge() != thatCookie.getMaxAge()) {
      return false;
   }
   if (thisCookie.getSecure() != thatCookie.getSecure()) {
      return false;
   }
   if (thisCookie.getVersion() != thatCookie.getVersion()) {
      return false;
   }
   if (thisCookie.getName() != null ? !thisCookie.getName().equals(
           thatCookie.getName()) : thatCookie.getName() != null) {
      return false;
   }
   if (thisCookie.getValue() != null ? !thisCookie.getValue().equals(
           thatCookie.getValue()) : thatCookie.getValue() != null) {
      return false;
   }
   if (thisCookie.getComment() != null ? !thisCookie.getComment().equals(
           thatCookie.getComment()) : thatCookie.getComment() != null) {
      return false;
   }
   if (thisCookie.getDomain() != null ? !thisCookie.getDomain().equals(
           thatCookie.getDomain()) : thatCookie.getDomain() != null) {
      return false;
   }
   if (thisCookie.getPath() != null ? !thisCookie.getPath().equals(
           thatCookie.getPath()) : thatCookie.getPath() != null) {
      return false;
   }
   return true;
}
 
Example 5
Source File: CookieTool.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
public SugarCookie(Cookie c)
{
    this(c.getName(), c.getValue());
    setMaxAge(c.getMaxAge());
    setComment(c.getComment());
    setPath(c.getPath());
    setVersion(c.getVersion());
    setSecure(c.getSecure());
    // avoid setDomain NPE
    if (c.getDomain() != null)
    {
        setDomain(c.getDomain());
    }
    this.plain = c;
}
 
Example 6
Source File: ResponseImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setCookieHeader(Cookie cookie)
{
  if (cookie == null) {
    return;
  }

  final StringBuffer header = new StringBuffer(32);
  String attrValue;
  int maxAge;
  header.append(cookie.getName() + "=" + cookie.getValue());
  if ((attrValue = cookie.getComment()) != null) {
    header.append(";Comment=" + attrValue);
  }
  if ((attrValue = cookie.getDomain()) != null) {
    header.append(";Domain=" + attrValue);
  }
  if ((maxAge = cookie.getMaxAge()) != -1) {
    if (maxAge > 0) {
      appendCookieExpires(header, maxAge);
    }
    header.append(";Max-Age=" + maxAge);
  }
  if ((attrValue = cookie.getPath()) != null) {
    header.append(";Path=" + attrValue);
  } else {
    header.append(";Path=/");
  }
  if (cookie.getSecure()) {
    header.append(";Secure");
  }
  header.append(";Version=" + cookie.getVersion());

  setHeader("Set-Cookie", header.toString());
}
 
Example 7
Source File: CookieHelper.java    From kisso with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 解决 servlet 3.0 以下版本不支持 HttpOnly
 * </p>
 *
 * @param response HttpServletResponse类型的响应
 * @param cookie   要设置httpOnly的cookie对象
 */
public static void addHttpOnlyCookie(HttpServletResponse response, Cookie cookie) {
    if (cookie == null) {
        return;
    }
    /**
     * 依次取得cookie中的名称、值、 最大生存时间、路径、域和是否为安全协议信息
     */
    String cookieName = cookie.getName();
    String cookieValue = cookie.getValue();
    int maxAge = cookie.getMaxAge();
    String path = cookie.getPath();
    String domain = cookie.getDomain();
    boolean isSecure = cookie.getSecure();
    StringBuffer sf = new StringBuffer();
    sf.append(cookieName + "=" + cookieValue + ";");
    if (maxAge >= 0) {
        sf.append("Max-Age=" + cookie.getMaxAge() + ";");
    }
    if (domain != null) {
        sf.append("domain=" + domain + ";");
    }
    if (path != null) {
        sf.append("path=" + path + ";");
    }
    if (isSecure) {
        sf.append("secure;HTTPOnly;");
    } else {
        sf.append("HTTPOnly;");
    }
    response.addHeader("Set-Cookie", sf.toString());
}
 
Example 8
Source File: AwsHttpServletResponse.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("COOKIE_USAGE")
@Override
public void addCookie(Cookie cookie) {
    if (request != null && request.getDispatcherType() == DispatcherType.INCLUDE && isCommitted()) {
        throw new IllegalStateException("Cannot add Cookies for include request when response is committed");
    }
    String cookieData = cookie.getName() + "=" + cookie.getValue();
    if (cookie.getPath() != null) {
        cookieData += "; Path=" + cookie.getPath();
    }
    if (cookie.getSecure()) {
        cookieData += "; Secure";
    }
    if (cookie.isHttpOnly()) {
        cookieData += "; HttpOnly";
    }
    if (cookie.getDomain() != null && !"".equals(cookie.getDomain().trim())) {
        cookieData += "; Domain=" + cookie.getDomain();
    }

    if (cookie.getMaxAge() > 0) {
        cookieData += "; Max-Age=" + cookie.getMaxAge();

        // we always set the timezone to GMT
        TimeZone gmtTimeZone = TimeZone.getTimeZone(COOKIE_DEFAULT_TIME_ZONE);
        Calendar currentTimestamp = Calendar.getInstance(gmtTimeZone);
        currentTimestamp.add(Calendar.SECOND, cookie.getMaxAge());
        SimpleDateFormat cookieDateFormatter = new SimpleDateFormat(HEADER_DATE_PATTERN);
        cookieDateFormatter.setTimeZone(gmtTimeZone);
        cookieData += "; Expires=" + cookieDateFormatter.format(currentTimestamp.getTime());
    }

    setHeader(HttpHeaders.SET_COOKIE, cookieData, false);
}
 
Example 9
Source File: ServletUnitHttpResponse.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void addCookieHeader() {
    if (_cookies.isEmpty()) return;

    StringBuffer sb = new StringBuffer();
    for (Enumeration e = _cookies.elements(); e.hasMoreElements();) {
        Cookie cookie = (Cookie) e.nextElement();
        sb.append( cookie.getName() ).append( '=' ).append( cookie.getValue() );
        if (cookie.getPath() != null) sb.append( ";path=" ).append( cookie.getPath() );
        if (cookie.getDomain() != null) sb.append( ";domain=" ).append( cookie.getDomain() );
        if (e.hasMoreElements()) sb.append( ',' );
    }
    setHeader( "Set-Cookie", sb.toString() );
}
 
Example 10
Source File: NettyHttpServletResponse.java    From spring-boot-starter-netty with GNU General Public License v3.0 5 votes vote down vote up
/**
     * 设置基本的请求头
     */
    public HttpResponse getNettyResponse() {
        if (committed) {
            return response;
        }
        committed = true;
        HttpHeaders headers = response.headers();
        if (null != contentType) {
            String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding; //Content Type 响应头的内容
            headers.set(HttpHeaderNames.CONTENT_TYPE, value);
        }
        CharSequence date = getFormattedDate();
        headers.set(HttpHeaderNames.DATE, date); // 时间日期响应头
        headers.set(HttpHeaderNames.SERVER, servletContext.getServerInfo()); //服务器信息响应头

        // cookies处理
//        long curTime = System.currentTimeMillis(); //用于根据maxAge计算Cookie的Expires
        //先处理Session ,如果是新Session需要通过Cookie写入
        if (request.getSession().isNew()) {
            String sessionCookieStr = NettyHttpSession.SESSION_COOKIE_NAME + "=" + request.getRequestedSessionId() + "; path=/; domain=" + request.getServerName();
            headers.add(HttpHeaderNames.SET_COOKIE, sessionCookieStr);
        }
        //其他业务或框架设置的cookie,逐条写入到响应头去
        for (Cookie cookie : cookies) {
            StringBuilder sb = new StringBuilder();
            sb.append(cookie.getName()).append("=").append(cookie.getValue())
                    .append("; max-Age=").append(cookie.getMaxAge());
            if (cookie.getPath() != null) sb.append("; path=").append(cookie.getPath());
            if (cookie.getDomain() != null) sb.append("; domain=").append(cookie.getDomain());
            headers.add(HttpHeaderNames.SET_COOKIE, sb.toString());
        }
        return response;
    }
 
Example 11
Source File: LegacyCookieProcessor.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public String generateHeader(Cookie cookie) {
    /*
     * The spec allows some latitude on when to send the version attribute
     * with a Set-Cookie header. To be nice to clients, we'll make sure the
     * version attribute is first. That means checking the various things
     * that can cause us to switch to a v1 cookie first.
     *
     * Note that by checking for tokens we will also throw an exception if a
     * control character is encountered.
     */
    int version = cookie.getVersion();
    String value = cookie.getValue();
    String path = cookie.getPath();
    String domain = cookie.getDomain();
    String comment = cookie.getComment();

    if (version == 0) {
        // Check for the things that require a v1 cookie
        if (needsQuotes(value, 0) || comment != null || needsQuotes(path, 0) || needsQuotes(domain, 0)) {
            version = 1;
        }
    }

    // Now build the cookie header
    StringBuffer buf = new StringBuffer(); // can't use StringBuilder due to DateFormat

    // Just use the name supplied in the Cookie
    buf.append(cookie.getName());
    buf.append("=");

    // Value
    maybeQuote(buf, value, version);

    // Add version 1 specific information
    if (version == 1) {
        // Version=1 ... required
        buf.append ("; Version=1");

        // Comment=comment
        if (comment != null) {
            buf.append ("; Comment=");
            maybeQuote(buf, comment, version);
        }
    }

    // Add domain information, if present
    if (domain != null) {
        buf.append("; Domain=");
        maybeQuote(buf, domain, version);
    }

    // Max-Age=secs ... or use old "Expires" format
    int maxAge = cookie.getMaxAge();
    if (maxAge >= 0) {
        if (version > 0) {
            buf.append ("; Max-Age=");
            buf.append (maxAge);
        }
        // IE6, IE7 and possibly other browsers don't understand Max-Age.
        // They do understand Expires, even with V1 cookies!
        if (version == 0 || getAlwaysAddExpires()) {
            // Wdy, DD-Mon-YY HH:MM:SS GMT ( Expires Netscape format )
            buf.append ("; Expires=");
            // To expire immediately we need to set the time in past
            if (maxAge == 0) {
                buf.append( ANCIENT_DATE );
            } else {
                COOKIE_DATE_FORMAT.get().format(
                        new Date(System.currentTimeMillis() + maxAge * 1000L),
                        buf,
                        new FieldPosition(0));
            }
        }
    }

    // Path=path
    if (path!=null) {
        buf.append ("; Path=");
        maybeQuote(buf, path, version);
    }

    // Secure
    if (cookie.getSecure()) {
      buf.append ("; Secure");
    }

    // HttpOnly
    if (cookie.isHttpOnly()) {
        buf.append("; HttpOnly");
    }

    SameSiteCookies sameSiteCookiesValue = getSameSiteCookies();

    if (!sameSiteCookiesValue.equals(SameSiteCookies.UNSET)) {
        buf.append("; SameSite=");
        buf.append(sameSiteCookiesValue.getValue());
    }

    return buf.toString();
}
 
Example 12
Source File: CredentialFlowStateHelper.java    From syndesis with Apache License 2.0 4 votes vote down vote up
static javax.ws.rs.core.Cookie toJaxRsCookie(final Cookie cookie) {
    return new javax.ws.rs.core.Cookie(cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain());
}
 
Example 13
Source File: RequestUtil.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header.
 * 
 * @param cookie
 *          The cookie to encode.
 * @return A string following RFC 2109.
 */
public static String encodeCookie(Cookie cookie) {

	StringBuilder buf = new StringBuilder(cookie.getName());
	buf.append("=");
	buf.append(cookie.getValue());

	if (cookie.getComment() != null) {
		buf.append("; Comment=\"");
		buf.append(cookie.getComment());
		buf.append("\"");
	}

	if (cookie.getDomain() != null) {
		buf.append("; Domain=\"");
		buf.append(cookie.getDomain());
		buf.append("\"");
	}

	long age = cookie.getMaxAge();
	if (cookie.getMaxAge() >= 0) {
		buf.append("; Max-Age=\"");
		buf.append(age);
		buf.append("\"");
	}

	if (cookie.getPath() != null) {
		buf.append("; Path=\"");
		buf.append(cookie.getPath());
		buf.append("\"");
	}

	if (cookie.getSecure()) {
		buf.append("; Secure");
	}

	if (cookie.getVersion() > 0) {
		buf.append("; Version=\"");
		buf.append(cookie.getVersion());
		buf.append("\"");
	}

	return (buf.toString());
}
 
Example 14
Source File: RequestUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header.
 * 
 * @param cookie
 *            The cookie to encode.
 * @return A string following RFC 2109.
 */
public static String encodeCookie(Cookie cookie) {

    StringBuilder buf = new StringBuilder(cookie.getName());
    buf.append("=");
    buf.append(cookie.getValue());

    if (cookie.getComment() != null) {
        buf.append("; Comment=\"");
        buf.append(cookie.getComment());
        buf.append("\"");
    }

    if (cookie.getDomain() != null) {
        buf.append("; Domain=\"");
        buf.append(cookie.getDomain());
        buf.append("\"");
    }

    if (cookie.getMaxAge() >= 0) {
        buf.append("; Max-Age=\"");
        buf.append(cookie.getMaxAge());
        buf.append("\"");
    }

    if (cookie.getPath() != null) {
        buf.append("; Path=\"");
        buf.append(cookie.getPath());
        buf.append("\"");
    }

    if (cookie.getSecure()) {
        buf.append("; Secure");
    }

    if (cookie.getVersion() > 0) {
        buf.append("; Version=\"");
        buf.append(cookie.getVersion());
        buf.append("\"");
    }

    return (buf.toString());
}
 
Example 15
Source File: RequestUtil.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Encode a cookie as per RFC 2109. The resulting string can be used as the value for a <code>Set-Cookie</code> header.
 * 
 * @param cookie
 *            The cookie to encode.
 * @return A string following RFC 2109.
 */
public static String encodeCookie(Cookie cookie) {

    StringBuilder buf = new StringBuilder(cookie.getName());
    buf.append("=");
    buf.append(cookie.getValue());

    if (cookie.getComment() != null) {
        buf.append("; Comment=\"");
        buf.append(cookie.getComment());
        buf.append("\"");
    }

    if (cookie.getDomain() != null) {
        buf.append("; Domain=\"");
        buf.append(cookie.getDomain());
        buf.append("\"");
    }

    if (cookie.getMaxAge() >= 0) {
        buf.append("; Max-Age=\"");
        buf.append(cookie.getMaxAge());
        buf.append("\"");
    }

    if (cookie.getPath() != null) {
        buf.append("; Path=\"");
        buf.append(cookie.getPath());
        buf.append("\"");
    }

    if (cookie.getSecure()) {
        buf.append("; Secure");
    }

    if (cookie.getVersion() > 0) {
        buf.append("; Version=\"");
        buf.append(cookie.getVersion());
        buf.append("\"");
    }

    return (buf.toString());
}
 
Example 16
Source File: HttpRequestUtils.java    From gitlab4j-api with MIT License 4 votes vote down vote up
/**
 * Build a String containing a multi-line dump of an HTTP request.
 * 
 * @param fromMethod the method that this method was called from
 * @param request the HTTP request build the request dump from
 * @param includePostData if true will include the POST data in the dump
 * @return a String containing a multi-line dump of the HTTP request, If an error occurs,
 * the message from the exception will be returned
 */
public static String getRequestDump(String fromMethod, HttpServletRequest request, boolean includePostData) {

    String shortDump = getShortRequestDump(fromMethod, request);
    StringBuilder buf = new StringBuilder(shortDump);
    try {

        buf.append("\nAttributes:\n");
        Enumeration<String> attrs = request.getAttributeNames();
        while (attrs.hasMoreElements()) {
            String attr = attrs.nextElement();
            buf.append("\t").append(attr).append(": ").append(request.getAttribute(attr)).append('\n');
        }

        buf.append("\nHeaders:\n");
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            buf.append("\t").append(header).append(": ").append(request.getHeader(header)).append('\n');
        }

        buf.append("\nParameters:\n");
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String param = params.nextElement();
            buf.append("\t").append(param).append(": ").append(request.getParameter(param)).append('\n');
        }

        buf.append("\nCookies:\n");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cstr = "\t" + cookie.getDomain() + "." + cookie.getPath() + "." + cookie.getName() + ": " + cookie.getValue() + "\n";
                buf.append(cstr);
            }
        }

        if (includePostData) {
            buf.append(getPostDataAsString(request)).append("\n");
        }

        return (buf.toString());

    } catch (IOException e) {
        return e.getMessage();
    }
}
 
Example 17
Source File: HttpRequestUtils.java    From choerodon-starters with Apache License 2.0 4 votes vote down vote up
/**
 * Build a String containing a multi-line dump of an HTTP request.
 *
 * @param fromMethod      the method that this method was called from
 * @param request         the HTTP request build the request dump from
 * @param includePostData if true will include the POST data in the dump
 * @return a String containing a multi-line dump of the HTTP request, If an error occurs,
 * the message from the exception will be returned
 */
public static String getRequestDump(String fromMethod, HttpServletRequest request, boolean includePostData) {

    String shortDump = getShortRequestDump(fromMethod, request);
    StringBuilder buf = new StringBuilder(shortDump);
    try {

        buf.append("\nAttributes:\n");
        Enumeration<String> attrs = request.getAttributeNames();
        while (attrs.hasMoreElements()) {
            String attr = attrs.nextElement();
            buf.append("\t").append(attr).append(": ").append(request.getAttribute(attr)).append('\n');
        }

        buf.append("\nHeaders:\n");
        Enumeration<String> headers = request.getHeaderNames();
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            buf.append("\t").append(header).append(": ").append(request.getHeader(header)).append('\n');
        }

        buf.append("\nParameters:\n");
        Enumeration<String> params = request.getParameterNames();
        while (params.hasMoreElements()) {
            String param = params.nextElement();
            buf.append("\t").append(param).append(": ").append(request.getParameter(param)).append('\n');
        }

        buf.append("\nCookies:\n");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cstr = "\t" + cookie.getDomain() + "." + cookie.getPath() + "." + cookie.getName() + ": " + cookie.getValue() + "\n";
                buf.append(cstr);
            }
        }

        if (includePostData) {
            buf.append(getPostDataAsString(request)).append("\n");
        }

        return (buf.toString());

    } catch (IOException e) {
        return e.getMessage();
    }
}