com.threewks.thundr.request.servlet.ServletSupport.java Source code

Java tutorial

Introduction

Here is the source code for com.threewks.thundr.request.servlet.ServletSupport.java

Source

/*
 * This file is a component of thundr, a software library from 3wks.
 * Read more: http://3wks.github.io/thundr/
 * Copyright (C) 2015 3wks, <thundr@3wks.com.au>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.threewks.thundr.request.servlet;

import static com.atomicleopard.expressive.Expressive.*;
import static org.apache.commons.lang3.StringUtils.trimToEmpty;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.Duration;

import com.atomicleopard.expressive.ETransformer;
import com.atomicleopard.expressive.Expressive;
import com.atomicleopard.expressive.transform.CollectionTransformer;
import com.threewks.thundr.http.Cookie;

public class ServletSupport {

    public static Map<String, List<String>> getHeaderMap(HttpServletRequest req) {
        Map<String, List<String>> headerMap = new LinkedHashMap<String, List<String>>();
        Iterable<String> iterable = Expressive.<String>iterable(req.getHeaderNames());
        for (String name : iterable) {
            headerMap.put(name, getHeaders(name, req));
        }
        return headerMap;
    }

    public static String getHeader(String name, HttpServletRequest req) {
        return req.getHeader(name);
    }

    public static List<String> getHeaders(String name, HttpServletRequest req) {
        return Expressive.list(Expressive.iterable(req.getHeaders(name)));
    }

    /**
     * Get the full set of request attirubtes in the given request.
     * 
     * @param request
     * @return
     */
    public static Map<String, Object> getAttributes(HttpServletRequest request) {
        Map<String, Object> attributes = new HashMap<String, Object>();
        if (request != null) {
            Enumeration<String> names = request.getAttributeNames();
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                attributes.put(name, request.getAttribute(name));
            }
        }
        return attributes;
    }

    /**
     * Set the request attributes to the given set.
     * 
     * @param request
     * @param attributes
     */
    public static void setAttributes(HttpServletRequest request, Map<String, Object> attributes) {
        if (request != null) {
            List<String> existing = list(iterable(request.getAttributeNames()));
            List<String> toRemove = list(existing).removeItems(attributes.keySet());
            for (String remove : toRemove) {
                request.removeAttribute(remove);
            }
            addAttributes(request, attributes);
        }
    }

    /**
     * Add the given attributes to the request
     * 
     * @param request
     * @param attributes
     */
    public static void addAttributes(HttpServletRequest request, Map<String, Object> attributes) {
        if (request != null) {
            for (Map.Entry<String, Object> attribute : attributes.entrySet()) {
                request.setAttribute(attribute.getKey(), attribute.getValue());
            }
        }
    }

    /**
     * Gets the first cookie of the given name from the request
     * 
     * @param name
     * @param req
     * @return
     */
    public static final javax.servlet.http.Cookie getCookie(String name, HttpServletRequest req) {
        if (req.getCookies() != null) {
            for (javax.servlet.http.Cookie cookie : req.getCookies()) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }

    /**
     * Gets all cookies of the given name from the request
     * 
     * @param name
     * @param req
     * @return
     */
    public static final List<javax.servlet.http.Cookie> getCookies(String name, HttpServletRequest req) {
        List<javax.servlet.http.Cookie> results = new ArrayList<>();
        if (req.getCookies() != null) {
            for (javax.servlet.http.Cookie cookie : req.getCookies()) {
                if (cookie.getName().equals(name)) {
                    results.add(cookie);
                }
            }
        }
        return results;
    }

    public static Cookie toThundrCookie(javax.servlet.http.Cookie cookie) {
        // @formatter:off
        Duration expires = cookie.getMaxAge() > 0 ? Duration.standardSeconds(cookie.getMaxAge()) : null;
        return Cookie.build(cookie.getName()).withValue(cookie.getValue()).withComment(cookie.getComment())
                .withDomain(cookie.getDomain()).withMaxAge(expires).withPath(cookie.getPath())
                .withSecure(cookie.getSecure()).withVersion(cookie.getVersion()).build();
        // @formatter:on
    }

    public static javax.servlet.http.Cookie toServletCookie(Cookie cookie) {
        javax.servlet.http.Cookie result = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
        if (cookie.getDomain() != null) {
            result.setDomain(cookie.getDomain());
        }
        if (cookie.getPath() != null) {
            result.setPath(cookie.getPath());
        }
        if (cookie.getMaxAge() != null) {
            result.setMaxAge((int) cookie.getMaxAge().getStandardSeconds());
        }
        if (cookie.getComment() != null) {
            result.setComment(cookie.getComment());
        }
        if (cookie.getVersion() != null) {
            result.setVersion(cookie.getVersion());
        }
        if (cookie.getSecure() != null) {
            result.setSecure(cookie.getSecure());
        }
        return result;
    }

    /**
     * Creates a CookieBuilder, which provides a fluent api for building a {@link Cookie}.
     * 
     * @param name
     * @return
     */
    public static final CookieBuilder cookie(String name) {
        return new CookieBuilder(name);
    }

    public static class CookieBuilder {
        private String name;
        private String value;
        private String path;
        private String domain;
        private Duration expires;
        private String comment;
        private Integer version;
        private Boolean secure;

        protected CookieBuilder() {

        }

        protected CookieBuilder(String name) {
            this.name = name;
        }

        public CookieBuilder withName(String name) {
            this.name = name;
            return this;
        }

        public CookieBuilder withValue(String value) {
            this.value = value;
            return this;
        }

        public CookieBuilder withPath(String path) {
            this.path = path;
            return this;
        }

        public CookieBuilder withDomain(String domain) {
            this.domain = domain;
            return this;
        }

        public CookieBuilder withExpires(Duration expires) {
            this.expires = expires;
            return this;
        }

        public CookieBuilder withVersion(Integer version) {
            this.version = version;
            return this;
        }

        public CookieBuilder withSecure(Boolean secure) {
            this.secure = secure;
            return this;
        }

        public CookieBuilder withComment(String comment) {
            this.comment = comment;
            return this;
        }

        public javax.servlet.http.Cookie build() {
            javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie(name, value);
            if (domain != null) {
                cookie.setDomain(domain);
            }
            if (path != null) {
                cookie.setPath(path);
            }
            if (expires != null) {
                cookie.setMaxAge((int) expires.getStandardSeconds());
            }
            if (comment != null) {
                cookie.setComment(comment);
            }
            if (version != null) {
                cookie.setVersion(version);
            }
            if (secure != null) {
                cookie.setSecure(secure);
            }
            return cookie;
        }

        @Override
        public String toString() {
            String domainAndPath = trimToEmpty(domain) + trimToEmpty(path);
            domainAndPath = StringUtils.isEmpty(domainAndPath) ? "" : " (" + domainAndPath + ")";
            String expires = this.expires == null ? "" : " expires " + this.expires.getStandardSeconds() + "s";
            return String.format("%s=%s%s%s%s%s;", name, value, Boolean.TRUE.equals(secure) ? " [secure]" : "",
                    domainAndPath, expires, version == null ? "" : " v" + version, trimToEmpty(comment));
        }
    }

    public static final ETransformer<Cookie, javax.servlet.http.Cookie> ToServletCookie = new ETransformer<Cookie, javax.servlet.http.Cookie>() {
        @Override
        public javax.servlet.http.Cookie from(Cookie from) {
            return toServletCookie(from);
        }
    };
    public static final ETransformer<javax.servlet.http.Cookie, Cookie> ToThundrCookie = new ETransformer<javax.servlet.http.Cookie, Cookie>() {

        @Override
        public Cookie from(javax.servlet.http.Cookie from) {
            return toThundrCookie(from);
        }
    };
    public static final CollectionTransformer<javax.servlet.http.Cookie, Cookie> ToThundrCookies = Expressive.Transformers
            .transformAllUsing(ToThundrCookie);
    public static final CollectionTransformer<Cookie, javax.servlet.http.Cookie> ToServletCookies = Expressive.Transformers
            .transformAllUsing(ToServletCookie);

}