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    *   https://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  
17  package io.netty.handler.codec.mqtt;
18  
19  import io.netty.util.CharsetUtil;
20  import io.netty.util.internal.ObjectUtil;
21  
22  /**
23   * Mqtt version specific constant values used by multiple classes in mqtt-codec.
24   */
25  public enum MqttVersion {
26      MQTT_3_1("MQIsdp", (byte) 3),
27      MQTT_3_1_1("MQTT", (byte) 4),
28      MQTT_5("MQTT", (byte) 5);
29  
30      private final String name;
31      private final byte level;
32  
33      MqttVersion(String protocolName, byte protocolLevel) {
34          name = ObjectUtil.checkNotNull(protocolName, "protocolName");
35          level = protocolLevel;
36      }
37  
38      public String protocolName() {
39          return name;
40      }
41  
42      public byte[] protocolNameBytes() {
43          return name.getBytes(CharsetUtil.UTF_8);
44      }
45  
46      public byte protocolLevel() {
47          return level;
48      }
49  
50      public static MqttVersion fromProtocolNameAndLevel(String protocolName, byte protocolLevel) {
51          MqttVersion mv = null;
52          switch (protocolLevel) {
53          case 3:
54              mv = MQTT_3_1;
55              break;
56          case 4:
57              mv = MQTT_3_1_1;
58              break;
59          case 5:
60              mv = MQTT_5;
61              break;
62          default:
63              break;
64          }
65          if (mv == null) {
66              throw new MqttUnacceptableProtocolVersionException(protocolName + " is an unknown protocol name");
67          }
68          if (mv.name.equals(protocolName)) {
69              return mv;
70          }
71          throw new MqttUnacceptableProtocolVersionException(protocolName + " and " + protocolLevel + " don't match");
72      }
73  }