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.paris.lutece.plugins.mylutece.modules.oauth.authentication.OAuthAuthentication.java

/**
 * Gets the user//from   ww w  .  jav a  2 s  . c o  m
 * @param request the reuqest
 * @return the user found.
 */
public OAuthUser getUser(HttpServletRequest request) {
    String strToken = request.getParameter(PARAMETER_OAUTH_TOKEN);
    String strVerifier = request.getParameter(PARAMETER_OAUTH_VERIFIER);

    if (StringUtils.isNotBlank(strToken) && StringUtils.isNotBlank(strVerifier)) {
        // FIXME : version specific
        Cookie cookie = findCookie(request, CONSTANT_COOKIE_TOKEN_SECRET);

        OAuthConsumer consumer = getConsumer();
        consumer.setTokenWithSecret(strToken, cookie.getValue());

        try {
            OAuthProvider provider = getProvider();
            provider.setOAuth10a(true);
            provider.retrieveAccessToken(consumer, strVerifier);

            // FIXME :  username.
            OAuthUser user = new OAuthUser(this.getName(), this);
            user.setToken(strToken);
            user.setVerifier(strVerifier);
            user.setTokenSecret(cookie.getValue());

            // get user infos
            if (StringUtils.isNotBlank(getCredentialUrl())) {
                HttpGet getMethod = new HttpGet(getCredentialUrl());

                consumer.sign(getMethod);

                HttpResponse httpResponse = getHttpClient().execute(getMethod);

                int nStatusCode = httpResponse.getStatusLine().getStatusCode();

                if (nStatusCode == HttpStatus.SC_OK) {
                    OAuthCredentialsRetrieverUtils.doRetrieveUserInfo(httpResponse, user,
                            getCredentialFormat());
                } else {
                    AppLogService.error(httpResponse.getStatusLine());
                    throw new AppException("Unable to find user infos : " + httpResponse.getStatusLine());
                }
            }

            return user;
        } catch (OAuthMessageSignerException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (OAuthNotAuthorizedException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (OAuthExpectationFailedException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (OAuthCommunicationException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (ClientProtocolException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (IllegalStateException e) {
            AppLogService.error(e.getMessage(), e);
        }
    }

    return null;
}

From source file:com.spshop.web.ShoppingController.java

private User retrieveUserNameAndPWDFromCookie(Cookie cookies[]) {
    try {/*from  w w w.  j a  va 2s  . c  om*/
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (COOKIE_ACCOUNT.equals(cookie.getName())) {
                    String value = Utils.OBJ.getDecry(cookie.getValue());
                    String[] mixUser = value.split(USER_NAME_PWD_SPLIT);
                    User user = new User();
                    user.setEmail(mixUser[0]);
                    user.setPassword(mixUser[1]);
                    return user;
                }
            }
        }
    } catch (Exception e) {
        logger.info(e.getMessage());
    }
    return null;
}

From source file:com.novartis.opensource.yada.plugin.AbstractPreprocessor.java

@Override
public String getCookie(String cookie) {
    Cookie[] cookies = getYADARequest().getRequest().getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (c.getName().equals(cookie)) {
                return c.getValue();
            }/*from   w ww.  j a  va 2s .c  o  m*/
        }
    }
    return null;
}

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

@Override
public String getId(final SlingHttpServletRequest request) {
    final Cookie cookie = request.getCookie(this.getSessionCookieName());
    if (cookie != null) {
        return StringUtils.stripToNull(cookie.getValue());
    }/*from   ww w .j  a  va2 s . c  o  m*/
    return null;
}

From source file:com.google.ie.web.controller.UserController.java

/**
 * Retrieve the value of friend connect authorization cookie from the
 * request./*from ww  w  . j  a v  a  2  s  . co  m*/
 * 
 * @param request
 * @return
 */
private String getAuthToken(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie != null && cookie.getName().equals(getFcauthCookieName())) {
                return cookie.getValue();
            }
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("The cookie " + getFcauthCookieName() + " was not found ");
    }
    return null;
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> void contributeCookies(final DefaultHttpClient httpClient,
        final HttpClientRequest<T> httpClientRequest) {
    final List<Cookie> cookies = httpClientRequest.getCookies();

    if (CollectionUtils.isNotEmpty(cookies)) {
        final CookieStore cookieStore = new BasicCookieStore();
        for (final Cookie cookie : cookies) {
            final BasicClientCookie httpCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());

            final int maxAge = cookie.getMaxAge();

            if (maxAge > 0) {
                final Date expire = new Date(System.currentTimeMillis() + maxAge * 1000L);
                httpCookie.setExpiryDate(expire);
                httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR, Integer.toString(maxAge));
            }//from ww  w . ja v a2 s. c  om

            httpCookie.setVersion(1);
            httpCookie.setPath(cookie.getPath());
            httpCookie.setDomain(cookie.getDomain());
            httpCookie.setSecure(cookie.getSecure());

            LOG.debug("Adding cookie to the request: '%s'", httpCookie);
            cookieStore.addCookie(httpCookie);
        }
        httpClient.setCookieStore(cookieStore);
    } else {
        LOG.debug("No cookies found.");
        httpClient.setCookieStore(null);
    }
}

From source file:UploadImageEdit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w  w w  . j av  a2s .c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, IOException_Exception {
    // Check that we have a file upload request
    PrintWriter writer = response.getWriter();
    String productName = "";
    String description = "";
    String price = "";
    String pictureName = "";
    String productId = "";

    Cookie cookie = null;
    Cookie[] cookies = null;
    String selectedCookie = "";
    // Get an array of Cookies associated with this domain
    cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            if (cookie.getName().equals("JuraganDiskon")) {
                selectedCookie = cookie.getValue();
            }
        }
    } else {
        writer.println("<h2>No cookies founds</h2>");
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here

        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = new File(new File(getServletContext().getRealPath("")).getParent()).getParent()
            + "/web/" + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            int k = 0;
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    k++;
                    writer.println("if = " + k);

                    String fileName = new File(item.getName()).getName();
                    pictureName = fileName;
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("message", "Upload has been done successfully!");
                    writer.println("pictureName = " + pictureName);
                } else {
                    k++;
                    writer.println("else = " + k);

                    // Get the field name
                    String fieldName = item.getName();
                    // Get the field value
                    String value = item.getString();
                    if (k == 0) {

                    } else if (k == 1) {
                        productId = value.trim();
                        writer.println("productId = " + productId);
                    } else if (k == 2) {
                        productName = value;
                        writer.println("productName = " + productName);
                    } else if (k == 3) {
                        description = value;
                        writer.println("description = " + description);
                    } else if (k == 4) {
                        price = value;
                        writer.println("price = " + price);
                    }

                }

            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    String update = editTheProduct(Integer.valueOf(productId), productName, price, description, pictureName,
            selectedCookie);
    writer.println(update);

    //redirects client to message page
    getServletContext().getRequestDispatcher("/yourProduct.jsp").forward(request, response);

}

From source file:AIR.Common.Web.Session.MultiValueCookie.java

public MultiValueCookie(Cookie cookie) {
    this._name = cookie.getName();
    //Shiva: we can limit the code to the else part rather than have 
    //the "if" part as well. The if part is there just for safety.
    if (StringUtils.isEmpty(cookie.getPath()))
        this._path = Server.getContextPath();
    else/*  www.j a v  a 2 s . c  o  m*/
        this._path = cookie.getPath();
    this._comment = cookie.getComment();
    this._domain = cookie.getDomain();
    this._isSecure = cookie.getSecure();
    this._encodedValue = cookie.getValue();
    this._cookie = cookie;
    deserializeCookieValue();
}

From source file:io.stallion.plugins.flatBlog.comments.CommentsEndpoints.java

public Comment processAndSaveComment(Comment comment) {
    if (FlatBlogSettings.getInstance().getModerationEnabled()) {
        if (comment.getAkismetApproved()
                || StringUtils.isEmpty(FlatBlogSettings.getInstance().getAkismetKey())) {
            comment.setState(State.PENDING_MODERATION);
        }//from w  w w .  ja  va 2s  .c o  m
    } else {
        if (comment.getAkismetApproved() || empty(FlatBlogSettings.getInstance().getAkismetKey())) {
            comment.setState(State.APPROVED);
            comment.setApproved(true);
        }
    }

    if (comment.isApproved()) {
        comment.setPreviouslyApproved(true);
    }

    Cookie cookie = Context.getRequest().getCookie(Constants.AUTHOR_SECRET_COOKIE);
    if (cookie == null) {
        cookie = Context.getResponse().addCookie(Constants.AUTHOR_SECRET_COOKIE,
                RandomStringUtils.randomAlphanumeric(30), 20 * 365 * 60 * 60 * 24);
    }
    comment.setAuthorSecret(cookie.getValue());

    Log.info("Save comment from {0}", comment.getAuthorEmail());

    comment.setCreatedTicks(DateUtils.mils());

    Contact contact = new Contact();
    contact.setEmail(comment.getAuthorEmail());
    contact.setDisplayName(comment.getAuthorDisplayName());
    contact.setWebSite(comment.getAuthorWebSite());
    contact.setEverCookie(RandomStringUtils.randomAlphanumeric(30));
    if (Literals.empty(contact.getId())) {
        Context.getResponse().addCookie("stContactToken", contact.getEverCookie(), 20 * 365 * 60 * 60 * 24);
    }
    contact = ContactsController.instance().getOrCreate(contact);

    comment.setContactId(contact.getId());
    CommentsController.instance().save(comment);

    /* Subscribe the commenter to updates */
    CommentSubscriptionInfo subscriptionInfo = new CommentSubscriptionInfo();
    if (comment.getMentionSubscribe() == true) {
        subscriptionInfo.setReplyNotifyFrequency(SubscriptionFrequency.DAILY);
    } else {
        subscriptionInfo.setReplyNotifyFrequency(SubscriptionFrequency.NEVER);
    }
    if (comment.getThreadSubscribe() == true) {
        subscriptionInfo.setThreadNotifyFrequency(SubscriptionFrequency.DAILY);
    } else {
        subscriptionInfo.setThreadNotifyFrequency(SubscriptionFrequency.NEVER);
    }
    CommentsController.instance().updateCommentSubscriptionInfo(subscriptionInfo, comment, contact);

    return comment;
}

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

private void handlerLoginForm(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        HashMap<String, Object> parameters, org.jdom.Document doc) throws VerticalAdminException {
    final UserStoreXmlCreator xmlCreator = new UserStoreXmlCreator(
            userStoreService.getUserStoreConnectorConfigs());
    List<UserStoreEntity> userStores = securityService.getUserStores();
    org.jdom.Document tempDoc = xmlCreator.createPagedDocument(userStores, 0, 100);

    org.jdom.Element dataElem = doc.getRootElement();
    dataElem.addContent(tempDoc.getRootElement().detach());

    // set correct language and get languages xml
    AdminConsoleTranslationService languageMap = AdminConsoleTranslationService.getInstance();
    String languageCode = request.getParameter("lang");
    Boolean cookieSet = false;//w w  w  .j av a2 s .c  o m
    if (languageCode == null) {
        Cookie cookie = CookieUtil.getCookie(request, "languageCode");
        if (cookie == null) {
            languageCode = languageMap.getDefaultLanguageCode();
        } else {
            languageCode = cookie.getValue();
            cookieSet = true;
        }
    }

    languageMap.toDoc(doc, languageCode);
    session.setAttribute("languageCode", languageCode);
    parameters.put("languagecode", languageCode);

    if (!cookieSet) {
        String deploymentPath = DeploymentPathResolver.getAdminDeploymentPath(request);
        CookieUtil.setCookie(response, "languageCode", languageCode, COOKIE_TIMEOUT, deploymentPath);
    }

    String userStoreKeyStr = request.getParameter("userStorekey");
    if (userStoreKeyStr != null) {
        parameters.put("userStorekey", userStoreKeyStr);
    }
    String username = request.getParameter("username");
    if (username != null) {
        parameters.put("username", username);
    }
    String password = request.getParameter("password");
    if (password != null) {
        parameters.put("password", password);
    }

    String errorCode = (String) session.getAttribute("passworderrorcode");
    if (errorCode != null) {
        session.removeAttribute("passworderrorcode");
        session.removeAttribute("passworderror");
    }

    errorCode = (String) session.getAttribute("loginerrorcode");
    if (errorCode != null) {
        parameters.put("errorcode", errorCode);
        parameters.put("errormessage", session.getAttribute("loginerror"));
    }

    // version and copyright info
    parameters.put("version", Version.getVersion());
    parameters.put("copyright", Version.getCopyright());

    String selectedUserStore = (String) session.getAttribute("selectedloginuserstore");
    if (StringUtils.isNotEmpty(selectedUserStore)) {
        parameters.put("selectedloginuserstore", selectedUserStore);
    }

    transformXML(request, response, doc, "login_form.xsl", parameters);
}