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:fr.smile.liferay.EsigatePortlet.java

/**
 * Transform request to IncominqRequest/*from ww w. j  av a2s  .com*/
 *
 * @param request
 * @param method
 * @return an incoming request
 * @throws IOException
 */
public IncomingRequest create(PortletRequest request, String method) throws IOException {

    HttpServletRequest httpServletRequest = PortalUtil
            .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));

    StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL);

    StringBuilder query = new StringBuilder();
    Enumeration<String> parameters = request.getParameterNames();
    String sep = "";
    while (parameters.hasMoreElements()) {
        String name = parameters.nextElement();
        String[] values = request.getParameterValues(name);
        if (!name.equals(ACTION_PARAMETER)) {
            for (String value : values) {
                query.append(sep);
                query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8"));
                sep = "&";
            }
        }
    }

    ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0);

    if (method.equals("GET")) {
        if (!query.toString().isEmpty()) {
            if (!uri.toString().contains("?")) {
                uri.append("?");
            } else {
                uri.append("&");
            }
            uri.append(query);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion "
                + protocolVersion);
    }
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(method, uri.toString(), protocolVersion));

    if (method.equals("POST")) {
        // create entity
        InputStream inputStream = IOUtils.toInputStream(query.toString());

        if (inputStream != null) {
            // Copy entity-related headers
            InputStreamEntity entity = new InputStreamEntity(inputStream, query.length());
            String contentTypeHeader = httpServletRequest.getContentType();
            if (contentTypeHeader != null) {
                entity.setContentType(contentTypeHeader);
            }
            String contentEncodingHeader = httpServletRequest.getCharacterEncoding();
            if (contentEncodingHeader != null) {
                entity.setContentEncoding(contentEncodingHeader);
            }
            builder.setEntity(entity);
        }
    }

    HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null);
    builder.setContext(context);
    builder.setRemoteAddr(httpServletRequest.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());
    // Copy cookies
    javax.servlet.http.Cookie[] src = request.getCookies();

    if (src != null) {
        LOG.debug("Copying " + src.length + " cookie(s) to response.");
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            dest.setSecure(c.getSecure());
            dest.setDomain(c.getDomain());
            dest.setPath(c.getPath());
            dest.setComment(c.getComment());
            dest.setVersion(c.getVersion());
            builder.addCookie(dest);
        }
    }

    builder.setSession(new HttpServletSession(httpServletRequest));

    IncomingRequest incomingRequest = builder.build();
    return incomingRequest;

}

From source file:com.activecq.experiments.redis.impl.RedisSessionUtilImpl.java

@Override
public String createSession(final SlingHttpServletRequest request, final SlingHttpServletResponse response) {
    if (this.hasValidSession(request)) {
        return this.getId(request);
    }/*w ww . j a va2s. co m*/

    final Cookie cookie = this.createSessionCookie();
    final String sessionId = cookie.getValue();

    this.initSession(sessionId);
    response.addCookie(cookie);

    return sessionId;
}

From source file:com.medallia.spider.SpiderServlet.java

private void addCookie(final Map<String, String> m, Cookie c) {
    m.put(c.getName(), c.getValue());
}

From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 * Validate the Authentication Cookie/*from w  ww . ja  v a 2 s.c  o m*/
 *
 * @param request
 * @param cookieName
 * @param secret
 * @return
 */
@Override
public SimpleCredentials extractCredentials(HttpServletRequest request) {
    Cookie cookie = CookieUtil.getCookie(request, cookieName);

    if (cookie == null) {
        return null;
    }

    // Get and decode cookie data
    String cookieData;
    try {
        if (StringUtils.isBlank(cookie.getValue())) {
            return null;
        }
        final String tmp = new Base64(true).decode(cookie.getValue()).toString();
        cookieData = URLDecoder.decode(tmp, cookieEncoding);
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    // Split the cookie data by the DATA_DELIMITER
    String[] values = splitCookieData(cookieData);

    if (values == null) {
        return null;
    }

    final String token = StringUtils.trimToNull(values[0]);
    final String timestamp = StringUtils.trimToNull(values[1]);
    final String userId = StringUtils.trimToNull(values[2]);

    // Could not get a required value from the cookie
    if (userId == null || token == null || timestamp == null) {
        return null;
    }

    final String expectedData;
    try {
        expectedData = encryptData(createDataToEncrypt(userId, timestamp));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CookieAuthenticationImpl.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

    // If Cookie token and Expected token don't match, return null
    if (!StringUtils.equals(token, expectedData)) {
        return null;
    }

    // TODO: Handle cookie timestamping more appropriately.

    // Check if the current time is greater than the acceptable cookie
    // expiry timestamp
    // long cookieTimestamp = Long.parseLong(timestamp);
    // if (System.currentTimeMillis() > cookieTimestamp) {
    //    return null;
    // }

    return new SimpleCredentials(userId, "".toCharArray());
}

From source file:com.liusoft.dlog4j.velocity.VelocityTool.java

public int get_cookie_as_int(String key) {
    Cookie cookie = RequestUtils.getCookie(request, key);
    if (cookie == null)
        return -1;
    try {/* w w  w.  j  a v a  2 s.  co m*/
        return Integer.parseInt(cookie.getValue());
    } catch (Exception e) {
    }
    return -1;
}

From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java

private String retrieveAuthTokenString(Cookie[] cookies) {

    /* no cookies */
    if (cookies == null)
        return null;
    for (Cookie c : cookies) {
        if (c.getName().equals(ConfigurationListener.getTokenName())) {
            /* found correct cookie */
            return c.getValue();
        }/*  w  ww  .jav a  2s.  c o  m*/
    }
    return null;
}

From source file:org.toobsframework.pres.component.Component.java

/**
 * Get the objects associated to this component
 * @param paramsIn - the parameters sent to the datasource to obtain th object
 * @param paramsOut/* ww  w  .  j a va2 s . c  o  m*/
 * @return an array of all the objects implementing IDataSourceObject
 */
public IDataProviderObject[] getObjects(IRequest request, Map<String, Object> paramsIn,
        Map<String, Object> paramsOut, IXMLTransformerHelper transformerHelper)
        throws ComponentException, ComponentNotInitializedException, ParameterException {
    List<IDataProviderObject> allObjects = new ArrayList<IDataProviderObject>();
    if (!this.initDone) {
        ComponentNotInitializedException ex = new ComponentNotInitializedException();
        ex.setComponentId(this.id);
        throw ex;
    }

    int len = objectsConfig.length;
    for (int i = 0; i < len; i++) {
        Map<String, Object> params = new HashMap<String, Object>(paramsIn);
        GetObject thisObjDef = objectsConfig[i];
        //Fix the params using the param mapping for 
        //this configuration.
        if (thisObjDef.getParameters() != null) {
            ParameterUtil.mapParameters(request,
                    "Component:" + this.id + ":GetObject:" + thisObjDef.getServiceProvider(),
                    thisObjDef.getParameters().getParameter(), params, params, this.id, allObjects);
        }

        List<IDataProviderObject> theseObjects = new ArrayList<IDataProviderObject>();

        //Call the appropriate action.
        Map<String, Object> outParams = new HashMap<String, Object>();
        // TODO: JG I need to put the cookies: notations into into parameters
        if (thisObjDef.getAction().equals("getCookie")) {
            String searchCriteria = ParameterUtil.resolveParam(request, thisObjDef.getSearchCriteria(),
                    params)[0];
            String thisGuidParam = ParameterUtil.resolveParam(request, thisObjDef.getGuidParam(), params)[0];
            String cookieName = (searchCriteria != null ? searchCriteria : "");
            Object guidValue = params.get(thisGuidParam);
            if (guidValue != null && guidValue.getClass().isArray()) {
                cookieName += ((String[]) guidValue)[0];
            } else {
                cookieName += guidValue;
            }
            String cookieValue = null;

            Cookie[] cookies = request.getHttpRequest().getCookies();
            if (cookies != null) {
                for (int c = 0; c < cookies.length; c++) {
                    Cookie cookie = cookies[c];
                    if (cookie.getName().equals(cookieName)) {
                        cookieValue = cookie.getValue();
                        break;
                    }
                }
            }
            if (cookieName != null && cookieValue != null) {
                theseObjects.add(this.createObject(new CookieVO(cookieName, cookieValue)));
            }
        } else {
            theseObjects.add(getDispatchedObject(request, thisObjDef, params, outParams));
        }
        // TODO SNIP!!!
        ParameterUtil.mapScriptParams(outParams, paramsIn);
        if (thisObjDef.getOutputParameters() != null) {
            ParameterUtil.mapOutputParameters(request, thisObjDef.getOutputParameters().getParameter(),
                    paramsIn, this.id, theseObjects);
            if (paramsOut != null) {
                ParameterUtil.mapOutputParameters(request, thisObjDef.getOutputParameters().getParameter(),
                        paramsOut, this.id, theseObjects);
            }
        }
        allObjects.addAll(theseObjects);
    }

    IDataProviderObject[] objArray = new IDataProviderObject[allObjects.size()];
    objArray = allObjects.toArray(objArray);
    return objArray;
}

From source file:com.zimbra.cs.service.ExternalUserProvServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String param = req.getParameter("p");
    if (param == null) {
        throw new ServletException("request missing param");
    }/*from w  ww. java2 s . co  m*/
    Map<Object, Object> tokenMap = validatePrelimToken(param);
    Map<String, String> reqHeaders = new HashMap<String, String>();
    String ownerId = (String) tokenMap.get("aid");
    String folderId = (String) tokenMap.get("fid");
    String extUserEmail = (String) tokenMap.get("email");

    Provisioning prov = Provisioning.getInstance();
    Account grantee;
    try {
        Account owner = prov.getAccountById(ownerId);
        Domain domain = prov.getDomain(owner);
        grantee = prov.getAccountByName(mapExtEmailToAcctName(extUserEmail, domain));
        if (grantee == null) {
            // external virtual account not created yet
            if (prov.isOctopus() && DebugConfig.skipVirtualAccountRegistrationPage) {
                // provision using 'null' password and display name
                // UI will ask the user to set these post provisioning
                provisionVirtualAccountAndRedirect(req, resp, null, null, ownerId, extUserEmail);
            } else {
                resp.addCookie(new Cookie("ZM_PRELIM_AUTH_TOKEN", param));
                req.setAttribute("extuseremail", extUserEmail);
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("extuseremail", extUserEmail);
                    reqHeaders.put("ZM_PRELIM_AUTH_TOKEN", param);
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(EXT_USER_PROV_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    ServletContext context = getServletContext().getContext("/zimbra");
                    if (context != null) {
                        RequestDispatcher dispatcher = context.getRequestDispatcher(PUBLIC_EXTUSERPROV_JSP);
                        dispatcher.forward(req, resp);
                    } else {
                        logger.warn("Could not access servlet context url /zimbra");
                        throw ServiceException.TEMPORARILY_UNAVAILABLE();
                    }
                }
            }
        } else {
            // create a new mountpoint in the external user's mailbox if not already created

            String[] sharedItems = owner.getSharedItem();
            int sharedFolderId = Integer.valueOf(folderId);
            String sharedFolderPath = null;
            MailItem.Type sharedFolderView = null;
            for (String sharedItem : sharedItems) {
                ShareInfoData sid = AclPushSerializer.deserialize(sharedItem);
                if (sid.getItemId() == sharedFolderId && extUserEmail.equalsIgnoreCase(sid.getGranteeId())) {
                    sharedFolderPath = sid.getPath();
                    sharedFolderView = sid.getFolderDefaultViewCode();
                    break;
                }
            }
            if (sharedFolderPath == null) {
                throw new ServletException("share not found");
            }
            String mountpointName = getMountpointName(owner, grantee, sharedFolderPath);

            ZMailbox.Options options = new ZMailbox.Options();
            options.setNoSession(true);
            options.setAuthToken(AuthProvider.getAuthToken(grantee).toZAuthToken());
            options.setUri(AccountUtil.getSoapUri(grantee));
            ZMailbox zMailbox = new ZMailbox(options);
            ZMountpoint zMtpt = null;
            try {
                zMtpt = zMailbox.createMountpoint(String.valueOf(getMptParentFolderId(sharedFolderView, prov)),
                        mountpointName, ZFolder.View.fromString(sharedFolderView.toString()),
                        ZFolder.Color.DEFAULTCOLOR, null, ZMailbox.OwnerBy.BY_ID, ownerId,
                        ZMailbox.SharedItemBy.BY_ID, folderId, false);
            } catch (ServiceException e) {
                logger.debug("Error in attempting to create mountpoint. Probably it already exists.", e);
            }
            if (zMtpt != null) {
                if (sharedFolderView == MailItem.Type.APPOINTMENT) {
                    // make sure that the mountpoint is checked in the UI by default
                    FolderActionSelector actionSelector = new FolderActionSelector(zMtpt.getId(), "check");
                    FolderActionRequest actionRequest = new FolderActionRequest(actionSelector);
                    try {
                        zMailbox.invokeJaxb(actionRequest);
                    } catch (ServiceException e) {
                        logger.warn("Error in invoking check action on calendar mountpoint", e);
                    }
                }
                HashSet<MailItem.Type> types = new HashSet<MailItem.Type>();
                types.add(sharedFolderView);
                enableAppFeatures(grantee, types);
            }

            // check if the external user is already logged-in
            String zAuthTokenCookie = null;
            javax.servlet.http.Cookie cookies[] = req.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("ZM_AUTH_TOKEN")) {
                        zAuthTokenCookie = cookie.getValue();
                        break;
                    }
                }
            }
            AuthToken zAuthToken = null;
            if (zAuthTokenCookie != null) {
                try {
                    zAuthToken = AuthProvider.getAuthToken(zAuthTokenCookie);
                } catch (AuthTokenException ignored) {
                    // auth token is not valid
                }
            }
            if (zAuthToken != null && !zAuthToken.isExpired() && zAuthToken.isRegistered()
                    && grantee.getId().equals(zAuthToken.getAccountId())) {
                // external virtual account already logged-in
                resp.sendRedirect("/");
            } else if (prov.isOctopus() && !grantee.isVirtualAccountInitialPasswordSet()
                    && DebugConfig.skipVirtualAccountRegistrationPage) {
                // seems like the virtual user did not set his password during his last visit, after an account was
                // provisioned for him
                setCookieAndRedirect(req, resp, grantee);
            } else {
                req.setAttribute("virtualacctdomain", domain.getName());
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("virtualacctdomain", domain.getName());
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(PUBLIC_LOGIN_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    RequestDispatcher dispatcher = getServletContext().getContext("/zimbra")
                            .getRequestDispatcher(PUBLIC_LOGIN_JSP);
                    dispatcher.forward(req, resp);
                }
            }
        }
    } catch (ServiceException e) {
        throw new ServletException(e);
    }
}

From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java

private boolean checkCookiesForToken(HttpServletRequest request, HttpSession session) {
    boolean cookieFound = false;

    // If there is no oauth credential, and the user has a dashboard cookie, add cookie value as
    // oauth session attribute.
    if (session.getAttribute(OAUTH_TOKEN) == null) {
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {

            // Loop through cookies to find dashboard cookie
            for (Cookie c : cookies) {
                if (c.getName().equals(DASHBOARD_COOKIE)) {

                    // DE883. We need to decrypt the cookie value to authenticate the token.
                    String decryptedCookie = null;
                    try {
                        String s = URLDecoder.decode(c.getValue(), "UTF-8");
                        decryptedCookie = propDecryptor.decrypt(s);
                    } catch (Exception e) {
                        LOG.error(e.getMessage());
                    }/*from   w  ww .  j  a va  2s. com*/
                    JsonObject json = restClient.sessionCheck(decryptedCookie);

                    // If user is not authenticated, expire the cookie, else set OAUTH_TOKEN to
                    // cookie value and continue
                    JsonElement authElement = json.get(Constants.ATTR_AUTHENTICATED);
                    if ((authElement != null) && (!authElement.getAsBoolean())) {
                        c.setMaxAge(0);
                        LOG.info(LOG_MESSAGE_AUTH_EXPIRING_COOKIE, new Object[] { request.getRemoteAddr() });
                    } else {
                        cookieFound = true;
                        session.setAttribute(OAUTH_TOKEN, decryptedCookie);
                        LOG.info(LOG_MESSAGE_AUTH_USING_COOKIE, new Object[] { request.getRemoteAddr() });
                    }

                }
            }
        }
    }

    return cookieFound;
}