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

The following examples show how to use javax.servlet.http.Cookie#getName() . 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 codeway_service with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 根据cookie名称读取cookie
 * @param request
 * @param cookieName1,cookieName2
 * @return map<cookieName,cookieValue>
 */

public static Map<String,String> readCookie(HttpServletRequest request, String ... cookieNames) {
    Map<String,String> cookieMap = new HashMap<String,String>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                String cookieValue = cookie.getValue();
                for(int i=0;i<cookieNames.length;i++){
                    if(cookieNames[i].equals(cookieName)){
                        cookieMap.put(cookieName,cookieValue);
                    }
                }
            }
        }
    return cookieMap;

}
 
Example 2
Source File: AuthServiceImpl.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void logout(String token) {

    //记录退出日志
    LogManager.me().executeLog(LogTaskFactory.exitLog(LoginContextHolder.getContext().getUser().getId(), getIp()));

    //删除Auth相关cookies
    Cookie[] cookies = HttpContext.getRequest().getCookies();
    for (Cookie cookie : cookies) {
        String tokenHeader = getTokenHeaderName();
        if (tokenHeader.equalsIgnoreCase(cookie.getName())) {
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            HttpContext.getResponse().addCookie(temp);
        }
    }

    //删除会话
    sessionManager.removeSession(token);
}
 
Example 3
Source File: CustomTokenResolver.java    From oauth2-resource with MIT License 6 votes vote down vote up
protected String resolveFromCookie(HttpServletRequest request) {

        String cookieToken = null;
        //根据请求数据,找到cookie数组
        Cookie[] cookies = request.getCookies();

        if (null != cookies && cookies.length > 0) {
            int foundTimes = 0;
            for (Cookie cookie : cookies) {
                if (null != cookie.getName() && "access_token".equalsIgnoreCase(cookie.getName().trim())) {
                    cookieToken = cookie.getValue().trim();
                    foundTimes++;
                }
            }
            if (foundTimes > 1) {
                BearerTokenError error = new BearerTokenError("invalid_request", HttpStatus.BAD_REQUEST, "Found multiple tokens in the request", "https://tools.ietf.org/html/rfc6750#section-3.1");
                throw new OAuth2AuthenticationException(error);
            }
        }
        return cookieToken;
    }
 
Example 4
Source File: LogsearchKRBAuthenticationFilter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
private String getUsernameFromRequest(HttpServletRequest httpRequest) {
  String userName = null;
  Cookie[] cookie = httpRequest.getCookies();
  if (cookie != null) {
    for (Cookie c : cookie) {
      if (c.getName().equalsIgnoreCase(AUTH_COOKIE_NAME)) {
        String cookieStr = c.getName() + "=" + c.getValue();
        Matcher m = usernamePattern.matcher(cookieStr);
        if (m.find()) {
          userName = m.group(1);
        }
      }
    }
  }
  logger.debug("kerberos username  from  request >>>>>>>>" + userName);
  return userName;
}
 
Example 5
Source File: AuthenticationFilter.java    From oxTrust with MIT License 6 votes vote down vote up
private Cookie getCurrentShibstateCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (ArrayHelper.isEmpty(cookies)) {
        return null;
    }

    Cookie resultCookie = null;
    for (Cookie cookie : cookies) {
        String cookieName = cookie.getName();
        if (cookieName.startsWith("_shibstate_")) {
            if (resultCookie == null) {
                resultCookie = cookie;
            } else {
                if (cookieName.compareTo(resultCookie.getName()) > 0) {
                    resultCookie = cookie;
                }
            }
        }
    }

    if (resultCookie == null) {
        return null;
    }
    return resultCookie;
}
 
Example 6
Source File: ServletServerHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected MultiValueMap<String, HttpCookie> initCookies() {
	MultiValueMap<String, HttpCookie> httpCookies = new LinkedMultiValueMap<>();
	Cookie[] cookies;
	synchronized (this.cookieLock) {
		cookies = this.request.getCookies();
	}
	if (cookies != null) {
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			HttpCookie httpCookie = new HttpCookie(name, cookie.getValue());
			httpCookies.add(name, httpCookie);
		}
	}
	return httpCookies;
}
 
Example 7
Source File: HttpUtil.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public static String getCookie(HttpServletRequest request, String lookup) {
	if ( request == null || lookup == null ) return null;

	// https://stackoverflow.com/questions/11047548/getting-cookie-in-servlet
	Cookie[] cookies = request.getCookies();
	if ( cookies == null ) return null;
	for (int i = 0; i < cookies.length; i++) {
		Cookie cookie=cookies[i];
		String cookieName = cookie.getName();
		String cookieValue = cookie.getValue();
		if ( StringUtils.isEmpty(cookieName) ) continue;
		if ( cookieName.equalsIgnoreCase(lookup) ) {
			return cookieValue;
		}
	}
	return null;
}
 
Example 8
Source File: CookieHelper.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * @return 获取全部Cookie
 */
public Map<String, BlurObject> getCookies() {
    Map<String, BlurObject> _returnValue = new HashMap<String, BlurObject>();
    Cookie[] _cookies = __request.getCookies();
    if (_cookies != null) {
        String _cookiePre = __owner.getModuleCfg().getCookiePrefix();
        int _preLength = StringUtils.length(_cookiePre);
        for (Cookie _cookie : _cookies) {
            String _name = _cookie.getName();
            if (_name.startsWith(_cookiePre)) {
                String _v = decodeValue(_cookie.getValue());
                _returnValue.put(_name.substring(_preLength), new BlurObject(_v));
            }
        }
    }
    return _returnValue;
}
 
Example 9
Source File: HttpCookieIdentityResolver.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public List<IdentityToken> resolve(HttpServletRequest input, X509Certificate[] transportAuthTokens) {
    List<IdentityToken> tokens = new ArrayList<IdentityToken>();

    Cookie[] cookies = input.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            String cookieValue = cookie.getValue();
            String cookieName = cookie.getName();
            for (SimpleIdentityTokenName t: SimpleIdentityTokenName.values()) {
                if (("X-Token-"+t.name()).equals(cookieName) && cookieValue != null && cookieValue.length() > 0) {
                    tokens.add(new IdentityToken(cookieName, cookieValue));
                }
            }
        }
    }
    return tokens;
}
 
Example 10
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 11
Source File: BaseController.java    From spring-boot-demo-all with Apache License 2.0 5 votes vote down vote up
/**
 * 删除cookie
 */
protected void deleteCookieByName(String cookieName) {
    Cookie[] cookies = this.getHttpServletRequest().getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(cookieName)) {
            Cookie temp = new Cookie(cookie.getName(), "");
            temp.setMaxAge(0);
            this.getHttpServletResponse().addCookie(temp);
        }
    }
}
 
Example 12
Source File: CookieHelper.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
private Cookie __doGetCookie(String cookieName) {
    Cookie[] _cookies = __request.getCookies();
    if (_cookies == null) {
        return null;
    } else {
        for (Cookie _cookie : _cookies) {
            String name = _cookie.getName();
            if (name.equals(cookieName)) {
                return _cookie;
            }
        }
        return null;
    }
}
 
Example 13
Source File: cfCookieData.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public void setData(Cookie _cdata, boolean bHttpOnly ) throws cfmRunTimeException {
	if (session.isFlushed()) {
		cfCatchData catchData = new cfCatchData();
		catchData.setType(cfCatchData.TYPE_TEMPLATE);
		catchData.setDetail("Unable to create Cookie because the page has been flushed");
		catchData.setMessage("Cannot create Cookie");
		throw new cfmRunTimeException(catchData);
	}
	super.setData(_cdata.getName(), new cookieWrapper(_cdata, true, bHttpOnly));
}
 
Example 14
Source File: AuthenticationFilter.java    From oxTrust with MIT License 5 votes vote down vote up
private Cookie cloneCokie(Cookie sourceCookie, String newValue, int maxAge) {
    Cookie resultCookie = new Cookie(sourceCookie.getName(), newValue);

    resultCookie.setPath("/");
    resultCookie.setMaxAge(maxAge);
    resultCookie.setVersion(1);
    resultCookie.setSecure(true);

    return resultCookie;
}
 
Example 15
Source File: AvoidRepeatHttpServletResponseWrapper.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 向Response中添加Cookie信息,同名Cookie不能重复添加
 * </p>
 */
public void addCookie(Cookie cookie) {
	String cookieName = cookie.getName();
       if ( !cookies.contains(cookieName) ) {
		super.addCookie(cookie);
		cookies.add(cookieName);
	}
}
 
Example 16
Source File: MainServlet.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
protected void printCookies(HttpServletRequest request, PrintWriter writer) throws ServletException, IOException {
    Cookie[] cookies = request.getCookies();
    boolean sticky = false;

    if ("true".equals(request.getParameter("sticky"))) {
        request.getSession(true);
        sticky = true;
    }

    if (cookies != null) {
        writer.println("<h2>Cookies:</h2>");
        for (Cookie cookie: cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            if ("__VCAP_ID__".equals(name)) {
                sticky = true;
            }
            writer.println("  Name: " + name + "<br/>");
            writer.println("  Value: " + value + "<br/>");
        }
        writer.println("<br/><br/>");
    }

    if (sticky) {
        writer.println("Sticky session is enabled. Refreshing the browser should keep routing to the same app instance.<br/><br/>");
    } else {
        writer.println("Sticky session is NOT enabled. Refreshing the browser should route to random app instances.<br/><br/><a href='?sticky=true'>start a sticky session</a>" +
                       "<br/><br/>");
    }
}
 
Example 17
Source File: Response.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Special method for adding a session cookie as we should be overriding
 * any previous
 * @param cookie
 */
public void addSessionCookieInternal(final Cookie cookie) {
    if (isCommitted()) {
        return;
    }

    String name = cookie.getName();
    final String headername = "Set-Cookie";
    final String startsWith = name + "=";
    final StringBuffer sb = generateCookieString(cookie);
    boolean set = false;
    MimeHeaders headers = getCoyoteResponse().getMimeHeaders();
    int n = headers.size();
    for (int i = 0; i < n; i++) {
        if (headers.getName(i).toString().equals(headername)) {
            if (headers.getValue(i).toString().startsWith(startsWith)) {
                headers.getValue(i).setString(sb.toString());
                set = true;
            }
        }
    }
    if (!set) {
        addHeader(headername, sb.toString());
    }


}
 
Example 18
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 19
Source File: MockHttpClient.java    From karate with MIT License 4 votes vote down vote up
@Override
protected HttpResponse makeHttpRequest(HttpBody entity, ScenarioContext context) {
    logger.info("making mock http client request: {} - {}", request.getMethod(), getRequestUri());
    MockHttpServletRequest req = requestBuilder.buildRequest(getServletContext());
    byte[] bytes;
    if (entity != null) {
        bytes = entity.getBytes();
        req.setContentType(entity.getContentType());
        if (entity.isMultiPart()) {
            for (MultiPartItem item : entity.getParts()) {
                MockMultiPart part = new MockMultiPart(item);
                req.addPart(part);
                if (!part.isFile()) {
                    req.addParameter(part.getName(), part.getValue());
                }
            }
        } else if (entity.isUrlEncoded()) {
            req.addParameters(entity.getParameters());
        } else {
            req.setContent(bytes);
        }
    } else {
        bytes = null;
    }
    MockHttpServletResponse res = new MockHttpServletResponse();
    logRequest(req, bytes);
    long startTime = System.currentTimeMillis();
    try {
        getServlet(request).service(req, res);
    } catch (Exception e) {
        String message = e.getMessage();
        if (message == null && e.getCause() != null) {
            message = e.getCause().getMessage();
        }
        logger.error("mock servlet request failed: {}", message);
        throw new RuntimeException(e);
    }
    HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis());
    bytes = res.getContentAsByteArray();
    logResponse(res, bytes);
    response.setUri(getRequestUri());
    response.setBody(bytes);
    response.setStatus(res.getStatus());
    for (Cookie c : res.getCookies()) {
        com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue());
        cookie.put(DOMAIN, c.getDomain());
        cookie.put(PATH, c.getPath());
        cookie.put(SECURE, c.getSecure() + "");
        cookie.put(MAX_AGE, c.getMaxAge() + "");
        cookie.put(VERSION, c.getVersion() + "");
        response.addCookie(cookie);
    }
    for (String headerName : res.getHeaderNames()) {
        response.putHeader(headerName, res.getHeaders(headerName));
    }
    return response;
}
 
Example 20
Source File: GitHandlerV1.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean handleRequest(HttpServletRequest request, HttpServletResponse response, String gitPathInfo) throws ServletException {

	String[] infoParts = gitPathInfo.split("\\/", 3); //$NON-NLS-1$
	if (infoParts.length < 2)
		return false; // malformed request, we don't know how to handle this

	String pathString = infoParts.length > 2 ? infoParts[2] : "";
	if (request.getContextPath().length() != 0) {
		IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
		IPath contextPath = new Path(request.getContextPath());
		if (contextPath.isPrefixOf(path)) {
			pathString = path.removeFirstSegments(contextPath.segmentCount()).toString();
		}
	}

	// TODO: Add to constants
	String tokenName = PreferenceHelper.getString("ltpa.token.name"); //$NON-NLS-1$
	if (tokenName != null) {
		javax.servlet.http.Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie currentCookie = cookies[i];
				if (tokenName.equals(currentCookie.getName())) {
					Cookie loginCookie = new Cookie(currentCookie.getName(), GitUtils.sanitizeCookie(currentCookie.getValue()));
					request.setAttribute(GitConstants.KEY_SSO_TOKEN, loginCookie);
				}
			}
		}
	}

	if (infoParts[1].equals(Branch.RESOURCE)) {
		return branchHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Clone.RESOURCE)) {
		return cloneHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Commit.RESOURCE)) {
		return commitHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(ConfigOption.RESOURCE)) {
		return configHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Diff.RESOURCE)) {
		return diffHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Index.RESOURCE)) {
		return indexHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Remote.RESOURCE)) {
		return remoteHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Status.RESOURCE)) {
		return statusHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Tag.RESOURCE)) {
		return tagHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Blame.RESOURCE)) {
		return blameHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Ignore.RESOURCE)) {
		return ignoreHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Tree.RESOURCE)) {
		return treeHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Stash.RESOURCE)) {
		return stashHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(Submodule.RESOURCE)) {
		return submoduleHandlerV1.handleRequest(request, response, pathString);
	} else if (infoParts[1].equals(PullRequest.RESOURCE)) {
		return pullRequestHandlerV1.handleRequest(request, response, pathString);
	}

	return false;
}