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:com.tremolosecurity.proxy.filter.PostProcess.java

protected void setHeadersCookies(HttpFilterRequest req, UrlHolder holder, HttpRequestBase method,
        String finalURL) throws Exception {
    Iterator<String> names;
    names = req.getHeaderNames();//from   ww  w . jav a 2s . co  m
    String cookieName = null;
    URL url = new URL(finalURL);

    while (names.hasNext()) {
        String name = names.next();
        if (name.equalsIgnoreCase("Cookie")) {
            cookieName = name;
            continue;
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Header : " + name);
        }

        Attribute attrib = req.getHeader(name);
        Iterator<String> attrVals = attrib.getValues().iterator();
        while (attrVals.hasNext()) {
            String val = attrVals.next();

            if (name.equalsIgnoreCase("Content-Type")) {
                continue;
            } else if (name.equalsIgnoreCase("If-Range")) {
                continue;
            } else if (name.equalsIgnoreCase("Range")) {
                continue;
            } else if (name.equalsIgnoreCase("If-None-Match")) {
                continue;
            }

            if (name.equalsIgnoreCase("HOST")) {

                if (holder.isOverrideHost()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Final URL : '" + finalURL + "'");
                    }

                    val = url.getHost();
                    if (url.getPort() != -1) {
                        StringBuffer b = new StringBuffer();
                        b.append(val).append(":").append(url.getPort());
                        val = b.toString();
                    }
                }
            } else if (name.equalsIgnoreCase("Referer")) {

                if (holder.isOverrideReferer()) {
                    URL origRef = new URL(val);
                    StringBuffer newRef = new StringBuffer();

                    newRef.append(url.getProtocol()).append("://").append(url.getHost());

                    if (url.getPort() != -1) {
                        newRef.append(':').append(url.getPort());
                    }

                    newRef.append(origRef.getPath());

                    if (origRef.getQuery() != null) {
                        newRef.append('?').append(origRef.getQuery());
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("Final Ref : '" + newRef.toString() + "'");
                    }

                    val = newRef.toString();

                }

            }

            if (this.addHeader(name)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(attrib.getName(), val));
            }
        }
    }

    HashMap<String, Attribute> fromResults = (HashMap<String, Attribute>) req
            .getAttribute(AzSys.AUTO_IDM_HTTP_HEADERS);
    if (fromResults != null) {
        names = fromResults.keySet().iterator();

        while (names.hasNext()) {
            String name = names.next();
            method.removeHeaders(name);

            Attribute attrib = fromResults.get(name);
            Iterator<String> attrVals = attrib.getValues().iterator();
            while (attrVals.hasNext()) {
                String val = attrVals.next();
                if (logger.isDebugEnabled()) {
                    logger.debug("Header Added - '" + name + "'='" + val + "'");
                }
                method.addHeader(new BasicHeader(name, val));
            }
        }
    }

    String sessionCookieName = "";

    if (holder.getApp().getCookieConfig() != null) {
        sessionCookieName = holder.getApp().getCookieConfig().getSessionCookieName();
    }

    HashSet<String> toRemove = new HashSet<String>();
    toRemove.add(sessionCookieName);
    toRemove.add("autoIdmSessionCookieName");
    toRemove.add("autoIdmAppName");
    toRemove.add("JSESSIONID");

    names = req.getCookieNames().iterator();
    StringBuffer cookieHeader = new StringBuffer();
    boolean isFirst = true;

    while (names.hasNext()) {
        String name = names.next();

        if (toRemove.contains(name)) {
            continue;
        }

        ArrayList<Cookie> cookies = req.getCookies(name);

        Iterator<Cookie> itc = cookies.iterator();
        while (itc.hasNext()) {
            Cookie cookie = itc.next();
            String cookieFinalName;
            if (cookie.getName().startsWith("JSESSIONID")) {
                String host = cookie.getName().substring(cookie.getName().indexOf('-') + 1);
                host = host.replaceAll("[|]", " ");
                if (!holder.getApp().getName().equalsIgnoreCase(host)) {
                    continue;
                }

                cookieFinalName = "JSESSIONID";
            } else {
                cookieFinalName = cookie.getName();
            }

            String val = cookie.getValue();
            if (logger.isDebugEnabled()) {
                logger.debug("Cookie Added - '" + name + "'='" + val + "'");
            }

            cookieHeader.append(cookieFinalName).append('=').append(val).append("; ");
        }
    }

    if (cookieHeader.length() > 0) {
        if (cookieName == null) {
            cookieName = "Cookie";
        }

        method.addHeader(new BasicHeader(cookieName, cookieHeader.toString()));
    }
}

From source file:de.innovationgate.wga.server.api.Call.java

/**
 * Adds a cookie to the call, so it will be send to the client
 * @param c/* w ww  .ja v a 2 s  . c  om*/
 * @throws WGException
 */
public void addCookie(Cookie c) throws WGException {
    testResponseHeaderWritable();
    getJavaResponse().addCookie(c.toJavaCookie());
    fetchCookies().put(c.getName(), c);
}

From source file:ed.net.CookieJar.java

/**
 * Validates & adds cookies to this object
 * //from  ww w . j  a  v  a 2  s.  co  m
 * @param source the origin server of the cookie
 * @param cookie the being added 
 */
public void addCookie(URL source, Cookie cookie) {
    try {
        validate(source, cookie);
    } catch (MalformedCookieException e) {
        //TODO: invalid cookies
        return;
    } catch (IllegalArgumentException e) {
        //TODO: invalid cookies
        return;
    }

    if (cookie.getMaxAge() == 0) {
        remove(cookie.getName());
        return;
    } else {
        _cookies.put(cookie.getName(), cookie);
        _creationDates.put(cookie.getName(), new Date());
    }
}

From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTest.java

@Test
public void buildRequestCookiesMulti() {
    webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2");

    MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext);

    Cookie[] cookies = actualRequest.getCookies();
    assertThat(cookies.length).isEqualTo(2);
    Cookie cookie = cookies[0];
    assertThat(cookie.getName()).isEqualTo("name");
    assertThat(cookie.getValue()).isEqualTo("value");
    cookie = cookies[1];// w  w  w  .j av a 2 s. c o  m
    assertThat(cookie.getName()).isEqualTo("name2");
    assertThat(cookie.getValue()).isEqualTo("value2");
}

From source file:nl.nn.adapterframework.http.rest.ApiListenerServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /**/* w  ww.  j av a2s.co  m*/
     * Initiate and populate messageContext
     */
    PipeLineSessionBase messageContext = new PipeLineSessionBase();
    messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request);
    messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response);
    messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext());
    messageContext.setSecurityHandler(new HttpSecurityHandler(request));

    try {
        String uri = request.getPathInfo();
        String method = request.getMethod().toUpperCase();
        log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]");

        if (uri == null) {
            response.setStatus(400);
            log.warn("Aborting request with status [400], empty uri");
            return;
        }

        if (uri.startsWith("/"))
            uri = uri.substring(1);
        if (uri.endsWith("/"))
            uri = uri.substring(0, uri.length() - 1);

        ApiDispatchConfig config = dispatcher.findConfigForUri(uri);
        if (config == null) {
            response.setStatus(404);
            log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]");
            return;
        }

        /**
         * Handle Cross-Origin Resource Sharing
         * TODO make this work behind loadbalancers/reverse proxies
         * TODO check if request ip/origin header matches allowOrigin property
         */
        String origin = request.getHeader("Origin");
        if (method.equals("OPTIONS") || origin != null) {
            response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin);
            String headers = request.getHeader("Access-Control-Request-Headers");
            if (headers != null)
                response.setHeader("Access-Control-Allow-Headers", headers);
            response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders);

            StringBuilder methods = new StringBuilder();
            for (String mtd : config.getMethods()) {
                methods.append(", ").append(mtd);
            }
            response.setHeader("Access-Control-Allow-Methods", methods.toString());

            //Only cut off OPTIONS (aka preflight) requests
            if (method.equals("OPTIONS")) {
                response.setStatus(200);
                log.trace("Aborting preflight request with status [200], method [" + method + "]");
                return;
            }
        }

        /**
         * Get serviceClient
         */
        ApiListener listener = config.getApiListener(method);
        if (listener == null) {
            response.setStatus(405);
            log.trace("Aborting request with status [405], method [" + method + "] not allowed");
            return;
        }

        log.trace("ApiListenerServlet calling service [" + listener.getName() + "]");

        /**
         * Check authentication
         */
        ApiPrincipal userPrincipal = null;

        if (listener.getAuthenticationMethod() != null) {

            String authorizationToken = null;
            Cookie authorizationCookie = null;
            if (listener.getAuthenticationMethod().equals("COOKIE")) {

                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("authenticationToken")) {
                        authorizationToken = cookie.getValue();
                        authorizationCookie = cookie;
                        authorizationCookie.setPath("/");
                    }
                }
            } else if (listener.getAuthenticationMethod().equals("HEADER")) {
                authorizationToken = request.getHeader("Authorization");
            }

            if (authorizationToken != null && cache.containsKey(authorizationToken))
                userPrincipal = (ApiPrincipal) cache.get(authorizationToken);

            if (userPrincipal == null || !userPrincipal.isLoggedIn()) {
                cache.remove(authorizationToken);
                if (authorizationCookie != null) {
                    authorizationCookie.setMaxAge(0);
                    response.addCookie(authorizationCookie);
                }

                response.setStatus(401);
                log.trace("Aborting request with status [401], no (valid) credentials supplied");
                return;
            }

            if (authorizationCookie != null) {
                authorizationCookie.setMaxAge(authTTL);
                response.addCookie(authorizationCookie);
            }
            userPrincipal.updateExpiry();
            userPrincipal.setToken(authorizationToken);
            cache.put(authorizationToken, userPrincipal, authTTL);
            messageContext.put("authorizationToken", authorizationToken);
        }
        messageContext.put("remoteAddr", request.getRemoteAddr());
        messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal);
        messageContext.put("uri", uri);

        /**
         * Evaluate preconditions
         */
        String accept = request.getHeader("Accept");
        if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) {
            if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) {
                response.setStatus(406);
                response.getWriter().print("It appears you expected the MediaType [" + accept
                        + "] but I only support the MediaType [" + listener.getContentType() + "] :)");
                log.trace("Aborting request with status [406], client expects [" + accept + "] got ["
                        + listener.getContentType() + "] instead");
                return;
            }
        }

        if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) {
            response.setStatus(415);
            log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes()
                    + "] got [" + request.getContentType() + "] instead");
            return;
        }

        String etagCacheKey = ApiCacheManager.buildCacheKey(uri);
        log.debug("Evaluating preconditions for listener[" + listener.getName() + "] etagKey[" + etagCacheKey
                + "]");
        if (cache.containsKey(etagCacheKey)) {
            String cachedEtag = (String) cache.get(etagCacheKey);
            log.debug("found etag value[" + cachedEtag + "] for key[" + etagCacheKey + "]");

            if (method.equals("GET")) {
                String ifNoneMatch = request.getHeader("If-None-Match");
                if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) {
                    response.setStatus(304);
                    log.trace(
                            "Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]");
                    return;
                }
            } else {
                String ifMatch = request.getHeader("If-Match");
                if (ifMatch != null && !ifMatch.equals(cachedEtag)) {
                    response.setStatus(412);
                    log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method ["
                            + method + "]");
                    return;
                }
            }
        }
        messageContext.put("updateEtag", listener.getUpdateEtag());

        /**
         * Check authorization
         */
        //TODO: authentication implementation

        /**
         * Map uriIdentifiers into messageContext 
         */
        String patternSegments[] = listener.getUriPattern().split("/");
        String uriSegments[] = uri.split("/");
        int uriIdentifier = 0;
        for (int i = 0; i < patternSegments.length; i++) {
            String segment = patternSegments[i];
            if (segment.startsWith("{") && segment.endsWith("}")) {
                String name;
                if (segment.equals("*"))
                    name = "uriIdentifier_" + uriIdentifier;
                else
                    name = segment.substring(1, segment.length() - 1);

                uriIdentifier++;
                log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]");
                messageContext.put(name, uriSegments[i]);
            }
        }

        /**
         * Map queryParameters into messageContext
         */
        Enumeration<?> paramnames = request.getParameterNames();
        while (paramnames.hasMoreElements()) {
            String paramname = (String) paramnames.nextElement();
            String paramvalue = request.getParameter(paramname);

            log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]");
            messageContext.put(paramname, paramvalue);
        }

        /**
         * Map multipart parts into messageContext
         */
        if (ServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();
                    log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]");
                    messageContext.put(fieldName, fieldValue);
                } else {
                    // Process form file field (input type="file").
                    String fieldName = item.getFieldName();
                    String fieldNameName = fieldName + "Name";
                    String fileName = FilenameUtils.getName(item.getName());
                    log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]");
                    messageContext.put(fieldNameName, fileName);
                    log.trace(
                            "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]");
                    messageContext.put(fieldName, item.getInputStream());
                }
            }
        }

        /**
         * Compile Allow header
         */
        StringBuilder methods = new StringBuilder();
        methods.append("OPTIONS, ");
        for (String mtd : config.getMethods()) {
            methods.append(mtd + ", ");
        }
        messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2));

        /**
         * Process the request through the pipeline
         */

        String body = "";
        if (!ServletFileUpload.isMultipartContent(request)) {
            body = Misc.streamToString(request.getInputStream(), "\n", false);
        }
        String result = listener.processRequest(null, body, messageContext);

        /**
         * Calculate an eTag over the processed result and store in cache
         */
        if (messageContext.get("updateEtag", true)) {
            log.debug("calculating etags over processed result");
            String cleanPattern = listener.getCleanPattern();
            if (result != null && method.equals("GET")) {
                String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode());
                log.debug("adding/overwriting etag with key[" + etagCacheKey + "] value[" + eTag + "]");
                cache.put(etagCacheKey, eTag);
                response.addHeader("etag", eTag);
            } else {
                log.debug("removing etag with key[" + etagCacheKey + "]");
                cache.remove(etagCacheKey);

                // Not only remove the eTag for the selected resources but also the collection
                String key = ApiCacheManager.getParentCacheKey(listener, uri);
                if (key != null) {
                    log.debug("removing parent etag with key[" + key + "]");
                    cache.remove(key);
                }
            }
        }

        /**
         * Add headers
         */
        response.addHeader("Allow", (String) messageContext.get("allowedMethods"));

        String contentType = listener.getContentType() + "; charset=utf-8";
        if (listener.getProduces().equals("ANY")) {
            contentType = messageContext.get("contentType", contentType);
        }
        response.setHeader("Content-Type", contentType);

        /**
         * Check if an exitcode has been defined or if a statuscode has been added to the messageContext.
         */
        int statusCode = messageContext.get("exitcode", 0);
        if (statusCode > 0)
            response.setStatus(statusCode);

        /**
         * Finalize the pipeline and write the result to the response
         */
        if (result != null)
            response.getWriter().print(result);
        log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]");
    } catch (Exception e) {
        log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e);
        try {
            response.flushBuffer();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (IllegalStateException ex) {
            //We're only informing the end user(s), no need to catch this error...
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}

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

/**
 * Delete all the cookies related to the user from the system
 * /*from  w  ww .j  a  v a2s. com*/
 * @param request {@link HttpServletRequest} object
 * @param response {@link HttpServletResponse} object
 */
private void removeCookieFromSystem(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            // Don't remove access token cookie
            if (!StringUtils.equals(cookie.getName(), AuthenticationFilter.ACCESS_TOKEN)) {
                /* Set the max age to zero so that the cookie is deleted */
                cookie.setMaxAge(WebConstants.ZERO);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("The age of the cookies related to the "
                + "user has been set to zero and the cookies set into the response");
    }

}

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  w ww.  j  a  va 2s .c  o m

            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:AIR.Common.Web.Session.CookieHolder.java

private boolean addCookieOnConstructor(Cookie cookie) {
    /*/*from   w w w  .j ava 2s . co m*/
     * the original code for this method would add those cookies by calling
     * "this.add". however, given cookie semantics, we had to update "this.add"
     * to also add the cookie to the response. but on request processing that
     * task is already carried out by the webserver. that is why we are copying
     * the code this "this.add" except the line where we add the cookie to the
     * response.
     */
    // MultiValueCookie mcookie = new MultiValueCookie (cookie, _context);
    // return this.add (mcookie);
    MultiValueCookie existingCookie = findCookie(cookie.getName());
    if (existingCookie != null)
        this.remove(existingCookie);
    return super.add(new MultiValueCookie(cookie));
}