Example usage for javax.servlet.http Cookie getName

List of usage examples for javax.servlet.http Cookie getName

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

From source file:com.meltmedia.cadmium.servlets.jersey.StatusService.java

@GET
@Path("/health")
@Produces("text/plain")
public String health(@Context HttpServletRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append("Server: " + request.getServerName() + "\n");
    builder.append("Scheme: " + request.getScheme() + "\n");
    builder.append("Port: " + request.getServerPort() + "\n");
    builder.append("ContextPath:  " + request.getContextPath() + "\n");
    builder.append("ServletPath: " + request.getServletPath() + "\n");
    builder.append("Uri: " + request.getRequestURI() + "\n");
    builder.append("Query: " + request.getQueryString() + "\n");
    Enumeration<?> headerNames = request.getHeaderNames();
    builder.append("Headers:\n");
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration<?> headers = request.getHeaders(name);
        builder.append("  '" + name + "':\n");
        while (headers.hasMoreElements()) {
            String headerValue = (String) headers.nextElement();
            builder.append("    -" + headerValue + "\n");
        }/* w w w  . j  a va  2  s .co m*/
    }
    if (request.getCookies() != null) {
        builder.append("Cookies:\n");
        for (Cookie cookie : request.getCookies()) {
            builder.append("  '" + cookie.getName() + "':\n");
            builder.append("    value: " + cookie.getValue() + "\n");
            builder.append("    domain: " + cookie.getDomain() + "\n");
            builder.append("    path: " + cookie.getPath() + "\n");
            builder.append("    maxAge: " + cookie.getMaxAge() + "\n");
            builder.append("    version: " + cookie.getVersion() + "\n");
            builder.append("    comment: " + cookie.getComment() + "\n");
            builder.append("    secure: " + cookie.getSecure() + "\n");
        }
    }
    return builder.toString();
}

From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java

public void validateTicket(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
    // Start with processing message from CDCServlet if this message is available (it should be in servlet request parameter "LARES")
    if (tryMessageFromCDC(httpRequest, httpResponse)) {
        return;/*from w  w w  .  jav a  2 s. c o m*/
    }

    // Now cookie should be set and we can continue with cookie processing
    String token = null;
    Cookie[] cookies = httpRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(this.cookieName)) {
            token = cookie.getValue();
            break;
        }
    }

    if (token == null) {
        throwIllegalStateException("No SSO Tokens Found");
    }

    if (token != null) {
        boolean isValid = this.isTokenValid(token);

        if (!isValid) {
            throwIllegalStateException("OpenSSO Token is not valid!!");
        }

        String subject = this.getSubject(token);
        if (subject != null) {
            this.saveSSOCredentials(subject, httpRequest);
        }
    }
}

From source file:org.apache.unomi.web.EventsCollectorServlet.java

private void doEvent(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Date timestamp = new Date();
    if (request.getParameter("timestamp") != null) {
        timestamp.setTime(Long.parseLong(request.getParameter("timestamp")));
    }//from  www.jav  a 2  s .  co  m

    //        logger.debug(HttpUtils.dumpRequestInfo(request));

    HttpUtils.setupCORSHeaders(request, response);

    String sessionId = request.getParameter("sessionId");
    if (sessionId == null) {
        logger.error(
                "No sessionId found in incoming request, aborting processing. See debug level for more information");
        if (logger.isDebugEnabled()) {
            logger.debug("Request dump:" + HttpUtils.dumpRequestInfo(request));
        }
        return;
    }

    Session session = profileService.loadSession(sessionId, timestamp);
    if (session == null) {
        logger.error("No session found for sessionId={}, aborting request !", sessionId);
        return;
    }

    String profileIdCookieName = "context-profile-id";

    Profile sessionProfile = session.getProfile();
    Profile profile = null;
    if (sessionProfile.getItemId() != null) {
        // Reload up-to-date profile
        profile = profileService.load(sessionProfile.getItemId());
        if (profile == null || profile instanceof Persona) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    } else {
        // Session uses anonymous profile, try to find profile from cookie
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (profileIdCookieName.equals(cookie.getName())) {
                profile = profileService.load(cookie.getValue());
            }
        }
        if (profile == null) {
            logger.error("No valid profile found or persona found for profileId={}, aborting request !",
                    session.getProfileId());
            return;
        }
    }

    String payload = HttpUtils.getPayload(request);
    if (payload == null) {
        logger.error("No event payload found for request, aborting !");
        return;
    }

    ObjectMapper mapper = CustomObjectMapper.getObjectMapper();
    JsonFactory factory = mapper.getFactory();
    EventsCollectorRequest events = null;
    try {
        events = mapper.readValue(factory.createParser(payload), EventsCollectorRequest.class);
    } catch (Exception e) {
        logger.error("Cannot read payload " + payload, e);
        return;
    }
    if (events == null || events.getEvents() == null) {
        logger.error("No events found in payload");
        return;
    }

    String thirdPartyId = eventService.authenticateThirdPartyServer(
            ((HttpServletRequest) request).getHeader("X-Unomi-Peer"), request.getRemoteAddr());

    int changes = 0;

    List<String> filteredEventTypes = privacyService.getFilteredEventTypes(profile.getItemId());

    for (Event event : events.getEvents()) {
        if (event.getEventType() != null) {
            Event eventToSend = new Event(event.getEventType(), session, profile, event.getScope(),
                    event.getSource(), event.getTarget(), event.getProperties(), timestamp);
            if (sessionProfile.isAnonymousProfile()) {
                // Do not keep track of profile in event
                eventToSend.setProfileId(null);
            }

            if (!eventService.isEventAllowed(event, thirdPartyId)) {
                logger.debug("Event is not allowed : {}", event.getEventType());
                continue;
            }
            if (filteredEventTypes != null && filteredEventTypes.contains(event.getEventType())) {
                logger.debug("Profile is filtering event type {}", event.getEventType());
                continue;
            }

            eventToSend.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request);
            eventToSend.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response);
            logger.debug("Received event " + event.getEventType() + " for profile=" + sessionProfile.getItemId()
                    + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp="
                    + timestamp);
            int eventChanged = eventService.send(eventToSend);
            //if the event execution changes the profile
            if ((eventChanged & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
                profile = eventToSend.getProfile();
            }
            changes |= eventChanged;
        }
    }

    if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED) {
        profileService.save(profile);
    }
    if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED) {
        profileService.saveSession(session);
    }

    PrintWriter responseWriter = response.getWriter();
    responseWriter.append("{\"updated\":" + changes + "}");
    responseWriter.flush();
}

From source file:com.alibaba.dubbo.governance.web.governance.module.screen.Providers.java

/**
 * searchcookie?/*from   w  ww . j  a  v a  2  s.c  o m*/
 * ??cookie?????
 * @param context
 * @param value
 */
private void setSearchHistroy(Map<String, Object> context, String value) {
    //?cookie
    String separatorsB = "\\.\\.\\.\\.\\.\\.";
    String newCookiev = value;
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if (c.getName().equals("HISTORY")) {
            String cookiev = c.getValue();
            String[] values = cookiev.split(separatorsB);
            int count = 1;
            for (String v : values) {
                if (count <= 10) {
                    if (!value.equals(v)) {
                        newCookiev = newCookiev + separatorsB + v;
                    }
                }
                count++;
            }
            break;
        }
    }

    Cookie _cookie = new Cookie("HISTORY", newCookiev);
    _cookie.setMaxAge(60 * 60 * 24 * 7); // Cookie30
    _cookie.setPath("/");
    response.addCookie(_cookie); // 
}

From source file:com.skilrock.lms.embedded.roleMgmt.common.PrivsInterceptor.java

public void createCookie() {
    boolean found = false;
    Cookie userSessionId = null;
    Cookie[] cookies = request.getCookies();
    for (Cookie element : cookies) {
        userSessionId = element;/*  w  ww  .  j  ava  2 s .c om*/
        if (userSessionId.getName().equals("LMSCookie")) {
            found = true;
            break;
        }
        if (!found) {
            userSessionId = new Cookie("LMSCookie", "");
            userSessionId.setMaxAge(24 * 60 * 60);
            userSessionId.setPath("/");
            response.addCookie(userSessionId);
        } else {
            userSessionId.setMaxAge(24 * 60 * 60);
            userSessionId.setPath("/");
            response.addCookie(userSessionId);
        }

    }

}

From source file:com.mentor.questa.vrm.jenkins.QuestaVrmHostAction.java

private boolean getActionCookie(StaplerRequest req) {
    boolean showActions = false;

    // check the current preference value
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("HostAction_showActions")) {
                showActions = Boolean.parseBoolean(cookie.getValue());
            }//from www  .j  a v  a 2  s . c om
        }
    }
    return showActions;
}

From source file:com.jaspersoft.jasperserver.war.control.JSCommonController.java

protected void setupLoginPage(HttpServletRequest req) {
    Cookie[] cookies = req.getCookies();
    String locale = null;/* w ww  .j  av  a  2 s.c om*/
    String preferredTz = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals(JasperServerConstImpl.getUserLocaleSessionAttr()))
                locale = cookie.getValue();
            if (cookie.getName().equals(JasperServerConstImpl.getUserTimezoneSessionAttr()))
                preferredTz = cookie.getValue();
        }
    }

    Locale displayLocale = req.getLocale();
    String preferredLocale;
    if (locale == null || locale.length() == 0) {
        preferredLocale = displayLocale.toString();
    } else {
        preferredLocale = locale;
    }

    if (preferredTz == null) {
        preferredTz = timezones.getDefaultTimeZoneID();
    }

    req.setAttribute("preferredLocale", preferredLocale);
    req.setAttribute("userLocales", locales.getUserLocales(displayLocale));
    req.setAttribute("preferredTimezone", preferredTz);
    req.setAttribute("userTimezones", timezones.getTimeZones(displayLocale));
    try {
        if (Integer.parseInt(passwordExpirationInDays) > 0) {
            allowUserPasswordChange = "true";
        }
    } catch (NumberFormatException e) {
        // if the value is NaN, then assume it's non postive.
        // not overwrite allowUserPasswordChange
    }
    req.setAttribute("allowUserPasswordChange", allowUserPasswordChange);
    req.setAttribute("passwordExpirationInDays", passwordExpirationInDays);
    req.setAttribute("passwordPattern", userAuthService.getAllowedPasswordPattern().replace("\\", "\\\\"));
    req.setAttribute("autoCompleteLoginForm", autoCompleteLoginForm);
    req.setAttribute(IS_DEVELOPMENT_ENVIRONMENT_TYPE, false);
    req.setAttribute(USERS_EXCEEDED, false);
    req.setAttribute(BAN_USER, false);
    req.setAttribute("isEncryptionOn", SecurityConfiguration.isEncryptionOn());
}

From source file:com.xwiki.authentication.AbstractAuthServiceImpl.java

protected Cookie getCookie(String cookieName, XWikiContext context) {
    Cookie[] cookies = context.getRequest().getCookies();

    if (cookies == null) {
        return null;
    }/*from   ww  w  .  j  a v a 2s .com*/

    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return cookie;
        }
    }

    return null;
}

From source file:com.evon.injectTemplate.InjectTemplateFilter.java

private String getCookieHashs(HttpServletRequest httpRequest) {
    Cookie cookies[] = httpRequest.getCookies();
    if (cookies == null) {
        return "";
    }/*w w w. j a va2s.com*/
    StringBuffer ret = new StringBuffer();
    for (Cookie cookie : cookies) {
        ret.append(cookie.getName().hashCode());
        ret.append(";");
        ret.append(cookie.getValue().hashCode());
        ret.append(";");
    }
    return ret.toString();
}

From source file:com.zz.globalsession.filter.AbstractGlobalSessionFilter.java

private Cookie getCurrentValidSessionIdCookie(HttpServletRequest req) {
    if (req.getCookies() != null) {
        for (Cookie cookie : req.getCookies()) {
            if (cookie.getName().equals(settings.getSessionIdKey()) && cookie.getValue() != null
                    && cookie.getValue().trim().length() > 0) {
                if (isValidSession(createGlobalSessionRequest(req, cookie.getValue()))) {
                    if (log.isDebugEnabled()) {
                        log.debug("SessionId cookie is found. (" + settings.getSessionIdKey() + " -> "
                                + cookie.getValue() + ")");
                    }/*from   w  ww .jav a 2s .  c  om*/
                    return cookie;
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("SessionId cookie is found but it's invalid. (" + settings.getSessionIdKey()
                                + " -> " + cookie.getValue() + ")");
                    }
                    continue;
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("SessionId cookie is not found.");
    }
    return null;
}