From 6b8af4e7e301cdc318d527301dd147ca16fb8fbd Mon Sep 17 00:00:00 2001 From: JamesChenX Date: Sun, 10 Dec 2023 19:45:02 +0800 Subject: [PATCH] Modernize Java code using pattern matching for switch to make code concise #866 --- .../admin/web/HttpRequestDispatcher.java | 22 +-- .../service/discovery/DiscoveryService.java | 1 - .../infra/collection/CollectionUtil.java | 23 ++- .../common/infra/exception/ThrowableInfo.java | 29 ++-- .../server/common/infra/json/JsonUtil.java | 67 ++++---- .../common/infra/netty/ByteBufUtil.java | 89 +++++----- .../infra/plugin/script/ValueDecoder.java | 40 ++--- .../common/infra/validation/Validator.java | 23 +-- .../storage/mongo/codec/BsonValueEncoder.java | 154 ++++++++---------- .../mongo/exception/MongoExceptionUtil.java | 72 ++++---- .../core/protocol/CommandArgsUtil.java | 44 ++--- .../mongo/MongoCollectionInitializer.java | 1 - 12 files changed, 262 insertions(+), 303 deletions(-) diff --git a/turms-server-common/src/main/java/im/turms/server/common/access/admin/web/HttpRequestDispatcher.java b/turms-server-common/src/main/java/im/turms/server/common/access/admin/web/HttpRequestDispatcher.java index 635acfaf56..304d22a328 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/access/admin/web/HttpRequestDispatcher.java +++ b/turms-server-common/src/main/java/im/turms/server/common/access/admin/web/HttpRequestDispatcher.java @@ -548,19 +548,15 @@ private static HttpHandlerResult> translateThrowable(Throwable th return HttpHandlerResult.create(statusCode.getHttpStatusCode(), new ResponseDTO<>(statusCode, reason)); } else { - ResponseStatusCode statusCode; - if (throwable instanceof IllegalArgumentException - || throwable instanceof ConstraintViolationException) { - statusCode = ResponseStatusCode.ILLEGAL_ARGUMENT; - } else if (throwable instanceof DuplicateKeyException) { - statusCode = ResponseStatusCode.RECORD_CONTAINS_DUPLICATE_KEY; - } else if (throwable instanceof DuplicateResourceException) { - statusCode = ResponseStatusCode.DUPLICATE_RESOURCE; - } else if (throwable instanceof ResourceNotFoundException) { - statusCode = ResponseStatusCode.RESOURCE_NOT_FOUND; - } else { - statusCode = ResponseStatusCode.SERVER_INTERNAL_ERROR; - } + ResponseStatusCode statusCode = switch (throwable) { + case IllegalArgumentException ignored -> ResponseStatusCode.ILLEGAL_ARGUMENT; + case ConstraintViolationException ignored -> ResponseStatusCode.ILLEGAL_ARGUMENT; + case DuplicateKeyException ignored -> + ResponseStatusCode.RECORD_CONTAINS_DUPLICATE_KEY; + case DuplicateResourceException ignored -> ResponseStatusCode.DUPLICATE_RESOURCE; + case ResourceNotFoundException ignored -> ResponseStatusCode.RESOURCE_NOT_FOUND; + default -> ResponseStatusCode.SERVER_INTERNAL_ERROR; + }; String reason = throwable.getMessage(); return HttpHandlerResult.create(statusCode.getHttpStatusCode(), new ResponseDTO<>(statusCode, reason)); diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/cluster/service/discovery/DiscoveryService.java b/turms-server-common/src/main/java/im/turms/server/common/infra/cluster/service/discovery/DiscoveryService.java index 6d5fc132fc..b360d15ce7 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/cluster/service/discovery/DiscoveryService.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/cluster/service/discovery/DiscoveryService.java @@ -471,7 +471,6 @@ private void onMemberUpdated(String nodeId, UpdateDescription updateDescription) // better maintainability considering possible field changes String fieldName = entry.getKey(); BsonValue value = entry.getValue(); - // TODO: pattern matching // Check status change if (fieldName.endsWith(Member.MemberStatus.Fields.lastHeartbeatDate)) { memberToUpdate.getStatus() diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/collection/CollectionUtil.java b/turms-server-common/src/main/java/im/turms/server/common/infra/collection/CollectionUtil.java index 0a52b1155c..81031c465b 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/collection/CollectionUtil.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/collection/CollectionUtil.java @@ -191,19 +191,18 @@ public static int getSize(@Nullable Map map) { } public static int getSize(@Nullable Iterable iterable) { - if (iterable == null) { - return 0; - } else if (iterable instanceof Collection collection) { - return collection.size(); - } else if (iterable instanceof Map map) { - return map.size(); - } else { - int size = 0; - for (Object ignored : iterable) { - size++; + return switch (iterable) { + case null -> 0; + case Collection collection -> collection.size(); + case Map map -> map.size(); + default -> { + int size = 0; + for (Object ignored : iterable) { + size++; + } + yield size; } - return size; - } + }; } public static boolean isEmpty(@Nullable Collection collection) { diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/exception/ThrowableInfo.java b/turms-server-common/src/main/java/im/turms/server/common/infra/exception/ThrowableInfo.java index fc902b4584..550367a766 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/exception/ThrowableInfo.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/exception/ThrowableInfo.java @@ -17,6 +17,8 @@ package im.turms.server.common.infra.exception; +import jakarta.annotation.Nullable; + import im.turms.server.common.access.common.ResponseStatusCode; import im.turms.server.common.infra.cluster.service.rpc.exception.RpcException; import im.turms.server.common.infra.io.ResourceNotFoundException; @@ -28,27 +30,24 @@ */ public record ThrowableInfo( ResponseStatusCode code, - String reason + @Nullable String reason ) { public static ThrowableInfo get(Throwable throwable) { - if (throwable instanceof ResponseException e) { - return new ThrowableInfo(e.getCode(), e.getReason()); - } else if (throwable instanceof RpcException e) { - return new ThrowableInfo(e.getStatusCode(), e.getMessage()); - } else if (throwable instanceof DuplicateKeyException e) { + return switch (throwable) { + case ResponseException e -> new ThrowableInfo(e.getCode(), e.getReason()); + case RpcException e -> new ThrowableInfo(e.getStatusCode(), e.getMessage()); // We consider DuplicateKeyException as a client error here, // because if it is an exception caused by the illegal args provided // by the server, it should recover in the upstream rather than // passing down DuplicateKeyException - return new ThrowableInfo( - ResponseStatusCode.RECORD_CONTAINS_DUPLICATE_KEY, - e.getMessage()); - } else if (throwable instanceof ResourceNotFoundException e) { - return new ThrowableInfo(ResponseStatusCode.RESOURCE_NOT_FOUND, e.getMessage()); - } else if (throwable instanceof ExtensionPointExecutionException e) { - return get(e.getCause()); - } - return new ThrowableInfo(ResponseStatusCode.SERVER_INTERNAL_ERROR, throwable.getMessage()); + case DuplicateKeyException e -> + new ThrowableInfo(ResponseStatusCode.RECORD_CONTAINS_DUPLICATE_KEY, e.getMessage()); + case ResourceNotFoundException e -> + new ThrowableInfo(ResponseStatusCode.RESOURCE_NOT_FOUND, e.getMessage()); + case ExtensionPointExecutionException e -> get(e.getCause()); + default -> + new ThrowableInfo(ResponseStatusCode.SERVER_INTERNAL_ERROR, throwable.getMessage()); + }; } } \ No newline at end of file diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/json/JsonUtil.java b/turms-server-common/src/main/java/im/turms/server/common/infra/json/JsonUtil.java index d9ff77d1c9..8a26d92230 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/json/JsonUtil.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/json/JsonUtil.java @@ -154,43 +154,48 @@ private static int estimateRecordSize(Object value) { } private static int estimateNonRecordSize(Object value) { - int size = 0; - if (value instanceof Iterable iterable) { - for (Object element : iterable) { - size += estimateSize(element); + return switch (value) { + case Iterable iterable -> { + int size = 0; + for (Object element : iterable) { + size += estimateSize(element); + } + yield size; + } + case Map map -> { + int size = 0; + for (Map.Entry entry : map.entrySet()) { + size += entry.getKey() instanceof String str + ? StringUtil.getLength(str) + : 16; + Object entryValue = entry.getValue(); + size += estimateSize(entryValue); + size += ESTIMATED_JSON_FIELD_METADATA_SIZE; + } + yield size; } - } else if (value.getClass() - .isArray()) { - if (value instanceof byte[] array) { - size += array.length; - } else if (value instanceof Object[] array) { + case Date ignored -> DateUtil.DATE_TIME_LENGTH; + case String str -> StringUtil.getLength(str); + case byte[] array -> array.length; + case Object[] array -> { + int size = 0; for (Object element : array) { size += estimateSize(element); } - } else { - // We don't support other array types now because we don't use them - LOGGER.warn("Unknown array type: " - + value.getClass() - .getName()); + yield size; } - } else if (value instanceof Map map) { - for (Map.Entry entry : map.entrySet()) { - size += entry.getKey() instanceof String str - ? StringUtil.getLength(str) - : 16; - Object entryValue = entry.getValue(); - size += estimateSize(entryValue); - size += ESTIMATED_JSON_FIELD_METADATA_SIZE; + default -> { + if (value.getClass() + .isArray()) { + // We don't support other array types now because we don't use them + LOGGER.warn("Unknown array type: " + + value.getClass() + .getName()); + } + // We don't use "String.valueOf(val).length()" for better performance + yield 16; } - } else if (value instanceof Date) { - size += DateUtil.DATE_TIME_LENGTH; - } else if (value instanceof String str) { - size += StringUtil.getLength(str); - } else { - // We don't use "String.valueOf(val).length()" for better performance - size += 16; - } - return size; + }; } private static RecordMetadata getRecordMetadata(Object value) { diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/netty/ByteBufUtil.java b/turms-server-common/src/main/java/im/turms/server/common/infra/netty/ByteBufUtil.java index 1b89785a99..4f6de0b520 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/netty/ByteBufUtil.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/netty/ByteBufUtil.java @@ -159,48 +159,34 @@ public static String getString(ByteBuf buffer) { } public static ByteBuf writeObject(Object obj) { - if (obj instanceof ByteBuf element) { - return element; - } - if (obj instanceof Byte element) { - return getPooledPreferredByteBuffer(element.intValue()); - } - if (obj instanceof Short element) { - return PooledByteBufAllocator.DEFAULT.directBuffer(Short.BYTES) + return switch (obj) { + case ByteBuf element -> element; + case Byte element -> getPooledPreferredByteBuffer(element.intValue()); + case Short element -> PooledByteBufAllocator.DEFAULT.directBuffer(Short.BYTES) .writeShort(element); - } - if (obj instanceof Integer element) { - return getPooledPreferredIntegerBuffer(element); - } - if (obj instanceof Long element) { - return PooledByteBufAllocator.DEFAULT.directBuffer(Long.BYTES) + case Integer element -> getPooledPreferredIntegerBuffer(element); + case Long element -> PooledByteBufAllocator.DEFAULT.directBuffer(Long.BYTES) .writeLong(element); - } - if (obj instanceof String element) { - byte[] bytes = StringUtil.getUtf8Bytes(element); - return PooledByteBufAllocator.DEFAULT.directBuffer(bytes.length) - .writeBytes(bytes); - } - if (obj instanceof Float element) { - return PooledByteBufAllocator.DEFAULT.directBuffer(Float.BYTES) + case String element -> { + byte[] bytes = StringUtil.getUtf8Bytes(element); + yield PooledByteBufAllocator.DEFAULT.directBuffer(bytes.length) + .writeBytes(bytes); + } + case Float element -> PooledByteBufAllocator.DEFAULT.directBuffer(Float.BYTES) .writeFloat(element); - } - if (obj instanceof Double element) { - return PooledByteBufAllocator.DEFAULT.directBuffer(Double.BYTES) + case Double element -> PooledByteBufAllocator.DEFAULT.directBuffer(Double.BYTES) .writeDouble(element); - } - if (obj instanceof Character element) { - return PooledByteBufAllocator.DEFAULT.directBuffer(Character.BYTES) + case Character element -> PooledByteBufAllocator.DEFAULT.directBuffer(Character.BYTES) .writeChar(element); - } - if (obj instanceof Boolean element) { - return getPooledPreferredByteBuffer(element + case Boolean element -> getPooledPreferredByteBuffer(element ? 1 : 0); - } - throw new IllegalArgumentException( - "Could not serialize the unknown value: " - + obj); + case null, + default -> + throw new IllegalArgumentException( + "Could not serialize the unknown value: " + + obj); + }; } public static ByteBuf[] writeObjects(Object... objs) { @@ -230,22 +216,21 @@ public static ByteBuf join(int estimatedSize, int delimiter, Object... elements) ByteBuf buffer = PooledByteBufAllocator.DEFAULT.directBuffer(estimatedSize); for (int i = 0, length = elements.length, last = length - 1; i < length; i++) { Object element = elements[i]; - if (element instanceof Integer num) { - buffer.writeBytes(NumberFormatter.toCharBytes(num)); - } else if (element instanceof Long num) { - buffer.writeBytes(NumberFormatter.toCharBytes(num)); - } else if (element instanceof String s) { - buffer.writeBytes(StringUtil.getBytes(s)); - } else if (element instanceof byte[] bytes) { - buffer.writeBytes(bytes); - } else if (element instanceof Character c) { - buffer.writeChar(c); - } else if (element != null) { - buffer.release(); - throw new IllegalArgumentException( - "Unsupported class: " - + element.getClass() - .getName()); + switch (element) { + case null -> { + } + case Integer num -> buffer.writeBytes(NumberFormatter.toCharBytes(num)); + case Long num -> buffer.writeBytes(NumberFormatter.toCharBytes(num)); + case Character c -> buffer.writeChar(c); + case String s -> buffer.writeBytes(StringUtil.getBytes(s)); + case byte[] bytes -> buffer.writeBytes(bytes); + default -> { + buffer.release(); + throw new IllegalArgumentException( + "Unsupported class: " + + element.getClass() + .getName()); + } } if (i != last) { buffer.writeByte(delimiter); @@ -254,4 +239,4 @@ public static ByteBuf join(int estimatedSize, int delimiter, Object... elements) return buffer; } -} +} \ No newline at end of file diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/plugin/script/ValueDecoder.java b/turms-server-common/src/main/java/im/turms/server/common/infra/plugin/script/ValueDecoder.java index 26d294f4bc..4b97cc0ab8 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/plugin/script/ValueDecoder.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/plugin/script/ValueDecoder.java @@ -38,8 +38,8 @@ public class ValueDecoder { private ValueDecoder() { } + @Nullable public static Object decode(@Nullable Value value) { - // TODO: pattern matching if (value == null || value.isNull()) { return null; } else if (value.isString()) { @@ -150,26 +150,26 @@ public static Mono decodeAsMonoIfPromise(Value value, boolean decodePromiseVa } public static ScriptExecutionException translateException(Object exception) { - if (exception instanceof ScriptExecutionException e) { - return e; - } else if (exception instanceof PolyglotException e) { - ScriptExceptionSource source = e.isHostException() - ? ScriptExceptionSource.HOST - : ScriptExceptionSource.SCRIPT; - return new ScriptExecutionException(e, source); - } else if (exception instanceof Throwable t) { - return new ScriptExecutionException(t, ScriptExceptionSource.HOST); - } else if (exception instanceof Value value && value.isException()) { - Throwable t; - try { - t = value.throwException(); - } catch (Exception e) { - t = e; + return switch (exception) { + case ScriptExecutionException e -> e; + case PolyglotException e -> new ScriptExecutionException( + e, + e.isHostException() + ? ScriptExceptionSource.HOST + : ScriptExceptionSource.SCRIPT); + case Throwable t -> new ScriptExecutionException(t, ScriptExceptionSource.HOST); + case Value value when value.isException() -> { + Throwable t; + try { + t = value.throwException(); + } catch (Exception e) { + t = e; + } + yield new ScriptExecutionException(t, ScriptExceptionSource.SCRIPT); } - return new ScriptExecutionException(t, ScriptExceptionSource.SCRIPT); - } else { - return new ScriptExecutionException(exception.toString(), ScriptExceptionSource.SCRIPT); - } + default -> + new ScriptExecutionException(exception.toString(), ScriptExceptionSource.SCRIPT); + }; } } \ No newline at end of file diff --git a/turms-server-common/src/main/java/im/turms/server/common/infra/validation/Validator.java b/turms-server-common/src/main/java/im/turms/server/common/infra/validation/Validator.java index c9ebaa7a17..f79ac16214 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/infra/validation/Validator.java +++ b/turms-server-common/src/main/java/im/turms/server/common/infra/validation/Validator.java @@ -40,20 +40,15 @@ private Validator() { } public static boolean isFalsy(@Nullable Object item) { - if (item == null) { - return true; - } - if (item instanceof String str) { - return str.isEmpty(); - } else if (item instanceof Collection collection) { - return collection.isEmpty(); - } else if (item.getClass() - .isArray()) { - return Array.getLength(item) <= 0; - } else if (item instanceof Map map) { - return map.isEmpty(); - } - return false; + return switch (item) { + case null -> true; + case String str -> str.isEmpty(); + case Collection collection -> collection.isEmpty(); + case Map map -> map.isEmpty(); + default -> item.getClass() + .isArray() + && Array.getLength(item) == 0; + }; } public static boolean isTruthy(@Nullable Object item) { diff --git a/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/codec/BsonValueEncoder.java b/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/codec/BsonValueEncoder.java index 9d844d2527..ff2470a183 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/codec/BsonValueEncoder.java +++ b/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/codec/BsonValueEncoder.java @@ -53,45 +53,47 @@ private BsonValueEncoder() { } public static BsonValue encodeValue(Object value) { - if (value instanceof Collection values) { - int size = values.size(); - List list = new ArrayList<>(size); - for (Object val : values) { - list.add(encodeSingleValue(val)); + return switch (value) { + case Collection values -> { + int size = values.size(); + List list = new ArrayList<>(size); + for (Object val : values) { + list.add(encodeSingleValue(val)); + } + yield BsonArrayUtil.newArray(list); } - return BsonArrayUtil.newArray(list); - } - if (value instanceof Map map) { - int size = map.size(); - Object key; - BsonDocument document = new BsonDocument(CollectionUtil.getMapCapability(size)); - for (Map.Entry entry : map.entrySet()) { - key = entry.getKey(); - if (key instanceof String str) { - document.put(str, encodeValue(entry.getValue())); - } else if (key instanceof Number number) { - document.put(number.toString(), encodeValue(entry.getValue())); - } else { - throw new IllegalArgumentException( - "Expecting the map key to be a string or number, but got: " - + key); + case Map map -> { + int size = map.size(); + Object key; + BsonDocument document = new BsonDocument(CollectionUtil.getMapCapability(size)); + for (Map.Entry entry : map.entrySet()) { + key = entry.getKey(); + if (key instanceof String str) { + document.put(str, encodeValue(entry.getValue())); + } else if (key instanceof Number number) { + document.put(number.toString(), encodeValue(entry.getValue())); + } else { + throw new IllegalArgumentException( + "Expecting the map key to be a string or number, but got: " + + key); + } } + yield document; } - return document; - } - if (value instanceof byte[] bytes) { - return new BsonBinary(bytes); - } - Class clazz = value.getClass(); - if (clazz.isArray()) { - int size = Array.getLength(value); - List list = new ArrayList<>(size); - for (int i = 0; i < size; i++) { - list.add(encodeSingleValue(Array.get(value, i))); + case byte[] bytes -> new BsonBinary(bytes); + default -> { + Class clazz = value.getClass(); + if (clazz.isArray()) { + int size = Array.getLength(value); + List list = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + list.add(encodeSingleValue(Array.get(value, i))); + } + yield BsonArrayUtil.newArray(list); + } + yield encodeSingleValue(value); } - return BsonArrayUtil.newArray(list); - } - return encodeSingleValue(value); + }; } public static BsonArray encodeValuesAsStrings(Collection> collection) { @@ -103,59 +105,37 @@ public static BsonArray encodeValuesAsStrings(Collection> coll } public static BsonValue encodeSingleValue(@Nullable Object value) { - if (value == null) { - return BsonNull.VALUE; - } - if (value instanceof BsonValue val) { - return val; - } - if (value instanceof Boolean val) { - return val + return switch (value) { + case null -> BsonNull.VALUE; + case Byte val -> new BsonInt32(val); + case Short val -> new BsonInt32(val); + case Integer val -> new BsonInt32(val); + case Long val -> new BsonInt64(val); + case Float val -> new BsonDouble(val); + case Double val -> new BsonDouble(val); + case Character val -> new BsonString(val.toString()); + case Boolean val -> val ? BsonBoolean.TRUE : BsonBoolean.FALSE; - } - if (value instanceof Long val) { - return new BsonInt64(val); - } - if (value instanceof Integer val) { - return new BsonInt32(val); - } - if (value instanceof String val) { - return new BsonString(val); - } - if (value instanceof Date val) { - return new BsonDateTime(val.getTime()); - } - if (value instanceof Byte val) { - return new BsonInt32(val); - } - if (value instanceof Short val) { - return new BsonInt32(val); - } - if (value instanceof Float val) { - return new BsonDouble(val); - } - if (value instanceof Double val) { - return new BsonDouble(val); - } - if (value instanceof Character val) { - return new BsonString(val.toString()); - } - if (value instanceof byte[] val) { - return new BsonBinary(val); - } - Class clazz = value.getClass(); - if (clazz.isEnum()) { - Enum element = (Enum) value; - return new BsonInt32(element.ordinal()); - } - EncoderContext encoderContext = EncoderContext.builder() - .build(); - BsonDocument document = new BsonDocument(); - BsonWriter writer = new BsonDocumentWriter(document); - EntityCodec codec = (EntityCodec) CodecPool.CODEC_REGISTRY.get(clazz); - codec.encode(writer, value, encoderContext); - return document; + case String val -> new BsonString(val); + case Date val -> new BsonDateTime(val.getTime()); + case byte[] val -> new BsonBinary(val); + case BsonValue val -> val; + default -> { + Class clazz = value.getClass(); + if (clazz.isEnum()) { + Enum element = (Enum) value; + yield new BsonInt32(element.ordinal()); + } + EncoderContext encoderContext = EncoderContext.builder() + .build(); + BsonDocument document = new BsonDocument(); + BsonWriter writer = new BsonDocumentWriter(document); + EntityCodec codec = (EntityCodec) CodecPool.CODEC_REGISTRY.get(clazz); + codec.encode(writer, value, encoderContext); + yield document; + } + }; } -} +} \ No newline at end of file diff --git a/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/exception/MongoExceptionUtil.java b/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/exception/MongoExceptionUtil.java index 30fc9f78cb..9b360c8bca 100644 --- a/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/exception/MongoExceptionUtil.java +++ b/turms-server-common/src/main/java/im/turms/server/common/storage/mongo/exception/MongoExceptionUtil.java @@ -35,49 +35,51 @@ private MongoExceptionUtil() { } public static boolean isErrorOf(Throwable throwable, int errorCode) { - if (throwable instanceof MongoException e) { - return e.getCode() == errorCode; - } - return false; + return throwable instanceof MongoException e && e.getCode() == errorCode; } public static Throwable translate(Throwable t) { - if (t instanceof MongoWriteException e) { - WriteError error = e.getError(); - if (error.getCategory() - .equals(ErrorCategory.DUPLICATE_KEY)) { - return new DuplicateKeyException(t.getMessage(), t); - } - if (error.getCode() == MongoErrorCodes.DOCUMENT_VALIDATION_FAILURE) { - throw new DocumentValidationFailureException(t.getMessage(), t); - } - } else if (t instanceof MongoBulkWriteException e) { - boolean areAllDuplicateKeyErrors = true; - boolean areAllValidationFailureErrors = true; - for (BulkWriteError error : e.getWriteErrors()) { - if (!error.getCategory() + return switch (t) { + case MongoWriteException e -> { + WriteError error = e.getError(); + if (error.getCategory() .equals(ErrorCategory.DUPLICATE_KEY)) { - areAllDuplicateKeyErrors = false; - if (!areAllValidationFailureErrors) { - break; - } + yield new DuplicateKeyException(t.getMessage(), t); } - if (error.getCode() != MongoErrorCodes.DOCUMENT_VALIDATION_FAILURE) { - areAllValidationFailureErrors = false; - if (!areAllDuplicateKeyErrors) { - break; - } + if (error.getCode() == MongoErrorCodes.DOCUMENT_VALIDATION_FAILURE) { + yield new DocumentValidationFailureException(t.getMessage(), t); } + yield t; } - if (areAllDuplicateKeyErrors) { - return new DuplicateKeyException(t.getMessage(), t); - } else if (areAllValidationFailureErrors) { - return new DocumentValidationFailureException(t.getMessage(), t); + case MongoBulkWriteException e -> { + boolean areAllDuplicateKeyErrors = true; + boolean areAllValidationFailureErrors = true; + for (BulkWriteError error : e.getWriteErrors()) { + if (!error.getCategory() + .equals(ErrorCategory.DUPLICATE_KEY)) { + areAllDuplicateKeyErrors = false; + if (!areAllValidationFailureErrors) { + break; + } + } + if (error.getCode() != MongoErrorCodes.DOCUMENT_VALIDATION_FAILURE) { + areAllValidationFailureErrors = false; + if (!areAllDuplicateKeyErrors) { + break; + } + } + } + if (areAllDuplicateKeyErrors) { + yield new DuplicateKeyException(t.getMessage(), t); + } else if (areAllValidationFailureErrors) { + yield new DocumentValidationFailureException(t.getMessage(), t); + } + yield t; } - } else if (t instanceof com.mongodb.DuplicateKeyException) { - return new DuplicateKeyException(t.getMessage(), t); - } - return t; + case com.mongodb.DuplicateKeyException ignored -> + new DuplicateKeyException(t.getMessage(), t); + default -> t; + }; } } \ No newline at end of file diff --git a/turms-server-common/src/main/java/io/lettuce/core/protocol/CommandArgsUtil.java b/turms-server-common/src/main/java/io/lettuce/core/protocol/CommandArgsUtil.java index 9288d485cb..c14e014317 100644 --- a/turms-server-common/src/main/java/io/lettuce/core/protocol/CommandArgsUtil.java +++ b/turms-server-common/src/main/java/io/lettuce/core/protocol/CommandArgsUtil.java @@ -70,29 +70,29 @@ public static void encodeArgs(CompositeByteBuf out, CommandArgs args) { return; } for (CommandArgs.SingularArgument arg : args.singularArguments) { - if (arg instanceof CommandArgs.IntegerArgument argument) { - writeBytesArg(out, NumberFormatter.toCharBytes(argument.val)); - } else if (arg instanceof CommandArgs.KeyArgument argument) { - ByteBuf key = (ByteBuf) argument.key; - if (key instanceof TurmsWrappedByteBuf buf - && buf.unwrap() instanceof CustomKeyBuffer) { - out.addComponent(true, key); - } else if (key == null) { - writeNullArg(out); - } else { - writeByteBuf(out, key); + switch (arg) { + case CommandArgs.IntegerArgument argument -> + writeBytesArg(out, NumberFormatter.toCharBytes(argument.val)); + case CommandArgs.KeyArgument argument -> { + ByteBuf key = (ByteBuf) argument.key; + if (key instanceof TurmsWrappedByteBuf buf + && buf.unwrap() instanceof CustomKeyBuffer) { + out.addComponent(true, key); + } else if (key == null) { + writeNullArg(out); + } else { + writeByteBuf(out, key); + } + } + case CommandArgs.DoubleArgument argument -> + writeStringArg(out, Double.toString(argument.val)); + case CommandArgs.CharArrayArgument argument -> writeCharsArg(out, argument.val); + case CommandArgs.BytesArgument argument -> writeBytesArg(out, argument.val); + case CommandArgs.StringArgument argument -> writeStringArg(out, argument.val); + case CommandArgs.ValueArgument argument -> + writeByteBuf(out, (ByteBuf) argument.val); + case null, default -> { } - } else if (arg instanceof CommandArgs.DoubleArgument argument) { - writeStringArg(out, Double.toString(argument.val)); - } else if (arg instanceof CommandArgs.CharArrayArgument argument) { - writeCharsArg(out, argument.val); - } else if (arg instanceof CommandArgs.BytesArgument argument) { - writeBytesArg(out, argument.val); - } else if (arg instanceof CommandArgs.StringArgument argument) { - writeStringArg(out, argument.val); - } else if (arg instanceof CommandArgs.ValueArgument argument) { - ByteBuf val = (ByteBuf) argument.val; - writeByteBuf(out, val); } } } diff --git a/turms-service/src/main/java/im/turms/service/storage/mongo/MongoCollectionInitializer.java b/turms-service/src/main/java/im/turms/service/storage/mongo/MongoCollectionInitializer.java index 3fbc893294..2993ba1680 100644 --- a/turms-service/src/main/java/im/turms/service/storage/mongo/MongoCollectionInitializer.java +++ b/turms-service/src/main/java/im/turms/service/storage/mongo/MongoCollectionInitializer.java @@ -290,7 +290,6 @@ private Mono ensureIndexesAndShards() { }; BiPredicate, Field> customIndexFilter = (entityClass, field) -> { String fieldName = field.getName(); - // TODO: pattern matching if (entityClass == Admin.class) { return isCustomIndexEnabled.test(fieldName, mongoProperties.getAdmin()