org.apache.commons.httpclient.Cookie Java Examples

The following examples show how to use org.apache.commons.httpclient.Cookie. 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: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return an array of {@link Cookie}s that should be submitted with a
 * request with given attributes, <tt>false</tt> otherwise.
 * @param host the host to which the request is being submitted
 * @param port the port to which the request is being submitted (currently
 * ignored)
 * @param path the path to which the request is being submitted
 * @param secure <tt>true</tt> if the request is using a secure protocol
 * @param cookies an array of <tt>Cookie</tt>s to be matched
 * @return an array of <tt>Cookie</tt>s matching the criterium
 */

public Cookie[] match(String host, int port, String path, 
    boolean secure, final Cookie cookies[]) {
        
    LOG.trace("enter CookieSpecBase.match("
        + "String, int, String, boolean, Cookie[])");

    if (cookies == null) {
        return null;
    }
    List matching = new LinkedList();
    for (int i = 0; i < cookies.length; i++) {
        if (match(host, port, path, secure, cookies[i])) {
            addInPathOrder(matching, cookies[i]);
        }
    }
    return (Cookie[]) matching.toArray(new Cookie[matching.size()]);
}
 
Example #2
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a RFC 2109 compliant <tt>"Cookie"</tt> header value containing all
 * {@link Cookie}s in <i>cookies</i> suitable for sending in a <tt>"Cookie"
 * </tt> header
 * @param cookies an array of {@link Cookie}s to be formatted
 * @return a string suitable for sending in a Cookie header.
 */
public String formatCookies(Cookie[] cookies) {
    LOG.trace("enter RFC2109Spec.formatCookieHeader(Cookie[])");
    int version = Integer.MAX_VALUE;
    // Pick the lowerest common denominator
    for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        if (cookie.getVersion() < version) {
            version = cookie.getVersion();
        }
    }
    final StringBuffer buffer = new StringBuffer();
    formatParam(buffer, 
            new NameValuePair("$Version", Integer.toString(version)), 
            version);
    for (int i = 0; i < cookies.length; i++) {
        buffer.append("; ");
        formatCookieAsVer(buffer, cookies[i], version);
    }
    return buffer.toString();
}
 
Example #3
Source File: ExchangeFormAuthenticator.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Look for session cookies.
 *
 * @return true if session cookies are available
 */
protected boolean isAuthenticated(HttpMethod method) {
    boolean authenticated = false;
    if (method.getStatusCode() == HttpStatus.SC_OK
            && "/ews/services.wsdl".equalsIgnoreCase(method.getPath())) {
        // direct EWS access returned wsdl
        authenticated = true;
    } else {
        // check cookies
        for (Cookie cookie : httpClient.getState().getCookies()) {
            // Exchange 2003 cookies
            if (cookie.getName().startsWith("cadata") || "sessionid".equals(cookie.getName())
                    // Exchange 2007 cookie
                    || "UserContext".equals(cookie.getName())
            ) {
                authenticated = true;
                break;
            }
        }
    }
    return authenticated;
}
 
Example #4
Source File: CookiePathComparator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public int compare(final Object o1, final Object o2) {
    Cookie c1 = (Cookie) o1;
    Cookie c2 = (Cookie) o2;
    String path1 = normalizePath(c1);
    String path2 = normalizePath(c2);
    if (path1.equals(path2)) {
        return 0;
    } else if (path1.startsWith(path2)) {
        return -1;
    } else if (path2.startsWith(path1)) {
        return 1;
    } else {
        // Does not really matter
        return 0;
    }
}
 
Example #5
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in
 * <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header
 * @param cookies an array of {@link Cookie}s to be formatted
 * @return a string suitable for sending in a Cookie header.
 * @throws IllegalArgumentException if an input parameter is illegal
 */

public String formatCookies(Cookie[] cookies)
  throws IllegalArgumentException {
    LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])");
    if (cookies == null) {
        throw new IllegalArgumentException("Cookie array may not be null");
    }
    if (cookies.length == 0) {
        throw new IllegalArgumentException("Cookie array may not be empty");
    }

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < cookies.length; i++) {
        if (i > 0) {
            buffer.append("; ");
        }
        buffer.append(formatCookie(cookies[i]));
    }
    return buffer.toString();
}
 
Example #6
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse cookie version attribute.
 */
public void parse(final Cookie cookie, final String value)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
        Cookie2 cookie2 = (Cookie2) cookie;
        if (value == null) {
            throw new MalformedCookieException(
                    "Missing value for version attribute");
        }
        int version = -1;
        try {
            version = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            version = -1;
        }
        if (version < 0) {
            throw new MalformedCookieException("Invalid cookie version.");
        }
        cookie2.setVersion(version);
        cookie2.setVersionAttributeSpecified(true);
    }
}
 
Example #7
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a string suitable for sending in a <tt>"Cookie"</tt> header 
 * as defined in RFC 2109 for backward compatibility with cookie version 0
 * @param buffer The string buffer to use for output
 * @param cookie The {@link Cookie} to be formatted as string
 * @param version The version to use.
 */
private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
    String value = cookie.getValue();
    if (value == null) {
        value = "";
    }
    formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
    if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
      buffer.append("; ");
      formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
    }
    if ((cookie.getDomain() != null) 
        && cookie.isDomainAttributeSpecified()) {
        buffer.append("; ");
        formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
    }
}
 
Example #8
Source File: CrawlerPack.java    From CrawlerPack with Apache License 2.0 6 votes vote down vote up
/**
 * Return a Cookie array
 * and auto importing domain and path when domain was empty.
 *
 * @param uri required Apache Common VFS supported file systems and response JSON format content.
 * @return Cookie[]
 */
Cookie[] getCookies(String uri){
    if( null == cookies || 0 == cookies.size()) return null;

    for(Cookie cookie: cookies){

        if("".equals(cookie.getDomain())){
            String domain = uri.replaceAll("^.*:\\/\\/([^\\/]+)[\\/]?.*$", "$1");
            cookie.setDomain(domain);
            cookie.setPath("/");
            cookie.setExpiryDate(null);
            cookie.setSecure(false);
        }
    }

    return cookies.toArray(new Cookie[cookies.size()]);
}
 
Example #9
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse RFC 2965 specific cookie attribute and update the corresponsing
 * {@link org.apache.commons.httpclient.Cookie} properties.
 *
 * @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the
 * <tt>Set-Cookie2</tt> header.
 * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated
 * @throws MalformedCookieException if an exception occurs during parsing
 */
public void parseAttribute(
        final NameValuePair attribute, final Cookie cookie)
        throws MalformedCookieException {
    if (attribute == null) {
        throw new IllegalArgumentException("Attribute may not be null.");
    }
    if (attribute.getName() == null) {
        throw new IllegalArgumentException("Attribute Name may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null.");
    }
    final String paramName = attribute.getName().toLowerCase();
    final String paramValue = attribute.getValue();

    CookieAttributeHandler handler = findAttribHandler(paramName);
    if (handler == null) {
        // ignore unknown attribute-value pairs
        if (LOG.isDebugEnabled())
            LOG.debug("Unrecognized cookie attribute: " +
                      attribute.toString());
    } else {
        handler.parse(cookie, paramValue);
    }
}
 
Example #10
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Performs RFC 2965 compliant {@link org.apache.commons.httpclient.Cookie} validation
 *
 * @param host the host from which the {@link org.apache.commons.httpclient.Cookie} was received
 * @param port the port from which the {@link org.apache.commons.httpclient.Cookie} was received
 * @param path the path from which the {@link org.apache.commons.httpclient.Cookie} was received
 * @param secure <tt>true</tt> when the {@link org.apache.commons.httpclient.Cookie} was received using a
 * secure connection
 * @param cookie The cookie to validate
 * @throws MalformedCookieException if an exception occurs during
 * validation
 */
public void validate(final String host, int port, final String path,
                     boolean secure, final Cookie cookie)
        throws MalformedCookieException {

    LOG.trace("enter RFC2965Spec.validate(String, int, String, "
              + "boolean, Cookie)");

    if (cookie instanceof Cookie2) {
        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 $");
        }
        CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); 
        for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
          CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
          handler.validate(cookie, origin);
        }
    } else {
        // old-style cookies are validated according to the old rules
        this.rfc2109.validate(host, port, path, secure, cookie);
    }
}
 
Example #11
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a string suitable for sending in a <tt>"Cookie"</tt> header as
 * defined in RFC 2965
 * @param cookie a {@link org.apache.commons.httpclient.Cookie} to be formatted as string
 * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
 */
public String formatCookie(final Cookie cookie) {
    LOG.trace("enter RFC2965Spec.formatCookie(Cookie)");

    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
        Cookie2 cookie2 = (Cookie2) cookie;
        int version = cookie2.getVersion();
        final StringBuffer buffer = new StringBuffer();
        this.formatter.format(buffer, new NameValuePair("$Version", Integer.toString(version)));
        buffer.append("; ");
        doFormatCookie2(cookie2, buffer);
        return buffer.toString();
    } else {
        // old-style cookies are formatted according to the old rules
        return this.rfc2109.formatCookie(cookie);
    }
}
 
Example #12
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse cookie path attribute.
 */
public void parse(final Cookie cookie, final String path)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (path == null) {
        throw new MalformedCookieException(
                "Missing value for path attribute");
    }
    if (path.trim().equals("")) {
        throw new MalformedCookieException(
                "Blank value for path attribute");
    }
    cookie.setPath(path);
    cookie.setPathAttributeSpecified(true);
}
 
Example #13
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse cookie max-age attribute.
 */
public void parse(final Cookie cookie, final String value)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (value == null) {
        throw new MalformedCookieException(
                "Missing value for max-age attribute");
    }
    int age = -1;
    try {
        age = Integer.parseInt(value);
    } catch (NumberFormatException e) {
        age = -1;
    }
    if (age < 0) {
        throw new MalformedCookieException ("Invalid max-age attribute.");
    }
    cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
}
 
Example #14
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Parse cookie port attribute.
 */
public void parse(final Cookie cookie, final String portValue)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
        Cookie2 cookie2 = (Cookie2) cookie;
        if ((portValue == null) || (portValue.trim().equals(""))) {
            // If the Port attribute is present but has no value, the
            // cookie can only be sent to the request-port.
            // Since the default port list contains only request-port, we don't
            // need to do anything here.
            cookie2.setPortAttributeBlank(true);
        } else {
            int[] ports = parsePortAttribute(portValue);
            cookie2.setPorts(ports);
        }
        cookie2.setPortAttributeSpecified(true);
    }
}
 
Example #15
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Validate cookie port attribute. If the Port attribute was specified
 * in header, the request port must be in cookie's port list.
 */
public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
    }
    if (cookie instanceof Cookie2) {
        Cookie2 cookie2 = (Cookie2) cookie;
        int port = origin.getPort();
        if (cookie2.isPortAttributeSpecified()) {
            if (!portMatch(port, cookie2.getPorts())) {
                throw new MalformedCookieException(
                        "Port attribute violates RFC 2965: "
                        + "Request port not found in cookie's port list.");
            }
        }
    }
}
 
Example #16
Source File: HttpClientUtil.java    From Gather-Platform with GNU General Public License v3.0 5 votes vote down vote up
public void addCookie(String cookie, String domain) {
    String[] data = cookie.split(";");
    for (String s : data) {
        String[] kvPair = s.split("=");
        if (kvPair.length == 2) {
            String name = kvPair[0];
            String value = kvPair[1];
            if (!name.equals("path") && !name.equals("domain")) {
                hc.getState().addCookie(new Cookie(domain, name, value));
            }
        }
    }

}
 
Example #17
Source File: CookiePathComparator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String normalizePath(final Cookie cookie) {
    String path = cookie.getPath();
    if (path == null) {
        path = "/";
    }
    if (!path.endsWith("/")) {
        path = path + "/";
    }
    return path;
}
 
Example #18
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * validate cookie version attribute. Version attribute is REQUIRED.
 */
public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
        Cookie2 cookie2 = (Cookie2) cookie;
        if (!cookie2.isVersionAttributeSpecified()) {
            throw new MalformedCookieException(
                    "Violates RFC 2965. Version attribute is required.");
        }
    }
}
 
Example #19
Source File: Filter5HttpProxy.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 请求转向不同同服务器的其他应用
 * </p>
 * @param appServer
 * @param req
 * @param response
 * @throws IOException
 * @throws BusinessServletException
 */
private void proxy4ForeignApplication(AppServer appServer, HttpServletResponse response) throws IOException, BusinessServletException {
       HttpClient client = HttpClientUtil.getHttpClient(appServer); // 创建HttpClient对象
	HttpState httpState = client.getState();
	
	/* 设置用户令牌相关Cookie,包括一个token Cookie和一个 sessionId Cookie */
       boolean isSecure = Context.getRequestContext().isSecure(); //是否https请求
       String currentAppCode = Context.getApplicationContext().getCurrentAppCode(); //当前应用code
       String domain = appServer.getDomain();
       String path   = appServer.getPath(); 
       if (Context.isOnline()) {
           httpState.addCookie(new Cookie(domain, RequestContext.USER_TOKEN, Context.getToken(), path, null, isSecure)); //token = ****************
       }
       if (Environment.getSessionId() != null) {
           httpState.addCookie(new Cookie(domain, currentAppCode, Environment.getSessionId(), path, null, isSecure)); // TSS = JSessionId
       }
	
	HttpMethod httpMethod = HttpClientUtil.getHttpMethod(appServer); // 创建HttpPost对象(等价于一个Post Http Request)
	try {
		// 请求
           int statusCode = client.executeMethod(httpMethod);
		if (statusCode == HttpStatus.SC_OK) {
			// 转发返回信息
			transmitResponse(appServer, response, client, httpMethod);
		} 
		else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
				|| (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statusCode == HttpStatus.SC_SEE_OTHER)
				|| (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
		    
			dealWithRedirect(appServer, response, client, httpMethod);
		} 
		
	} finally {
		httpMethod.releaseConnection();
	}
}
 
Example #20
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param host the host to which the request is being submitted
 * @param port the port to which the request is being submitted (ignored)
 * @param path the path to which the request is being submitted
 * @param secure <tt>true</tt> if the request is using a secure connection
 * @return true if the cookie matches the criterium
 */
public boolean match(String host, int port, String path,
                     boolean secure, final Cookie cookie) {

    LOG.trace("enter RFC2965.match("
              + "String, int, String, boolean, Cookie");
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (cookie instanceof Cookie2) {
        // check if cookie has expired
        if (cookie.isPersistent() && cookie.isExpired()) {
            return false;
        }
        CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); 
        for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) {
            CookieAttributeHandler handler = (CookieAttributeHandler) i.next();
            if (!handler.match(cookie, origin)) {
                return false;
            }
        }
        return true;
    } else {
        // old-style cookies are matched according to the old rules
        return this.rfc2109.match(host, port, path, secure, cookie);
    }
}
 
Example #21
Source File: RestApiLoginFilterITCase.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Test if a session cookie is created
 * 
 * @throws HttpException
 * @throws IOException
 */
@Test
public void testCookieAuthentication() throws HttpException, IOException {
    final HttpClient c = getAuthenticatedCookieBasedClient("administrator", "olat");
    final Cookie[] cookies = c.getState().getCookies();
    assertNotNull(cookies);
    assertTrue(cookies.length > 0);
}
 
Example #22
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Return a string suitable for sending in a <tt>"Cookie"</tt> header
 * @param cookie a {@link Cookie} to be formatted as string
 * @return a string suitable for sending in a <tt>"Cookie"</tt> header.
 */
public String formatCookie(Cookie cookie) {
    LOG.trace("enter CookieSpecBase.formatCookie(Cookie)");
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    StringBuffer buf = new StringBuffer();
    buf.append(cookie.getName());
    buf.append("=");
    String s = cookie.getValue();
    if (s != null) {
        buf.append(s);
    }
    return buf.toString();
}
 
Example #23
Source File: CrawlerPack.java    From CrawlerPack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a cookie with the given name and value.
 *
 * @param name    the cookie name
 * @param value   the cookie value
 * @return CrawlerPack
 */
public CrawlerPack addCookie(String name, String value){
    if( null == name ) {
        log.warn("addCookie: Cookie name null.");
        return this;
    }

    cookies.add( new Cookie("", name, value) );

    return this;
}
 
Example #24
Source File: SsoUtil.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static void addSsoCredential(HttpMethod method, HttpState state, String defaultForwardHost) {
	try {
		String name=SsoUtil.getSsoTokenName();
		String value=SsoUtil.getSsoToken();
		if (StringUtils.isEmpty(value)) {
			if (log.isDebugEnabled()) log.debug("no value for SsoCredential ["+name+"]");
		} else {
			if (log.isDebugEnabled()) log.debug("constructing SsoCredentialCookie ["+name+"]");
			Cookie ssoCookie = new Cookie();
			ssoCookie.setName(name);
		
			ssoCookie.setValue(value);
			String forwardHost;
			try {
				URI uri = method.getURI();
				forwardHost = uri.getHost();
				if (StringUtils.isEmpty(forwardHost)) {
					if (log.isDebugEnabled()) log.debug("did not find host from URI ["+uri.getURI()+"], will use default ["+defaultForwardHost+"] for SSO credential cookie");
					forwardHost=defaultForwardHost;
				}
			} catch (Throwable t) {
				log.warn("could not extract host from URI", t);
				forwardHost = defaultForwardHost;					
			}
			ssoCookie.setDomain(forwardHost);
			// path must have a value, otherwise cookie is not appended to request
			ssoCookie.setPath("/");
			if (log.isDebugEnabled()) log.debug("set SSOcookie attributes: domain ["+ssoCookie.getDomain()+"] path ["+ssoCookie.getPath()+"]");
			state.addCookie(ssoCookie);
		}
		
	} catch (Exception e) {
		log.warn("could not obtain SsoToken: "+e.getMessage());
	}
}
 
Example #25
Source File: HttpClientUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * 处理二次转发请求(request2)转发成功后 返回的Cookie信息,将这些cookie设置到初始的请求和响应里
 * @param cookies 
 *            注:是org.apache.commons.httpclient.Cookie
 * @param targetAppServer
 */
public static void transmitReturnCookies(org.apache.commons.httpclient.Cookie[] cookies, AppServer targetAppServer) {
    RequestContext requestContext = Context.getRequestContext();
    if (requestContext == null) return;
    
    XHttpServletRequest request = requestContext.getRequest();
    HttpServletResponse response = Context.getResponse();
    if (response == null || request == null) return;
    
    // 转发返回Cookies
    for (int i = 0; i < cookies.length; i++) {
        String cookieName = cookies[i].getName();
        
        //如果当前应用本身的cookie,则无需转发
        if (cookieName.equals(Context.getApplicationContext().getCurrentAppCode())) continue; 
        
        if (cookieName.equals(targetAppServer.getSessionIdName())) {
            cookieName = targetAppServer.getCode();
        }
        
        String cpath = request.getContextPath();
        javax.servlet.http.Cookie cookie = createCookie(cookieName, cookies[i].getValue(), cpath);
        cookie.setMaxAge(-1);
        cookie.setSecure(request.isSecure());
        
        if (response.isCommitted()) {
            response.addCookie(cookie);
        }
        
        // 同时也添加到request中,以用于二次、三次的远程接口调用
        request.addCookie(cookie); 
    }
}
 
Example #26
Source File: NetscapeDraftSpec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
  * Parse the cookie attribute and update the corresponsing {@link Cookie}
  * properties as defined by the Netscape draft specification
  *
  * @param attribute {@link NameValuePair} cookie attribute from the
  * <tt>Set- Cookie</tt>
  * @param cookie {@link Cookie} to be updated
  * @throws MalformedCookieException if an exception occurs during parsing
  */
public void parseAttribute(
    final NameValuePair attribute, final Cookie cookie)
    throws MalformedCookieException {
        
    if (attribute == null) {
        throw new IllegalArgumentException("Attribute may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null.");
    }
    final String paramName = attribute.getName().toLowerCase();
    final String paramValue = attribute.getValue();

    if (paramName.equals("expires")) {

        if (paramValue == null) {
            throw new MalformedCookieException(
                "Missing value for expires attribute");
        }
        try {
            DateFormat expiryFormat = new SimpleDateFormat(
                "EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US);
            Date date = expiryFormat.parse(paramValue);
            cookie.setExpiryDate(date);
        } catch (ParseException e) {
            throw new MalformedCookieException("Invalid expires "
                + "attribute: " + e.getMessage());
        }
    } else {
        super.parseAttribute(attribute, cookie);
    }
}
 
Example #27
Source File: HttpClientUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
  * <p>
  * 初始化HttpClient对象,同时设置转发应用的Cookie信息。
  * 将当前请求中的cookie信息(除去sessionId cookie 和 token cookie)设置到新的请求中来
  * </p>
  * @param targetAS 转发的目标应用
  * @return
  */
 public static HttpClient getHttpClient(AppServer targetAS) {
 	HttpState initialState = new HttpState();
     HttpServletRequest request = Context.getRequestContext().getRequest();
     javax.servlet.http.Cookie[] cookies = request.getCookies();
     cookies = (javax.servlet.http.Cookie[]) EasyUtils.checkNull(cookies, new javax.servlet.http.Cookie[] {});
     
     // 设置转发Cookies信息
     AppServer currentAS = Context.getApplicationContext().getCurrentAppServer();
     for (javax.servlet.http.Cookie cookie : request.getCookies()) {
         String cookieName = cookie.getName();
         if (cookieName.equals(currentAS.getSessionIdName()) 
         		|| cookieName.equals(RequestContext.USER_TOKEN)) {
             continue;
         }
         
         // 保存当前应用以外的sessionId信息的cookie一般是以其应用Code命名的,当前应用的则以JSESSIONID命名
         if (cookieName.equals(targetAS.getCode())) { 
             cookieName = targetAS.getSessionIdName();
         }
         String domain = targetAS.getDomain();
String path   = targetAS.getPath();
Cookie apacheCookie = new Cookie(domain, cookieName, cookie.getValue(), path, null, request.isSecure());
         initialState.addCookie(apacheCookie);
     }
     
     HttpClient client = getHttpClient();
     client.setState(initialState);
     
     return client;
 }
 
Example #28
Source File: DavMailCookieSpec.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void validate(String host, int port, String path,
                     boolean secure, final Cookie cookie) throws MalformedCookieException {
    // workaround for space in cookie name
    String cookieName = cookie.getName();
    if (cookieName != null && cookieName.indexOf(' ') >= 0) {
        cookie.setName(cookieName.replaceAll(" ", ""));
    } else {
        cookieName = null;
    }
    // workaround for invalid cookie path
    String cookiePath = cookie.getPath();
    if (cookiePath != null && !path.startsWith(cookiePath)) {
        cookie.setPath(path);
    } else {
        cookiePath = null;
    }
    // workaround for invalid cookie domain
    int dotIndex = -1;
    if (host.endsWith(cookie.getDomain())) {
        String hostWithoutDomain = host.substring(0, host.length()
                - cookie.getDomain().length());
        dotIndex = hostWithoutDomain.indexOf('.');
    }
    if (".login.microsoftonline.com".equals(cookie.getDomain())) {
        cookie.setDomain(host);
    }
    if (dotIndex != -1) {
        // discard additional host name part
        super.validate(host.substring(dotIndex + 1), port, path, secure, cookie);
    } else {
        super.validate(host, port, path, secure, cookie);
    }
    if (cookieName != null) {
        cookie.setName(cookieName);
    }
    if (cookiePath != null) {
        cookie.setPath(cookiePath);
    }
}
 
Example #29
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Adds the given cookie into the given list in descending path order. That
 * is, more specific path to least specific paths.  This may not be the
 * fastest algorythm, but it'll work OK for the small number of cookies
 * we're generally dealing with.
 *
 * @param list - the list to add the cookie to
 * @param addCookie - the Cookie to add to list
 */
private static void addInPathOrder(List list, Cookie addCookie) {
    int i = 0;

    for (i = 0; i < list.size(); i++) {
        Cookie c = (Cookie) list.get(i);
        if (addCookie.compare(addCookie, c) > 0) {
            break;
        }
    }
    list.add(i, addCookie);
}
 
Example #30
Source File: HttpMessageTransportData.java    From jrpip with Apache License 2.0 5 votes vote down vote up
@Override
public int hashCode()
{
    int result = this.authenticatedUrl.hashCode();
    for(Cookie c: cookies)
    {
        result = 31 * result + c.hashCode();
    }
    return result;
}