Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Get the password stored (in a cookie) in the request. Also checks the validity of the cookie.
 * //from  w ww. ja  v a2  s. c o  m
 * @param request The servlet request.
 * @param response The servlet response.
 * @return The password value, or <tt>null</tt> if not found or the cookie isn't valid.
 * @todo Also use the URL, in case cookies are disabled [XWIKI-1071].
 */
@Override
public String getRememberedPassword(HttpServletRequest request, HttpServletResponse response) {
    String password = getCookieValue(request.getCookies(), getCookiePrefix() + COOKIE_PASSWORD, DEFAULT_VALUE);
    if (!password.equals(DEFAULT_VALUE)) {
        if (checkValidation(request, response)) {
            if (this.protection.equals(PROTECTION_ALL) || this.protection.equals(PROTECTION_ENCRYPTION)) {
                password = decryptText(password);
            }
            return password;
        }
    }
    return null;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Get the username stored (in a cookie) in the request. Also checks the validity of the cookie.
 * /*ww  w  .j a  va 2 s  .  c  om*/
 * @param request The servlet request.
 * @param response The servlet response.
 * @return The username value, or <tt>null</tt> if not found or the cookie isn't valid.
 * @todo Also use the URL, in case cookies are disabled [XWIKI-1071].
 */
@Override
public String getRememberedUsername(HttpServletRequest request, HttpServletResponse response) {
    String username = getCookieValue(request.getCookies(), getCookiePrefix() + COOKIE_USERNAME, DEFAULT_VALUE);

    if (!username.equals(DEFAULT_VALUE)) {
        if (checkValidation(request, response)) {
            if (this.protection.equals(PROTECTION_ALL) || this.protection.equals(PROTECTION_ENCRYPTION)) {
                username = decryptText(username);
            }
            return username;
        }
    }
    return null;
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <p>Lookup a client conference number stored in a cookie. If no phone number is provided by the client a random SIP URI phone number is automatically generated.</p>
 * <p>A conference definition template file is used to create the conference definition for the phone number.</p>
 * <p>The auto-assigned phone number is then stored in a cookie and returned to the client.</p>
 * @param out standard output Output writer
 * @param request The HTTP request object
 * @param response The HTTP response object
 *///from   w ww.j a va 2  s.co  m
private boolean doCreateNumber(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String strOutputNumber = null;

    Cookie[] arrCookies = request.getCookies();
    if (null != arrCookies) {
        for (Cookie cookie : arrCookies) {
            //logger.debug("cookie name: " + cookie.getName() + ", path: " + cookie.getPath() + ", domain: " + cookie.getDomain() + ", maxAge: " + cookie.getMaxAge() + ", value: " + cookie.getValue());
            if (COOKIE_NUMBER_KEY.equals(cookie.getName())) {
                if (null != (strOutputNumber = cookie.getValue()) && strOutputNumber.length() == 0) {
                    strOutputNumber = null;
                }
                logger.debug("Using cookie stored conference output number: '" + strOutputNumber + "'.");
                break;
            }
        }
    }

    strOutputNumber = createConferenceDefinition(strOutputNumber);

    if (null != strOutputNumber) {

        int cookieAgeDays = 7;
        Cookie cookie = new Cookie(COOKIE_NUMBER_KEY, strOutputNumber);
        cookie.setMaxAge(cookieAgeDays * SECONDS_IN_DAY);
        cookie.setPath("/" + getUriDirSegment(request.getRequestURI(), 0) + "/");
        logger.debug("Setting cookie " + COOKIE_NUMBER_KEY + "=" + strOutputNumber);
        response.addCookie(cookie);
        out.println("number=" + strOutputNumber);
    }

    return true;
}

From source file:custom.application.login.java

public Object validate() {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST");
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE");

    Cookie cookie = StringUtilities.getCookieByName(request.getCookies(), "username");
    if (cookie != null) {
        this.setVariable("username", cookie.getValue());
        String user_field = cookie.getValue()
                + "<input class=\"text\" id=\"username\" name=\"username\" type=\"hidden\" value=\""
                + cookie.getValue()//from   ww w.  ja  v a 2s . co  m
                + "\"/>  <a href=\"javascript:void(0)\" onclick=\"restoreField()\">[%login.user.change%]</a>";

        this.setVariable("user_field", user_field);
    } else {
        this.setVariable("username", "");
        this.setVariable("user_field",
                "<input class=\"text\" id=\"username\" name=\"username\" type=\"text\" value=\"\"/>");
    }

    this.setText("login.tips.text", this.getLink("bible"));

    try {
        Reforward reforward = new Reforward(request, response);

        if (request.getMethod().equalsIgnoreCase("post")) {
            this.passport = new passport(request, response, "waslogined");
            if (this.passport.login()) {
                reforward.forward();
            }
        }

        this.setVariable("from", reforward.getFromURL());
    } catch (ApplicationException e) {
        this.setVariable("error", "<div class=\"error\">" + e.getRootCause().getMessage() + "</div>");
    }

    this.setVariable("action",
            this.config.get("default.base_url") + this.context.getAttribute("REQUEST_ACTION").toString());

    HttpSession session = request.getSession();
    if (session.getAttribute("usr") != null) {
        this.usr = (User) session.getAttribute("usr");

        this.setVariable("user.status", "");
        this.setVariable("user.profile",
                "<a href=\"javascript:void(0)\" onmousedown=\"profileMenu.show(event,'1')\">"
                        + this.usr.getEmail() + "</a>");
    } else {
        this.setVariable("user.status", "<a href=\"" + this.getLink("user/login") + "\">"
                + this.getProperty("page.login.caption") + "</a>");
        this.setVariable("user.profile", "");
    }

    return this;
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Remove a cookie./*from www  .  j a  va 2  s.co  m*/
 * 
 * @param request The servlet request.
 * @param response The servlet response.
 * @param cookieName The name of the cookie that must be removed.
 */
private void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
    Cookie cookie = getCookie(request.getCookies(), cookieName);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setPath(this.cookiePath);
        addCookie(response, cookie);
        String cookieDomain = getCookieDomain(request);
        if (cookieDomain != null) {
            cookie.setDomain(cookieDomain);
            addCookie(response, cookie);
        }
    }
}

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

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String displayName = req.getParameter("displayname");
    String password = req.getParameter("password");

    String prelimToken = null;/*from w  ww.  j av  a  2s.c  o  m*/
    javax.servlet.http.Cookie cookies[] = req.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("ZM_PRELIM_AUTH_TOKEN")) {
                prelimToken = cookie.getValue();
                break;
            }
        }
    }
    if (prelimToken == null) {
        throw new ServletException("unauthorized request");
    }
    Map<Object, Object> tokenMap = validatePrelimToken(prelimToken);
    String ownerId = (String) tokenMap.get("aid");
    //        String folderId = (String) tokenMap.get("fid");
    String extUserEmail = (String) tokenMap.get("email");

    provisionVirtualAccountAndRedirect(req, resp, displayName, password, ownerId, extUserEmail);
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

protected ActionForward process(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response, String name) {
    ActionForward forward = null;//from   w  ww  .  j  av  a2s .co  m

    AdminBean adminBean = getAdminBean(request);
    if (adminBean == null) {
        Cookie cookies[] = request.getCookies();
        if (cookies == null) {
            return actionMapping.findForward("sessionexpire");
        }
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals(Constants.SESSION_COOKIE_USER)) {
                return actionMapping.findForward("sessionexpire");
            }
        }
        return actionMapping.findForward("login");
    }

    EntityManager em = null;
    try {
        em = JpaConnection.getInstance().getCurrentEntityManager();
        em.getTransaction().begin();

        if (actionMapping instanceof AdminActionMapping) {
            AdminActionMapping adminMapping = (AdminActionMapping) actionMapping;
            String userTypes = adminMapping.getUserTypes();
            String tokens[] = userTypes.split(",");
            User user = adminBean.getUser();
            String userType = user.getUserType();
            boolean found = false;
            for (int i = 0; i < tokens.length; i++) {
                if (userType.equals(tokens[i])) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new com.jada.admin.SecurityException(
                        "user " + user.getUserId() + " is blocked from accessing " + actionMapping.getPath());
            }
        }

        logger.debug("RequestURL  > " + request.getRequestURL());
        logger.debug("QueryString > " + request.getQueryString());
        if (Utility.getLogLevel(logger).equals(Level.DEBUG)) {
            logger.debug("Request Information ...");
            Enumeration<?> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String key = (String) enumeration.nextElement();
                String line = "";
                line += "key=" + key + " value=";
                String values[] = request.getParameterValues(key);
                for (int i = 0; i < values.length; i++) {
                    if (i > 0) {
                        line += ",";
                    }
                    line += "[" + values[i] + "]";
                }
                logger.debug(line);
            }
        }
        AdminMaintActionForm form = (AdminMaintActionForm) actionForm;
        forward = customProcess(actionMapping, form, request, response, name);

        em = JpaConnection.getInstance().getCurrentEntityManager();
        if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
        }
        if (form != null) {
            if (form.isStream) {
                streamWebService(response, form.getStreamData());
            } else {
                encodeForm(form);
            }
        }

    } catch (Throwable e) {
        logger.error("Exception encountered in " + actionMapping.getName());
        logger.error("Exception", e);
        if (e instanceof com.jada.admin.SecurityException) {
            forward = actionMapping.findForward("securityException");
        } else {
            forward = actionMapping.findForward("exception");
        }
    } finally {
        try {
            em = JpaConnection.getInstance().getCurrentEntityManager();
            if (em.isOpen()) {
                if (em.getTransaction().isActive()) {
                    em.getTransaction().rollback();
                }
            }
            em.close();
        } catch (Throwable e1) {
            logger.error("Could not rollback transaction after exception!", e1);
        }
    }
    return forward;
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

private Cookie getCookie(HttpServletRequest request, HttpServletResponse response, String cookieName)
        throws IOException {
    Cookie[] cookies = request.getCookies();
    int length = cookies.length;
    boolean found = false;
    int i = 0;//from ww  w. j  av a 2  s  .c o m
    while ((i < length) && !found) {
        found = cookies[i].getName().equals(cookieName);
        i++;
    }
    i--;
    if (!found) {
        //response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, cookieName + "cookie not found");
        return null;
    }
    return cookies[i];

}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * This is the main method that does the LDAP authentication using user's 
 * credential in the format of username and password. It creates a 
 * connection with the user credentials and reads his/her own information. 
 * It does not read any other LDAP attribute out of the user entry.
 * <p>//from w w w. j a  v  a  2s. c om
 * If the LDAP authentication result is OK, it creates an 
 * authentication cookie. Anyway, the HTTP response code is returned in this 
 * method to inform the caller on the status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    logger.debug("LDAP Unique Credentials Start");

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    // Read cookies
    cookies = request.getCookies();

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("LDAPUniqueCreds: trying to get creds from repository ID: " + id);
    Credential cred = null;
    try {
        cred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (cred == null) {
        cred = creds.getCredential("root");
        if (cred != null) {
            logger.info("LDAPUniqueCreds: credential ID used is \"root\"");
        } else {
            logger.error("LDAPUniqueCreds: No credentials available for " + id);
        }
    }

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    //If the required cookie was not found need to authenticate.
    logger.debug("Authenticating");
    try {

        //read values from config file (if any)
        readLDAPParameters(id);

        //Check if the LDAP credentials are OK                      
        logger.debug("Base user is: " + ldapBaseuser);
        Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain,
                rdnAttr);

        try {
            logger.debug("Connection to LDAP");
            DirContext ctx = ldapconn.openConnection();
            if (ctx == null) {
                //Just send a comment  
                logger.debug("The user(" + cred.getUsername() + ")/password doesn't match");
                ldapconn.closeConnection(ctx);
                return (HttpServletResponse.SC_UNAUTHORIZED);
            }

            logger.debug("User properly authenticated against the LDAP");

            //Close the connection
            ldapconn.closeConnection(ctx);

        } catch (Exception ex) {
            logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex);
            return (HttpServletResponse.SC_UNAUTHORIZED);
        } finally {
        }

        Cookie extAuthCookie = null;

        extAuthCookie = settingCookie();

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        //This would be set to OK or 401 in a real AuthN module
        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("Sample authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // Debug
    logger.debug("Sample Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

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

private Cookie doCookie(HttpServletRequest req)
        throws IllegalArgumentException, IllegalStateException, UnauthorizedException {

    String authToken = null;/*w  ww  . jav  a2  s.  c o  m*/
    String authTokenStr = retrieveAuthTokenString(req.getCookies());

    if (authTokenStr == null) {
        String gripe = "Authentication token not found!";
        throw new IllegalStateException(gripe);
    } else {

        String[] authTokeStrParts = authTokenStr.split("-");
        authToken = authTokeStrParts[0];
        byte[] signature = Base64.decodeBase64(authTokeStrParts[1]);

        if (!isValidSignature(authToken, signature)) {
            String gripe = "Authentication token is not valid!";
            throw new IllegalStateException(gripe);
        }

    }

    AuthToken token = null;
    token = AuthTokenFactory.makeCookieAuthToken(authToken);
    assertTimeToLive(token);

    return makeAuthTokenCookie(token, CookieUse.INTERNAL);

}