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:hudson.plugins.timestamper.format.TimestampFormatterImpl.java

/**
 * Create a new {@link TimestampFormatterImpl}.
 * //from   w w  w . j a v  a  2 s.c  o m
 * @param systemTimeFormat
 *          the system clock time format
 * @param elapsedTimeFormat
 *          the elapsed time format
 * @param timeZoneId
 *          the configured time zone identifier
 * @param request
 *          the current HTTP request
 */
public TimestampFormatterImpl(String systemTimeFormat, String elapsedTimeFormat, Optional<String> timeZoneId,
        HttpServletRequest request) {

    String cookieValue = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("jenkins-timestamper".equals(cookie.getName())) {
                cookieValue = cookie.getValue();
                break;
            }
        }
    }

    if ("elapsed".equalsIgnoreCase(cookieValue)) {
        formatTimestamp = new ElapsedTimeFormatFunction(elapsedTimeFormat);
    } else if ("none".equalsIgnoreCase(cookieValue)) {
        formatTimestamp = new EmptyFormatFunction();
    } else {
        // "system", no cookie, or unrecognised cookie
        TimeZone timeZone = null;
        if (timeZoneId.isPresent()) {
            timeZone = TimeZone.getTimeZone(timeZoneId.get());
        }
        FastDateFormat format = FastDateFormat.getInstance(systemTimeFormat, timeZone);
        formatTimestamp = new SystemTimeFormatFunction(format);
    }
}

From source file:com.acc.storefront.filters.RequestLoggerFilter.java

protected void logCookies(final HttpServletRequest httpRequest) {
    if (LOG.isDebugEnabled()) {
        final Cookie[] cookies = httpRequest.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("COOKIE Name: [" + cookie.getName() + "] Path: [" + cookie.getPath()
                            + "] Value: [" + cookie.getValue() + "]");
                }/*from  ww  w. ja v  a  2s . c o  m*/
            }
        }
    }
}

From source file:nl.surfnet.mujina.saml.SSOSuccessAuthnResponder.java

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    AuthnRequestInfo info = (AuthnRequestInfo) request.getSession()
            .getAttribute(AuthnRequestInfo.class.getName());

    if (info == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from   w  ww  .  ja va  2 s .co m
    }

    logger.debug("AuthnRequestInfo: {}", info);

    SimpleAuthentication authToken = (SimpleAuthentication) SecurityContextHolder.getContext()
            .getAuthentication();
    DateTime authnInstant = new DateTime(request.getSession().getCreationTime());

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(idpConfiguration.getEntityID()));
    criteriaSet.add(new UsageCriteria(UsageType.SIGNING));
    Credential signingCredential = null;
    try {
        signingCredential = credentialResolver.resolveSingle(criteriaSet);
    } catch (org.opensaml.xml.security.SecurityException e) {
        logger.warn("Unable to resolve EntityID while signing", e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    Validate.notNull(signingCredential);

    AuthnResponseGenerator authnResponseGenerator = new AuthnResponseGenerator(signingCredential,
            idpConfiguration.getEntityID(), timeService, idService, idpConfiguration);
    EndpointGenerator endpointGenerator = new EndpointGenerator();

    final String remoteIP = request.getRemoteAddr();
    String attributeJson = null;

    if (null != request.getCookies()) {
        for (Cookie current : request.getCookies()) {
            if (current.getName().equalsIgnoreCase("mujina-attr")) {
                logger.info("Found a attribute cookie, this is used for the assertion response");
                attributeJson = URLDecoder.decode(current.getValue(), "UTF-8");
            }
        }
    }
    String acsEndpointURL = info.getAssertionConsumerURL();
    if (idpConfiguration.getAcsEndpoint() != null) {
        acsEndpointURL = idpConfiguration.getAcsEndpoint().getUrl();
    }
    Response authResponse = authnResponseGenerator.generateAuthnResponse(remoteIP, authToken, acsEndpointURL,
            responseValidityTimeInSeconds, info.getAuthnRequestID(), authnInstant, attributeJson,
            info.getEntityId());
    Endpoint endpoint = endpointGenerator.generateEndpoint(
            org.opensaml.saml2.metadata.AssertionConsumerService.DEFAULT_ELEMENT_NAME, acsEndpointURL, null);

    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());

    String relayState = request.getParameter("RelayState");

    //we could use a different adapter to send the response based on request issuer...
    try {
        adapter.sendSAMLMessage(authResponse, endpoint, response, relayState, signingCredential);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    }
}

From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java

/**
 * Prepara i {@link Cookie}s da inoltrare
 *
 * @param request {@link HttpServletRequest}
 * @return cookies string//  w w w .ja v a 2s .  c o  m
 */
private String _prepareCookies(HttpServletRequest request) {
    StringBuilder _cookieBuffer = new StringBuilder();
    try {
        Cookie[] _cookies = request.getCookies();
        for (Cookie _cookie : _cookies) {
            _cookieBuffer.append(_cookie.getName()).append("=")
                    .append(URLEncoder.encode(_cookie.getValue(), "UTF-8"));
            _cookieBuffer.append("; ");
        }
    } catch (UnsupportedEncodingException uee) {
        uee.printStackTrace(System.err);
    }

    if (_cookieBuffer.length() > 2) {
        _cookieBuffer.delete(_cookieBuffer.length() - 2, _cookieBuffer.length());
    }
    return _cookieBuffer.toString();
}

From source file:cn.vlabs.umt.ui.servlet.LogoutServlet.java

private String getUserName(HttpServletRequest request) {
    User user = SessionUtils.getUser(request);
    String username = null;//from  w  w  w  . j  a v  a2  s.  co  m
    if (user == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (Attributes.COOKIE_NAME.equals(cookie.getName())
                        && StringUtils.isNotEmpty(cookie.getValue())) {
                    try {
                        username = new String(cred.decrypt(HexUtil.toBytes(cookie.getValue())), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                    }
                }
            }
        }
    } else {
        username = user.getCstnetId();
    }
    return username;
}

From source file:com.itjenny.web.ArticleController.java

@RequestMapping(value = "{title}/{chapterCssId}", method = RequestMethod.POST)
public ModelAndView checkAnswer(HttpServletRequest request, @PathVariable String title,
        @PathVariable String chapterCssId, @RequestParam String answer) {
    Integer chapterIndex = Integer.valueOf(chapterCssId.replace(Consts.CHAPTER, StringUtils.EMPTY));
    ModelAndView mav = new ModelAndView();
    ModelMap model = new ModelMap();
    for (Cookie cookie : request.getCookies()) {
        if (cookie.getName().equals("keynote")) {
            Article article = articleService.get(title);
            if (article == null || !article.getUserId().equals(sessionService.getLoginUser().getUserId())) {
                break;
            }//w  w w .  j  av  a2s. c o  m

            // keynote mode
            if (!articleService.isChapterExisted(title, chapterIndex + 1)) {
                bookmarkService.complete(title);
                return new ModelAndView("redirect:/article/" + title + "/license");
            }
            model.addAttribute("chapter", articleService.getChapter(title, chapterIndex + 1));
            model.addAttribute("totalSection", articleService.getTotalSection(title));
            model.addAttribute("answer", articleService.getChapter(title, chapterIndex).getQuiz().getAnswer());
            mav.setViewName(View.CHAPTER);
            mav.addAllObjects(model);

            bookmarkService.updateChapter(title, chapterIndex + 1);
            return mav;
        }
    }

    // word mode
    Chapter chapter = articleService.getChapter(title, chapterIndex);
    if (answerService.check(chapter, answer)) {
        if (!articleService.isChapterExisted(title, chapterIndex + 1)) {
            bookmarkService.complete(title);
            return new ModelAndView("redirect:/article/" + title + "/license");
        }
        model.addAttribute("chapter", articleService.getChapter(title, chapterIndex + 1));
        model.addAttribute("totalSection", articleService.getTotalSection(title));
        model.addAttribute("answer", articleService.getChapter(title, chapterIndex).getQuiz().getAnswer());
        mav.setViewName(View.CHAPTER);
        mav.addAllObjects(model);

        bookmarkService.updateChapter(title, chapterIndex + 1);
    } else {
        mav.setViewName(View.WRONG);
        mav.addAllObjects(model);
    }
    return mav;
}

From source file:com.foilen.smalltools.spring.security.CookiesGeneratedCsrfTokenRepository.java

@Override
public CsrfToken generateToken(HttpServletRequest request) {
    AssertTools.assertNotNull(salt, "You must set the salt");
    AssertTools.assertFalse(cookieNames.isEmpty(), "You must set at least one cookie");

    // Search all the cookies
    Map<String, String> valuesByName = new HashMap<>();
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookieNames.contains(cookie.getName())) {
                String previousValue = valuesByName.put(cookie.getName(), cookie.getValue());
                if (previousValue != null) {
                    throw new SmallToolsException(
                            "The cookie with name " + cookie.getName() + " contains more than one value");
                }//from   w  w  w  .  java 2s  . co  m
            }
        }
    }

    // Generate the token
    StringBuilder allValues = new StringBuilder(salt);
    for (String cookieName : cookieNames) {
        String cookieValue = valuesByName.get(cookieName);
        logger.debug("Adding cookie {} with value {}", cookieName, cookieValue);
        allValues.append(cookieName).append(cookieValue);
    }

    String token = HashSha256.hashString(allValues.toString());
    logger.debug("Token is {}", token);
    return new DefaultCsrfToken(HEADER_NAME, PARAMETER_NAME, token);
}

From source file:com.hypersocket.session.json.SessionUtils.java

public Locale getLocale(HttpServletRequest request) {

    if (request.getSession().getAttribute(USER_LOCALE) == null) {

        Cookie[] cookies = request.getCookies();
        for (Cookie c : cookies) {
            if (c.getName().equals(HYPERSOCKET_LOCALE)) {
                return new Locale(c.getValue());
            }/*from ww  w  .  j  av a  2  s .c  om*/
        }
        return configurationService.getDefaultLocale();
    } else {
        return new Locale((String) request.getSession().getAttribute(USER_LOCALE));
    }

}

From source file:es.logongas.ix3.web.security.impl.WebSessionSidStorageImplAbstractJws.java

private String getJwsCompactInCookie(HttpServletRequest httpServletRequest) {
    Cookie[] cookies = httpServletRequest.getCookies();

    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (jwsCookieName.equals(cookie.getName())) {
                return cookie.getValue();
            }/*from  www.j  av  a  2  s  .  c o m*/
        }
    }

    return null;
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.OAuth2Resource.java

@GET
@Timed/*from w w  w  .j  av  a 2 s . c  om*/
@Path(value = "/logout")
public Response logout(@Context final HttpServletRequest request) {
    // invalidate cookie if exists
    ResponseBuilder reply = Response.ok();

    for (Cookie c : request.getCookies()) {
        if (OAuth2AuthFilter.AUTH_COOKIE_NAME.equals(c.getName())) {
            reply.cookie(new NewCookie(OAuth2AuthFilter.AUTH_COOKIE_NAME, null, "/", request.getServerName(),
                    null, 0, true));
            break;
        }
    }

    return reply.build();
}