View Javadoc
1   /*
2    * Copyright 2015 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.cookie;
17  
18  import static io.netty.handler.codec.http.cookie.CookieUtil.add;
19  import static io.netty.handler.codec.http.cookie.CookieUtil.addQuoted;
20  import static io.netty.handler.codec.http.cookie.CookieUtil.stringBuilder;
21  import static io.netty.handler.codec.http.cookie.CookieUtil.stripTrailingSeparator;
22  import static io.netty.handler.codec.http.cookie.CookieUtil.stripTrailingSeparatorOrNull;
23  import static io.netty.util.internal.ObjectUtil.checkNotNull;
24  import io.netty.handler.codec.http.HttpRequest;
25  import io.netty.util.internal.InternalThreadLocalMap;
26  
27  import java.util.Arrays;
28  import java.util.Collection;
29  import java.util.Comparator;
30  import java.util.Iterator;
31  import java.util.List;
32  
33  /**
34   * A <a href="http://tools.ietf.org/html/rfc6265">RFC6265</a> compliant cookie encoder to be used client side, so
35   * only name=value pairs are sent.
36   *
37   * Note that multiple cookies are supposed to be sent at once in a single "Cookie" header.
38   *
39   * <pre>
40   * // Example
41   * {@link HttpRequest} req = ...;
42   * res.setHeader("Cookie", {@link ClientCookieEncoder}.encode("JSESSIONID", "1234"));
43   * </pre>
44   *
45   * @see ClientCookieDecoder
46   */
47  public final class ClientCookieEncoder extends CookieEncoder {
48  
49      /**
50       * Strict encoder that validates that name and value chars are in the valid scope and (for methods that accept
51       * multiple cookies) sorts cookies into order of decreasing path length, as specified in RFC6265.
52       */
53      public static final ClientCookieEncoder STRICT = new ClientCookieEncoder(true);
54  
55      /**
56       * Lax instance that doesn't validate name and value, and (for methods that accept multiple cookies) keeps
57       * cookies in the order in which they were given.
58       */
59      public static final ClientCookieEncoder LAX = new ClientCookieEncoder(false);
60  
61      private ClientCookieEncoder(boolean strict) {
62          super(strict);
63      }
64  
65      /**
66       * Encodes the specified cookie into a Cookie header value.
67       *
68       * @param name
69       *            the cookie name
70       * @param value
71       *            the cookie value
72       * @return a Rfc6265 style Cookie header value
73       */
74      public String encode(String name, String value) {
75          return encode(new DefaultCookie(name, value));
76      }
77  
78      /**
79       * Encodes the specified cookie into a Cookie header value.
80       *
81       * @param cookie the specified cookie
82       * @return a Rfc6265 style Cookie header value
83       */
84      public String encode(Cookie cookie) {
85          StringBuilder buf = stringBuilder();
86          encode(buf, checkNotNull(cookie, "cookie"));
87          return stripTrailingSeparator(buf);
88      }
89  
90      /**
91       * Sort cookies into decreasing order of path length, breaking ties by sorting into increasing chronological
92       * order of creation time, as recommended by RFC 6265.
93       */
94      private static final Comparator<Cookie> COOKIE_COMPARATOR = new Comparator<Cookie>() {
95          @Override
96          public int compare(Cookie c1, Cookie c2) {
97              String path1 = c1.path();
98              String path2 = c2.path();
99              // Cookies with unspecified path default to the path of the request. We don't
100             // know the request path here, but we assume that the length of an unspecified
101             // path is longer than any specified path (i.e. pathless cookies come first),
102             // because setting cookies with a path longer than the request path is of
103             // limited use.
104             int len1 = path1 == null ? Integer.MAX_VALUE : path1.length();
105             int len2 = path2 == null ? Integer.MAX_VALUE : path2.length();
106             int diff = len2 - len1;
107             if (diff != 0) {
108                 return diff;
109             }
110             // Rely on Java's sort stability to retain creation order in cases where
111             // cookies have same path length.
112             return -1;
113         }
114     };
115 
116     /**
117      * Encodes the specified cookies into a single Cookie header value.
118      *
119      * @param cookies
120      *            some cookies
121      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
122      */
123     public String encode(Cookie... cookies) {
124         if (checkNotNull(cookies, "cookies").length == 0) {
125             return null;
126         }
127 
128         StringBuilder buf = stringBuilder();
129         if (strict) {
130             if (cookies.length == 1) {
131                 encode(buf, cookies[0]);
132             } else {
133                 Cookie[] cookiesSorted = Arrays.copyOf(cookies, cookies.length);
134                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
135                 for (Cookie c : cookiesSorted) {
136                     encode(buf, c);
137                 }
138             }
139         } else {
140             for (Cookie c : cookies) {
141                 encode(buf, c);
142             }
143         }
144         return stripTrailingSeparatorOrNull(buf);
145     }
146 
147     /**
148      * Encodes the specified cookies into a single Cookie header value.
149      *
150      * @param cookies
151      *            some cookies
152      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
153      */
154     public String encode(Collection<? extends Cookie> cookies) {
155         if (checkNotNull(cookies, "cookies").isEmpty()) {
156             return null;
157         }
158 
159         StringBuilder buf = stringBuilder();
160         if (strict) {
161             if (cookies.size() == 1) {
162                 encode(buf, cookies.iterator().next());
163             } else {
164                 Cookie[] cookiesSorted = cookies.toArray(new Cookie[0]);
165                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
166                 for (Cookie c : cookiesSorted) {
167                     encode(buf, c);
168                 }
169             }
170         } else {
171             for (Cookie c : cookies) {
172                 encode(buf, c);
173             }
174         }
175         return stripTrailingSeparatorOrNull(buf);
176     }
177 
178     /**
179      * Encodes the specified cookies into a single Cookie header value.
180      *
181      * @param cookies some cookies
182      * @return a Rfc6265 style Cookie header value, null if no cookies are passed.
183      */
184     public String encode(Iterable<? extends Cookie> cookies) {
185         Iterator<? extends Cookie> cookiesIt = checkNotNull(cookies, "cookies").iterator();
186         if (!cookiesIt.hasNext()) {
187             return null;
188         }
189 
190         StringBuilder buf = stringBuilder();
191         if (strict) {
192             Cookie firstCookie = cookiesIt.next();
193             if (!cookiesIt.hasNext()) {
194                 encode(buf, firstCookie);
195             } else {
196                 List<Cookie> cookiesList = InternalThreadLocalMap.get().arrayList();
197                 cookiesList.add(firstCookie);
198                 while (cookiesIt.hasNext()) {
199                     cookiesList.add(cookiesIt.next());
200                 }
201                 Cookie[] cookiesSorted = cookiesList.toArray(new Cookie[0]);
202                 Arrays.sort(cookiesSorted, COOKIE_COMPARATOR);
203                 for (Cookie c : cookiesSorted) {
204                     encode(buf, c);
205                 }
206             }
207         } else {
208             while (cookiesIt.hasNext()) {
209                 encode(buf, cookiesIt.next());
210             }
211         }
212         return stripTrailingSeparatorOrNull(buf);
213     }
214 
215     private void encode(StringBuilder buf, Cookie c) {
216         final String name = c.name();
217         final String value = c.value() != null ? c.value() : "";
218 
219         validateCookie(name, value);
220 
221         if (c.wrap()) {
222             addQuoted(buf, name, value);
223         } else {
224             add(buf, name, value);
225         }
226     }
227 }