View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http;
17  
18  import static io.netty.handler.codec.http.CookieEncoderUtil.*;
19  
20  import java.util.ArrayList;
21  import java.util.Collection;
22  import java.util.Collections;
23  import java.util.Date;
24  import java.util.List;
25  
26  /**
27   * A <a href="http://tools.ietf.org/html/rfc6265">RFC6265</a> compliant cookie encoder to be used server side,
28   * so some fields are sent (Version is typically ignored).
29   *
30   * As Netty's Cookie merges Expires and MaxAge into one single field, only Max-Age field is sent.
31   *
32   * Note that multiple cookies are supposed to be sent at once in a single "Set-Cookie" header.
33   *
34   * <pre>
35   * // Example
36   * {@link HttpRequest} req = ...;
37   * res.setHeader("Cookie", {@link ServerCookieEncoder}.encode("JSESSIONID", "1234"));
38   * </pre>
39   *
40   * @see ServerCookieDecoder
41   */
42  public final class ServerCookieEncoder {
43  
44      /**
45       * Encodes the specified cookie name-value pair into a Set-Cookie header value.
46       *
47       * @param name the cookie name
48       * @param value the cookie value
49       * @return a single Set-Cookie header value
50       */
51      public static String encode(String name, String value) {
52          return encode(new DefaultCookie(name, value));
53      }
54  
55      /**
56       * Encodes the specified cookie into a Set-Cookie header value.
57       *
58       * @param cookie the cookie
59       * @return a single Set-Cookie header value
60       */
61      public static String encode(Cookie cookie) {
62          if (cookie == null) {
63              throw new NullPointerException("cookie");
64          }
65  
66          StringBuilder buf = stringBuilder();
67  
68          addUnquoted(buf, cookie.name(), cookie.value());
69  
70          if (cookie.maxAge() != Long.MIN_VALUE) {
71              add(buf, CookieHeaderNames.MAX_AGE, cookie.maxAge());
72              Date expires = new Date(cookie.maxAge() * 1000 + System.currentTimeMillis());
73              addUnquoted(buf, CookieHeaderNames.EXPIRES, HttpHeaderDateFormat.get().format(expires));
74          }
75  
76          if (cookie.path() != null) {
77              addUnquoted(buf, CookieHeaderNames.PATH, cookie.path());
78          }
79  
80          if (cookie.domain() != null) {
81              addUnquoted(buf, CookieHeaderNames.DOMAIN, cookie.domain());
82          }
83          if (cookie.isSecure()) {
84              buf.append(CookieHeaderNames.SECURE);
85              buf.append((char) HttpConstants.SEMICOLON);
86              buf.append((char) HttpConstants.SP);
87          }
88          if (cookie.isHttpOnly()) {
89              buf.append(CookieHeaderNames.HTTPONLY);
90              buf.append((char) HttpConstants.SEMICOLON);
91              buf.append((char) HttpConstants.SP);
92          }
93  
94          return stripTrailingSeparator(buf);
95      }
96  
97      /**
98       * Batch encodes cookies into Set-Cookie header values.
99       *
100      * @param cookies a bunch of cookies
101      * @return the corresponding bunch of Set-Cookie headers
102      */
103     public static List<String> encode(Cookie... cookies) {
104         if (cookies == null) {
105             throw new NullPointerException("cookies");
106         }
107 
108         if (cookies.length == 0) {
109             return Collections.emptyList();
110         }
111 
112         List<String> encoded = new ArrayList<String>(cookies.length);
113         for (Cookie c : cookies) {
114             if (c == null) {
115                 break;
116             }
117             encoded.add(encode(c));
118         }
119         return encoded;
120     }
121 
122     /**
123      * Batch encodes cookies into Set-Cookie header values.
124      *
125      * @param cookies a bunch of cookies
126      * @return the corresponding bunch of Set-Cookie headers
127      */
128     public static List<String> encode(Collection<Cookie> cookies) {
129         if (cookies == null) {
130             throw new NullPointerException("cookies");
131         }
132 
133         if (cookies.isEmpty()) {
134             return Collections.emptyList();
135         }
136 
137         List<String> encoded = new ArrayList<String>(cookies.size());
138         for (Cookie c : cookies) {
139             if (c == null) {
140                 break;
141             }
142             encoded.add(encode(c));
143         }
144         return encoded;
145     }
146 
147     /**
148      * Batch encodes cookies into Set-Cookie header values.
149      *
150      * @param cookies a bunch of cookies
151      * @return the corresponding bunch of Set-Cookie headers
152      */
153     public static List<String> encode(Iterable<Cookie> cookies) {
154         if (cookies == null) {
155             throw new NullPointerException("cookies");
156         }
157 
158         if (!cookies.iterator().hasNext()) {
159             return Collections.emptyList();
160         }
161 
162         List<String> encoded = new ArrayList<String>();
163         for (Cookie c : cookies) {
164             if (c == null) {
165                 break;
166             }
167             encoded.add(encode(c));
168         }
169         return encoded;
170     }
171 
172     private ServerCookieEncoder() {
173         // Unused
174     }
175 }