1/*
2 * Copyright (C) 2014 Square, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.squareup.okhttp;
17
18import com.squareup.okhttp.internal.Util;
19import java.io.IOException;
20import java.util.Arrays;
21import java.util.List;
22import okio.ByteString;
23
24/**
25 * Contains protocols that OkHttp supports
26 * <a href="http://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04">NPN</a> or
27 * <a href="http://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg">ALPN</a> selection.
28 *
29 * <p>
30 * <h3>Protocol vs Scheme</h3>
31 * Despite its name, {@link java.net.URL#getProtocol()} returns the
32 * {@link java.net.URI#getScheme() scheme} (http, https, etc.) of the URL, not
33 * the protocol (http/1.1, spdy/3.1, etc.).  OkHttp uses the word protocol to
34 * indicate how HTTP messages are framed.
35 */
36public enum Protocol {
37  HTTP_2("HTTP-draft-09/2.0", true),
38  SPDY_3("spdy/3.1", true),
39  HTTP_11("http/1.1", false);
40
41  public static final List<Protocol> HTTP2_SPDY3_AND_HTTP =
42      Util.immutableList(Arrays.asList(HTTP_2, SPDY_3, HTTP_11));
43  public static final List<Protocol> SPDY3_AND_HTTP11 =
44      Util.immutableList(Arrays.asList(SPDY_3, HTTP_11));
45  public static final List<Protocol> HTTP2_AND_HTTP_11 =
46      Util.immutableList(Arrays.asList(HTTP_2, HTTP_11));
47
48  /** Identifier string used in NPN or ALPN selection. */
49  public final ByteString name;
50
51  /**
52   * When true the protocol is binary framed and derived from SPDY.
53   *
54   * @see com.squareup.okhttp.internal.spdy.Variant
55   */
56  public final boolean spdyVariant;
57
58  Protocol(String name, boolean spdyVariant) {
59    this.name = ByteString.encodeUtf8(name);
60    this.spdyVariant = spdyVariant;
61  }
62
63  /**
64   * Returns the protocol matching {@code input} or {@link #HTTP_11} is on
65   * {@code null}. Throws an {@link IOException} when {@code input} doesn't
66   * match the {@link #name} of a supported protocol.
67   */
68  public static Protocol find(ByteString input) throws IOException {
69    if (input == null) return HTTP_11;
70    for (Protocol protocol : values()) {
71      if (protocol.name.equals(input)) return protocol;
72    }
73    throw new IOException("Unexpected protocol: " + input.utf8());
74  }
75}
76