Example usage for javax.servlet.http Cookie getValue

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

Introduction

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

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetWithCookiesFormHelperImpl.java

@Override
protected String getRawFormData(final String formName, final SlingHttpServletRequest request,
        final SlingHttpServletResponse response) {
    final String cookieName = getGetLookupKey(formName);
    final Cookie cookie = CookieUtil.getCookie(request, cookieName);

    String data = "";
    if (response != null && cookie != null) {
        CookieUtil.dropCookies(request, response, ROOT_COOKIE_PATH, cookieName);
        // Get the QP lookup for this form
        data = this.decode(cookie.getValue());
    } else {/*from  w w  w .ja v a 2 s. c o  m*/
        log.warn(
                "SlingHttpServletResponse required for removing cookie. Please use formHelper.getForm({}, slingRequest, slingResponse);",
                formName);
    }
    return data;
}

From source file:com.enonic.vertical.adminweb.ResourceHandlerServlet.java

public void handlerMenu(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        AdminService admin, ExtendedMap formItems, ExtendedMap parameters, User user, Document verticalDoc)
        throws VerticalAdminException, TransformerException, IOException {

    //get resource tree xml
    ResourceFolder root = resourceService.getResourceRoot();
    ResourceXmlCreator xmlCreator = new ResourceXmlCreator();
    xmlCreator.setIncludeFullPath(true);
    xmlCreator.setListFolders(true);//w w w. j a  v  a  2s  . com
    xmlCreator.setListResources(false);
    XMLDocument resourcesDoc = xmlCreator.createResourceTreeXml(root);

    Cookie cookie = CookieUtil.getCookie(request, "resourcePickerPath");
    if (cookie != null) {
        try {
            String resourcePickerPathBase64AndUrlEncoded = cookie.getValue();
            String resourcePickerPathBase64Encoded = UrlPathDecoder
                    .decode(resourcePickerPathBase64AndUrlEncoded);
            String resourcePickerPath = new String(Base64Util.decode(resourcePickerPathBase64Encoded), "UTF-8");
            if (resourcePickerPath != null) {
                parameters.put("path", resourcePickerPath);
            }
        } catch (IllegalArgumentException e) {
            LOG.warn("Value in Cookie 'resourcePickerPath' is not base64 encoded ");
        }

    }

    // add popup parameters
    parameters.put("mimetype", formItems.get("mimetype", ""));
    parameters.put("extension", formItems.get("extension", ""));
    parameters.put("fieldname", formItems.get("fieldname"));
    parameters.put("subop", formItems.get("subop", ""));
    parameters.put("sourceKey", formItems.get("sourceKey", ""));
    parameters.put("destinationKey", formItems.get("destinationKey", ""));

    transformXML(request, response, resourcesDoc.getAsDOMDocument(), "resource_selector_frame1.xsl",
            parameters);
}

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");
        }//from   ww  w  . j  a  va2s. c om
    }
    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: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() + ")");
                    }//  www  .ja  v  a 2s  .co  m
                    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;
}

From source file:com.duroty.application.admin.utils.AdminDefaultAction.java

/**
 * DOCUMENT ME!/*from w ww .j  ava 2 s .  c  o  m*/
 *
 * @param request DOCUMENT ME!
 * @param response DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws LanguageControlException DOCUMENT ME!
 */
protected Locale languageControl(HttpServletRequest request, HttpServletResponse response)
        throws LanguageControlException {
    Preferences preferences = null;
    String language = null;
    String name = Configuration.properties.getProperty(Configuration.COOKIE_LANGUAGE);
    int maxAge = Integer.parseInt(Configuration.properties.getProperty(Configuration.COOKIE_MAX_AGE));

    Cookie cookie = CookieManager.getCookie(name, request);

    if (cookie != null) {
        language = cookie.getValue();
        cookie.setMaxAge(maxAge);
        CookieManager.setCookie("/", cookie, response);
    } else {
    }

    try {
        preferences = getPreferencesInstance(request);
        language = preferences.getPreferences().getLanguage();
    } catch (RemoteException e) {
    } catch (NamingException e) {
    } catch (CreateException e) {
    } catch (MailException e) {
    }

    Boolean b = new Boolean(Configuration.properties.getProperty(Configuration.AUTO_LOCALE));
    boolean autoLocale = b.booleanValue();

    if (language == null) {
        if (!autoLocale) {
            throw new LanguageControlException("Choose Language. The language is empty", null);
        } else {
            language = Configuration.properties.getProperty(Configuration.DEFAULT_LANGUAGE);
        }
    }

    cookie = new Cookie(name, language);
    cookie.setMaxAge(maxAge);
    CookieManager.setCookie("/", cookie, response);

    return new Locale(language);
}

From source file:com.salesmanager.core.util.www.SalesManagerInterceptor.java

public String intercept(ActionInvocation invoke) throws Exception {
    try {/*from  www. j  av a  2 s . com*/

        HttpServletRequest req = (HttpServletRequest) ServletActionContext.getRequest();
        HttpServletResponse resp = (HttpServletResponse) ServletActionContext.getResponse();

        req.setCharacterEncoding("UTF-8");

        // get cookies
        Map cookiesMap = new HashMap();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                cookiesMap.put(cookie.getName(), cookie);
            }
        }

        /**
         * MERCHANT ID
         */

        // look at merchantId in url parameter
        String merchantId = (String) req.getParameter("merchantId");

        Cookie storeCookie = (Cookie) cookiesMap.get("STORE");

        int iMerchantId = Constants.DEFAULT_MERCHANT_ID;
        MerchantStore store = null;

        if (StringUtils.isBlank(merchantId)) {// no merchantId in the
            // request

            // check for store
            store = (MerchantStore) req.getSession().getAttribute("STORE");

            if (merchantId == null) {

                if (store != null) {

                    iMerchantId = store.getMerchantId();
                } else {
                    // check for cookie
                    Cookie c = (Cookie) cookiesMap.get("STORE");
                    if (c != null && !StringUtils.isBlank(c.getValue())) {

                        String v = c.getValue();
                        iMerchantId = Integer.valueOf(v);
                    } else {
                        // assign defaultMerchantId
                        iMerchantId = Constants.DEFAULT_MERCHANT_ID;
                    }
                    // set store
                    store = this.setMerchantStore(req, resp, merchantId);
                    if (store == null) {
                        return "NOSTORE";
                    }
                }
            }

        } else {// merchantId in the request

            // check for store in the session
            store = (MerchantStore) req.getSession().getAttribute("STORE");

            if (store != null) {
                // check if both match
                if (!merchantId.equals(String.valueOf(store.getMerchantId()))) {// if they differ
                    store = this.setMerchantStore(req, resp, merchantId);
                } else {
                    iMerchantId = store.getMerchantId();
                }

            } else {
                // set store
                store = this.setMerchantStore(req, resp, merchantId);
                if (store == null) {
                    return "NOSTORE";
                }
            }
        }

        req.setAttribute("STORE", store);

        if (StringUtils.isBlank(store.getTemplateModule())) {
            return "NOSTORE";
        }

        req.setAttribute("templateId", store.getTemplateModule());

        ActionContext ctx = ActionContext.getContext();
        LocaleUtil.setLocaleForRequest(req, resp, ctx, store);

        HttpSession session = req.getSession();
        Principal p = (Principal) session.getAttribute("PRINCIPAL");

        if (p != null) {
            try {
                SalesManagerPrincipalProxy proxy = new SalesManagerPrincipalProxy(p);
                BaseActionAware action = ((BaseActionAware) invoke.getAction());
                action.setPrincipalProxy(proxy);
            } catch (Exception e) {
                log.error("The current action does not implement PrincipalAware "
                        + invoke.getAction().getClass());
            }
        }

        String r = baseIntercept(invoke, req, resp);
        if (r != null) {
            return r;
        }

        return invoke.invoke();

    } catch (Exception e) {
        log.error(e);
        ActionSupport action = (ActionSupport) invoke.getAction();
        action.addActionError(action.getText("errors.technical") + " " + e.getMessage());
        if (e instanceof ActionException) {
            return Action.ERROR;
        } else {
            return "GENERICERROR";
        }

    }

}

From source file:com.ei.itop.common.tag.MessageTag.java

private Locale getLocale() {
    Cookie cookie = WebUtils.getCookie((HttpServletRequest) pageContext.getRequest(), "locale");
    if (cookie != null) {
        return StringUtils.parseLocaleString(cookie.getValue());
    } else {//w  ww .jav  a2 s  . c  o  m
        return Locale.ENGLISH;
    }
}

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

/**
 * searchcookie?/*from  ww  w.ja  v  a  2s .co 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:org.obiba.shiro.web.filter.AuthenticationFilter.java

private String extractSessionId(HttpServletRequest request, @Nullable Cookie sessionCookie) {
    String sessionId = request.getHeader(headerCredentials);
    if (sessionId == null) {
        Cookie safeSessionCookie = sessionCookie == null ? WebUtils.getCookie(request, sessionIdCookieName)
                : sessionCookie;/*from  w  w w.  ja  v  a2  s . com*/
        if (safeSessionCookie != null) {
            sessionId = safeSessionCookie.getValue();
        }
    }
    return sessionId;
}

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 ww  w. j  a va 2 s  . com*/

    //        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();
}