1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * Copyright (C) 2015-2016 Neo Visionaries Inc.
 *
 * 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 NeoVisionaries.WebSockets;


import java.util.LinkedHashMap;
import java.util.Map;


/**
 * A class to hold the name and the parameters of
 * a WebSocket extension.
 * 
 * <EMBED CLASS='external-html' DATA-FILE-ID=LICENSE>
 */
public class WebSocketExtension
{
    /**
     * The name of <code>permessage-deflate</code> extension that is
     * defined in <a href="https://tools.ietf.org/html/rfc7692#section-7"
     * >7&#46; The "permessage-deflate" Extension</a> in <a href=
     * "https://tools.ietf.org/html/rfc7692">RFC 7692</a>.
     *
     * @since 1.17
     */
    public static final String PERMESSAGE_DEFLATE = "permessage-deflate";


    private final String mName;
    private final Map<String, String> mParameters;


    /**
     * Constructor with an extension name.
     *
     * @param name
     *         The extension name.
     *
     * @throws IllegalArgumentException
     *         The given name is not a valid token.
     */
    public WebSocketExtension(String name)
    {
        // Check the validity of the name.
        if (Token.isValid(name) == false)
        {
            // The name is not a valid token.
            throw new IllegalArgumentException("'name' is not a valid token.");
        }

        mName       = name;
        mParameters = new LinkedHashMap<String, String>();
    }


    /**
     * Copy constructor.
     *
     * @param source
     *         A source extension. Must not be {@code null}.
     *
     * @throws IllegalArgumentException
     *         The given argument is {@code null}.
     *
     * @since 1.6
     */
    public WebSocketExtension(WebSocketExtension source)
    {
        if (source == null)
        {
            // If the given instance is null.
            throw new IllegalArgumentException("'source' is null.");
        }

        mName       = source.getName();
        mParameters = new LinkedHashMap<String, String>(source.getParameters());
    }


    /**
     * Get the extension name.
     *
     * @return
     *         The extension name.
     */
    public String getName()
    {
        return mName;
    }


    /**
     * Get the parameters.
     *
     * @return
     *         The parameters.
     */
    public Map<String, String> getParameters()
    {
        return mParameters;
    }


    /**
     * Check if the parameter identified by the key is contained.
     *
     * @param key
     *         The name of the parameter.
     *
     * @return
     *         {@code true} if the parameter is contained.
     */
    public boolean containsParameter(String key)
    {
        return mParameters.containsKey(key);
    }


    /**
     * Get the value of the specified parameter.
     *
     * @param key
     *         The name of the parameter.
     *
     * @return
     *         The value of the parameter. {@code null} may be returned.
     */
    public String getParameter(String key)
    {
        return mParameters.get(key);
    }


    /**
     * Set a value to the specified parameter.
     *
     * @param key
     *         The name of the parameter.
     *
     * @param value
     *         The value of the parameter. If not {@code null}, it must be
     *         a valid token. Note that <a href="http://tools.ietf.org/html/rfc6455"
     *         >RFC 6455</a> says "<i>When using the quoted-string syntax
     *         variant, the value after quoted-string unescaping MUST
     *         conform to the 'token' ABNF.</i>"
     *
     * @return
     *         {@code this} object.
     *
     * @throws IllegalArgumentException
     *         <ul>
     *         <li>The key is not a valid token.</li>
     *         <li>The value is not {@code null} and it is not a valid token.</li>
     *         </ul>
     */
    public WebSocketExtension setParameter(String key, String value)
    {
        // Check the validity of the key.
        if (Token.isValid(key) == false)
        {
            // The key is not a valid token.
            throw new IllegalArgumentException("'key' is not a valid token.");
        }

        // If the value is not null.
        if (value != null)
        {
            // Check the validity of the value.
            if (Token.isValid(value) == false)
            {
                // The value is not a valid token.
                throw new IllegalArgumentException("'value' is not a valid token.");
            }
        }

        mParameters.put(key, value);

        return this;
    }


    /**
     * Stringify this object into the format "{name}[; {key}[={value}]]*".
     */
    @Override
    public String toString()
    {
        StringBuilder builder = new StringBuilder(mName);

        for (Map.Entry<String, String> entry : mParameters.entrySet())
        {
            // "; {key}"
            builder.append("; ").append(entry.getKey());

            String value = entry.getValue();

            if (value != null && value.length() != 0)
            {
                // "={value}"
                builder.append("=").append(value);
            }
        }

        return builder.toString();
    }


    /**
     * Validate this instance. This method is expected to be overridden.
     */
    void validate() throws WebSocketException
    {
    }


    /**
     * Parse a string as a {@link WebSocketExtension}. The input string
     * should comply with the format described in <a href=
     * "https://tools.ietf.org/html/rfc6455#section-9.1">9.1. Negotiating
     * Extensions</a> in <a href="https://tools.ietf.org/html/rfc6455"
     * >RFC 6455</a>.
     *
     * @param string
     *         A string that represents a WebSocket extension.
     *
     * @return
     *         A new {@link WebSocketExtension} instance that represents
     *         the given string. If the input string does not comply with
     *         RFC 6455, {@code null} is returned.
     */
    public static WebSocketExtension parse(String string)
    {
        if (string == null)
        {
            return null;
        }

        // Split the string by semi-colons.
        String[] elements = string.trim().split("\\s*;\\s*");

        if (elements.length == 0)
        {
            // Even an extension name is not included.
            return null;
        }

        // The first element is the extension name.
        String name = elements[0];

        if (Token.isValid(name) == false)
        {
            // The extension name is not a valid token.
            return null;
        }

        // Create an instance for the extension name.
        WebSocketExtension extension = createInstance(name);

        // For each "{key}[={value}]".
        for (int i = 1; i < elements.length; ++i)
        {
            // Split by '=' to get the key and the value.
            String[] pair = elements[i].split("\\s*=\\s*", 2);

            // If {key} is not contained.
            if (pair.length == 0 || pair[0].length() == 0)
            {
                // Ignore.
                continue;
            }

            // The name of the parameter.
            String key = pair[0];

            if (Token.isValid(key) == false)
            {
                // The parameter name is not a valid token.
                // Ignore this parameter.
                continue;
            }

            // The value of the parameter.
            String value = extractValue(pair);

            if (value != null)
            {
                if (Token.isValid(value) == false)
                {
                    // The parameter value is not a valid token.
                    // Ignore this parameter.
                    continue;
                }
            }

            // Add the pair of the key and the value.
            extension.setParameter(key, value);
        }

        return extension;
    }


    private static String extractValue(String[] pair)
    {
        if (pair.length != 2)
        {
            return null;
        }

        return Token.unquote(pair[1]);
    }


    private static WebSocketExtension createInstance(String name)
    {
        if (PERMESSAGE_DEFLATE.equals(name))
        {
            return new PerMessageDeflateExtension(name);
        }

        return new WebSocketExtension(name);
    }
}