MqttProperties.java 13.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * Copyright 2020 The Netty Project
 *
 * The Netty Project licenses this file to you 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:
 *
 *   https://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 net.dreamlu.iot.mqtt.codec;

import java.util.*;

/**
 * MQTT Properties container
23 24
 *
 * @author netty
25 26 27 28 29
 */
public final class MqttProperties {

	public enum MqttPropertyType {
		// single byte properties
30 31 32
		/**
		 * 有效载荷标识(Payload Format Indicator),该属性只存在于 PUBLISH 报文和 CONNECT 报文的遗嘱属性中。
		 */
33
		PAYLOAD_FORMAT_INDICATOR(0x01),
34 35 36
		/**
		 * 请求问题信息
		 */
37
		REQUEST_PROBLEM_INFORMATION(0x17),
38 39 40
		/**
		 * 请求响应信息
		 */
41
		REQUEST_RESPONSE_INFORMATION(0x19),
42 43 44
		/**
		 * 服务器支持得最高 qos 级别
		 */
45
		MAXIMUM_QOS(0x24),
46 47 48
		/**
		 * 保留消息可用
		 */
49
		RETAIN_AVAILABLE(0x25),
50 51 52
		/**
		 * 订阅通配符可用
		 */
53
		WILDCARD_SUBSCRIPTION_AVAILABLE(0x28),
54 55 56
		/**
		 * 订阅标识符可用
		 */
57
		SUBSCRIPTION_IDENTIFIER_AVAILABLE(0x29),
58 59 60
		/**
		 * $share 共享订阅可用
		 */
61 62 63
		SHARED_SUBSCRIPTION_AVAILABLE(0x2A),

		// two bytes properties
64 65 66
		/**
		 * 服务器 keep alive
		 */
67
		SERVER_KEEP_ALIVE(0x13),
68 69 70
		/**
		 * 告知对方自己希望处理未决的最大的 Qos1 或者 Qos2 PUBLISH消息个数,如果不存在,则默认是65535。作用:流控。
		 */
71
		RECEIVE_MAXIMUM(0x21),
72 73 74
		/**
		 * topic 别名最大值
		 */
75
		TOPIC_ALIAS_MAXIMUM(0x22),
76 77 78
		/**
		 * topic 别名
		 */
79 80 81 82
		TOPIC_ALIAS(0x23),

		// four bytes properties
		PUBLICATION_EXPIRY_INTERVAL(0x02),
83 84 85
		/**
		 * session 超时时间,连接时使用
		 */
86
		SESSION_EXPIRY_INTERVAL(0x11),
87 88 89
		/**
		 * 遗嘱消息延迟时间
		 */
90
		WILL_DELAY_INTERVAL(0x18),
91 92 93
		/**
		 * 最大包体大小
		 */
94 95 96
		MAXIMUM_PACKET_SIZE(0x27),

		// Variable Byte Integer
97 98 99
		/**
		 * 订阅标识符
		 */
100 101 102
		SUBSCRIPTION_IDENTIFIER(0x0B),

		// UTF-8 Encoded String properties
103 104 105 106
		/**
		 * 内容类型(Content Type),只存在于 PUBLISH 报文和 CONNECT 报文的遗嘱属性中。
		 * 例如:存放 MIME 类型,比如 text/plain 表示文本文件,audio/aac 表示音频文件。
		 */
107
		CONTENT_TYPE(0x03),
108 109 110
		/**
		 * 响应的 topic
		 */
111
		RESPONSE_TOPIC(0x08),
112 113 114
		/**
		 * 指定的客户标识符
		 */
115
		ASSIGNED_CLIENT_IDENTIFIER(0x12),
116 117 118
		/**
		 * 身份验证方法
		 */
119
		AUTHENTICATION_METHOD(0x15),
120 121 122
		/**
		 * 响应信息
		 */
123
		RESPONSE_INFORMATION(0x1A),
124 125 126
		/**
		 * 服务器参考
		 */
127
		SERVER_REFERENCE(0x1C),
128 129 130 131
		/**
		 * 所有的ACK以及DISCONNECT 都可以携带 Reason String属性告知对方一些特殊的信息,
		 * 一般来说是ACK失败的情况下会使用该属性告知对端为什么失败,可用来弥补Reason Code信息不够。
		 */
132
		REASON_STRING(0x1F),
133 134 135
		/**
		 * 用户属性
		 */
136 137 138
		USER_PROPERTY(0x26),

		// Binary Data
139 140 141
		/**
		 * 相关数据
		 */
142
		CORRELATION_DATA(0x09),
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
		AUTHENTICATION_DATA(0x16);

		private static final MqttPropertyType[] VALUES;

		static {
			VALUES = new MqttPropertyType[43];
			for (MqttPropertyType v : values()) {
				VALUES[v.value] = v;
			}
		}

		private final int value;

		MqttPropertyType(int value) {
			this.value = value;
		}

		public int value() {
			return value;
		}

		public static MqttPropertyType valueOf(int type) {
			MqttPropertyType t = null;
			try {
				t = VALUES[type];
			} catch (ArrayIndexOutOfBoundsException ignored) {
				// nop
			}
			if (t == null) {
				throw new IllegalArgumentException("unknown property type: " + type);
			}
			return t;
		}
	}

	public static final MqttProperties NO_PROPERTIES = new MqttProperties(false);

	static MqttProperties withEmptyDefaults(MqttProperties properties) {
		if (properties == null) {
			return MqttProperties.NO_PROPERTIES;
		}
		return properties;
	}

	/**
	 * MQTT property base class
	 *
	 * @param <T> property type
	 */
	public abstract static class MqttProperty<T> {
		final T value;
		final int propertyId;

		protected MqttProperty(int propertyId, T value) {
			this.propertyId = propertyId;
			this.value = value;
		}

		/**
		 * Get MQTT property value
		 *
		 * @return property value
		 */
		public T value() {
			return value;
		}

		/**
		 * Get MQTT property ID
		 *
		 * @return property ID
		 */
		public int propertyId() {
			return propertyId;
		}

		@Override
		public int hashCode() {
			return propertyId + 31 * value.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null || getClass() != obj.getClass()) {
				return false;
			}
			MqttProperty that = (MqttProperty) obj;
			return this.propertyId == that.propertyId && this.value.equals(that.value);
		}
	}

	public static final class IntegerProperty extends MqttProperty<Integer> {

		public IntegerProperty(int propertyId, Integer value) {
			super(propertyId, value);
		}

		@Override
		public String toString() {
			return "IntegerProperty(" + propertyId + ", " + value + ")";
		}
	}

	public static final class StringProperty extends MqttProperty<String> {

		public StringProperty(int propertyId, String value) {
			super(propertyId, value);
		}

		@Override
		public String toString() {
			return "StringProperty(" + propertyId + ", " + value + ")";
		}
	}

	public static final class StringPair {
		public final String key;
		public final String value;

		public StringPair(String key, String value) {
			this.key = key;
			this.value = value;
		}

		@Override
		public int hashCode() {
			return key.hashCode() + 31 * value.hashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj) {
				return true;
			}
			if (obj == null || getClass() != obj.getClass()) {
				return false;
			}
			StringPair that = (StringPair) obj;

			return that.key.equals(this.key) && that.value.equals(this.value);
		}
	}

	//User properties are the only properties that may be included multiple times and
	//are the only properties where ordering is required. Therefore, they need a special handling
	public static final class UserProperties extends MqttProperty<List<StringPair>> {
		public UserProperties() {
			super(MqttPropertyType.USER_PROPERTY.value, new ArrayList<>());
		}

		/**
		 * Create user properties from the collection of the String pair values
		 *
		 * @param values string pairs. Collection entries are copied, collection itself isn't shared
		 */
		public UserProperties(Collection<StringPair> values) {
			this();
			this.value.addAll(values);
		}

		private static UserProperties fromUserPropertyCollection(Collection<UserProperty> properties) {
			UserProperties userProperties = new UserProperties();
			for (UserProperty property : properties) {
				userProperties.add(new StringPair(property.value.key, property.value.value));
			}
			return userProperties;
		}

		public void add(StringPair pair) {
			this.value.add(pair);
		}

		public void add(String key, String value) {
			this.value.add(new StringPair(key, value));
		}

		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder("UserProperties(");
			boolean first = true;
			for (StringPair pair : value) {
				if (!first) {
					builder.append(", ");
				}
如梦技术's avatar
如梦技术 已提交
333
				builder.append(pair.key).append("->").append(pair.value);
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
				first = false;
			}
			builder.append(")");
			return builder.toString();
		}
	}

	public static final class UserProperty extends MqttProperty<StringPair> {
		public UserProperty(String key, String value) {
			super(MqttPropertyType.USER_PROPERTY.value, new StringPair(key, value));
		}

		@Override
		public String toString() {
			return "UserProperty(" + value.key + ", " + value.value + ")";
		}
	}

	public static final class BinaryProperty extends MqttProperty<byte[]> {

		public BinaryProperty(int propertyId, byte[] value) {
			super(propertyId, value);
		}

		@Override
		public String toString() {
			return "BinaryProperty(" + propertyId + ", " + value.length + " bytes)";
		}
	}

	public MqttProperties() {
		this(true);
	}

	private MqttProperties(boolean canModify) {
		this.canModify = canModify;
	}

	private Map<Integer, MqttProperty> props;
	private List<UserProperty> userProperties;
	private List<IntegerProperty> subscriptionIds;
	private final boolean canModify;

	public void add(MqttProperty property) {
		if (!canModify) {
			throw new UnsupportedOperationException("adding property isn't allowed");
		}
		Map<Integer, MqttProperty> props = this.props;
		if (property.propertyId == MqttPropertyType.USER_PROPERTY.value) {
			List<UserProperty> userProperties = this.userProperties;
			if (userProperties == null) {
				userProperties = new ArrayList<>(1);
				this.userProperties = userProperties;
			}
			if (property instanceof UserProperty) {
				userProperties.add((UserProperty) property);
			} else if (property instanceof UserProperties) {
				for (StringPair pair : ((UserProperties) property).value) {
					userProperties.add(new UserProperty(pair.key, pair.value));
				}
			} else {
				throw new IllegalArgumentException("User property must be of UserProperty or UserProperties type");
			}
		} else if (property.propertyId == MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value) {
			List<IntegerProperty> subscriptionIds = this.subscriptionIds;
			if (subscriptionIds == null) {
如梦技术's avatar
如梦技术 已提交
400
				subscriptionIds = new ArrayList<>(1);
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
				this.subscriptionIds = subscriptionIds;
			}
			if (property instanceof IntegerProperty) {
				subscriptionIds.add((IntegerProperty) property);
			} else {
				throw new IllegalArgumentException("Subscription ID must be an integer property");
			}
		} else {
			if (props == null) {
				props = new HashMap<>();
				this.props = props;
			}
			props.put(property.propertyId, property);
		}
	}

	public Collection<? extends MqttProperty> listAll() {
		Map<Integer, MqttProperty> props = this.props;
		if (props == null && subscriptionIds == null && userProperties == null) {
如梦技术's avatar
如梦技术 已提交
420
			return Collections.emptyList();
421 422 423 424 425 426 427
		}
		if (subscriptionIds == null && userProperties == null) {
			return props.values();
		}
		if (props == null && userProperties == null) {
			return subscriptionIds;
		}
如梦技术's avatar
如梦技术 已提交
428
		List<MqttProperty> propValues = new ArrayList<>(props != null ? props.size() : 1);
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
		if (props != null) {
			propValues.addAll(props.values());
		}
		if (subscriptionIds != null) {
			propValues.addAll(subscriptionIds);
		}
		if (userProperties != null) {
			propValues.add(UserProperties.fromUserPropertyCollection(userProperties));
		}
		return propValues;
	}

	public boolean isEmpty() {
		Map<Integer, MqttProperty> props = this.props;
		return props == null || props.isEmpty();
	}

	/**
	 * Get property by ID. If there are multiple properties of this type (can be with Subscription ID)
	 * then return the first one.
	 *
	 * @param propertyId ID of the property
	 * @return a property if it is set, null otherwise
	 */
	public MqttProperty getProperty(int propertyId) {
454
		if (MqttPropertyType.USER_PROPERTY.value == propertyId) {
455 456 457 458 459 460 461
			//special handling to keep compatibility with earlier versions
			List<UserProperty> userProperties = this.userProperties;
			if (userProperties == null) {
				return null;
			}
			return UserProperties.fromUserPropertyCollection(userProperties);
		}
462
		if (MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value == propertyId) {
463 464 465 466 467 468 469 470 471 472
			List<IntegerProperty> subscriptionIds = this.subscriptionIds;
			if (subscriptionIds == null || subscriptionIds.isEmpty()) {
				return null;
			}
			return subscriptionIds.get(0);
		}
		Map<Integer, MqttProperty> props = this.props;
		return props == null ? null : props.get(propertyId);
	}

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
	/**
	 * Get property by ID. If there are multiple properties of this type (can be with Subscription ID)
	 * then return the first one.
	 *
	 * @param mqttPropertyType Type of the property
	 * @return a property if it is set, null otherwise
	 */
	public MqttProperty getProperty(MqttPropertyType mqttPropertyType) {
		return getProperty(mqttPropertyType.value);
	}

	/**
	 * Get property by ID. If there are multiple properties of this type (can be with Subscription ID)
	 * then return the first one.
	 *
	 * @param mqttPropertyType Type of the property
浅梦2013's avatar
浅梦2013 已提交
489
	 * @param <T>              泛型标记
浅梦2013's avatar
浅梦2013 已提交
490
	 * @return a property value if it is set, null otherwise
491 492 493 494 495 496 497 498 499
	 */
	public <T> T getPropertyValue(MqttPropertyType mqttPropertyType) {
		MqttProperty property = getProperty(mqttPropertyType.value);
		if (property == null) {
			return null;
		}
		return (T) property.value();
	}

500 501 502 503 504 505 506 507 508 509
	/**
	 * Get properties by ID.
	 * Some properties (Subscription ID and User Properties) may occur multiple times,
	 * this method returns all their values in order.
	 *
	 * @param propertyId ID of the property
	 * @return all properties having specified ID
	 */
	public List<? extends MqttProperty> getProperties(int propertyId) {
		if (propertyId == MqttPropertyType.USER_PROPERTY.value) {
如梦技术's avatar
如梦技术 已提交
510
			return userProperties == null ? Collections.emptyList() : userProperties;
511 512
		}
		if (propertyId == MqttPropertyType.SUBSCRIPTION_IDENTIFIER.value) {
如梦技术's avatar
如梦技术 已提交
513
			return subscriptionIds == null ? Collections.emptyList() : subscriptionIds;
514 515 516
		}
		Map<Integer, MqttProperty> props = this.props;
		return (props == null || !props.containsKey(propertyId)) ?
如梦技术's avatar
如梦技术 已提交
517
			Collections.emptyList() :
518 519 520
			Collections.singletonList(props.get(propertyId));
	}
}