Java Code Examples for javax.servlet.http.Cookie

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/http/.

Source file: CookieUtils.java

  19 
vote

/** 
 * schreibt ein Cookie in den Request
 * @param response der HttpServletResponse
 * @param name der Name des Cookie
 * @param value der Wert des Cookie
 * @param maxAge die Lebensdauer in Sekunden
 */
public static void addCookie(HttpServletResponse response,String name,String value,int maxAge,String domain){
  Cookie cookie=new Cookie(name,value);
  cookie.setMaxAge(maxAge);
  if (!Strings.isEmpty(domain)) {
    cookie.setDomain(domain);
  }
  response.addCookie(cookie);
}
 

Example 2

From project myberkeley, under directory /accountprovider/src/main/java/org/sakaiproject/nakamura/accountprovider/.

Source file: CookieUtils.java

  19 
vote

public static void clearCookie(HttpServletResponse response,String name){
  Cookie c=new HttpOnlyCookie(name,"");
  c.setMaxAge(0);
  c.setPath("/");
  response.addCookie(c);
}
 

Example 3

From project ajah, under directory /ajah-servlet/src/main/java/com/ajah/servlet/util/.

Source file: CookieUtils.java

  18 
vote

/** 
 * Clears a cookies by setting its  {@link Cookie#setMaxAge(int)} to 0;
 * @param cookieName The name of the cookie to clear
 * @param response Response to set updated cookies on, required.
 * @param request
 */
public static void clearCookie(final String cookieName,final HttpServletRequest request,final HttpServletResponse response){
  AjahUtils.requireParam(cookieName,"cookieName");
  AjahUtils.requireParam(request,"request");
  AjahUtils.requireParam(response,"response");
  final Cookie cookie=getCookie(request,cookieName);
  cookie.setMaxAge(0);
  response.addCookie(cookie);
}
 

Example 4

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/server/.

Source file: AuthenticationFilter.java

  18 
vote

/** 
 * Creates the Alfredo authentiation HTTP cookie. <p> It sets the domain and path specified in the configuration.
 * @param token authentication token for the cookie.
 * @return the HTTP cookie.
 */
protected Cookie createCookie(String token){
  Cookie cookie=new Cookie(AuthenticatedURL.AUTH_COOKIE,token);
  if (getCookieDomain() != null) {
    cookie.setDomain(getCookieDomain());
  }
  if (getCookiePath() != null) {
    cookie.setPath(getCookiePath());
  }
  return cookie;
}
 

Example 5

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/util/.

Source file: RequestUtil.java

  18 
vote

/** 
 * Convenience method to set a cookie.
 * @param response the current response
 * @param name the name of the cookie
 * @param value the value of the cookie
 * @param path the path to set it on
 */
public static void setCookie(final HttpServletResponse response,final String name,final String value,final String path){
  if (RequestUtil.log.isDebugEnabled()) {
    RequestUtil.log.debug("Setting cookie '" + name + "' on path '"+ path+ "'");
  }
  final Cookie cookie=new Cookie(name,value);
  cookie.setSecure(false);
  cookie.setPath(path);
  cookie.setMaxAge(3600 * 24 * 30);
  response.addCookie(cookie);
}
 

Example 6

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/util/.

Source file: Sessions.java

  18 
vote

/** 
 * Logouts a user with the specified request.
 * @param request the specified request
 * @param response the specified response
 * @return {@code true} if succeed, otherwise returns {@code false}
 */
public static boolean logout(final HttpServletRequest request,final HttpServletResponse response){
  final HttpSession session=request.getSession(false);
  if (null != session) {
    final Cookie cookie=new Cookie("b3log-latke",null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    session.invalidate();
    return true;
  }
  return false;
}
 

Example 7

From project Blitz, under directory /src/com/laxser/blitz/util/.

Source file: BasicCookieManager.java

  18 
vote

public void saveCookie(HttpServletResponse response,String key,String value,int second,String path){
  Cookie cookie=new Cookie(key,value);
  cookie.setPath(path);
  cookie.setMaxAge(second);
  cookie.setDomain("." + this.domainMain);
  response.addCookie(cookie);
}
 

Example 8

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/web/support/.

Source file: CookieRetrievingCookieGenerator.java

  18 
vote

public void addCookie(final HttpServletRequest request,final HttpServletResponse response,final String cookieValue){
  if (!StringUtils.hasText(request.getParameter(RememberMeCredentials.REQUEST_PARAMETER_REMEMBER_ME))) {
    super.addCookie(response,cookieValue);
  }
 else {
    final Cookie cookie=createCookie(cookieValue);
    cookie.setMaxAge(this.rememberMeMaxAge);
    if (isCookieSecure()) {
      cookie.setSecure(true);
    }
    response.addCookie(cookie);
  }
}
 

Example 9

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-impl/src/main/java/com/utest/webservice/impl/v2/.

Source file: UserWebServiceImpl.java

  18 
vote

@PUT @Path("/login") @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Override public Boolean login(@Context MessageContext context) throws Exception {
  Integer auth=UserUtil.getCurrentUserId();
  if (auth == null) {
    throw new org.apache.cxf.interceptor.security.AccessDeniedException("No logged in user!");
  }
  final AuthenticatedUserInfo authInfo=(AuthenticatedUserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  String sessionId=SessionUtil.extractSession(context,true);
  userService.login(authInfo,sessionId);
  String token=Base64.encodeObject(SecurityContextHolder.getContext().getAuthentication(),Base64.GZIP | Base64.DONT_BREAK_LINES);
  Cookie loginCookie=new Cookie(SessionUtil.AUTH_TOKEN,token);
  loginCookie.setMaxAge(getLoginExpirationSeconds());
  context.getHttpServletResponse().addCookie(loginCookie);
  return Boolean.TRUE;
}
 

Example 10

From project clutter, under directory /src/clutter/hypertoolkit/security/.

Source file: Baker.java

  18 
vote

public Cookie makeCookie(String cookieName,String cookieValue){
  Cookie cookie=new Cookie(cookieName,cookieValue);
  cookie.setVersion(1);
  cookie.setMaxAge((int)TimeUnit.SECONDS.convert(365 * 2,TimeUnit.DAYS));
  return cookie;
}
 

Example 11

From project cometd, under directory /cometd-java/cometd-java-server/src/main/java/org/cometd/server/transport/.

Source file: LongPollingTransport.java

  18 
vote

protected String setBrowserId(HttpServletRequest request,HttpServletResponse response){
  String browser_id=Long.toHexString(request.getRemotePort()) + Long.toString(getBayeux().randomLong(),36) + Long.toString(System.currentTimeMillis(),36)+ Long.toString(request.getRemotePort(),36);
  Cookie cookie=new Cookie(_browserId,browser_id);
  cookie.setPath("/");
  cookie.setMaxAge(-1);
  response.addCookie(cookie);
  return browser_id;
}
 

Example 12

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/.

Source file: HttpClientRequest.java

  18 
vote

/** 
 * @param cookie cookie to add to the request
 */
public Builder<Type> replaceCookie(@Nonnull final Cookie cookie){
  for (Iterator<Cookie> it=cookies.iterator(); it.hasNext(); ) {
    final Cookie oldCookie=it.next();
    if (StringUtils.equals(cookie.getName(),oldCookie.getName())) {
      it.remove();
    }
  }
  return addCookie(cookie);
}
 

Example 13

From project cotopaxi-core, under directory /src/main/java/br/octahedron/cotopaxi/controller/.

Source file: ControllerContext.java

  18 
vote

/** 
 * Adds a cookie.
 * @param name a String specifying the name of the cookie
 * @param value a String specifying the value of the cookie
 * @param domain a String containing the domain name within which this cookie is visible; form is according to RFC 2109
 * @param maxAge an integer specifying the maximum age of the cookie in seconds; if negative, means the cookie is not stored; if zero, deletes the cookie
 * @see Cookie
 */
protected void addCookie(String name,String value,String domain,int maxAge){
  Cookie c=new Cookie(name,value);
  if (domain != null) {
    c.setDomain(domain);
  }
  if (maxAge != -1) {
    c.setMaxAge(maxAge);
  }
  this.getCookies().add(c);
}
 

Example 14

From project dolphin, under directory /dolphinmaple/src/com/tan/servlet/.

Source file: BookMarkServlet.java

  18 
vote

private void putCookies(HttpServletResponse response){
  Cookie u_cookie=new Cookie("username","dolphin");
  u_cookie.setMaxAge(3600);
  Cookie u_password=new Cookie("password","includemain");
  u_password.setMaxAge(3600);
  response.addCookie(u_cookie);
  response.addCookie(u_password);
}
 

Example 15

From project FunctionalTestsPortlet, under directory /src/main/java/org/jasig/portlet/test/cookie/.

Source file: CreateCookieFormBackingObject.java

  18 
vote

/** 
 * @return
 */
public Cookie toCookie(){
  Cookie cookie=new Cookie(name,value);
  cookie.setComment(comment);
  if (domain != null) {
    cookie.setDomain(domain);
  }
  cookie.setMaxAge(maxAge);
  cookie.setPath(path);
  cookie.setSecure(secure);
  cookie.setVersion(version);
  return cookie;
}
 

Example 16

From project greenhouse, under directory /src/main/java/com/springsource/greenhouse/home/.

Source file: DateTimeZoneHandlerInterceptor.java

  18 
vote

private Integer getMillisOffset(HttpServletRequest request){
  Cookie cookie=WebUtils.getCookie(request,"Greenhouse.timeZoneOffset");
  if (cookie != null) {
    return Integer.valueOf(cookie.getValue());
  }
 else {
    return null;
  }
}
 

Example 17

From project guj.com.br, under directory /src/net/jforum/.

Source file: ControllerUtils.java

  18 
vote

/** 
 * Gets a cookie by its name.
 * @param name The cookie name to retrieve
 * @return The <code>Cookie</code> object if found, or <code>null</code> oterwhise
 */
public static Cookie getCookie(String name){
  Cookie[] cookies=JForumExecutionContext.getRequest().getCookies();
  if (cookies != null) {
    for (int i=0; i < cookies.length; i++) {
      Cookie c=cookies[i];
      if (c.getName().equals(name)) {
        return c;
      }
    }
  }
  return null;
}
 

Example 18

From project happening, under directory /src-ui/org/vaadin/training/fundamentals/happening/.

Source file: HappeningApplication.java

  18 
vote

@Override public void clearCookie(){
  if (response != null) {
    Cookie cookie=new Cookie("userid","");
    cookie.setPath("/");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
  }
}
 

Example 19

From project inproctester, under directory /inproctester-tests/src/main/java/com/thoughtworks/inproctester/testapp/.

Source file: TestServlet.java

  18 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/html");
  resp.setCharacterEncoding("UTF-8");
  Cookie flashMessageCookie=getCookie(req,FLASH_MESSAGE_COOKIE_NAME);
  if (flashMessageCookie != null) {
    req.setAttribute("message",flashMessageCookie.getValue());
    Cookie cookie=new Cookie(FLASH_MESSAGE_COOKIE_NAME,"");
    cookie.setMaxAge(0);
    resp.addCookie(cookie);
  }
  req.setAttribute("contact",contact);
  getServletContext().getRequestDispatcher("/test.ftl").forward(req,resp);
}
 

Example 20

From project isohealth, under directory /Oauth/java/example/webapp/src/main/java/net/oauth/example/consumer/webapp/.

Source file: CookieMap.java

  18 
vote

public void put(String name,String value){
  if (value == null) {
    remove(name);
  }
 else   if (!value.equals(name2value.get(name))) {
    Cookie c=new Cookie(name,value);
    c.setPath(path);
    response.addCookie(c);
    name2value.put(name,value);
  }
}
 

Example 21

From project jdonframework, under directory /JdonAccessory/src/com/jdon/security/web/.

Source file: LoginServlet.java

  18 
vote

private void deleteAllCookie(HttpServletRequest request,HttpServletResponse response){
  Cookie rememberMe=RequestUtil.getCookie(request,"rememberMe");
  if (rememberMe != null)   RequestUtil.deleteCookie(response,rememberMe,"/");
  Cookie userCookie=RequestUtil.getCookie(request,"username");
  if (userCookie != null)   RequestUtil.deleteCookie(response,userCookie,"/");
  Cookie passCookie=RequestUtil.getCookie(request,"password");
  if (passCookie != null)   RequestUtil.deleteCookie(response,passCookie,"/");
}
 

Example 22

From project jforum2, under directory /src/net/jforum/.

Source file: ControllerUtils.java

  18 
vote

/** 
 * Gets a cookie by its name.
 * @param name The cookie name to retrieve
 * @return The <code>Cookie</code> object if found, or <code>null</code> oterwhise
 */
public static Cookie getCookie(String name){
  Cookie[] cookies=JForumExecutionContext.getRequest().getCookies();
  if (cookies != null) {
    for (int i=0; i < cookies.length; i++) {
      Cookie c=cookies[i];
      if (c.getName().equals(name)) {
        return c;
      }
    }
  }
  return null;
}
 

Example 23

From project jsecurity, under directory /web/src/main/java/org/apache/ki/web/attr/.

Source file: CookieAttribute.java

  18 
vote

/** 
 * Returns the cookie with the given name from the request or <tt>null</tt> if no cookie with that name could be found.
 * @param request    the current executing http request.
 * @param cookieName the name of the cookie to find and return.
 * @return the cookie with the given name from the request or <tt>null</tt> if no cookiewith that name could be found.
 */
private static Cookie getCookie(HttpServletRequest request,String cookieName){
  Cookie cookies[]=request.getCookies();
  if (cookies != null) {
    for (    Cookie cookie : cookies) {
      if (cookie.getName().equals(cookieName)) {
        return cookie;
      }
    }
  }
  return null;
}
 

Example 24

From project jspwiki, under directory /src/org/apache/wiki/auth/login/.

Source file: CookieAssertionLoginModule.java

  18 
vote

/** 
 * Sets the username cookie.  The cookie value is URLEncoded in UTF-8.
 * @param response The Servlet response
 * @param name     The name to write into the cookie.
 */
public static void setUserCookie(HttpServletResponse response,String name){
  name=TextUtil.urlEncodeUTF8(name);
  Cookie userId=new Cookie(PREFS_COOKIE_NAME,name);
  userId.setMaxAge(1001 * 24 * 60* 60);
  response.addCookie(userId);
}
 

Example 25

From project LanguageSpecCreator, under directory /src/liber/edit/server/.

Source file: Postings.java

  18 
vote

/** 
 * Stores the user and project IDs in cookies for LIBER to find
 */
private void storeID(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
  String userID=request.getParameter("userid");
  Cookie koekje=new Cookie(USER,userID);
  response.addCookie(koekje);
  String projectID=request.getParameter("projectid");
  if (projectID != null) {
    Cookie c=new Cookie(PROJECT,projectID);
    response.addCookie(c);
  }
}
 

Example 26

From project logback, under directory /logback-access/src/test/java/ch/qos/logback/access/pattern/.

Source file: ConverterTest.java

  18 
vote

@Test public void testRequestCookieConverter(){
  RequestCookieConverter converter=new RequestCookieConverter();
  List<String> optionList=new ArrayList<String>();
  optionList.add("testName");
  converter.setOptionList(optionList);
  converter.start();
  String result=converter.convert(event);
  Cookie cookie=request.getCookies()[0];
  assertEquals(cookie.getValue(),result);
}
 

Example 27

From project lorsource, under directory /src/main/java/ru/org/linux/auth/.

Source file: LoginController.java

  18 
vote

private void createCookies(HttpServletResponse response,HttpServletRequest request,User user){
  Cookie cookie=new Cookie("password",user.getMD5(configuration.getSecret()));
  cookie.setMaxAge(60 * 60 * 24* 31* 24);
  cookie.setPath("/");
  cookie.setHttpOnly(true);
  response.addCookie(cookie);
  Cookie prof=new Cookie("profile",user.getNick());
  prof.setMaxAge(60 * 60 * 24* 31* 12);
  prof.setPath("/");
  response.addCookie(prof);
  user.acegiSecurityHack(response,request.getSession());
  CSRFProtectionService.generateCSRFCookie(request,response);
}
 

Example 28

From project MEditor, under directory /editor-confutils/src/main/java/cz/mzk/editor/server/.

Source file: HttpCookies.java

  18 
vote

/** 
 * Reset cookie.
 * @param request the request
 * @param response the response
 * @param name the name
 */
public static void resetCookie(HttpServletRequest request,HttpServletResponse response,String name){
  Cookie cookie=findCookie(request,name);
  if (cookie != null) {
    cookie.setMaxAge(0);
    response.addCookie(cookie);
  }
}
 

Example 29

From project memcached-session-manager, under directory /core/src/test/java/de/javakaffee/web/msm/.

Source file: RequestTrackingHostValveTest.java

  18 
vote

@Test public final void testBackupSessionInvokedWhenResponseCookiePresent() throws IOException, ServletException {
  when(_request.getRequestedSessionId()).thenReturn(null);
  final Cookie cookie=new Cookie(_sessionTrackerValve.getSessionCookieName(),"foo");
  when(_response.getHeader(eq("Set-Cookie"))).thenReturn(generateCookieString(cookie));
  _sessionTrackerValve.invoke(_request,_response);
  verify(_service).backupSession(eq("foo"),eq(false),anyString());
}
 

Example 30

From project mgwt, under directory /src/main/java/com/googlecode/mgwt/linker/server/propertyprovider/.

Source file: MgwtOsPropertyProvider.java

  18 
vote

public String getRetinaCookieValue(HttpServletRequest req){
  Cookie[] cookies=req.getCookies();
  if (cookies == null)   return null;
  for (int i=0; i < cookies.length; i++) {
    Cookie cookie=cookies[i];
    if ("mgwt_ios_retina".equals(cookie.getName()))     return (cookie.getValue());
  }
  return null;
}
 

Example 31

From project agile, under directory /agile-web/src/main/java/org/headsupdev/agile/web/dialogs/.

Source file: LoginDialog.java

  17 
vote

protected void onSubmit(){
  ((WebResponse)getResponse()).clearCookie(new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,""));
  org.headsupdev.agile.api.User user=owner.getSecurityManager().getUserByUsername(username);
  if (user == null) {
    info("Invalid username");
    return;
  }
  String encodedPass=HashUtil.getMD5Hex(password);
  if (!encodedPass.equals(user.getPassword())) {
    info("Incorrect password");
    return;
  }
  if (!user.canLogin()) {
    info("Account is not currently active");
    return;
  }
  if (remember) {
    String rememberKey=String.valueOf(new Random(System.currentTimeMillis()).nextInt());
    Cookie cookie=new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,username + ":" + rememberKey);
    cookie.setMaxAge(60 * 60 * 24* 32);
    ((WebResponse)getResponse()).addCookie(cookie);
    owner.addRememberMe(username,rememberKey);
  }
 else   if (((HeadsUpSession)getSession()).getUser() != null) {
    ((WebResponse)getResponse()).clearCookie(new Cookie(HeadsUpPage.REMEMBER_COOKIE_NAME,""));
    owner.removeRememberMe(((HeadsUpSession)getSession()).getUser().getUsername());
  }
  ((StoredUser)user).setLastLogin(new Date());
  ((HeadsUpSession)getSession()).setUser(user);
  if (!continueToOriginalDestination()) {
    Class previous=((HeadsUpSession)getSession()).getPreviousPageClass();
    if (previous != null) {
      setResponsePage(previous,((HeadsUpSession)getSession()).getPreviousPageParameters());
    }
 else {
      setResponsePage(owner.getPageClass(""));
    }
  }
}
 

Example 32

From project azure4j-blog-samples, under directory /ACSExample/src/com/persistent/azure/acs/filter/.

Source file: AuthorizationFilter.java

  17 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpServletRequest=(HttpServletRequest)request;
  HttpServletResponse httpServletResponse=(HttpServletResponse)response;
  String acsToken=httpServletRequest.getParameter("wresult");
  if (null != acsToken && acsToken.trim().length() == 0) {
    acsToken=null;
  }
  if (!(httpServletRequest.getRequestURI().contains("claims.do") && acsToken != null)) {
    Cookie[] cookies=httpServletRequest.getCookies();
    Cookie currentCookie=null;
    String cookieName=resourceBundle.getString("acs.cookie.name");
    if (cookies != null && cookies.length > 0) {
      for (      Cookie c : cookies) {
        if (cookieName.equals(c.getName())) {
          currentCookie=c;
          break;
        }
      }
    }
    if (currentCookie == null) {
      StringBuffer loginURL=new StringBuffer();
      loginURL.append(resourceBundle.getString("acs.url"));
      loginURL.append("/v2/wsfederation?wa=wsignin1.0&wtrealm=");
      loginURL.append(resourceBundle.getString("acs.realm"));
      httpServletResponse.sendRedirect(loginURL.toString());
    }
 else {
      chain.doFilter(request,response);
    }
  }
 else {
    chain.doFilter(request,response);
  }
}
 

Example 33

From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/processor/.

Source file: LoginProcessor.java

  17 
vote

/** 
 * Tries to login with cookie.
 * @param request the specified request
 * @param response the specified response
 */
public static void tryLogInWithCookie(final HttpServletRequest request,final HttpServletResponse response){
  final Cookie[] cookies=request.getCookies();
  if (null == cookies || 0 == cookies.length) {
    return;
  }
  try {
    for (int i=0; i < cookies.length; i++) {
      final Cookie cookie=cookies[i];
      if (!"b3log-latke".equals(cookie.getName())) {
        continue;
      }
      final JSONObject cookieJSONObject=new JSONObject(cookie.getValue());
      final String userEmail=cookieJSONObject.optString(User.USER_EMAIL);
      if (Strings.isEmptyOrNull(userEmail)) {
        break;
      }
      final JSONObject user=userQueryService.getUserByEmail(userEmail.toLowerCase().trim());
      if (null == user) {
        break;
      }
      final String userPassword=user.optString(User.USER_PASSWORD);
      final String hashPassword=cookieJSONObject.optString(User.USER_PASSWORD);
      if (MD5.hash(userPassword).equals(hashPassword)) {
        Sessions.login(request,response,user);
        LOGGER.log(Level.INFO,"Logged in with cookie[email={0}]",userEmail);
      }
    }
  }
 catch (  final Exception e) {
    LOGGER.log(Level.WARNING,"Parses cookie failed, clears the cookie[name=b3log-latke]",e);
    final Cookie cookie=new Cookie("b3log-latke",null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
  }
}
 

Example 34

From project brix-cms, under directory /brix-core/src/main/java/org/brixcms/web/.

Source file: BrixRequestCycleProcessor.java

  17 
vote

public String getWorkspace(){
  String workspace=getWorkspaceFromUrl();
  if (workspace != null) {
    return workspace;
  }
  RequestCycle rc=RequestCycle.get();
  workspace=rc.getMetaData(WORKSPACE_METADATA);
  if (workspace == null) {
    WebRequest req=(WebRequest)RequestCycle.get().getRequest();
    WebResponse resp=(WebResponse)RequestCycle.get().getResponse();
    Cookie cookie=req.getCookie(COOKIE_NAME);
    workspace=getDefaultWorkspaceName();
    if (cookie != null) {
      if (cookie.getValue() != null)       workspace=cookie.getValue();
    }
    if (!checkSession(workspace)) {
      workspace=getDefaultWorkspaceName();
    }
    if (workspace == null) {
      throw new IllegalStateException("Could not resolve jcr workspace to use for this request");
    }
    Cookie c=new Cookie(COOKIE_NAME,workspace);
    c.setPath("/");
    if (workspace.toString().equals(getDefaultWorkspaceName()) == false)     resp.addCookie(c);
 else     if (cookie != null)     resp.clearCookie(cookie);
    rc.setMetaData(WORKSPACE_METADATA,workspace);
  }
  return workspace;
}
 

Example 35

From project com.idega.content, under directory /src/java/com/idega/content/tree/.

Source file: HtmlTreeRenderer.java

  17 
vote

private void restoreStateFromCookies(FacesContext context,UIComponent component){
  String nodeId=null;
  HtmlTree tree=(HtmlTree)component;
  TreeState state=tree.getDataModel().getTreeState();
  Map cookieMap=context.getExternalContext().getRequestCookieMap();
  Cookie treeCookie=(Cookie)cookieMap.get(component.getId());
  if (treeCookie == null || treeCookie.getValue() == null) {
    return;
  }
  String nodeState=null;
  Map attrMap=getCookieAttr(treeCookie);
  Iterator i=attrMap.keySet().iterator();
  while (i.hasNext()) {
    nodeId=(String)i.next();
    nodeState=(String)attrMap.get(nodeId);
    if (NODE_STATE_EXPANDED.equals(nodeState)) {
      if (!state.isNodeExpanded(nodeId)) {
        state.toggleExpanded(nodeId);
      }
    }
 else     if (NODE_STATE_CLOSED.equals(nodeState)) {
      if (state.isNodeExpanded(nodeId)) {
        state.toggleExpanded(nodeId);
      }
    }
  }
}
 

Example 36

From project echo2, under directory /src/testapp/interactive/java/nextapp/echo2/testapp/interactive/testscreen/.

Source file: ContainerContextTest.java

  17 
vote

public ContainerContextTest(){
  super();
  setCellSpacing(new Extent(10));
  SplitPaneLayoutData splitPaneLayoutData=new SplitPaneLayoutData();
  splitPaneLayoutData.setInsets(new Insets(10));
  setLayoutData(splitPaneLayoutData);
  ApplicationInstance app=ApplicationInstance.getActive();
  ContainerContext containerContext=(ContainerContext)app.getContextProperty(ContainerContext.CONTEXT_PROPERTY_NAME);
  Column clientPropertiesColumn=new Column();
  add(clientPropertiesColumn);
  clientPropertiesColumn.add(new Label("Client Properties"));
  clientPropertiesColumn.add(createClientPropertiesTable(containerContext));
  Column initialParametersColumn=new Column();
  add(initialParametersColumn);
  initialParametersColumn.add(new Label("Initial Parameters"));
  initialParametersColumn.add(createInitialParametersTable(containerContext));
  Column applicationPropertiesColumn=new Column();
  add(applicationPropertiesColumn);
  applicationPropertiesColumn.add(new Label("ApplicationInstance Properties"));
  applicationPropertiesColumn.add(createApplicationPropertiesTable(app));
  Column cookiesColumn=new Column();
  add(cookiesColumn);
  cookiesColumn.add(new Label("Cookies"));
  cookiesColumn.add(createCookieTable(containerContext));
  Button setCookieButton=new Button("Set Cookie");
  setCookieButton.setStyleName("Default");
  setCookieButton.addActionListener(new ActionListener(){
    public void actionPerformed(    ActionEvent e){
      int value=(int)(Math.random() * 3);
      Cookie cookie=new Cookie("TestCookie" + value,"Mmmmm Cookies " + value);
      BrowserSetCookieCommand command=new BrowserSetCookieCommand(cookie);
      ApplicationInstance.getActive().enqueueCommand(command);
    }
  }
);
  cookiesColumn.add(setCookieButton);
}
 

Example 37

From project gatein-sso, under directory /agent/src/main/java/org/gatein/sso/agent/opensso/.

Source file: OpenSSOAgent.java

  17 
vote

/** 
 * This method is useful only for Cross-Domain (CD) authentication scenario when GateIn and OpenSSO are in different DNS domains and they can't share cookie. It performs: <li>Parse and validate message from OpenSSO CDCServlet.</li> <li>Use ssoToken from parsed message and establish OpenSSO cookie iPlanetDirectoryPro</li> <li>Redirects to InitiateLoginFilter but with cookie established. So in next request, we can perform agent validation against OpenSSO server</li>
 * @param httpRequest
 * @param httpResponse
 * @return true if parameter LARES with message from CDC is present in HttpServletRequest
 * @throws IOException
 */
protected boolean tryMessageFromCDC(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws IOException {
  String encodedCDCMessage=httpRequest.getParameter("LARES");
  if (encodedCDCMessage == null) {
    if (log.isTraceEnabled()) {
      log.trace("Message from CDC not found in this HttpServletRequest");
    }
    return false;
  }
  CDMessageContext messageContext=cdcMessageParser.parseMessage(encodedCDCMessage);
  if (log.isTraceEnabled()) {
    log.trace("Successfully parsed messageContext " + messageContext);
  }
  validateCDMessageContext(httpRequest,messageContext);
  String ssoToken=messageContext.getSsoToken();
  Cookie cookie=new Cookie(cookieName,"\"" + ssoToken + "\"");
  cookie.setPath(httpRequest.getContextPath());
  httpResponse.addCookie(cookie);
  if (log.isTraceEnabled()) {
    log.trace("Cookie " + cookieName + " with value "+ ssoToken+ " added to HttpResponse");
  }
  String urlToRedirect=httpResponse.encodeRedirectURL(httpRequest.getRequestURI());
  httpResponse.sendRedirect(urlToRedirect);
  return true;
}
 

Example 38

From project gitblit, under directory /src/com/gitblit/.

Source file: GitBlit.java

  17 
vote

/** 
 * Sets a cookie for the specified user.
 * @param response
 * @param user
 */
public void setCookie(WebResponse response,UserModel user){
  if (userService == null) {
    return;
  }
  if (userService.supportsCookies()) {
    Cookie userCookie;
    if (user == null) {
      userCookie=new Cookie(Constants.NAME,"");
    }
 else {
      String cookie=userService.getCookie(user);
      if (StringUtils.isEmpty(cookie)) {
        userCookie=new Cookie(Constants.NAME,"");
      }
 else {
        userCookie=new Cookie(Constants.NAME,cookie);
        userCookie.setMaxAge(Integer.MAX_VALUE);
      }
    }
    userCookie.setPath("/");
    response.addCookie(userCookie);
  }
}
 

Example 39

From project IOCipherServer, under directory /src/Acme/Serve/.

Source file: Serve.java

  17 
vote

private void addCookie(String name,String value,String path,String domain){
  if (SESSION_COOKIE_NAME.equals(name) && sessionCookieValue == null) {
    sessionCookieValue=value;
    try {
      serve.getSession(sessionCookieValue).userTouch();
      reqSessionValue=sessionCookieValue;
    }
 catch (    IllegalStateException ise) {
    }
catch (    NullPointerException npe) {
    }
  }
 else {
    Cookie c;
    inCookies.addElement(c=new Cookie(name,value));
    if (path != null) {
      c.setPath(path);
      if (domain != null)       c.setDomain(domain);
    }
  }
}
 

Example 40

From project ipdburt, under directory /iddb-web/src/main/java/iddb/web/security/service/.

Source file: CommonUserService.java

  17 
vote

protected void createUserSession(HttpServletRequest request,HttpServletResponse response,Subject subject,boolean persistent){
  HttpSession session=request.getSession(true);
  session.setAttribute(UserService.SUBJECT,subject);
  saveLocal(subject);
  String sessionKey=HashUtils.generate(subject.getLoginId());
  session.setAttribute(UserService.SESSION_KEY,sessionKey);
  Cookie cookieKey=new Cookie("iddb-k",sessionKey);
  Cookie cookieUser=new Cookie("iddb-u",subject.getKey().toString());
  cookieKey.setPath(request.getContextPath() + "/");
  cookieUser.setPath(request.getContextPath() + "/");
  if (persistent) {
    cookieKey.setMaxAge(COOKIE_EXPIRE_REMEMBER);
    cookieUser.setMaxAge(COOKIE_EXPIRE_REMEMBER);
  }
 else {
    cookieKey.setMaxAge(-1);
    cookieUser.setMaxAge(-1);
  }
  response.addCookie(cookieKey);
  response.addCookie(cookieUser);
  log.trace("Create new session {}, {}, {}",new String[]{sessionKey,subject.getKey().toString(),request.getRemoteAddr()});
  createSession(sessionKey,subject.getKey(),request.getRemoteAddr());
}
 

Example 41

From project jboss-jsp-api_spec, under directory /src/main/java/javax/servlet/jsp/el/.

Source file: ImplicitObjectELResolver.java

  17 
vote

/** 
 * Creates the Map that maps cookie name to the first matching Cookie in request.getCookies().
 */
public static Map createCookieMap(PageContext pContext){
  HttpServletRequest request=(HttpServletRequest)pContext.getRequest();
  Cookie[] cookies=request.getCookies();
  Map ret=new HashMap();
  for (int i=0; cookies != null && i < cookies.length; i++) {
    Cookie cookie=cookies[i];
    if (cookie != null) {
      String name=cookie.getName();
      if (!ret.containsKey(name)) {
        ret.put(name,cookie);
      }
    }
  }
  return ret;
}
 

Example 42

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/lang/jstl/.

Source file: ImplicitObjects.java

  17 
vote

/** 
 * Creates the Map that maps cookie name to the first matching Cookie in request.getCookies().
 */
public static Map createCookieMap(PageContext pContext){
  HttpServletRequest request=(HttpServletRequest)pContext.getRequest();
  Cookie[] cookies=request.getCookies();
  Map ret=new HashMap();
  for (int i=0; cookies != null && i < cookies.length; i++) {
    Cookie cookie=cookies[i];
    if (cookie != null) {
      String name=cookie.getName();
      if (!ret.containsKey(name)) {
        ret.put(name,cookie);
      }
    }
  }
  return ret;
}
 

Example 43

From project jbossportletbridge, under directory /core/portletbridge-impl/src/main/java/org/jboss/portletbridge/context/.

Source file: AbstractExternalContext.java

  17 
vote

@Override public void addResponseCookie(String name,String value,Map<String,Object> properties){
  Cookie cookie=new Cookie(name,value);
  if (properties != null && properties.size() != 0) {
    for (    Map.Entry<String,Object> entry : properties.entrySet()) {
      String key=entry.getKey();
      ALLOWABLE_COOKIE_PROPERTIES p=ALLOWABLE_COOKIE_PROPERTIES.valueOf(key);
      Object v=entry.getValue();
switch (p) {
case domain:
        cookie.setDomain((String)v);
      break;
case maxAge:
    cookie.setMaxAge((Integer)v);
  break;
case path:
cookie.setPath((String)v);
break;
case secure:
cookie.setSecure((Boolean)v);
break;
default :
throw new IllegalStateException();
}
}
}
((PortletResponse)response).addProperty(cookie);
}
 

Example 44

From project Jetwick, under directory /src/main/java/de/jetwick/ui/.

Source file: MySession.java

  17 
vote

public void onNewSession(WebRequest request,ElasticUserSearch uSearch){
  if (!twitterSearchInitialized) {
    twitterSearchInitialized=true;
    Cookie cookie=request.getCookie(TwitterSearch.COOKIE);
    if (cookie != null) {
      setUser(uSearch.findByTwitterToken(cookie.getValue()));
      if (user != null) {
        user.setLastVisit(new Date());
        uSearch.save(user,false);
        logger.info("Found cookie for user:" + getUser().getScreenName());
      }
    }
 else     logger.info("No cookie found. IP=" + request.getHttpServletRequest().getRemoteHost());
  }
}
 

Example 45

From project LGDEditTool, under directory /src/java/LGDEditTool/SiteHandling/.

Source file: User.java

  17 
vote

/** 
 * Creates to cookies, one contains the username (email), the other is a md5-hash and determines whether the user is logged in or not.
 * @param response HTTP response, for saving the cookies
 * @throws Exception 
 */
public void createCookie(HttpServletResponse response) throws Exception {
  if (this.username.equals(""))   return;
  Cookie u=new Cookie("lgd_username",this.username);
  u.setMaxAge(365 * 24 * 60* 60);
  MessageDigest md=MessageDigest.getInstance("MD5");
  md.update((this.username + Boolean.toString(this.loggedIn)).getBytes());
  byte byteData[]=md.digest();
  StringBuilder sb=new StringBuilder();
  for (int i=0; i < byteData.length; i++) {
    sb.append(Integer.toString((byteData[i] & 0xff) + 0x100,16).substring(1));
  }
  Cookie l=new Cookie("lgd_loggedIn",sb.toString());
  l.setMaxAge(60 * 60);
  response.addCookie(u);
  response.addCookie(l);
}
 

Example 46

From project Mockey, under directory /src/java/com/mockey/model/.

Source file: ResponseFromService.java

  17 
vote

private void setCookiesFromHeader(Header[] headers){
  for (  Header header : headers) {
    if (header.getName().equals("Set-Cookie")) {
      String headerValue=header.getValue();
      String[] fields=headerValue.split(";\\s*");
      String expires=null;
      String path=null;
      String domain=null;
      boolean secure=false;
      boolean httpOnly=false;
      for (int j=1; j < fields.length; j++) {
        if ("secure".equalsIgnoreCase(fields[j])) {
          secure=true;
        }
 else         if ("httpOnly".equalsIgnoreCase(fields[j])) {
          httpOnly=true;
        }
 else         if (fields[j].indexOf('=') > 0) {
          String[] f=fields[j].split("=");
          if ("expires".equalsIgnoreCase(f[0])) {
            expires=f[1];
          }
 else           if ("domain".equalsIgnoreCase(f[0])) {
            domain=f[1];
          }
 else           if ("path".equalsIgnoreCase(f[0])) {
            path=f[1];
          }
        }
      }
      String[] cookieParts=headerValue.split("=",2);
      String cookieBody=cookieParts[1];
      String[] cookieBodyParts=cookieBody.split("; ");
      Cookie cookie=new Cookie(cookieParts[0],cookieBodyParts[0]);
      this.cookieList.add(cookie);
    }
  }
}
 

Example 47

From project amber, under directory /oauth-2.0/client-demo/src/main/java/org/apache/amber/oauth2/client/demo/controller/.

Source file: AuthzController.java

  16 
vote

@RequestMapping("/authorize") public ModelAndView authorize(@ModelAttribute("oauthParams") OAuthParams oauthParams,HttpServletRequest req,HttpServletResponse res) throws OAuthSystemException, IOException {
  try {
    Utils.validateAuthorizationParams(oauthParams);
    res.addCookie(new Cookie("clientId",oauthParams.getClientId()));
    res.addCookie(new Cookie("clientSecret",oauthParams.getClientSecret()));
    res.addCookie(new Cookie("authzEndpoint",oauthParams.getAuthzEndpoint()));
    res.addCookie(new Cookie("tokenEndpoint",oauthParams.getTokenEndpoint()));
    res.addCookie(new Cookie("redirectUri",oauthParams.getRedirectUri()));
    res.addCookie(new Cookie("scope",oauthParams.getScope()));
    res.addCookie(new Cookie("app",oauthParams.getApplication()));
    OAuthClientRequest request=OAuthClientRequest.authorizationLocation(oauthParams.getAuthzEndpoint()).setClientId(oauthParams.getClientId()).setRedirectURI(oauthParams.getRedirectUri()).setResponseType(ResponseType.CODE.toString()).setScope(oauthParams.getScope()).buildQueryMessage();
    return new ModelAndView(new RedirectView(request.getLocationUri()));
  }
 catch (  ApplicationException e) {
    oauthParams.setErrorMessage(e.getMessage());
    return new ModelAndView("get_authz");
  }
}
 

Example 48

From project components-ness-httpserver_1, under directory /src/test/java/com/nesscomputing/httpserver/log/file/.

Source file: FileRequestLogTest.java

  16 
vote

@Test public void testRequestLogging(){
  final Config config=Config.getFixedConfig("ness.httpserver.request-log.file.enabled","true","ness.httpserver.request-log.file.fields","remoteAddr,cookie:trumpet-json-api-authorization,cookie:not-here,method,requestUri,query,responseCode,responseHeader:Content-Length,elapsedTime");
  final Injector inj=Guice.createInjector(Stage.PRODUCTION,disableStuff(),new LogFieldsModule(),new FileRequestLogModule(config));
  inj.injectMembers(this);
  Assert.assertNotNull(fileRequestLog);
  StringWriter buffer=new StringWriter();
  fileRequestLog.setWriter(new PrintWriter(buffer));
  Request req=createMock(Request.class);
  Response resp=createMock(Response.class);
  expect(req.getRemoteAddr()).andReturn("1.2.3.4").anyTimes();
  Cookie[] cookies={new Cookie("trumpet-JSON-api-AUTHORIZATION","omgwtfbbq")};
  expect(req.getCookies()).andReturn(cookies).anyTimes();
  expect(req.getMethod()).andReturn("GET").anyTimes();
  expect(req.getRequestURI()).andReturn("foo").anyTimes();
  expect(req.getRequestURL()).andReturn(new StringBuffer("foo")).anyTimes();
  expect(req.getQueryString()).andReturn("?bar").anyTimes();
  expect(req.getTimeStamp()).andReturn(10000L).anyTimes();
  expect(resp.getStatus()).andReturn(201).anyTimes();
  expect(resp.getHeader("Content-Length")).andReturn("42").anyTimes();
  replayAll();
  DateTimeUtils.setCurrentMillisFixed(11500);
  fileRequestLog.log(req,resp);
  assertEquals("1.2.3.4\tomgwtfbbq\t\tGET\tfoo\t?bar\t201\t42\t1500\n",buffer.getBuffer().toString());
  verifyAll();
}
 

Example 49

From project molindo-wicket-utils, under directory /src/main/java/at/molindo/wicketutils/utils/.

Source file: WicketUtils.java

  16 
vote

public static Cookie getCookie(final String name){
  final Cookie[] cookies=getHttpServletRequest().getCookies();
  if (cookies == null) {
    return null;
  }
  for (  final Cookie c : cookies) {
    if (name.equals(c.getName())) {
      return c;
    }
  }
  return null;
}
 

Example 50

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/.

Source file: Wiki.java

  15 
vote

/** 
 * Returns the value of the cookie on the client, or "" if there is no such cookie.
 * @param name The name of the cookie.
 * @return The value of the cookie.
 */
public String getCookie(String name){
  for (  Cookie cookie : getContainerContext().getCookies()) {
    if ((name + "").equals(cookie.getName())) {
      String value=cookie.getValue();
      if (value == null)       return "";
      return value;
    }
  }
  return "";
}
 

Example 51

From project core_5, under directory /exo.core.component.security.core/src/main/java/org/exoplatform/services/security/j2ee/websphere/.

Source file: WebsphereFilter.java

  15 
vote

/** 
 * Remove ltpa token cookies.
 * @param req HttpServletRequest
 * @param res HttpServletResponse
 */
private void removeLtpaTokenCookie(HttpServletRequest req,HttpServletResponse res){
  Cookie[] cooks=req.getCookies();
  if (cooks != null) {
    for (    Cookie cook : cooks) {
      if (LOG.isDebugEnabled())       LOG.debug("WebsphereFilter.removeLtpaTokenCookie() cook.getName() = " + cook.getName());
      if (cook != null && (cookieName.equalsIgnoreCase(cook.getName()) || cookieName2.equalsIgnoreCase(cook.getName()))) {
        cook.setMaxAge(0);
        cook.setPath("/");
        res.addCookie(cook);
        if (LOG.isDebugEnabled())         LOG.debug("WebsphereFilter.removeLtpaTokenCookie() REMOVED LtpaToken = ");
      }
    }
  }
}
 

Example 52

From project echo3, under directory /src/server-java/webcontainer/nextapp/echo/webcontainer/.

Source file: ContainerContextImpl.java

  15 
vote

/** 
 * @see nextapp.echo.webcontainer.ContainerContext#addCookie(javax.servlet.http.Cookie)
 */
public void addCookie(Cookie cookie) throws IllegalStateException {
  Connection conn=WebContainerServlet.getActiveConnection();
  if (conn == null) {
    throw new IllegalStateException("No connection available to set cookie.");
  }
  conn.getResponse().addCookie(cookie);
}
 

Example 53

From project hdiv, under directory /hdiv-core/src/main/java/org/hdiv/filter/.

Source file: ResponseWrapper.java

  15 
vote

/** 
 * Adds the specified cookie to the response. It can be called multiple times to set more than one cookie.
 * @param cookie The <code>Cookie</code> to return to the client
 * @see javax.servlet.http.HttpServletResponse#addCookie
 */
public void addCookie(Cookie cookie){
  SavedCookie savedCookie=new SavedCookie(cookie);
  this.cookies.put(savedCookie.getName(),savedCookie);
  this.updateSessionCookies();
  if (this.confidentiality && !this.avoidCookiesConfidentiality) {
    cookie.setValue("0");
  }
  super.addCookie(cookie);
}
 

Example 54

From project i2m-jsf, under directory /src/main/java/dk/i2m/jsf/.

Source file: JsfUtils.java

  15 
vote

/** 
 * Gets the value of a  {@link Cookie} with the given {@code name} from the given  {@code request}.
 * @param request Request from where to extract the  {@link Cookie} value
 * @param name Name of the  {@link Cookie}
 * @return Value of the {@link Cookie} with the given {@code name} or {@code null} if it doesn't exist in the given {@code request}
 * @throws CookieNotFoundException If the requested  {@link Cookie} was not found in the request
 */
public static String getCookieValue(HttpServletRequest request,String name) throws CookieNotFoundException {
  Cookie[] cookies=request.getCookies();
  if (cookies != null) {
    for (    Cookie cookie : cookies) {
      if (name.equals(cookie.getName())) {
        return cookie.getValue();
      }
    }
  }
  throw new CookieNotFoundException(name + " not found in HttpServletRequest");
}
 

Example 55

From project jabox, under directory /bts-chiliproject/src/main/java/org/jabox/its/chiliproject/.

Source file: ChiliprojectRepository.java

  15 
vote

public void addRepository(final Project project,final ChiliprojectRepositoryConfig config,final SCMConnectorConfig scmConfig,final String username,final String password) throws MalformedURLException, IOException, SAXException {
  LOGGER.info("Redmine add Repository: " + scmConfig.getScmUrl());
  if (!config.isAddRepositoryConfiguration()) {
    return;
  }
  List<Cookie> cookies=(List<Cookie>)_wt.getDialog().getCookies();
  for (  Cookie cookie : cookies) {
    _wc.putCookie(cookie.getName(),cookie.getValue());
  }
  PostMethodWebRequest form=new PostMethodWebRequest(config.getServer().getUrl() + "/repositories/edit/" + project.getName());
  form.setParameter("authenticity_token",getAuthenticityToken(_wt.getPageSource()));
  form.setParameter("repository_scm","Subversion");
  form.setParameter("repository[url]",scmConfig.getScmUrl());
  form.setParameter("repository[login]",username);
  form.setParameter("repository[password]",password);
  form.setParameter("commit","Create");
  _wc.getResponse(form);
}
 

Example 56

From project jsf-test, under directory /mock/src/main/java/org/jboss/test/faces/stub/faces/.

Source file: StubExternalContext.java

  15 
vote

@Override public Map getRequestCookieMap(){
  Map<String,Cookie> cookieMap=new HashMap<String,Cookie>();
  if (request != null && request.getCookies() != null) {
    for (    Cookie cookie : request.getCookies()) {
      cookieMap.put(cookie.getName(),cookie);
    }
  }
  return cookieMap;
}
 

Example 57

From project jsfunit, under directory /examples-arquillian/hellojsf/src/test/java/org/jboss/jsfunit/example/hellojsf/.

Source file: FacadeAPITest.java

  15 
vote

private String getCookieValue(JSFServerSession server,String cookieName){
  Object cookie=server.getFacesContext().getExternalContext().getRequestCookieMap().get(cookieName);
  if (cookie != null) {
    return ((Cookie)cookie).getValue();
  }
  return null;
}
 

Example 58

From project juzu, under directory /core/src/test/java/juzu/test/protocol/mock/.

Source file: MockHttpContext.java

  15 
vote

public MockHttpContext(){
  this.cookies=new ArrayList<Cookie>();
  this.scheme="http";
  this.serverPort=80;
  this.serverName="localhost";
  this.contextPath="";
}
 

Example 59

From project lime-mvc, under directory /test/org/zdevra/guice/mvc/.

Source file: TestRequest.java

  15 
vote

public TestRequest(){
  this.attributes=new HashMap<String,Object>();
  this.parameters=new HashMap<String,String>();
  this.headerItems=new HashMap<String,String[]>();
  this.cookies=new LinkedList<Cookie>();
  this.characterEncoding="UTF8";
  this.protocol="HTTP/1.1";
  this.secure=false;
  this.authType="";
  this.method="GET";
  this.content=new ByteArrayInputStream(new byte[]{});
  this.contentSize=0;
  this.contentType="text/html";
  this.contentServlet=new InnerInputStream();
  this.scheme="http";
  this.serverName="localhost";
  this.serverPort=80;
  this.contextPath="";
  this.servletPath="";
  this.infoPath="";
  this.query="";
  this.remoteAddr="";
  this.remoteHost="";
  this.remotePort=0;
  this.localAddr="127.0.0.1";
  this.localHost="localhost";
  this.localPort=80;
}
 

Example 60

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/oauth/client/src/main/java/demo/oauth/client/model/.

Source file: Common.java

  15 
vote

public static String findCookieValue(HttpServletRequest request,String key){
  Cookie[] cookies=request.getCookies();
  for (  Cookie cooky : cookies) {
    if (cooky.getName().equals(key)) {
      return cooky.getValue();
    }
  }
  return "";
}
 

Example 61

From project meetupnow, under directory /src/meetupnow/.

Source file: MUCookie.java

  15 
vote

public static String getCookie(javax.servlet.http.Cookie[] c){
  if (c != null) {
    for (int i=0; i < c.length; i++) {
      if (c[i].getName().equals("meetup_access")) {
        return c[i].getValue();
      }
    }
  }
  return "empty";
}