From 964d732425f3155032e6985ed7f914ff36e73607 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Laura=20Endre=C3=9F?= Date: Tue, 23 Mar 2021 11:53:48 +0100 Subject: [PATCH] Fix formatting and update some versions --- .../syntaxapi/command/ArgumentIdentifier.java | 12 +- .../syntaxapi/command/ArgumentMap.java | 206 +- .../command/ArgumentRangeIdentifier.java | 12 +- .../command/ArgumentRangeSerializer.java | 103 +- .../syntaxapi/command/ArgumentSerializer.java | 169 +- .../syntaxapi/command/ArgumentSuperType.java | 34 +- .../syntaxapi/command/ArgumentType.java | 74 +- .../syntaxapi/command/Arguments.java | 262 +-- .../syntaxapi/command/BaseArgument.java | 125 +- .../syntaxapi/command/BaseArgumentRange.java | 73 +- .../syntaxapi/command/BaseCommand.java | 8 +- .../syntaxapi/command/BaseCompletion.java | 2 +- .../syntaxapi/command/BaseInfo.java | 24 +- .../syntaxapi/command/CommandManager.java | 450 ++-- .../syntaxapi/command/CommandProcess.java | 216 +- .../command/DefaultArgumentIdentifier.java | 263 +-- .../DefaultArgumentRangeIdentifier.java | 165 +- .../DefaultArgumentRangeSerializer.java | 150 +- .../command/DefaultArgumentSerializer.java | 233 +- .../syntaxapi/command/DefaultCompletion.java | 63 +- .../syntaxapi/command/DefaultInfo.java | 6 +- .../syntaxapi/command/ExecutionState.java | 18 +- .../syntaxapi/command/NumberEnum.java | 57 +- .../syntaxapi/command/NumericArgument.java | 2 +- .../syntaxapi/command/RangeSuperType.java | 10 +- .../syntaxapi/command/RangeType.java | 50 +- .../syntaxapi/command/Ranges.java | 230 +- .../command/SerializationHelper.java | 40 +- .../command/arguments/ArrayArgument.java | 74 +- .../command/arguments/BigDecimalArgument.java | 76 +- .../command/arguments/BigIntegerArgument.java | 76 +- .../command/arguments/BooleanArgument.java | 66 +- .../command/arguments/ByteArgument.java | 76 +- .../command/arguments/DoubleArgument.java | 76 +- .../command/arguments/FloatArgument.java | 76 +- .../command/arguments/IntegerArgument.java | 76 +- .../command/arguments/ListArgument.java | 66 +- .../command/arguments/LongArgument.java | 76 +- .../command/arguments/ObjectArgument.java | 58 +- .../command/arguments/ShortArgument.java | 76 +- .../command/arguments/StringArgument.java | 66 +- .../command/helper/EqualArgumentHelper.java | 97 +- .../command/helper/JVMArgumentHelper.java | 137 +- .../command/range/CollectionSizeRange.java | 153 +- .../command/range/NumberChooseRange.java | 213 +- .../command/range/NumberValueRange.java | 232 +- .../syntaxapi/command/range/StateRange.java | 134 +- .../command/range/TextChooseRange.java | 143 +- .../command/range/TextSizeRange.java | 131 +- .../syntaxapi/config/BaseConfig.java | 18 +- .../syntaxapi/config/BaseSection.java | 426 ++-- .../syntaxapi/config/ConfigTools.java | 74 +- .../syntaxapi/config/IBaseSection.java | 36 +- .../syntaxapi/config/SectionMap.java | 8 +- .../syntaxapi/config/json/JsonConfig.java | 88 +- .../config/json/JsonConfigSection.java | 240 +- .../syntaxapi/config/nbt/NbtConfig.java | 90 +- .../config/nbt/NbtConfigSection.java | 406 ++-- .../syntaxapi/config/toml/TomlConfig.java | 88 +- .../config/toml/TomlConfigSection.java | 104 +- .../syntaxapi/config/yaml/YamlConfig.java | 5 +- .../config/yaml/YamlConfigSection.java | 1 - .../config/yaml/exceptions/YamlException.java | 104 +- .../config/yaml/utils/LinkedConstructor.java | 114 +- .../config/yaml/utils/LinkedRepresenter.java | 24 +- .../syntaxapi/data/DataAdapter.java | 40 +- .../syntaxapi/data/DataAdapterContext.java | 2 +- .../syntaxapi/data/DataAdapterRegistry.java | 59 +- .../syntaxapi/data/DataContainer.java | 102 +- .../syntaxapi/data/DataFactory.java | 44 +- .../syntaxapi/data/DataType.java | 80 +- .../syntaxapi/data/DataTypeChain.java | 346 +-- .../syntaxapi/data/IDataContainer.java | 40 +- .../syntaxapi/data/PrimitiveDataType.java | 152 +- data/data-nbtcontainer/pom.xml | 2 +- .../data/container/nbt/NbtAdapter.java | 418 ++-- .../container/nbt/NbtAdapterRegistry.java | 26 +- .../data/container/nbt/NbtContainer.java | 175 +- .../syntaxapi/data/test/ContainerTest.java | 40 +- .../data/property/AbstractProperties.java | 182 +- .../syntaxapi/data/property/Properties.java | 2 +- .../syntaxapi/data/property/Property.java | 168 +- .../syntaxapi/event/Cancelable.java | 4 +- .../syntaxphoenix/syntaxapi/event/Event.java | 6 +- .../syntaxapi/event/EventAnalyser.java | 86 +- .../syntaxapi/event/EventCall.java | 227 +- .../syntaxapi/event/EventExecutor.java | 116 +- .../syntaxapi/event/EventHandler.java | 4 +- .../syntaxapi/event/EventManager.java | 429 ++-- .../syntaxapi/event/EventMethod.java | 101 +- .../syntaxapi/event/EventPriority.java | 39 +- .../exception/DownloadFailedException.java | 104 +- .../exception/NotImplementedException.java | 106 +- .../exception/ObjectLockedException.java | 106 +- .../syntaxapi/logging/AsyncLogger.java | 328 +-- .../syntaxapi/logging/ILogger.java | 42 +- .../syntaxapi/logging/LogTypeId.java | 16 +- .../syntaxapi/logging/LoggerState.java | 148 +- .../syntaxapi/logging/SynLogger.java | 640 +++--- .../logging/color/ColorProcessor.java | 2 +- .../syntaxapi/logging/color/ColorTools.java | 70 +- .../syntaxapi/logging/color/LogType.java | 84 +- .../syntaxapi/logging/color/LogTypeColor.java | 130 +- .../syntaxapi/logging/color/LogTypeMap.java | 156 +- .../syntaxapi/nbt/NbtAbstractList.java | 234 +- .../syntaxapi/nbt/NbtBigDecimal.java | 90 +- .../syntaxapi/nbt/NbtBigInt.java | 90 +- .../syntaxphoenix/syntaxapi/nbt/NbtByte.java | 116 +- .../syntaxapi/nbt/NbtByteArray.java | 97 +- .../syntaxapi/nbt/NbtCompound.java | 1126 +++++----- .../syntaxapi/nbt/NbtDouble.java | 116 +- .../syntaxphoenix/syntaxapi/nbt/NbtEnd.java | 47 +- .../syntaxphoenix/syntaxapi/nbt/NbtFloat.java | 116 +- .../syntaxphoenix/syntaxapi/nbt/NbtInt.java | 116 +- .../syntaxapi/nbt/NbtIntArray.java | 107 +- .../syntaxphoenix/syntaxapi/nbt/NbtList.java | 452 ++-- .../syntaxphoenix/syntaxapi/nbt/NbtLong.java | 116 +- .../syntaxapi/nbt/NbtLongArray.java | 107 +- .../syntaxapi/nbt/NbtNamedTag.java | 84 +- .../syntaxapi/nbt/NbtNumber.java | 94 +- .../syntaxphoenix/syntaxapi/nbt/NbtShort.java | 116 +- .../syntaxapi/nbt/NbtString.java | 106 +- .../syntaxphoenix/syntaxapi/nbt/NbtTag.java | 98 +- .../syntaxphoenix/syntaxapi/nbt/NbtType.java | 458 ++-- .../nbt/tools/MojangsonDeserializer.java | 12 +- .../nbt/tools/MojangsonParseException.java | 34 +- .../syntaxapi/nbt/tools/MojangsonParser.java | 768 +++---- .../nbt/tools/MojangsonSerializer.java | 76 +- .../syntaxapi/nbt/tools/MojangsonWriter.java | 469 ++-- .../syntaxapi/nbt/tools/NbtDeserializer.java | 65 +- .../syntaxapi/nbt/tools/NbtInputStream.java | 423 ++-- .../syntaxapi/nbt/tools/NbtMatcher.java | 183 +- .../syntaxapi/nbt/tools/NbtOutputStream.java | 384 ++-- .../syntaxapi/nbt/tools/NbtParser.java | 260 +-- .../syntaxapi/nbt/tools/NbtSerializer.java | 74 +- .../syntaxapi/nbt/utils/NbtLoadable.java | 2 +- .../syntaxapi/nbt/utils/NbtSaveable.java | 2 +- .../syntaxapi/net/AsyncSocketServer.java | 175 +- .../syntaxapi/net/SocketServer.java | 274 +-- .../syntaxapi/net/http/Answer.java | 317 +-- .../net/http/ContentDeserializer.java | 8 +- .../syntaxapi/net/http/ContentSerializer.java | 8 +- .../net/http/ContentToUrlModifier.java | 11 +- .../syntaxapi/net/http/ContentType.java | 278 +-- .../syntaxapi/net/http/Cookie.java | 76 +- .../syntaxapi/net/http/CustomRequestData.java | 26 +- .../net/http/DefaultDeserializers.java | 55 +- .../net/http/DefaultSerializers.java | 63 +- .../syntaxapi/net/http/FileAnswer.java | 48 +- .../syntaxapi/net/http/HttpSender.java | 24 +- .../syntaxapi/net/http/HttpServer.java | 27 +- .../syntaxapi/net/http/HttpWriter.java | 232 +- .../syntaxapi/net/http/JsonAnswer.java | 180 +- .../net/http/JsonContentDeserializer.java | 10 +- .../net/http/JsonContentSerializer.java | 12 +- .../syntaxapi/net/http/NamedAnswer.java | 62 +- .../syntaxapi/net/http/NamedType.java | 8 +- .../syntaxapi/net/http/PathHandler.java | 2 +- .../syntaxapi/net/http/ReceivedRequest.java | 349 +-- .../net/http/RedirectRequestHandler.java | 202 +- .../syntaxapi/net/http/Refreshable.java | 2 +- .../syntaxapi/net/http/Request.java | 18 +- .../syntaxapi/net/http/RequestContent.java | 38 +- .../syntaxapi/net/http/RequestData.java | 2 +- .../syntaxapi/net/http/RequestExecution.java | 54 +- .../syntaxapi/net/http/RequestGate.java | 2 +- .../syntaxapi/net/http/RequestHandler.java | 2 +- .../syntaxapi/net/http/RequestSerializer.java | 2 +- .../syntaxapi/net/http/RequestState.java | 32 +- .../syntaxapi/net/http/RequestType.java | 66 +- .../syntaxapi/net/http/RequestValidator.java | 5 +- .../syntaxapi/net/http/Response.java | 127 +- .../syntaxapi/net/http/ResponseCode.java | 236 +- .../syntaxapi/net/http/SimpleFileAnswer.java | 22 +- .../net/http/SpecialSerializers.java | 144 +- .../net/http/StandardContentType.java | 98 +- .../syntaxapi/net/http/StandardNamedType.java | 64 +- .../net/http/web/IWebPathHandler.java | 2 +- .../net/http/web/WebPathAdapter.java | 20 +- .../net/http/web/WebPathHandler.java | 54 +- .../net/http/web/WebRedirectHandler.java | 88 +- .../syntaxapi/net/http/web/WebServer.java | 162 +- .../syntaxapi/utils/net/SimpleConversion.java | 30 +- .../syntaxapi/utils/net/UrlReflection.java | 14 +- net/src/test/java/net/test/RestHandler.java | 3 +- .../syntaxphoenix/syntaxapi/random/Keys.java | 233 +- .../random/LinearCongruentialGenerator.java | 445 ++-- .../syntaxapi/random/MurmurHashGenerator.java | 367 ++-- .../syntaxapi/random/NumberGeneratorType.java | 34 +- .../random/PermutedCongruentialGenerator.java | 414 ++-- .../random/RandomNumberGenerator.java | 98 +- .../reflection/AbstractReflectCache.java | 70 +- .../syntaxapi/reflection/ClassCache.java | 60 +- .../syntaxapi/reflection/ClasspathAccess.java | 180 +- .../syntaxapi/reflection/PackageAccess.java | 90 +- .../syntaxapi/reflection/Reflect.java | 12 +- .../syntaxapi/reflection/ReflectCache.java | 18 +- .../reflection/ReflectionHelper.java | 709 +++--- .../syntaxapi/reflection/ReflectionTools.java | 183 +- .../syntaxapi/service/IService.java | 10 +- .../syntaxapi/service/IServiceValue.java | 48 +- .../syntaxapi/service/ServiceAnalyser.java | 71 +- .../syntaxapi/service/ServiceContainer.java | 122 +- .../syntaxapi/service/ServiceFieldValue.java | 130 +- .../syntaxapi/service/ServiceManager.java | 402 ++-- .../syntaxapi/service/ServiceMethodValue.java | 130 +- .../syntaxapi/service/ServicePriority.java | 39 +- .../syntaxapi/service/SubscribeService.java | 13 +- .../syntaxapi/service/ValueType.java | 4 +- .../service/download/DisconnectReason.java | 6 +- .../syntaxapi/service/download/Download.java | 138 +- .../service/download/DownloadListener.java | 15 +- .../service/download/DownloadService.java | 318 +-- .../syntaxapi/test/SyntaxExecutor.java | 68 +- .../syntaxapi/test/SyntaxTest.java | 175 +- .../syntaxapi/test/menu/AbstractMenu.java | 85 +- .../syntaxapi/test/menu/MainMenu.java | 182 +- .../syntaxapi/test/menu/menus/TestMenu.java | 234 +- .../syntaxapi/test/tests/ColorTest.java | 12 +- .../syntaxapi/test/tests/DownloadTest.java | 55 +- .../syntaxapi/test/tests/LoggerTest.java | 20 +- .../syntaxapi/test/tests/NbtTest.java | 60 +- .../test/tests/RandomChooseTest.java | 43 +- .../syntaxapi/test/tests/RandomTest.java | 30 +- .../syntaxapi/test/tests/RequestTest.java | 24 +- .../syntaxapi/test/tests/ServiceTest.java | 8 +- .../syntaxapi/test/tests/SocketTest.java | 88 +- .../syntaxapi/test/tests/ThreadTest.java | 118 +- .../syntaxapi/test/tests/VersionTest.java | 85 +- .../syntaxapi/test/utils/InputReader.java | 140 +- .../syntaxapi/test/utils/Printer.java | 142 +- .../syntaxapi/thread/SynReportThrower.java | 2 +- .../syntaxapi/thread/SynThreadFactory.java | 98 +- .../syntaxapi/thread/SynThreadPool.java | 93 +- .../syntaxapi/thread/SynThreadReporter.java | 2 +- .../syntaxapi/utils/alias/Alias.java | 196 +- .../syntaxapi/utils/alias/AliasMap.java | 218 +- .../syntaxapi/utils/cache/CacheList.java | 262 +-- .../syntaxapi/utils/cache/CacheMap.java | 230 +- .../syntaxapi/utils/cache/CachedObject.java | 33 +- .../syntaxapi/utils/general/Status.java | 473 ++-- .../syntaxapi/utils/io/Deserializer.java | 132 +- .../syntaxapi/utils/io/PrintWriter.java | 75 +- .../syntaxapi/utils/io/Serializer.java | 113 +- .../syntaxapi/utils/io/TextDeserializer.java | 89 +- .../syntaxapi/utils/io/TextSerializer.java | 127 +- .../java/lang/AbstractStringBuilder.java | 1131 +++++----- .../utils/java/lang/CharacterTools.java | 136 +- .../utils/java/lang/IntegerTools.java | 44 +- .../syntaxapi/utils/java/lang/LongTools.java | 26 +- .../utils/java/lang/StringBuilder.java | 492 ++--- .../utils/java/lang/StringTools.java | 192 +- .../syntaxapi/utils/java/Arrays.java | 150 +- .../syntaxapi/utils/java/Collect.java | 236 +- .../syntaxapi/utils/java/Exceptions.java | 166 +- .../syntaxapi/utils/java/Files.java | 198 +- .../syntaxapi/utils/java/Lists.java | 126 +- .../syntaxapi/utils/java/Numbers.java | 8 +- .../syntaxapi/utils/java/Primitives.java | 129 +- .../syntaxapi/utils/java/Streams.java | 32 +- .../syntaxapi/utils/java/Strings.java | 151 +- .../syntaxapi/utils/java/Times.java | 22 +- .../syntaxapi/utils/java/UniCode.java | 18 +- .../syntaxapi/utils/java/Zipper.java | 141 +- .../syntaxapi/utils/java/tools/Compare.java | 2 +- .../syntaxapi/utils/java/tools/Container.java | 802 +++---- .../syntaxapi/json/JsonArray.java | 177 +- .../syntaxapi/json/JsonEntry.java | 48 +- .../syntaxapi/json/JsonObject.java | 213 +- .../syntaxapi/json/JsonValue.java | 95 +- .../syntaxapi/json/ValueType.java | 98 +- .../syntaxapi/json/io/EndOfFileException.java | 8 +- .../syntaxapi/json/io/JsonParser.java | 132 +- .../syntaxapi/json/io/JsonReader.java | 1937 +++++++++-------- .../syntaxapi/json/io/JsonScope.java | 16 +- .../syntaxapi/json/io/JsonState.java | 56 +- .../json/io/JsonSyntaxException.java | 20 +- .../syntaxapi/json/io/JsonToken.java | 84 +- .../syntaxapi/json/io/JsonWriter.java | 372 ++-- .../json/utils/SynchronizedIterator.java | 50 +- .../syntaxapi/json/utils/TrackElement.java | 74 +- .../syntaxapi/json/utils/Tracker.java | 50 +- .../syntaxapi/json/value/JsonBigDecimal.java | 14 +- .../syntaxapi/json/value/JsonBigInteger.java | 14 +- .../syntaxapi/json/value/JsonBoolean.java | 14 +- .../syntaxapi/json/value/JsonByte.java | 14 +- .../syntaxapi/json/value/JsonDouble.java | 14 +- .../syntaxapi/json/value/JsonFloat.java | 14 +- .../syntaxapi/json/value/JsonInteger.java | 14 +- .../syntaxapi/json/value/JsonLong.java | 14 +- .../syntaxapi/json/value/JsonNull.java | 29 +- .../syntaxapi/json/value/JsonNumber.java | 6 +- .../syntaxapi/json/value/JsonShort.java | 14 +- .../syntaxapi/json/value/JsonSimple.java | 16 +- .../syntaxapi/json/value/JsonString.java | 14 +- .../syntaxapi/test/json/JsonTest.java | 47 +- .../syntaxapi/nbt/tools/NbtJsonParser.java | 418 ++-- .../syntaxapi/utils/json/JsonTools.java | 144 +- .../syntaxapi/utils/json/ValueIdentifier.java | 83 +- .../syntaxapi/utils/key/AbstractKey.java | 8 +- .../syntaxapi/utils/key/AbstractKeyed.java | 16 +- .../syntaxapi/utils/key/AbstractNamedKey.java | 8 +- .../utils/key/AbstractNamespace.java | 8 +- .../utils/key/AbstractNamespaced.java | 16 +- .../syntaxapi/utils/key/IKey.java | 26 +- .../syntaxapi/utils/key/IKeyed.java | 2 +- .../syntaxapi/utils/key/INamedKey.java | 26 +- .../syntaxapi/utils/key/INamespace.java | 28 +- .../syntaxapi/utils/key/INamespaced.java | 2 +- .../syntaxapi/utils/key/KeyConstants.java | 13 +- .../syntaxapi/utils/key/Namespace.java | 94 +- .../syntaxapi/utils/key/NamespacedKey.java | 106 +- .../utils/position/BlockLocation.java | 152 +- .../syntaxapi/utils/position/Location.java | 18 +- .../utils/position/VectorLocation.java | 152 +- .../utils/position/grid/GridLayer.java | 406 ++-- .../utils/position/grid/GridMap.java | 629 +++--- .../utils/position/grid/GridRow.java | 267 +-- .../utils/position/grid/GridType.java | 24 +- .../utils/position/grid/GridValue.java | 61 +- .../syntaxapi/version/DefaultVersion.java | 94 +- .../syntaxapi/version/Version.java | 330 +-- .../syntaxapi/version/VersionAnalyzer.java | 2 +- .../syntaxapi/version/VersionFormatter.java | 2 +- .../syntaxapi/version/VersionManager.java | 473 ++-- .../syntaxapi/version/VersionState.java | 8 +- 326 files changed, 21219 insertions(+), 20593 deletions(-) diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentIdentifier.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentIdentifier.java index 7cddd49..fabe9ec 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentIdentifier.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentIdentifier.java @@ -8,12 +8,12 @@ */ public abstract class ArgumentIdentifier { - public static final ArgumentIdentifier DEFAULT = new DefaultArgumentIdentifier(); + public static final ArgumentIdentifier DEFAULT = new DefaultArgumentIdentifier(); - /** - * @param rawArguments array of raw arguments - * @return list of complex arguments - */ - public abstract ArrayList process(String... rawArguments); + /** + * @param rawArguments array of raw arguments + * @return list of complex arguments + */ + public abstract ArrayList process(String... rawArguments); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentMap.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentMap.java index a075246..60f2cb9 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentMap.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentMap.java @@ -11,104 +11,112 @@ public final class ArgumentMap { - public static final ArgumentMap EMPTY = new ArgumentMap(Collections.emptyMap()); - - protected final Map arguments = Collections.synchronizedMap(new HashMap<>()); - - private final boolean locked; - - public ArgumentMap() { - locked = true; - } - - public ArgumentMap(Map arguments) { - this.arguments.putAll(arguments); - locked = false; - } - - final Map getHandle() { - return arguments; - } - - public final boolean isLocked() { - return locked; - } - - public final boolean set(String key, BaseArgument value) { - return !locked && !arguments.containsKey(key) && arguments.put(key, value) == null; - } - - public final Optional get(String key) { - return Optional.ofNullable(arguments.get(key)); - } - - public final Optional get(String key, ArgumentType type) { - return get(key).filter(argument -> argument.getType() == type); - } - - public final Optional get(String key, ArgumentSuperType type) { - return get(key).filter(argument -> argument.getSuperType() == type); - } - - @SuppressWarnings("unchecked") - public final Optional number(String key, E sample) { - return number(key, (Class) sample.getClass()); - } - - @SuppressWarnings("unchecked") - public final Optional number(String key, Class sample) { - Optional optional = get(key, ArgumentSuperType.NUMBER); - if (!optional.isPresent()) - return Optional.empty(); - Optional option = NumberEnum.of(sample); - if (!option.isPresent()) - return Optional.empty(); - NumericArgument argument = optional.get().asNumeric(); - boolean primitive = Primitives.isPrimitive(sample); - switch (option.get()) { - case BYTE: - if (argument.getType() == ArgumentType.BYTE) - return option(primitive ? argument.asByte().getValue().byteValue() : argument.asByte().getValue(), sample); - byte value = argument.asNumber().byteValue(); - return option(primitive ? value : Byte.valueOf(value), sample); - case SHORT: - if (argument.getType() == ArgumentType.SHORT) - return option(primitive ? argument.asShort().getValue().shortValue() : argument.asShort().getValue(), sample); - short value0 = argument.asNumber().shortValue(); - return option(primitive ? value0 : Short.valueOf(value0), sample); - case INTEGER: - if (argument.getType() == ArgumentType.INTEGER) - return option(primitive ? argument.asInteger().getValue().intValue() : argument.asInteger().getValue(), sample); - int value1 = argument.asNumber().intValue(); - return option(primitive ? value1 : Integer.valueOf(value1), sample); - case LONG: - if (argument.getType() == ArgumentType.LONG) - return option(primitive ? argument.asLong().getValue().longValue() : argument.asLong().getValue(), sample); - long value2 = argument.asNumber().longValue(); - return option(primitive ? value2 : Long.valueOf(value2), sample); - case FLOAT: - if (argument.getType() == ArgumentType.FLOAT) - return option(primitive ? argument.asFloat().getValue().floatValue() : argument.asFloat().getValue(), sample); - float value3 = argument.asNumber().floatValue(); - return option(primitive ? value3 : Float.valueOf(value3), sample); - case DOUBLE: - if (argument.getType() == ArgumentType.DOUBLE) - return option(primitive ? argument.asDouble().getValue().doubleValue() : argument.asDouble().getValue(), sample); - double value4 = argument.asNumber().doubleValue(); - return option(primitive ? value4 : Double.valueOf(value4), sample); - case BIG_INTEGER: - return (Optional) Optional - .of(argument.getType() == ArgumentType.BIG_INTEGER ? argument.asBigInteger().getValue() : new BigInteger(argument.asNumber().toString())); - case BIG_DECIMAL: - return (Optional) Optional - .of(argument.getType() == ArgumentType.BIG_DECIMAL ? argument.asBigDecimal().getValue() : new BigDecimal(argument.asNumber().toString())); - } - return Optional.empty(); - } - - @SuppressWarnings("unchecked") - private final Optional option(T value, Class sample) { - return Optional.of(value).map(internal -> (E) internal); - } + public static final ArgumentMap EMPTY = new ArgumentMap(Collections.emptyMap()); + + protected final Map arguments = Collections.synchronizedMap(new HashMap<>()); + + private final boolean locked; + + public ArgumentMap() { + locked = true; + } + + public ArgumentMap(Map arguments) { + this.arguments.putAll(arguments); + locked = false; + } + + final Map getHandle() { + return arguments; + } + + public final boolean isLocked() { + return locked; + } + + public final boolean set(String key, BaseArgument value) { + return !locked && !arguments.containsKey(key) && arguments.put(key, value) == null; + } + + public final Optional get(String key) { + return Optional.ofNullable(arguments.get(key)); + } + + public final Optional get(String key, ArgumentType type) { + return get(key).filter(argument -> argument.getType() == type); + } + + public final Optional get(String key, ArgumentSuperType type) { + return get(key).filter(argument -> argument.getSuperType() == type); + } + + @SuppressWarnings("unchecked") + public final Optional number(String key, E sample) { + return number(key, (Class) sample.getClass()); + } + + @SuppressWarnings("unchecked") + public final Optional number(String key, Class sample) { + Optional optional = get(key, ArgumentSuperType.NUMBER); + if (!optional.isPresent()) { + return Optional.empty(); + } + Optional option = NumberEnum.of(sample); + if (!option.isPresent()) { + return Optional.empty(); + } + NumericArgument argument = optional.get().asNumeric(); + boolean primitive = Primitives.isPrimitive(sample); + switch (option.get()) { + case BYTE: + if (argument.getType() == ArgumentType.BYTE) { + return option(primitive ? argument.asByte().getValue().byteValue() : argument.asByte().getValue(), sample); + } + byte value = argument.asNumber().byteValue(); + return option(primitive ? value : Byte.valueOf(value), sample); + case SHORT: + if (argument.getType() == ArgumentType.SHORT) { + return option(primitive ? argument.asShort().getValue().shortValue() : argument.asShort().getValue(), sample); + } + short value0 = argument.asNumber().shortValue(); + return option(primitive ? value0 : Short.valueOf(value0), sample); + case INTEGER: + if (argument.getType() == ArgumentType.INTEGER) { + return option(primitive ? argument.asInteger().getValue().intValue() : argument.asInteger().getValue(), sample); + } + int value1 = argument.asNumber().intValue(); + return option(primitive ? value1 : Integer.valueOf(value1), sample); + case LONG: + if (argument.getType() == ArgumentType.LONG) { + return option(primitive ? argument.asLong().getValue().longValue() : argument.asLong().getValue(), sample); + } + long value2 = argument.asNumber().longValue(); + return option(primitive ? value2 : Long.valueOf(value2), sample); + case FLOAT: + if (argument.getType() == ArgumentType.FLOAT) { + return option(primitive ? argument.asFloat().getValue().floatValue() : argument.asFloat().getValue(), sample); + } + float value3 = argument.asNumber().floatValue(); + return option(primitive ? value3 : Float.valueOf(value3), sample); + case DOUBLE: + if (argument.getType() == ArgumentType.DOUBLE) { + return option(primitive ? argument.asDouble().getValue().doubleValue() : argument.asDouble().getValue(), sample); + } + double value4 = argument.asNumber().doubleValue(); + return option(primitive ? value4 : Double.valueOf(value4), sample); + case BIG_INTEGER: + return (Optional) Optional.of(argument.getType() == ArgumentType.BIG_INTEGER ? argument.asBigInteger().getValue() + : new BigInteger(argument.asNumber().toString())); + case BIG_DECIMAL: + return (Optional) Optional.of(argument.getType() == ArgumentType.BIG_DECIMAL ? argument.asBigDecimal().getValue() + : new BigDecimal(argument.asNumber().toString())); + } + return Optional.empty(); + } + + @SuppressWarnings("unchecked") + private final Optional option(T value, Class sample) { + return Optional.of(value).map(internal -> (E) internal); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeIdentifier.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeIdentifier.java index a8b4bfe..55fb99a 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeIdentifier.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeIdentifier.java @@ -4,12 +4,12 @@ public abstract class ArgumentRangeIdentifier { - public static final ArgumentRangeIdentifier DEFAULT = new DefaultArgumentRangeIdentifier(); + public static final ArgumentRangeIdentifier DEFAULT = new DefaultArgumentRangeIdentifier(); - /** - * @param rawRanges array of raw ranges - * @return list of complex ranges - */ - public abstract ArrayList process(String... rawRanges); + /** + * @param rawRanges array of raw ranges + * @return list of complex ranges + */ + public abstract ArrayList process(String... rawRanges); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeSerializer.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeSerializer.java index a4c9266..3d64ea3 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeSerializer.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentRangeSerializer.java @@ -1,56 +1,61 @@ package com.syntaxphoenix.syntaxapi.command; -import com.syntaxphoenix.syntaxapi.command.range.*; +import com.syntaxphoenix.syntaxapi.command.range.CollectionSizeRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberValueRange; +import com.syntaxphoenix.syntaxapi.command.range.StateRange; +import com.syntaxphoenix.syntaxapi.command.range.TextChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.TextSizeRange; public abstract class ArgumentRangeSerializer { - public static final ArgumentRangeSerializer DEFAULT = new DefaultArgumentRangeSerializer(); - - public String toString(BaseArgumentRange range) { - RangeType type = range.getType(); - String output = ""; - switch (type) { - case TEXT_SIZE_RANGE: - output = toString(range.asTextSize()); - break; - case TEXT_CHOOSE_RANGE: - output = toString(range.asTextChoose()); - break; - case STATE_RANGE: - output = toString(range.asState()); - break; - case COLLECTION_SIZE_RANGE: - output = toString(range.asCollectionSize()); - break; - case NUMBER_VALUE_RANGE: - output = toString(range.asNumberValue()); - break; - case NUMBER_CHOOSE_RANGE: - output = toString(range.asNumberChoose()); - break; - case CUSTOM: - output = range.toString(); - break; - } - return output; - } - - public abstract String toString(CollectionSizeRange range); - - public abstract String toString(NumberValueRange range); - - public abstract String toString(NumberChooseRange range); - - public abstract String toString(StateRange range); - - public abstract String toString(TextSizeRange range); - - public abstract String toString(TextChooseRange range); - - /** - * @param ranges array of complex ranges - * @return array of raw ranges - */ - public abstract String[] asStringArray(BaseArgumentRange... ranges); + public static final ArgumentRangeSerializer DEFAULT = new DefaultArgumentRangeSerializer(); + + public String toString(BaseArgumentRange range) { + RangeType type = range.getType(); + String output = ""; + switch (type) { + case TEXT_SIZE_RANGE: + output = toString(range.asTextSize()); + break; + case TEXT_CHOOSE_RANGE: + output = toString(range.asTextChoose()); + break; + case STATE_RANGE: + output = toString(range.asState()); + break; + case COLLECTION_SIZE_RANGE: + output = toString(range.asCollectionSize()); + break; + case NUMBER_VALUE_RANGE: + output = toString(range.asNumberValue()); + break; + case NUMBER_CHOOSE_RANGE: + output = toString(range.asNumberChoose()); + break; + case CUSTOM: + output = range.toString(); + break; + } + return output; + } + + public abstract String toString(CollectionSizeRange range); + + public abstract String toString(NumberValueRange range); + + public abstract String toString(NumberChooseRange range); + + public abstract String toString(StateRange range); + + public abstract String toString(TextSizeRange range); + + public abstract String toString(TextChooseRange range); + + /** + * @param ranges array of complex ranges + * @return array of raw ranges + */ + public abstract String[] asStringArray(BaseArgumentRange... ranges); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSerializer.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSerializer.java index 8766fd6..24cda26 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSerializer.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSerializer.java @@ -1,86 +1,97 @@ package com.syntaxphoenix.syntaxapi.command; -import com.syntaxphoenix.syntaxapi.command.arguments.*; +import com.syntaxphoenix.syntaxapi.command.arguments.ArrayArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigDecimalArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigIntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BooleanArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ByteArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.DoubleArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.FloatArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.IntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ListArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.LongArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ShortArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.StringArgument; public abstract class ArgumentSerializer { - public static final ArgumentSerializer DEFAULT = new DefaultArgumentSerializer(); - - public String toString(BaseArgument argument) { - ArgumentType type = argument.getType(); - String output = ""; - switch (type) { - case BOOLEAN: - output = toString(argument.asBoolean()); - break; - case BYTE: - output = toString(argument.asByte()); - break; - case SHORT: - output = toString(argument.asShort()); - break; - case ARRAY: - output = toString(argument.asArray()); - break; - case BIG_INTEGER: - output = toString(argument.asBigInteger()); - break; - case BIG_DECIMAL: - output = toString(argument.asBigDecimal()); - break; - case DOUBLE: - output = toString(argument.asDouble()); - break; - case FLOAT: - output = toString(argument.asFloat()); - break; - case INTEGER: - output = toString(argument.asInteger()); - break; - case LIST: - output = toString(argument.asList()); - break; - case LONG: - output = toString(argument.asLong()); - break; - case STRING: - output = toString(argument.asString()); - break; - case CUSTOM: - output = argument.asObject().toString(); - break; - } - return output; - } - - public abstract String toString(ArrayArgument argument); - - public abstract String toString(BigDecimalArgument argument); - - public abstract String toString(BigIntegerArgument argument); - - public abstract String toString(DoubleArgument argument); - - public abstract String toString(ByteArgument argument); - - public abstract String toString(ShortArgument argument); - - public abstract String toString(FloatArgument argument); - - public abstract String toString(IntegerArgument argument); - - public abstract String toString(ListArgument argument); - - public abstract String toString(LongArgument argument); - - public abstract String toString(StringArgument argument); - - public abstract String toString(BooleanArgument argument); - - /** - * @param arguments array of complex arguments - * @return array of raw arguments - */ - public abstract String[] asStringArray(BaseArgument... arguments); + public static final ArgumentSerializer DEFAULT = new DefaultArgumentSerializer(); + + public String toString(BaseArgument argument) { + ArgumentType type = argument.getType(); + String output = ""; + switch (type) { + case BOOLEAN: + output = toString(argument.asBoolean()); + break; + case BYTE: + output = toString(argument.asByte()); + break; + case SHORT: + output = toString(argument.asShort()); + break; + case ARRAY: + output = toString(argument.asArray()); + break; + case BIG_INTEGER: + output = toString(argument.asBigInteger()); + break; + case BIG_DECIMAL: + output = toString(argument.asBigDecimal()); + break; + case DOUBLE: + output = toString(argument.asDouble()); + break; + case FLOAT: + output = toString(argument.asFloat()); + break; + case INTEGER: + output = toString(argument.asInteger()); + break; + case LIST: + output = toString(argument.asList()); + break; + case LONG: + output = toString(argument.asLong()); + break; + case STRING: + output = toString(argument.asString()); + break; + case CUSTOM: + output = argument.asObject().toString(); + break; + } + return output; + } + + public abstract String toString(ArrayArgument argument); + + public abstract String toString(BigDecimalArgument argument); + + public abstract String toString(BigIntegerArgument argument); + + public abstract String toString(DoubleArgument argument); + + public abstract String toString(ByteArgument argument); + + public abstract String toString(ShortArgument argument); + + public abstract String toString(FloatArgument argument); + + public abstract String toString(IntegerArgument argument); + + public abstract String toString(ListArgument argument); + + public abstract String toString(LongArgument argument); + + public abstract String toString(StringArgument argument); + + public abstract String toString(BooleanArgument argument); + + /** + * @param arguments array of complex arguments + * @return array of raw arguments + */ + public abstract String[] asStringArray(BaseArgument... arguments); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSuperType.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSuperType.java index 8f63e2b..9e75dc0 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSuperType.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentSuperType.java @@ -9,24 +9,24 @@ */ public enum ArgumentSuperType { - TEXT, - STATE, - OBJECT, - NUMBER, - COLLECTION; + TEXT, + STATE, + OBJECT, + NUMBER, + COLLECTION; - /* - * - */ + /* + * + */ - public ArgumentType[] getSubTypes() { - Collection types = new ArrayList<>(); - for (ArgumentType type : ArgumentType.values()) { - if (type.getSuperType().equals(this)) { - types.add(type); - } - } - return types.toArray(new ArgumentType[0]); - } + public ArgumentType[] getSubTypes() { + Collection types = new ArrayList<>(); + for (ArgumentType type : ArgumentType.values()) { + if (type.getSuperType().equals(this)) { + types.add(type); + } + } + return types.toArray(new ArgumentType[0]); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentType.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentType.java index 27ae8b7..cf0098b 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentType.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ArgumentType.java @@ -1,8 +1,8 @@ package com.syntaxphoenix.syntaxapi.command; import java.lang.reflect.Array; -import java.math.BigInteger; import java.math.BigDecimal; +import java.math.BigInteger; import java.util.ArrayList; /** @@ -12,41 +12,41 @@ public enum ArgumentType { - CUSTOM(ArgumentSuperType.OBJECT, Object.class), - BOOLEAN(ArgumentSuperType.STATE, Boolean.class), - STRING(ArgumentSuperType.TEXT, String.class), - BYTE(ArgumentSuperType.NUMBER, Byte.class), - SHORT(ArgumentSuperType.NUMBER, Short.class), - INTEGER(ArgumentSuperType.NUMBER, Integer.class), - FLOAT(ArgumentSuperType.NUMBER, Float.class), - LONG(ArgumentSuperType.NUMBER, Long.class), - DOUBLE(ArgumentSuperType.NUMBER, Double.class), - BIG_DECIMAL(ArgumentSuperType.NUMBER, BigDecimal.class), - BIG_INTEGER(ArgumentSuperType.NUMBER, BigInteger.class), - LIST(ArgumentSuperType.COLLECTION, ArrayList.class), - ARRAY(ArgumentSuperType.COLLECTION, Array.class); - - /** - * - */ - - private final ArgumentSuperType superType; - private final Class classType; - - /** - * - */ - private ArgumentType(ArgumentSuperType superType, Class classType) { - this.superType = superType; - this.classType = classType; - } - - public ArgumentSuperType getSuperType() { - return superType; - } - - public Class getClassType() { - return classType; - } + CUSTOM(ArgumentSuperType.OBJECT, Object.class), + BOOLEAN(ArgumentSuperType.STATE, Boolean.class), + STRING(ArgumentSuperType.TEXT, String.class), + BYTE(ArgumentSuperType.NUMBER, Byte.class), + SHORT(ArgumentSuperType.NUMBER, Short.class), + INTEGER(ArgumentSuperType.NUMBER, Integer.class), + FLOAT(ArgumentSuperType.NUMBER, Float.class), + LONG(ArgumentSuperType.NUMBER, Long.class), + DOUBLE(ArgumentSuperType.NUMBER, Double.class), + BIG_DECIMAL(ArgumentSuperType.NUMBER, BigDecimal.class), + BIG_INTEGER(ArgumentSuperType.NUMBER, BigInteger.class), + LIST(ArgumentSuperType.COLLECTION, ArrayList.class), + ARRAY(ArgumentSuperType.COLLECTION, Array.class); + + /** + * + */ + + private final ArgumentSuperType superType; + private final Class classType; + + /** + * + */ + private ArgumentType(ArgumentSuperType superType, Class classType) { + this.superType = superType; + this.classType = classType; + } + + public ArgumentSuperType getSuperType() { + return superType; + } + + public Class getClassType() { + return classType; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Arguments.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Arguments.java index 327e389..052eddc 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Arguments.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Arguments.java @@ -14,136 +14,136 @@ */ public class Arguments implements Iterable { - private final List arguments; - private boolean locked = false; - - public Arguments() { - this.arguments = new ArrayList<>(); - } - - public Arguments(List arguments) { - this.arguments = arguments; - } - - public int count() { - return arguments.size(); - } - - public BaseArgument get(int position) { - if (position < 1) { - throw negativeOrZero(); - } - if (position > count()) { - throw outOfBounce(position); - } - return arguments.get(position - 1); - } - - public void add(BaseArgument argument, int position) { - if (locked) { - throw locked(); - } - if (position < 1) { - throw negativeOrZero(); - } - if (argument == null) { - return; - } - arguments.add(position - 1, argument); - } - - public void add(BaseArgument argument) { - if (locked) { - throw locked(); - } - if (argument == null) { - return; - } - arguments.add(argument); - } - - public boolean match(Predicate filter) { - return arguments.stream().anyMatch(filter); - } - - public ArgumentType getType(int position) { - return get(position).getType(); - } - - public ArgumentSuperType getSuperType(int position) { - return getType(position).getSuperType(); - } - - protected boolean isLocked() { - return locked; - } - - protected void setLocked(boolean locked) { - this.locked = locked; - } - - /* - * toString - */ - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - public String toString(int start) { - return toString(start, arguments.size()); - } - - public String toString(int start, int end) { - return toString(start, end, ArgumentSerializer.DEFAULT); - } - - public String toString(ArgumentSerializer serializer) { - return new ListArgument<>(arguments).toString(serializer); - } - - public String toString(int start, ArgumentSerializer serializer) { - return toString(start, serializer); - } - - public String toString(int start, int end, ArgumentSerializer serializer) { - return new ListArgument<>(arguments.subList(start, end)).toString(serializer); - } - - /** - * Exception Construction - */ - - private IllegalArgumentException negativeOrZero() { - return new IllegalArgumentException("Bound must be positive!"); - } - - private IndexOutOfBoundsException outOfBounce(int position) { - return new IndexOutOfBoundsException("Index: " + position + " - Size: " + count()); - } - - private ObjectLockedException locked() { - return new ObjectLockedException("Cannot edit a locked object!"); - } - - /* - * - * Utils - * - */ - - @Override - public Iterator iterator() { - return arguments.iterator(); - } - - public Arguments copy(int start) { - return copy(start, arguments.size()); - } - - public Arguments copy(int start, int end) { - return new Arguments(arguments.subList(start, end)); - } + private final List arguments; + private boolean locked = false; + + public Arguments() { + this.arguments = new ArrayList<>(); + } + + public Arguments(List arguments) { + this.arguments = arguments; + } + + public int count() { + return arguments.size(); + } + + public BaseArgument get(int position) { + if (position < 1) { + throw negativeOrZero(); + } + if (position > count()) { + throw outOfBounce(position); + } + return arguments.get(position - 1); + } + + public void add(BaseArgument argument, int position) { + if (locked) { + throw locked(); + } + if (position < 1) { + throw negativeOrZero(); + } + if (argument == null) { + return; + } + arguments.add(position - 1, argument); + } + + public void add(BaseArgument argument) { + if (locked) { + throw locked(); + } + if (argument == null) { + return; + } + arguments.add(argument); + } + + public boolean match(Predicate filter) { + return arguments.stream().anyMatch(filter); + } + + public ArgumentType getType(int position) { + return get(position).getType(); + } + + public ArgumentSuperType getSuperType(int position) { + return getType(position).getSuperType(); + } + + protected boolean isLocked() { + return locked; + } + + protected void setLocked(boolean locked) { + this.locked = locked; + } + + /* + * toString + */ + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + public String toString(int start) { + return toString(start, arguments.size()); + } + + public String toString(int start, int end) { + return toString(start, end, ArgumentSerializer.DEFAULT); + } + + public String toString(ArgumentSerializer serializer) { + return new ListArgument<>(arguments).toString(serializer); + } + + public String toString(int start, ArgumentSerializer serializer) { + return toString(start, serializer); + } + + public String toString(int start, int end, ArgumentSerializer serializer) { + return new ListArgument<>(arguments.subList(start, end)).toString(serializer); + } + + /** + * Exception Construction + */ + + private IllegalArgumentException negativeOrZero() { + return new IllegalArgumentException("Bound must be positive!"); + } + + private IndexOutOfBoundsException outOfBounce(int position) { + return new IndexOutOfBoundsException("Index: " + position + " - Size: " + count()); + } + + private ObjectLockedException locked() { + return new ObjectLockedException("Cannot edit a locked object!"); + } + + /* + * + * Utils + * + */ + + @Override + public Iterator iterator() { + return arguments.iterator(); + } + + public Arguments copy(int start) { + return copy(start, arguments.size()); + } + + public Arguments copy(int start, int end) { + return new Arguments(arguments.subList(start, end)); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgument.java index 27374b6..9dbc883 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgument.java @@ -1,6 +1,17 @@ package com.syntaxphoenix.syntaxapi.command; -import com.syntaxphoenix.syntaxapi.command.arguments.*; +import com.syntaxphoenix.syntaxapi.command.arguments.ArrayArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigDecimalArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigIntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BooleanArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ByteArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.DoubleArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.FloatArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.IntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ListArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.LongArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ShortArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.StringArgument; /** * @author Lauriichen @@ -9,81 +20,81 @@ @SuppressWarnings("unchecked") public abstract class BaseArgument { - public abstract ArgumentType getType(); + public abstract ArgumentType getType(); - public Class getClassType() { - return getType().getClassType(); - } + public Class getClassType() { + return getType().getClassType(); + } - public ArgumentSuperType getSuperType() { - return getType().getSuperType(); - } + public ArgumentSuperType getSuperType() { + return getType().getSuperType(); + } - public abstract Object asObject(); + public abstract Object asObject(); - @Override - public abstract String toString(); + @Override + public abstract String toString(); - public abstract String toString(ArgumentSerializer serializer); + public abstract String toString(ArgumentSerializer serializer); - public BooleanArgument asBoolean() { - return (BooleanArgument) this; - } + public BooleanArgument asBoolean() { + return (BooleanArgument) this; + } - public ArrayArgument asArray() { - return (ArrayArgument) this; - } + public ArrayArgument asArray() { + return (ArrayArgument) this; + } - public ListArgument asList() { - return (ListArgument) this; - } + public ListArgument asList() { + return (ListArgument) this; + } - public StringArgument asString() { - return (StringArgument) this; - } + public StringArgument asString() { + return (StringArgument) this; + } - public NumericArgument asNumeric() { - return (NumericArgument) this; - } + public NumericArgument asNumeric() { + return (NumericArgument) this; + } - public IntegerArgument asInteger() { - return (IntegerArgument) this; - } + public IntegerArgument asInteger() { + return (IntegerArgument) this; + } - public LongArgument asLong() { - return (LongArgument) this; - } + public LongArgument asLong() { + return (LongArgument) this; + } - public ByteArgument asByte() { - return (ByteArgument) this; - } + public ByteArgument asByte() { + return (ByteArgument) this; + } - public ShortArgument asShort() { - return (ShortArgument) this; - } + public ShortArgument asShort() { + return (ShortArgument) this; + } - public FloatArgument asFloat() { - return (FloatArgument) this; - } + public FloatArgument asFloat() { + return (FloatArgument) this; + } - public DoubleArgument asDouble() { - return (DoubleArgument) this; - } + public DoubleArgument asDouble() { + return (DoubleArgument) this; + } - public BigIntegerArgument asBigInteger() { - return (BigIntegerArgument) this; - } + public BigIntegerArgument asBigInteger() { + return (BigIntegerArgument) this; + } - public BigDecimalArgument asBigDecimal() { - return (BigDecimalArgument) this; - } + public BigDecimalArgument asBigDecimal() { + return (BigDecimalArgument) this; + } - public E as(Class example) { - return (E) asObject(); - } + public E as(Class example) { + return (E) asObject(); + } - public E as(E example) { - return (E) asObject(); - } + public E as(E example) { + return (E) asObject(); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgumentRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgumentRange.java index 481caf3..0e448a5 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgumentRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseArgumentRange.java @@ -1,55 +1,60 @@ package com.syntaxphoenix.syntaxapi.command; -import com.syntaxphoenix.syntaxapi.command.range.*; +import com.syntaxphoenix.syntaxapi.command.range.CollectionSizeRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberValueRange; +import com.syntaxphoenix.syntaxapi.command.range.StateRange; +import com.syntaxphoenix.syntaxapi.command.range.TextChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.TextSizeRange; public abstract class BaseArgumentRange { - private String label; + private String label; - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public BaseArgumentRange setLabel(String label) { - this.label = label; - return this; - } + public BaseArgumentRange setLabel(String label) { + this.label = label; + return this; + } - public abstract RangeType getType(); + public abstract RangeType getType(); - public abstract Class getInputType(); + public abstract Class getInputType(); - public abstract boolean hasType(BaseArgument argument); + public abstract boolean hasType(BaseArgument argument); - public abstract boolean isInRange(BaseArgument argument); + public abstract boolean isInRange(BaseArgument argument); - @Override - public abstract String toString(); + @Override + public abstract String toString(); - public abstract String toString(ArgumentRangeSerializer serializer); + public abstract String toString(ArgumentRangeSerializer serializer); - public TextSizeRange asTextSize() { - return (TextSizeRange) this; - } + public TextSizeRange asTextSize() { + return (TextSizeRange) this; + } - public TextChooseRange asTextChoose() { - return (TextChooseRange) this; - } + public TextChooseRange asTextChoose() { + return (TextChooseRange) this; + } - public StateRange asState() { - return (StateRange) this; - } + public StateRange asState() { + return (StateRange) this; + } - public CollectionSizeRange asCollectionSize() { - return (CollectionSizeRange) this; - } + public CollectionSizeRange asCollectionSize() { + return (CollectionSizeRange) this; + } - public NumberValueRange asNumberValue() { - return (NumberValueRange) this; - } + public NumberValueRange asNumberValue() { + return (NumberValueRange) this; + } - public NumberChooseRange asNumberChoose() { - return (NumberChooseRange) this; - } + public NumberChooseRange asNumberChoose() { + return (NumberChooseRange) this; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCommand.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCommand.java index 74e9290..7ce3b8f 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCommand.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCommand.java @@ -6,10 +6,10 @@ */ public abstract class BaseCommand { - public abstract void execute(BaseInfo info, Arguments arguments); + public abstract void execute(BaseInfo info, Arguments arguments); - public BaseCompletion complete(BaseInfo info, Arguments arguments) { - return null; - } + public BaseCompletion complete(BaseInfo info, Arguments arguments) { + return null; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCompletion.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCompletion.java index 85fbf3e..654dfda 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCompletion.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseCompletion.java @@ -2,6 +2,6 @@ public abstract class BaseCompletion { - public abstract Object getCompletion(); + public abstract Object getCompletion(); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseInfo.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseInfo.java index 9e86658..05e3779 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseInfo.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/BaseInfo.java @@ -2,20 +2,20 @@ public abstract class BaseInfo { - private final CommandManager manager; - private final String label; + private final CommandManager manager; + private final String label; - public BaseInfo(CommandManager manager, String label) { - this.manager = manager; - this.label = label; - } + public BaseInfo(CommandManager manager, String label) { + this.manager = manager; + this.label = label; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public CommandManager getManager() { - return manager; - } + public CommandManager getManager() { + return manager; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandManager.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandManager.java index 0f4850f..58d270d 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandManager.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandManager.java @@ -15,225 +15,235 @@ */ public class CommandManager { - protected BiFunction infoConstructor = ((manager, label) -> new DefaultInfo(manager, label)); - - protected final AliasMap commands = new AliasMap<>(); - protected ArgumentIdentifier validator = ArgumentIdentifier.DEFAULT; - protected ILogger logger = null; - - protected String splitter = " "; - protected String prefix = "!"; - - /* - * Getter - */ - - public AliasMap getClonedMap() { - synchronized (commands) { - return commands.clone(); - } - } - - @SuppressWarnings("unchecked") - public Entry[] getEntries() { - synchronized (commands) { - return commands.entrySet().toArray(new Entry[0]); - } - } - - public BaseCommand[] getCommands() { - synchronized (commands) { - return commands.values().toArray(new BaseCommand[0]); - } - } - - public Alias[] getAliases() { - synchronized (commands) { - return commands.keySet().toArray(new Alias[0]); - } - } - - public String getPrefix() { - return prefix; - } - - public String getSplitter() { - return splitter; - } - - public BiFunction getInfoConstructor() { - return infoConstructor; - } - - public ArgumentIdentifier getValidator() { - return validator; - } - - public boolean hasLogger() { - return logger != null; - } - - public ILogger getLogger() { - return logger; - } - - /* - * Setter - */ - - public CommandManager setPrefix(String prefix) { - this.prefix = prefix; - return this; - } - - public CommandManager setSplitter(String splitter) { - this.splitter = splitter; - return this; - } - - public CommandManager setInfoConstructor(BiFunction infoConstructor) { - this.infoConstructor = infoConstructor; - return this; - } - - public CommandManager setValidator(ArgumentIdentifier validator) { - this.validator = validator; - return this; - } - - public CommandManager setLogger(ILogger logger) { - this.logger = logger; - return this; - } - - /* - * Management - */ - - public CommandManager register(BaseCommand command, String name, String... aliases) { - return register(command, new Alias(name, aliases)); - } - - public CommandManager register(BaseCommand command, String description, String name, String[] aliases) { - return register(command, new Alias(name, aliases).setDescription(description)); - } - - public CommandManager register(BaseCommand command, Alias alias) { - synchronized (commands) { - if (commands.hasConflict(alias).isEmpty()) { - commands.put(alias, command); - } - } - return this; - } - - public CommandManager unregister(BaseCommand command) { - synchronized (commands) { - if (!commands.containsValue(command)) - return this; - Optional> optional = commands.entrySet().stream().filter(entry -> entry.getValue().equals(command)).findFirst(); - if (optional.isPresent()) - commands.remove(optional.get().getKey()); - } - return this; - } - - public CommandManager unregister(String name) { - synchronized (commands) { - if (commands.hasConflict(new Alias(name)).isEmpty()) - return this; - Optional optional = commands.keySet().stream().filter(alias -> alias.isLabel(name)).findFirst(); - if (optional.isPresent()) - commands.remove(optional.get()); - } - return this; - } - - public CommandManager unregister(Alias alias) { - synchronized (commands) { - String[] conflicts = commands.hasConflict(alias).toArray(new String[0]); - if (conflicts.length == 0) - return this; - Alias[] aliases = commands.keySet().stream().filter(current -> hasLabel(conflicts, current)).toArray(size -> new Alias[size]); - for (int index = 0; index < aliases.length; index++) - commands.remove(aliases[index]); - } - return this; - } - - private boolean hasLabel(String[] source, Alias compare) { - for (int index = 0; index < source.length; index++) - if (compare.isLabel(source[index])) - return true; - return false; - } - - public CommandManager unregisterAll() { - synchronized (commands) { - commands.clear(); - } - return this; - } - - /* - * Command Processing - */ - - public CommandProcess process(String message) { - CommandProcess process = new CommandProcess(this); - if (!message.startsWith(prefix) || message.equals(prefix)) { - return process.lock(); - } - return process(message.replace(prefix, "").split(splitter)); - } - - public CommandProcess process(String... message) { - return process(new CommandProcess(this), message); - } - - private CommandProcess process(CommandProcess process, String... message) { - String command = message[0].toLowerCase(); - process.setLabel(command); - if (command.isEmpty()) { - return process.lock(); - } - process.setValid(true); - synchronized (commands) { - if (!commands.containsKey(command)) { - return process.lock(); - } - process.setCommand(commands.get(command)); - } - process.setArguments(new Arguments(validator.process(Arrays.subArray(size -> new String[size], message, 1)))); - return process.lock(); - } - - /* - * Command Execution - */ - - public ExecutionState execute(String message) { - return process(message).execute(); - } - - public ExecutionState execute(CommandProcess process) { - ExecutionState state = process.asState(); - if (!state.isRunnable()) { - return state; - } - return execute(process.getCommand(), process.constructInfo(), process.getArguments()); - } - - public ExecutionState execute(BaseCommand command, BaseInfo info, Arguments arguments) { - try { - command.execute(info, arguments); - } catch (Throwable throwable) { - if (hasLogger()) { - logger.log(throwable); - } - return ExecutionState.FAILED; - } - return ExecutionState.SUCCESS; - } + protected BiFunction infoConstructor = ((manager, label) -> new DefaultInfo(manager, + label)); + + protected final AliasMap commands = new AliasMap<>(); + protected ArgumentIdentifier validator = ArgumentIdentifier.DEFAULT; + protected ILogger logger = null; + + protected String splitter = " "; + protected String prefix = "!"; + + /* + * Getter + */ + + public AliasMap getClonedMap() { + synchronized (commands) { + return commands.clone(); + } + } + + @SuppressWarnings("unchecked") + public Entry[] getEntries() { + synchronized (commands) { + return commands.entrySet().toArray(new Entry[0]); + } + } + + public BaseCommand[] getCommands() { + synchronized (commands) { + return commands.values().toArray(new BaseCommand[0]); + } + } + + public Alias[] getAliases() { + synchronized (commands) { + return commands.keySet().toArray(new Alias[0]); + } + } + + public String getPrefix() { + return prefix; + } + + public String getSplitter() { + return splitter; + } + + public BiFunction getInfoConstructor() { + return infoConstructor; + } + + public ArgumentIdentifier getValidator() { + return validator; + } + + public boolean hasLogger() { + return logger != null; + } + + public ILogger getLogger() { + return logger; + } + + /* + * Setter + */ + + public CommandManager setPrefix(String prefix) { + this.prefix = prefix; + return this; + } + + public CommandManager setSplitter(String splitter) { + this.splitter = splitter; + return this; + } + + public CommandManager setInfoConstructor(BiFunction infoConstructor) { + this.infoConstructor = infoConstructor; + return this; + } + + public CommandManager setValidator(ArgumentIdentifier validator) { + this.validator = validator; + return this; + } + + public CommandManager setLogger(ILogger logger) { + this.logger = logger; + return this; + } + + /* + * Management + */ + + public CommandManager register(BaseCommand command, String name, String... aliases) { + return register(command, new Alias(name, aliases)); + } + + public CommandManager register(BaseCommand command, String description, String name, String[] aliases) { + return register(command, new Alias(name, aliases).setDescription(description)); + } + + public CommandManager register(BaseCommand command, Alias alias) { + synchronized (commands) { + if (commands.hasConflict(alias).isEmpty()) { + commands.put(alias, command); + } + } + return this; + } + + public CommandManager unregister(BaseCommand command) { + synchronized (commands) { + if (!commands.containsValue(command)) { + return this; + } + Optional> optional = commands.entrySet().stream().filter(entry -> entry.getValue().equals(command)) + .findFirst(); + if (optional.isPresent()) { + commands.remove(optional.get().getKey()); + } + } + return this; + } + + public CommandManager unregister(String name) { + synchronized (commands) { + if (commands.hasConflict(new Alias(name)).isEmpty()) { + return this; + } + Optional optional = commands.keySet().stream().filter(alias -> alias.isLabel(name)).findFirst(); + if (optional.isPresent()) { + commands.remove(optional.get()); + } + } + return this; + } + + public CommandManager unregister(Alias alias) { + synchronized (commands) { + String[] conflicts = commands.hasConflict(alias).toArray(new String[0]); + if (conflicts.length == 0) { + return this; + } + Alias[] aliases = commands.keySet().stream().filter(current -> hasLabel(conflicts, current)).toArray(size -> new Alias[size]); + for (int index = 0; index < aliases.length; index++) { + commands.remove(aliases[index]); + } + } + return this; + } + + private boolean hasLabel(String[] source, Alias compare) { + for (int index = 0; index < source.length; index++) { + if (compare.isLabel(source[index])) { + return true; + } + } + return false; + } + + public CommandManager unregisterAll() { + synchronized (commands) { + commands.clear(); + } + return this; + } + + /* + * Command Processing + */ + + public CommandProcess process(String message) { + CommandProcess process = new CommandProcess(this); + if (!message.startsWith(prefix) || message.equals(prefix)) { + return process.lock(); + } + return process(message.replace(prefix, "").split(splitter)); + } + + public CommandProcess process(String... message) { + return process(new CommandProcess(this), message); + } + + private CommandProcess process(CommandProcess process, String... message) { + String command = message[0].toLowerCase(); + process.setLabel(command); + if (command.isEmpty()) { + return process.lock(); + } + process.setValid(true); + synchronized (commands) { + if (!commands.containsKey(command)) { + return process.lock(); + } + process.setCommand(commands.get(command)); + } + process.setArguments(new Arguments(validator.process(Arrays.subArray(size -> new String[size], message, 1)))); + return process.lock(); + } + + /* + * Command Execution + */ + + public ExecutionState execute(String message) { + return process(message).execute(); + } + + public ExecutionState execute(CommandProcess process) { + ExecutionState state = process.asState(); + if (!state.isRunnable()) { + return state; + } + return execute(process.getCommand(), process.constructInfo(), process.getArguments()); + } + + public ExecutionState execute(BaseCommand command, BaseInfo info, Arguments arguments) { + try { + command.execute(info, arguments); + } catch (Throwable throwable) { + if (hasLogger()) { + logger.log(throwable); + } + return ExecutionState.FAILED; + } + return ExecutionState.SUCCESS; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandProcess.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandProcess.java index 76c30fd..fc14921 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandProcess.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/CommandProcess.java @@ -6,113 +6,113 @@ public class CommandProcess { - private final CommandManager manager; - private BiFunction infoConstructor; - - private boolean locked = false; - private boolean valid = false; - private BaseCommand command; - private Arguments arguments; - private String label; - - public CommandProcess(CommandManager manager) { - this.manager = manager; - this.infoConstructor = manager.getInfoConstructor(); - } - - public CommandProcess setValid(boolean valid) { - if (!isLocked()) { - this.valid = valid; - } else { - throw locked(); - } - return this; - } - - public boolean isValid() { - return valid; - } - - public CommandProcess setLabel(String label) { - if (!isLocked()) { - this.label = label; - } else { - throw locked(); - } - return this; - } - - public String getLabel() { - return label; - } - - public CommandProcess setCommand(BaseCommand command) { - if (!isLocked()) { - this.command = command; - } else { - throw locked(); - } - return this; - } - - public BaseCommand getCommand() { - return command; - } - - public CommandProcess setArguments(Arguments arguments) { - if (!isLocked()) { - this.arguments = arguments; - } else { - throw locked(); - } - return this; - } - - public Arguments getArguments() { - return arguments; - } - - public CommandProcess setInfoConstructor(BiFunction info) { - this.infoConstructor = info; - return this; - } - - public BaseInfo constructInfo() { - return infoConstructor.apply(manager, label == null ? "" : label); - } - - public ExecutionState asState() { - return isValid() ? (command == null ? ExecutionState.NOT_EXISTENT : ExecutionState.READY) : ExecutionState.NO_COMMAND; - } - - public ExecutionState execute() { - return execute(manager); - } - - public ExecutionState execute(CommandManager manager) { - if (!arguments.isLocked()) { - arguments.setLocked(true); - } - return manager.execute(this); - } - - public CommandProcess lock() { - if (!isLocked()) { - locked = true; - } - return this; - } - - public boolean isLocked() { - return locked; - } - - /* - * - */ - - private ObjectLockedException locked() { - return new ObjectLockedException("Cannot edit a locked object!"); - } + private final CommandManager manager; + private BiFunction infoConstructor; + + private boolean locked = false; + private boolean valid = false; + private BaseCommand command; + private Arguments arguments; + private String label; + + public CommandProcess(CommandManager manager) { + this.manager = manager; + this.infoConstructor = manager.getInfoConstructor(); + } + + public CommandProcess setValid(boolean valid) { + if (!isLocked()) { + this.valid = valid; + } else { + throw locked(); + } + return this; + } + + public boolean isValid() { + return valid; + } + + public CommandProcess setLabel(String label) { + if (!isLocked()) { + this.label = label; + } else { + throw locked(); + } + return this; + } + + public String getLabel() { + return label; + } + + public CommandProcess setCommand(BaseCommand command) { + if (!isLocked()) { + this.command = command; + } else { + throw locked(); + } + return this; + } + + public BaseCommand getCommand() { + return command; + } + + public CommandProcess setArguments(Arguments arguments) { + if (!isLocked()) { + this.arguments = arguments; + } else { + throw locked(); + } + return this; + } + + public Arguments getArguments() { + return arguments; + } + + public CommandProcess setInfoConstructor(BiFunction info) { + this.infoConstructor = info; + return this; + } + + public BaseInfo constructInfo() { + return infoConstructor.apply(manager, label == null ? "" : label); + } + + public ExecutionState asState() { + return isValid() ? (command == null ? ExecutionState.NOT_EXISTENT : ExecutionState.READY) : ExecutionState.NO_COMMAND; + } + + public ExecutionState execute() { + return execute(manager); + } + + public ExecutionState execute(CommandManager manager) { + if (!arguments.isLocked()) { + arguments.setLocked(true); + } + return manager.execute(this); + } + + public CommandProcess lock() { + if (!isLocked()) { + locked = true; + } + return this; + } + + public boolean isLocked() { + return locked; + } + + /* + * + */ + + private ObjectLockedException locked() { + return new ObjectLockedException("Cannot edit a locked object!"); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentIdentifier.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentIdentifier.java index 2a02687..e7c8527 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentIdentifier.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentIdentifier.java @@ -8,7 +8,18 @@ import java.util.Set; import java.util.regex.Pattern; -import com.syntaxphoenix.syntaxapi.command.arguments.*; +import com.syntaxphoenix.syntaxapi.command.arguments.ArrayArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigDecimalArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigIntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BooleanArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ByteArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.DoubleArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.FloatArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.IntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ListArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.LongArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ShortArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.StringArgument; import com.syntaxphoenix.syntaxapi.utils.java.Strings; /** @@ -17,131 +28,131 @@ */ public class DefaultArgumentIdentifier extends ArgumentIdentifier { - public static final Pattern LIST = Pattern.compile("\\A\\{{1}.*[,( )?]?.*\\}{1}\\z"); - public static final Pattern ARRAY = Pattern.compile("\\A\\[{1}.*[,( )?]?.*\\]{1}\\z"); + public static final Pattern LIST = Pattern.compile("\\A\\{{1}.*[,( )?]?.*\\}{1}\\z"); + public static final Pattern ARRAY = Pattern.compile("\\A\\[{1}.*[,( )?]?.*\\]{1}\\z"); - @Override - public ArrayList process(String... arguments) { - ArrayList list = new ArrayList<>(); - if (arguments == null || arguments.length == 0) { - return list; - } - for (String argument : arguments) { - if (argument.trim().isEmpty()) { - list.add(new StringArgument(argument)); - continue; - } - if (Strings.isBoolean(argument)) { - list.add(new BooleanArgument(Boolean.valueOf(argument))); - continue; - } else if (Strings.isNumeric(argument)) { - try { - list.add(new ByteArgument(Byte.parseByte(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - list.add(new ShortArgument(Short.parseShort(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - list.add(new IntegerArgument(Integer.parseInt(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - list.add(new LongArgument(Long.parseLong(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - list.add(new BigIntegerArgument(new BigInteger(argument))); - continue; - } catch (NumberFormatException e) { - } - list.add(new StringArgument(argument)); - continue; - } else if (Strings.isDecimal(argument)) { - String number = argument.split("\\.")[0]; - try { - Integer.parseInt(number); - list.add(new FloatArgument(Float.parseFloat(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - Long.parseLong(number); - list.add(new DoubleArgument(Double.parseDouble(argument))); - continue; - } catch (NumberFormatException e) { - } - try { - list.add(new BigDecimalArgument(new BigDecimal(argument))); - continue; - } catch (NumberFormatException e) { - } - list.add(new StringArgument(argument)); - continue; - } else if (LIST.matcher(argument).matches()) { - String[] args = argument.replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","); - HashMap> argumentMap = new HashMap<>(); - for (String arg : args) { - if (arg.isEmpty()) { - continue; - } - if (arg.startsWith(" ")) { - arg = arg.replaceFirst(" ", ""); - } - ArrayList value = process(arg); - for (BaseArgument out : value) { - ArgumentType type = out.getType(); - if (argumentMap.containsKey(type)) { - argumentMap.get(type).add(out); - } else { - ArrayList output = new ArrayList<>(); - output.add(out); - argumentMap.put(type, output); - } - } - } - Set>> entries = argumentMap.entrySet(); - for (Entry> entry : entries) { - list.add(new ListArgument<>(entry.getValue())); - } - continue; - } else if (ARRAY.matcher(argument).matches()) { - String[] args = argument.replaceFirst("\\A\\[", "").replaceFirst("\\]\\z", "").split(","); - HashMap> argumentMap = new HashMap<>(); - for (String arg : args) { - if (arg.isEmpty()) { - continue; - } - if (arg.startsWith(" ")) { - arg = arg.replaceFirst(" ", ""); - } - ArrayList value = process(arg); - for (BaseArgument out : value) { - ArgumentType type = out.getType(); - if (argumentMap.containsKey(type)) { - argumentMap.get(type).add(out); - } else { - ArrayList output = new ArrayList<>(); - output.add(out); - argumentMap.put(type, output); - } - } - } - Set>> entries = argumentMap.entrySet(); - for (Entry> entry : entries) { - list.add(new ArrayArgument<>(entry.getValue().toArray(new BaseArgument[0]))); - } - continue; - } - list.add(new StringArgument(argument)); - continue; - } - return list; - } + @Override + public ArrayList process(String... arguments) { + ArrayList list = new ArrayList<>(); + if (arguments == null || arguments.length == 0) { + return list; + } + for (String argument : arguments) { + if (argument.trim().isEmpty()) { + list.add(new StringArgument(argument)); + continue; + } + if (Strings.isBoolean(argument)) { + list.add(new BooleanArgument(Boolean.valueOf(argument))); + continue; + } else if (Strings.isNumeric(argument)) { + try { + list.add(new ByteArgument(Byte.parseByte(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + list.add(new ShortArgument(Short.parseShort(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + list.add(new IntegerArgument(Integer.parseInt(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + list.add(new LongArgument(Long.parseLong(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + list.add(new BigIntegerArgument(new BigInteger(argument))); + continue; + } catch (NumberFormatException e) { + } + list.add(new StringArgument(argument)); + continue; + } else if (Strings.isDecimal(argument)) { + String number = argument.split("\\.")[0]; + try { + Integer.parseInt(number); + list.add(new FloatArgument(Float.parseFloat(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + Long.parseLong(number); + list.add(new DoubleArgument(Double.parseDouble(argument))); + continue; + } catch (NumberFormatException e) { + } + try { + list.add(new BigDecimalArgument(new BigDecimal(argument))); + continue; + } catch (NumberFormatException e) { + } + list.add(new StringArgument(argument)); + continue; + } else if (LIST.matcher(argument).matches()) { + String[] args = argument.replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","); + HashMap> argumentMap = new HashMap<>(); + for (String arg : args) { + if (arg.isEmpty()) { + continue; + } + if (arg.startsWith(" ")) { + arg = arg.replaceFirst(" ", ""); + } + ArrayList value = process(arg); + for (BaseArgument out : value) { + ArgumentType type = out.getType(); + if (argumentMap.containsKey(type)) { + argumentMap.get(type).add(out); + } else { + ArrayList output = new ArrayList<>(); + output.add(out); + argumentMap.put(type, output); + } + } + } + Set>> entries = argumentMap.entrySet(); + for (Entry> entry : entries) { + list.add(new ListArgument<>(entry.getValue())); + } + continue; + } else if (ARRAY.matcher(argument).matches()) { + String[] args = argument.replaceFirst("\\A\\[", "").replaceFirst("\\]\\z", "").split(","); + HashMap> argumentMap = new HashMap<>(); + for (String arg : args) { + if (arg.isEmpty()) { + continue; + } + if (arg.startsWith(" ")) { + arg = arg.replaceFirst(" ", ""); + } + ArrayList value = process(arg); + for (BaseArgument out : value) { + ArgumentType type = out.getType(); + if (argumentMap.containsKey(type)) { + argumentMap.get(type).add(out); + } else { + ArrayList output = new ArrayList<>(); + output.add(out); + argumentMap.put(type, output); + } + } + } + Set>> entries = argumentMap.entrySet(); + for (Entry> entry : entries) { + list.add(new ArrayArgument<>(entry.getValue().toArray(new BaseArgument[0]))); + } + continue; + } + list.add(new StringArgument(argument)); + continue; + } + return list; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeIdentifier.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeIdentifier.java index 3092c60..dd51acf 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeIdentifier.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeIdentifier.java @@ -5,7 +5,12 @@ import java.math.BigDecimal; import java.util.ArrayList; -import com.syntaxphoenix.syntaxapi.command.range.*; +import com.syntaxphoenix.syntaxapi.command.range.CollectionSizeRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberValueRange; +import com.syntaxphoenix.syntaxapi.command.range.StateRange; +import com.syntaxphoenix.syntaxapi.command.range.TextChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.TextSizeRange; import com.syntaxphoenix.syntaxapi.reflection.ClassCache; import com.syntaxphoenix.syntaxapi.utils.java.Strings; @@ -15,88 +20,98 @@ */ public class DefaultArgumentRangeIdentifier extends ArgumentRangeIdentifier { - @SuppressWarnings({ - "rawtypes", - "unchecked" - }) - @Override - public ArrayList process(String... ranges) { - ArrayList list = new ArrayList<>(); - if (ranges == null || ranges.length == 0) { - return list; - } - for (String range : ranges) { - if (range.startsWith("collection::")) { - String[] part = (range = range.replaceFirst("collection::", "")).split("[", 2); + @SuppressWarnings({ + "rawtypes", + "unchecked" + }) + @Override + public ArrayList process(String... ranges) { + ArrayList list = new ArrayList<>(); + if (ranges == null || ranges.length == 0) { + return list; + } + for (String range : ranges) { + if (range.startsWith("collection::")) { + String[] part = (range = range.replaceFirst("collection::", "")).split("[", 2); - String type = part[0]; - Class valueType; - if ((valueType = ClassCache.getClass(type)) == null) - continue; + String type = part[0]; + Class valueType; + if ((valueType = ClassCache.getClass(type)) == null) { + continue; + } - part = part[1].split("\\,", 2); - if (!(Strings.isNumeric(part[0]) && Strings.isNumeric(part[1]))) - continue; + part = part[1].split("\\,", 2); + if (!(Strings.isNumeric(part[0]) && Strings.isNumeric(part[1]))) { + continue; + } - int min, max; + int min, max; - try { - min = Integer.parseInt(part[0]); - max = Integer.parseInt(part[1].substring(0, part[1].length() - 1)); - } catch (NumberFormatException ignore) { - continue; - } - list.add(new CollectionSizeRange(min, max, valueType)); - } else if (range.startsWith("number0[")) { - String[] part = (range = range.replaceFirst("number0[", "")).split("\\,", 2); - if (!((Strings.isNumeric(part[0]) || Strings.isDecimal(part[0])) && (Strings.isNumeric(part[1]) || Strings.isDecimal(part[1])))) - continue; + try { + min = Integer.parseInt(part[0]); + max = Integer.parseInt(part[1].substring(0, part[1].length() - 1)); + } catch (NumberFormatException ignore) { + continue; + } + list.add(new CollectionSizeRange(min, max, valueType)); + } else if (range.startsWith("number0[")) { + String[] part = (range = range.replaceFirst("number0[", "")).split("\\,", 2); + if (!((Strings.isNumeric(part[0]) || Strings.isDecimal(part[0])) + && (Strings.isNumeric(part[1]) || Strings.isDecimal(part[1])))) { + continue; + } - BigDecimal min, max; + BigDecimal min, max; - try { - min = new BigDecimal(part[0]); - max = new BigDecimal(part[1].substring(0, part[1].length() - 1)); - } catch (NumberFormatException ignore) { - continue; - } - list.add(new NumberValueRange(min, max)); - } else if (range.startsWith("number1[")) { - String[] part = (range = range.replaceFirst("number1[", "")).split("\\:", 2); - if (!(Strings.isBoolean(part[0]) && LIST.matcher(part[1] = part[1].substring(0, part[1].length() - 1)).matches())) - continue; - list.add(new NumberChooseRange(Boolean.valueOf(part[0]), (Object[]) part[1].replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","))); - } else if (range.startsWith("text0[")) { - String[] part = (range = range.replaceFirst("text0[", "")).split("\\,", 2); - if (!(Strings.isNumeric(part[0]) && Strings.isNumeric(part[1]))) - continue; + try { + min = new BigDecimal(part[0]); + max = new BigDecimal(part[1].substring(0, part[1].length() - 1)); + } catch (NumberFormatException ignore) { + continue; + } + list.add(new NumberValueRange(min, max)); + } else if (range.startsWith("number1[")) { + String[] part = (range = range.replaceFirst("number1[", "")).split("\\:", 2); + if (!(Strings.isBoolean(part[0]) && LIST.matcher(part[1] = part[1].substring(0, part[1].length() - 1)).matches())) { + continue; + } + list.add(new NumberChooseRange(Boolean.valueOf(part[0]), + (Object[]) part[1].replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","))); + } else if (range.startsWith("text0[")) { + String[] part = (range = range.replaceFirst("text0[", "")).split("\\,", 2); + if (!(Strings.isNumeric(part[0]) && Strings.isNumeric(part[1]))) { + continue; + } - int min, max; + int min, max; - try { - min = Integer.parseInt(part[0]); - max = Integer.parseInt(part[1].substring(0, part[1].length() - 1)); - } catch (NumberFormatException ignore) { - continue; - } - list.add(new TextSizeRange(min, max)); - } else if (range.startsWith("text1[")) { - String[] part = (range = range.replaceFirst("text1[", "")).split("\\:", 2); - if (!(Strings.isBoolean(part[0]) && LIST.matcher(part[1] = part[1].substring(0, part[1].length() - 1)).matches())) - continue; - list.add(new TextChooseRange(Boolean.valueOf(part[0]), part[1].replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","))); - } else if (range.startsWith("state0[")) { - if ((range = range.replaceFirst("state0[", "")).length() == 1) { - list.add(new StateRange()); - continue; - } - if (!Strings.isBoolean(range = range.substring(0, range.length() - 1))) - continue; - list.add(new StateRange(Boolean.valueOf(range))); - } - } + try { + min = Integer.parseInt(part[0]); + max = Integer.parseInt(part[1].substring(0, part[1].length() - 1)); + } catch (NumberFormatException ignore) { + continue; + } + list.add(new TextSizeRange(min, max)); + } else if (range.startsWith("text1[")) { + String[] part = (range = range.replaceFirst("text1[", "")).split("\\:", 2); + if (!(Strings.isBoolean(part[0]) && LIST.matcher(part[1] = part[1].substring(0, part[1].length() - 1)).matches())) { + continue; + } + list.add(new TextChooseRange(Boolean.valueOf(part[0]), + part[1].replaceFirst("\\A\\{", "").replaceFirst("\\}\\z", "").split(","))); + } else if (range.startsWith("state0[")) { + if ((range = range.replaceFirst("state0[", "")).length() == 1) { + list.add(new StateRange()); + continue; + } + if (!Strings.isBoolean(range = range.substring(0, range.length() - 1))) { + continue; + } + list.add(new StateRange(Boolean.valueOf(range))); + } + } - return null; - } + return null; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeSerializer.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeSerializer.java index efcb633..1f2f4b2 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeSerializer.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentRangeSerializer.java @@ -2,81 +2,87 @@ import java.util.List; -import com.syntaxphoenix.syntaxapi.command.range.*; +import com.syntaxphoenix.syntaxapi.command.range.CollectionSizeRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.NumberValueRange; +import com.syntaxphoenix.syntaxapi.command.range.StateRange; +import com.syntaxphoenix.syntaxapi.command.range.TextChooseRange; +import com.syntaxphoenix.syntaxapi.command.range.TextSizeRange; import com.syntaxphoenix.syntaxapi.utils.java.lang.StringBuilder; public class DefaultArgumentRangeSerializer extends ArgumentRangeSerializer { - public static final String SIZE_FORMAT = "%s[%s,%s]"; - public static final String COLLECTION_SIZE_FORMAT = "%s::%s[%s,%s]"; - - public static final String CHOOSE_FORMAT = "%s[%s:%s]"; - - /* - * - */ - - @Override - public String toString(CollectionSizeRange range) { - return String.format(COLLECTION_SIZE_FORMAT, "collection0", range.getInputType().toString(), range.getMinimum(), range.getMaximum()); - } - - @Override - public String toString(NumberValueRange range) { - return String.format(SIZE_FORMAT, "number0", range.getMinimum().toString(), range.getMaximum().toString()); - } - - @Override - public String toString(NumberChooseRange range) { - return String.format(CHOOSE_FORMAT, "number1", range.isBlacklist(), toString(range.getValues())); - } - - @Override - public String toString(StateRange range) { - return String.format(CHOOSE_FORMAT, "state0", range.isEnabled(), range.getDisallowed()); - } - - @Override - public String toString(TextSizeRange range) { - return String.format(SIZE_FORMAT, "text0", range.getMinimum(), range.getMaximum()); - } - - @Override - public String toString(TextChooseRange range) { - return String.format(CHOOSE_FORMAT, "text1", range.isBlacklist(), toString(range.getValues())); - } - - /* - * - */ - - @Override - public String[] asStringArray(BaseArgumentRange... ranges) { - if (ranges == null || ranges.length == 0) { - return new String[0]; - } - int length = ranges.length; - String[] array = new String[length]; - for (int index = 0; index < length; index++) { - array[index] = ranges[index].toString(); - } - return array; - } - - /* - * - */ - - private String toString(List values) { - StringBuilder builder = new StringBuilder(); - if (!values.isEmpty()) { - for (Object value : values) { - builder.append(value.toString()); - builder.append(','); - } - } - String built = builder.toStringClear(); - return built.substring(0, built.length() - 1); - } + public static final String SIZE_FORMAT = "%s[%s,%s]"; + public static final String COLLECTION_SIZE_FORMAT = "%s::%s[%s,%s]"; + + public static final String CHOOSE_FORMAT = "%s[%s:%s]"; + + /* + * + */ + + @Override + public String toString(CollectionSizeRange range) { + return String.format(COLLECTION_SIZE_FORMAT, "collection0", range.getInputType().toString(), range.getMinimum(), + range.getMaximum()); + } + + @Override + public String toString(NumberValueRange range) { + return String.format(SIZE_FORMAT, "number0", range.getMinimum().toString(), range.getMaximum().toString()); + } + + @Override + public String toString(NumberChooseRange range) { + return String.format(CHOOSE_FORMAT, "number1", range.isBlacklist(), toString(range.getValues())); + } + + @Override + public String toString(StateRange range) { + return String.format(CHOOSE_FORMAT, "state0", range.isEnabled(), range.getDisallowed()); + } + + @Override + public String toString(TextSizeRange range) { + return String.format(SIZE_FORMAT, "text0", range.getMinimum(), range.getMaximum()); + } + + @Override + public String toString(TextChooseRange range) { + return String.format(CHOOSE_FORMAT, "text1", range.isBlacklist(), toString(range.getValues())); + } + + /* + * + */ + + @Override + public String[] asStringArray(BaseArgumentRange... ranges) { + if (ranges == null || ranges.length == 0) { + return new String[0]; + } + int length = ranges.length; + String[] array = new String[length]; + for (int index = 0; index < length; index++) { + array[index] = ranges[index].toString(); + } + return array; + } + + /* + * + */ + + private String toString(List values) { + StringBuilder builder = new StringBuilder(); + if (!values.isEmpty()) { + for (Object value : values) { + builder.append(value.toString()); + builder.append(','); + } + } + String built = builder.toStringClear(); + return built.substring(0, built.length() - 1); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentSerializer.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentSerializer.java index c61b6d2..59a595c 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentSerializer.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultArgumentSerializer.java @@ -4,119 +4,130 @@ import java.util.Iterator; import java.util.List; -import com.syntaxphoenix.syntaxapi.command.arguments.*; +import com.syntaxphoenix.syntaxapi.command.arguments.ArrayArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigDecimalArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BigIntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.BooleanArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ByteArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.DoubleArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.FloatArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.IntegerArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ListArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.LongArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.ShortArgument; +import com.syntaxphoenix.syntaxapi.command.arguments.StringArgument; public class DefaultArgumentSerializer extends ArgumentSerializer { - @Override - public String toString(ArrayArgument argument) { - BaseArgument[] value = argument.getValue(); - if (value == null || value.length == 0) { - return "[]"; - } - Iterator iterator = Arrays.stream(value).iterator(); - StringBuilder builder = new StringBuilder(); - builder.append('['); - while (iterator.hasNext()) { - BaseArgument entry = iterator.next(); - if (entry == null) { - continue; - } - builder.append(toString(entry)); - if (iterator.hasNext()) { - builder.append(','); - builder.append(' '); - } - } - builder.append(']'); - return builder.toString(); - } - - @Override - public String toString(BigIntegerArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(BigDecimalArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(DoubleArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(ByteArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(ShortArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(FloatArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(IntegerArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(ListArgument argument) { - List value = argument.getValue(); - if (value == null || value.isEmpty()) { - return "{}"; - } - Iterator iterator = value.iterator(); - StringBuilder builder = new StringBuilder(); - builder.append('{'); - while (iterator.hasNext()) { - BaseArgument entry = iterator.next(); - if (entry == null) { - continue; - } - builder.append(toString(entry)); - if (iterator.hasNext()) { - builder.append(','); - builder.append(' '); - } - } - builder.append('}'); - return builder.toString(); - } - - @Override - public String toString(LongArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String toString(StringArgument argument) { - return argument.getValue(); - } - - @Override - public String toString(BooleanArgument argument) { - return argument.getValue().toString(); - } - - @Override - public String[] asStringArray(BaseArgument... arguments) { - if (arguments == null || arguments.length == 0) { - return new String[0]; - } - int length = arguments.length; - String[] array = new String[length]; - for (int index = 0; index < length; index++) { - array[index] = arguments[index].toString(this); - } - return array; - } + @Override + public String toString(ArrayArgument argument) { + BaseArgument[] value = argument.getValue(); + if (value == null || value.length == 0) { + return "[]"; + } + Iterator iterator = Arrays.stream(value).iterator(); + StringBuilder builder = new StringBuilder(); + builder.append('['); + while (iterator.hasNext()) { + BaseArgument entry = iterator.next(); + if (entry == null) { + continue; + } + builder.append(toString(entry)); + if (iterator.hasNext()) { + builder.append(','); + builder.append(' '); + } + } + builder.append(']'); + return builder.toString(); + } + + @Override + public String toString(BigIntegerArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(BigDecimalArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(DoubleArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(ByteArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(ShortArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(FloatArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(IntegerArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(ListArgument argument) { + List value = argument.getValue(); + if (value == null || value.isEmpty()) { + return "{}"; + } + Iterator iterator = value.iterator(); + StringBuilder builder = new StringBuilder(); + builder.append('{'); + while (iterator.hasNext()) { + BaseArgument entry = iterator.next(); + if (entry == null) { + continue; + } + builder.append(toString(entry)); + if (iterator.hasNext()) { + builder.append(','); + builder.append(' '); + } + } + builder.append('}'); + return builder.toString(); + } + + @Override + public String toString(LongArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String toString(StringArgument argument) { + return argument.getValue(); + } + + @Override + public String toString(BooleanArgument argument) { + return argument.getValue().toString(); + } + + @Override + public String[] asStringArray(BaseArgument... arguments) { + if (arguments == null || arguments.length == 0) { + return new String[0]; + } + int length = arguments.length; + String[] array = new String[length]; + for (int index = 0; index < length; index++) { + array[index] = arguments[index].toString(this); + } + return array; + } } \ No newline at end of file diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultCompletion.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultCompletion.java index 041909b..813907f 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultCompletion.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultCompletion.java @@ -2,36 +2,37 @@ public class DefaultCompletion extends BaseCompletion { - private final Arguments arguments = new Arguments(); - - public DefaultCompletion add(BaseArgument argument) { - arguments.add(argument); - return this; - } - - public DefaultCompletion addSafe(BaseArgument argument) { - if (!arguments.match(current -> current.asObject().equals(argument.asObject()))) - arguments.add(argument); - return this; - } - - public DefaultCompletion addAll(BaseArgument... arguments) { - for (BaseArgument argument : arguments) { - add(argument); - } - return this; - } - - public DefaultCompletion addAllSafe(BaseArgument... arguments) { - for (BaseArgument argument : arguments) { - addSafe(argument); - } - return this; - } - - @Override - public Arguments getCompletion() { - return arguments; - } + private final Arguments arguments = new Arguments(); + + public DefaultCompletion add(BaseArgument argument) { + arguments.add(argument); + return this; + } + + public DefaultCompletion addSafe(BaseArgument argument) { + if (!arguments.match(current -> current.asObject().equals(argument.asObject()))) { + arguments.add(argument); + } + return this; + } + + public DefaultCompletion addAll(BaseArgument... arguments) { + for (BaseArgument argument : arguments) { + add(argument); + } + return this; + } + + public DefaultCompletion addAllSafe(BaseArgument... arguments) { + for (BaseArgument argument : arguments) { + addSafe(argument); + } + return this; + } + + @Override + public Arguments getCompletion() { + return arguments; + } } \ No newline at end of file diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultInfo.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultInfo.java index 9c737bf..49931cb 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultInfo.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/DefaultInfo.java @@ -2,8 +2,8 @@ public class DefaultInfo extends BaseInfo { - public DefaultInfo(CommandManager manager, String label) { - super(manager, label); - } + public DefaultInfo(CommandManager manager, String label) { + super(manager, label); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ExecutionState.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ExecutionState.java index a57c7bd..78c2ef3 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ExecutionState.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/ExecutionState.java @@ -2,14 +2,14 @@ public enum ExecutionState { - SUCCESS, - READY, - FAILED, - NOT_EXISTENT, - NO_COMMAND; - - public boolean isRunnable() { - return this == READY; - } + SUCCESS, + READY, + FAILED, + NOT_EXISTENT, + NO_COMMAND; + + public boolean isRunnable() { + return this == READY; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumberEnum.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumberEnum.java index 7b474fa..4a7bc0c 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumberEnum.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumberEnum.java @@ -1,38 +1,39 @@ package com.syntaxphoenix.syntaxapi.command; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.Arrays; import java.util.List; import java.util.Optional; -import java.math.BigInteger; -import java.math.BigDecimal; public enum NumberEnum { - BYTE(Byte.class, byte.class), - SHORT(Short.class, short.class), - INTEGER(Integer.class, int.class), - LONG(Long.class, long.class), - FLOAT(Float.class, float.class), - DOUBLE(Double.class, double.class), - BIG_INTEGER(BigInteger.class), - BIG_DECIMAL(BigDecimal.class); - - final List> classes; - - private NumberEnum(Class... array) { - classes = Arrays.asList(array); - } - - public static Optional of(Object object) { - return of(object instanceof Class ? (Class) object : object.getClass()); - } - - public static Optional of(Class clazz) { - for (NumberEnum number : values()) { - if (number.classes.contains(clazz)) - return Optional.of(number); - } - return Optional.empty(); - } + BYTE(Byte.class, byte.class), + SHORT(Short.class, short.class), + INTEGER(Integer.class, int.class), + LONG(Long.class, long.class), + FLOAT(Float.class, float.class), + DOUBLE(Double.class, double.class), + BIG_INTEGER(BigInteger.class), + BIG_DECIMAL(BigDecimal.class); + + final List> classes; + + private NumberEnum(Class... array) { + classes = Arrays.asList(array); + } + + public static Optional of(Object object) { + return of(object instanceof Class ? (Class) object : object.getClass()); + } + + public static Optional of(Class clazz) { + for (NumberEnum number : values()) { + if (number.classes.contains(clazz)) { + return Optional.of(number); + } + } + return Optional.empty(); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumericArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumericArgument.java index d082675..76dca88 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumericArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/NumericArgument.java @@ -2,6 +2,6 @@ public abstract class NumericArgument extends BaseArgument { - public abstract Number asNumber(); + public abstract Number asNumber(); } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeSuperType.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeSuperType.java index 934f84e..712dd73 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeSuperType.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeSuperType.java @@ -2,10 +2,10 @@ public enum RangeSuperType { - OBJECT, - TEXT, - STATE, - NUMBER, - COLLECTION; + OBJECT, + TEXT, + STATE, + NUMBER, + COLLECTION; } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeType.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeType.java index 372458d..0ee0001 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeType.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/RangeType.java @@ -4,40 +4,40 @@ public enum RangeType { - CUSTOM(RangeSuperType.OBJECT, Object.class), + CUSTOM(RangeSuperType.OBJECT, Object.class), - TEXT_SIZE_RANGE(RangeSuperType.TEXT, CharSequence.class), - TEXT_CHOOSE_RANGE(RangeSuperType.TEXT, CharSequence.class), + TEXT_SIZE_RANGE(RangeSuperType.TEXT, CharSequence.class), + TEXT_CHOOSE_RANGE(RangeSuperType.TEXT, CharSequence.class), - STATE_RANGE(RangeSuperType.STATE, boolean.class), + STATE_RANGE(RangeSuperType.STATE, boolean.class), - NUMBER_VALUE_RANGE(RangeSuperType.NUMBER, Number.class), - NUMBER_CHOOSE_RANGE(RangeSuperType.NUMBER, Number.class), + NUMBER_VALUE_RANGE(RangeSuperType.NUMBER, Number.class), + NUMBER_CHOOSE_RANGE(RangeSuperType.NUMBER, Number.class), - COLLECTION_SIZE_RANGE(RangeSuperType.COLLECTION, Collection.class); + COLLECTION_SIZE_RANGE(RangeSuperType.COLLECTION, Collection.class); - /* - * - */ + /* + * + */ - private final RangeSuperType superType; - private final Class inputType; + private final RangeSuperType superType; + private final Class inputType; - /* - * - */ + /* + * + */ - private RangeType(RangeSuperType superType, Class inputType) { - this.superType = superType; - this.inputType = inputType; - } + private RangeType(RangeSuperType superType, Class inputType) { + this.superType = superType; + this.inputType = inputType; + } - public RangeSuperType getSuperType() { - return superType; - } + public RangeSuperType getSuperType() { + return superType; + } - public Class getInputType() { - return inputType; - } + public Class getInputType() { + return inputType; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Ranges.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Ranges.java index 6a9e186..65c85c1 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Ranges.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/Ranges.java @@ -7,120 +7,120 @@ public class Ranges implements Iterable { - private final ArrayList ranges; - private boolean locked = false; - - public Ranges() { - this.ranges = new ArrayList<>(); - } - - public Ranges(ArrayList ranges) { - this.ranges = ranges; - } - - public int count() { - return ranges.size(); - } - - public BaseArgumentRange get(int position) { - if (position < 1) { - throw negativeOrZero(); - } - if (position > count()) { - throw outOfBounce(position); - } - return ranges.get(position - 1); - } - - public void add(BaseArgumentRange argument, int position) { - if (locked) { - throw locked(); - } - if (position < 1) { - throw negativeOrZero(); - } - if (argument == null) { - return; - } - ranges.add(position - 1, argument); - } - - public void add(BaseArgumentRange argument) { - if (locked) { - throw locked(); - } - if (argument == null) { - return; - } - ranges.add(argument); - } - - public Class getInputType(int position) { - return get(position).getInputType(); - } - - public RangeType getType(int position) { - return get(position).getType(); - } - - public RangeSuperType getSuperType(int position) { - return getType(position).getSuperType(); - } - - protected boolean isLocked() { - return locked; - } - - protected void setLocked(boolean locked) { - this.locked = locked; - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - public String toString(ArgumentSerializer serializer) { - return toString(ArgumentRangeSerializer.DEFAULT, serializer); - } - - public String toString(ArgumentRangeSerializer serializer) { - return toString(serializer, ArgumentSerializer.DEFAULT); - } - - public String toString(ArgumentRangeSerializer range, ArgumentSerializer argument) { - return null; - } - - /* - * Exception Construction - */ - - private IllegalArgumentException negativeOrZero() { - return new IllegalArgumentException("Bound must be positive!"); - } - - private IndexOutOfBoundsException outOfBounce(int position) { - return new IndexOutOfBoundsException("Index: " + position + " - Size: " + count()); - } - - private ObjectLockedException locked() { - return new ObjectLockedException("Cannot edit a locked object!"); - } - - /* - * - * - * - */ - - @Override - public Iterator iterator() { - return ranges.iterator(); - } + private final ArrayList ranges; + private boolean locked = false; + + public Ranges() { + this.ranges = new ArrayList<>(); + } + + public Ranges(ArrayList ranges) { + this.ranges = ranges; + } + + public int count() { + return ranges.size(); + } + + public BaseArgumentRange get(int position) { + if (position < 1) { + throw negativeOrZero(); + } + if (position > count()) { + throw outOfBounce(position); + } + return ranges.get(position - 1); + } + + public void add(BaseArgumentRange argument, int position) { + if (locked) { + throw locked(); + } + if (position < 1) { + throw negativeOrZero(); + } + if (argument == null) { + return; + } + ranges.add(position - 1, argument); + } + + public void add(BaseArgumentRange argument) { + if (locked) { + throw locked(); + } + if (argument == null) { + return; + } + ranges.add(argument); + } + + public Class getInputType(int position) { + return get(position).getInputType(); + } + + public RangeType getType(int position) { + return get(position).getType(); + } + + public RangeSuperType getSuperType(int position) { + return getType(position).getSuperType(); + } + + protected boolean isLocked() { + return locked; + } + + protected void setLocked(boolean locked) { + this.locked = locked; + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + public String toString(ArgumentSerializer serializer) { + return toString(ArgumentRangeSerializer.DEFAULT, serializer); + } + + public String toString(ArgumentRangeSerializer serializer) { + return toString(serializer, ArgumentSerializer.DEFAULT); + } + + public String toString(ArgumentRangeSerializer range, ArgumentSerializer argument) { + return null; + } + + /* + * Exception Construction + */ + + private IllegalArgumentException negativeOrZero() { + return new IllegalArgumentException("Bound must be positive!"); + } + + private IndexOutOfBoundsException outOfBounce(int position) { + return new IndexOutOfBoundsException("Index: " + position + " - Size: " + count()); + } + + private ObjectLockedException locked() { + return new ObjectLockedException("Cannot edit a locked object!"); + } + + /* + * + * + * + */ + + @Override + public Iterator iterator() { + return ranges.iterator(); + } } \ No newline at end of file diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/SerializationHelper.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/SerializationHelper.java index 75741d9..6298c5c 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/SerializationHelper.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/SerializationHelper.java @@ -4,32 +4,32 @@ public abstract class SerializationHelper { - protected final ArgumentIdentifier identifier; - protected final ArgumentSerializer serializer; + protected final ArgumentIdentifier identifier; + protected final ArgumentSerializer serializer; - public SerializationHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { - this.identifier = identifier; - this.serializer = serializer; - } + public SerializationHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { + this.identifier = identifier; + this.serializer = serializer; + } - public ArgumentIdentifier getIdentifier() { - return identifier; - } + public ArgumentIdentifier getIdentifier() { + return identifier; + } - public ArgumentSerializer getSerializer() { - return serializer; - } + public ArgumentSerializer getSerializer() { + return serializer; + } - public abstract Map serializeMap(String... arguments); + public abstract Map serializeMap(String... arguments); - public abstract String[] deserializeMap(Map map); + public abstract String[] deserializeMap(Map map); - public final ArgumentMap serialize(String... arguments) { - return new ArgumentMap(serializeMap(arguments)); - } + public final ArgumentMap serialize(String... arguments) { + return new ArgumentMap(serializeMap(arguments)); + } - public final String[] deserialize(ArgumentMap map) { - return deserializeMap(map.getHandle()); - } + public final String[] deserialize(ArgumentMap map) { + return deserializeMap(map.getHandle()); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ArrayArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ArrayArgument.java index 329eb45..9aa6f7f 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ArrayArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ArrayArgument.java @@ -13,42 +13,42 @@ @SuppressWarnings("unchecked") public class ArrayArgument extends BaseArgument { - private E[] value; - - public ArrayArgument(ArgumentType type) { - this.value = (E[]) Array.newInstance(type.getClassType(), 8); - } - - public ArrayArgument(ArgumentType type, int length) { - this.value = (E[]) Array.newInstance(type.getClassType(), length); - } - - public ArrayArgument(E... value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.ARRAY; - } - - @Override - public Object asObject() { - return value; - } - - public E[] getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private E[] value; + + public ArrayArgument(ArgumentType type) { + this.value = (E[]) Array.newInstance(type.getClassType(), 8); + } + + public ArrayArgument(ArgumentType type, int length) { + this.value = (E[]) Array.newInstance(type.getClassType(), length); + } + + public ArrayArgument(E... value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.ARRAY; + } + + @Override + public Object asObject() { + return value; + } + + public E[] getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigDecimalArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigDecimalArgument.java index df77253..38dcb5a 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigDecimalArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigDecimalArgument.java @@ -12,43 +12,43 @@ */ public class BigDecimalArgument extends NumericArgument { - private BigDecimal value; - - public BigDecimalArgument() { - this.value = BigDecimal.ZERO.abs(); - } - - public BigDecimalArgument(BigDecimal value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.BIG_DECIMAL; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public BigDecimal getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private BigDecimal value; + + public BigDecimalArgument() { + this.value = BigDecimal.ZERO.abs(); + } + + public BigDecimalArgument(BigDecimal value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.BIG_DECIMAL; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public BigDecimal getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigIntegerArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigIntegerArgument.java index 508413c..fc1a478 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigIntegerArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BigIntegerArgument.java @@ -12,43 +12,43 @@ */ public class BigIntegerArgument extends NumericArgument { - private BigInteger value; - - public BigIntegerArgument() { - this.value = BigInteger.ZERO.abs(); - } - - public BigIntegerArgument(BigInteger value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.BIG_INTEGER; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public BigInteger getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private BigInteger value; + + public BigIntegerArgument() { + this.value = BigInteger.ZERO.abs(); + } + + public BigIntegerArgument(BigInteger value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.BIG_INTEGER; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public BigInteger getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BooleanArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BooleanArgument.java index 5622657..ce30fb9 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BooleanArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/BooleanArgument.java @@ -6,38 +6,38 @@ public class BooleanArgument extends BaseArgument { - private Boolean value; - - public BooleanArgument() { - this.value = false; - } - - public BooleanArgument(Boolean value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.BOOLEAN; - } - - @Override - public Object asObject() { - return value; - } - - public Boolean getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Boolean value; + + public BooleanArgument() { + this.value = false; + } + + public BooleanArgument(Boolean value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.BOOLEAN; + } + + @Override + public Object asObject() { + return value; + } + + public Boolean getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ByteArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ByteArgument.java index e9adb7f..dd39049 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ByteArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ByteArgument.java @@ -6,43 +6,43 @@ public class ByteArgument extends NumericArgument { - private Byte value; - - public ByteArgument() { - this.value = 0; - } - - public ByteArgument(Byte value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.BYTE; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Byte getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Byte value; + + public ByteArgument() { + this.value = 0; + } + + public ByteArgument(Byte value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.BYTE; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Byte getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/DoubleArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/DoubleArgument.java index bcaf0e7..f093fc6 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/DoubleArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/DoubleArgument.java @@ -10,43 +10,43 @@ */ public class DoubleArgument extends NumericArgument { - private Double value; - - public DoubleArgument() { - this.value = 0D; - } - - public DoubleArgument(Double value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.DOUBLE; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Double getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Double value; + + public DoubleArgument() { + this.value = 0D; + } + + public DoubleArgument(Double value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.DOUBLE; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Double getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/FloatArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/FloatArgument.java index 9bc062e..8e820a5 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/FloatArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/FloatArgument.java @@ -10,43 +10,43 @@ */ public class FloatArgument extends NumericArgument { - private Float value; - - public FloatArgument() { - this.value = 0F; - } - - public FloatArgument(Float value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.FLOAT; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Float getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Float value; + + public FloatArgument() { + this.value = 0F; + } + + public FloatArgument(Float value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.FLOAT; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Float getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/IntegerArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/IntegerArgument.java index 98efe29..38d0a54 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/IntegerArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/IntegerArgument.java @@ -10,43 +10,43 @@ */ public class IntegerArgument extends NumericArgument { - private Integer value; - - public IntegerArgument() { - this.value = 0; - } - - public IntegerArgument(Integer value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.INTEGER; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Integer getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Integer value; + + public IntegerArgument() { + this.value = 0; + } + + public IntegerArgument(Integer value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.INTEGER; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ListArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ListArgument.java index f20c229..6090cf1 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ListArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ListArgument.java @@ -13,38 +13,38 @@ */ public class ListArgument extends BaseArgument { - private List value; - - public ListArgument() { - this.value = new ArrayList<>(); - } - - public ListArgument(List value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.LIST; - } - - @Override - public Object asObject() { - return value; - } - - public List getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private List value; + + public ListArgument() { + this.value = new ArrayList<>(); + } + + public ListArgument(List value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.LIST; + } + + @Override + public Object asObject() { + return value; + } + + public List getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/LongArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/LongArgument.java index 8ef9cff..e6a7a96 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/LongArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/LongArgument.java @@ -10,43 +10,43 @@ */ public class LongArgument extends NumericArgument { - private Long value; - - public LongArgument() { - this.value = 0L; - } - - public LongArgument(Long value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.LONG; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Long getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Long value; + + public LongArgument() { + this.value = 0L; + } + + public LongArgument(Long value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.LONG; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Long getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ObjectArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ObjectArgument.java index d358e65..6b1fbfc 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ObjectArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ObjectArgument.java @@ -6,34 +6,34 @@ public class ObjectArgument extends BaseArgument { - private E value; - - public ObjectArgument(E value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.CUSTOM; - } - - @Override - public Object asObject() { - return value; - } - - public E getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private E value; + + public ObjectArgument(E value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.CUSTOM; + } + + @Override + public Object asObject() { + return value; + } + + public E getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ShortArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ShortArgument.java index 4a01786..c18e083 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ShortArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/ShortArgument.java @@ -6,43 +6,43 @@ public class ShortArgument extends NumericArgument { - private Short value; - - public ShortArgument() { - this.value = 0; - } - - public ShortArgument(Short value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.SHORT; - } - - @Override - public Object asObject() { - return value; - } - - @Override - public Number asNumber() { - return value; - } - - public Short getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private Short value; + + public ShortArgument() { + this.value = 0; + } + + public ShortArgument(Short value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.SHORT; + } + + @Override + public Object asObject() { + return value; + } + + @Override + public Number asNumber() { + return value; + } + + public Short getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/StringArgument.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/StringArgument.java index fbd2030..d31e189 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/StringArgument.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/arguments/StringArgument.java @@ -10,38 +10,38 @@ */ public class StringArgument extends BaseArgument { - private String value; - - public StringArgument() { - this.value = ""; - } - - public StringArgument(String value) { - this.value = value; - } - - @Override - public ArgumentType getType() { - return ArgumentType.STRING; - } - - @Override - public Object asObject() { - return value; - } - - public String getValue() { - return value; - } - - @Override - public String toString() { - return toString(ArgumentSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentSerializer serializer) { - return serializer.toString(this); - } + private String value; + + public StringArgument() { + this.value = ""; + } + + public StringArgument(String value) { + this.value = value; + } + + @Override + public ArgumentType getType() { + return ArgumentType.STRING; + } + + @Override + public Object asObject() { + return value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return toString(ArgumentSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/EqualArgumentHelper.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/EqualArgumentHelper.java index 925ff9b..6fede5b 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/EqualArgumentHelper.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/EqualArgumentHelper.java @@ -18,56 +18,61 @@ public final class EqualArgumentHelper extends SerializationHelper { - public static final EqualArgumentHelper DEFAULT = new EqualArgumentHelper(DefaultArgumentIdentifier.DEFAULT, DefaultArgumentSerializer.DEFAULT); + public static final EqualArgumentHelper DEFAULT = new EqualArgumentHelper(DefaultArgumentIdentifier.DEFAULT, + DefaultArgumentSerializer.DEFAULT); - private final Pattern entryPattern = Pattern.compile("(?[a-zA-Z0-9._-]+)(?=|:)(?\")?(?.+[^\"])(?(?\")+)?"); + private final Pattern entryPattern = Pattern + .compile("(?[a-zA-Z0-9._-]+)(?=|:)(?\")?(?.+[^\"])(?(?\")+)?"); - public EqualArgumentHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { - super(identifier, serializer); - } + public EqualArgumentHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { + super(identifier, serializer); + } - public Map serializeMap(String... arguments) { - HashMap output = new HashMap<>(); - if (arguments.length == 0) - return Collections.unmodifiableMap(output); - for (int index = 0; index < arguments.length; index++) { - Matcher matcher = entryPattern.matcher(arguments[index]); - if (!matcher.matches()) { - continue; - } - String key = matcher.group("Key"); - String value1 = matcher.group("Value1"); - String value2 = matcher.group("Value2"); - if (value1 == null && value2 == null) { - output.put(key, new StringArgument()); - continue; - } - if (value2 != null && matcher.group("Start") != null) { - value2 = value2.substring(0, value2.length() - 1); - } - output.put(key, DefaultArgumentIdentifier.DEFAULT.process(orEmpty(value1) + orEmpty(value2)).get(0)); - } - return Collections.unmodifiableMap(output); - } + public Map serializeMap(String... arguments) { + HashMap output = new HashMap<>(); + if (arguments.length == 0) { + return Collections.unmodifiableMap(output); + } + for (int index = 0; index < arguments.length; index++) { + Matcher matcher = entryPattern.matcher(arguments[index]); + if (!matcher.matches()) { + continue; + } + String key = matcher.group("Key"); + String value1 = matcher.group("Value1"); + String value2 = matcher.group("Value2"); + if (value1 == null && value2 == null) { + output.put(key, new StringArgument()); + continue; + } + if (value2 != null && matcher.group("Start") != null) { + value2 = value2.substring(0, value2.length() - 1); + } + output.put(key, ArgumentIdentifier.DEFAULT.process(orEmpty(value1) + orEmpty(value2)).get(0)); + } + return Collections.unmodifiableMap(output); + } - public String[] deserializeMap(Map arguments) { - if (arguments.isEmpty()) - return new String[0]; - ArrayList list = new ArrayList<>(); - arguments.entrySet().forEach(entry -> { - BaseArgument argument = entry.getValue(); - if (!(argument instanceof BooleanArgument)) { - list.add(entry.getKey() + "=\"" + argument.toString(serializer) + '"'); - return; - } - if (!(argument.asBoolean()).getValue()) - list.add("false"); - }); - return list.toArray(new String[list.size()]); - } + public String[] deserializeMap(Map arguments) { + if (arguments.isEmpty()) { + return new String[0]; + } + ArrayList list = new ArrayList<>(); + arguments.entrySet().forEach(entry -> { + BaseArgument argument = entry.getValue(); + if (!(argument instanceof BooleanArgument)) { + list.add(entry.getKey() + "=\"" + argument.toString(serializer) + '"'); + return; + } + if (!(argument.asBoolean()).getValue()) { + list.add("false"); + } + }); + return list.toArray(new String[list.size()]); + } - private String orEmpty(String value) { - return value == null ? "" : value; - } + private String orEmpty(String value) { + return value == null ? "" : value; + } } \ No newline at end of file diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/JVMArgumentHelper.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/JVMArgumentHelper.java index b88d29b..3508d6f 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/JVMArgumentHelper.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/helper/JVMArgumentHelper.java @@ -15,74 +15,79 @@ public final class JVMArgumentHelper extends SerializationHelper { - public static final JVMArgumentHelper DEFAULT = new JVMArgumentHelper(DefaultArgumentIdentifier.DEFAULT, DefaultArgumentSerializer.DEFAULT); + public static final JVMArgumentHelper DEFAULT = new JVMArgumentHelper(DefaultArgumentIdentifier.DEFAULT, + DefaultArgumentSerializer.DEFAULT); - public JVMArgumentHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { - super(identifier, serializer); - } + public JVMArgumentHelper(ArgumentIdentifier identifier, ArgumentSerializer serializer) { + super(identifier, serializer); + } - public Map serializeMap(String... arguments) { - HashMap output = new HashMap<>(); - if (arguments.length == 0) - return Collections.unmodifiableMap(output); - for (int index = 0; index < arguments.length; index++) { - String first = arguments[index]; - if (!first.startsWith("--")) - continue; - first = first.substring(2); - if (index + 1 >= arguments.length) { - output.put(first, new BooleanArgument(true)); - continue; - } - String second = arguments[index + 1]; - if (second.startsWith("--")) { - output.put(first, new BooleanArgument(true)); - continue; - } - if (second.startsWith("\"")) { - StringBuilder builder = new StringBuilder(); - String type = second.substring(1); - if (index + 2 >= arguments.length) { - type = type.substring(0, type.length() - 1); - } - if (type.endsWith("\"")) { - builder.append(type.substring(0, type.length() - 1)); - } else { - builder.append(type); - for (int current = index + 2; current < arguments.length; current++) { - builder.append(' '); - if (!arguments[current].endsWith("\"")) { - builder.append(arguments[current]); - continue; - } - builder.append(arguments[current].substring(0, arguments[current].length() - 1)); - break; - } - } - output.put(first, identifier.process(builder.toString()).get(0)); - continue; - } else { - output.put(first, identifier.process(second).get(0)); - } - } - return Collections.unmodifiableMap(output); - } + public Map serializeMap(String... arguments) { + HashMap output = new HashMap<>(); + if (arguments.length == 0) { + return Collections.unmodifiableMap(output); + } + for (int index = 0; index < arguments.length; index++) { + String first = arguments[index]; + if (!first.startsWith("--")) { + continue; + } + first = first.substring(2); + if (index + 1 >= arguments.length) { + output.put(first, new BooleanArgument(true)); + continue; + } + String second = arguments[index + 1]; + if (second.startsWith("--")) { + output.put(first, new BooleanArgument(true)); + continue; + } + if (second.startsWith("\"")) { + StringBuilder builder = new StringBuilder(); + String type = second.substring(1); + if (index + 2 >= arguments.length) { + type = type.substring(0, type.length() - 1); + } + if (type.endsWith("\"")) { + builder.append(type.substring(0, type.length() - 1)); + } else { + builder.append(type); + for (int current = index + 2; current < arguments.length; current++) { + builder.append(' '); + if (!arguments[current].endsWith("\"")) { + builder.append(arguments[current]); + continue; + } + builder.append(arguments[current].substring(0, arguments[current].length() - 1)); + break; + } + } + output.put(first, identifier.process(builder.toString()).get(0)); + continue; + } else { + output.put(first, identifier.process(second).get(0)); + } + } + return Collections.unmodifiableMap(output); + } - public String[] deserializeMap(Map arguments) { - if (arguments.isEmpty()) - return new String[0]; - ArrayList list = new ArrayList<>(); - arguments.entrySet().forEach(entry -> { - list.add("--" + entry.getKey()); - BaseArgument argument = entry.getValue(); - if (!(argument instanceof BooleanArgument)) { - list.add('"' + argument.toString(serializer) + '"'); - return; - } - if (!(argument.asBoolean()).getValue()) - list.add("false"); - }); - return list.toArray(new String[list.size()]); - } + public String[] deserializeMap(Map arguments) { + if (arguments.isEmpty()) { + return new String[0]; + } + ArrayList list = new ArrayList<>(); + arguments.entrySet().forEach(entry -> { + list.add("--" + entry.getKey()); + BaseArgument argument = entry.getValue(); + if (!(argument instanceof BooleanArgument)) { + list.add('"' + argument.toString(serializer) + '"'); + return; + } + if (!(argument.asBoolean()).getValue()) { + list.add("false"); + } + }); + return list.toArray(new String[list.size()]); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/CollectionSizeRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/CollectionSizeRange.java index fa3f986..c3a7aad 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/CollectionSizeRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/CollectionSizeRange.java @@ -9,81 +9,82 @@ public class CollectionSizeRange extends BaseArgumentRange { - private final int minimum; - private final int maximum; - - private final Class type; - - public CollectionSizeRange(int minimum, int maximum, Class type) { - this.minimum = minimum; - this.maximum = maximum; - this.type = type; - } - - public CollectionSizeRange(NumberValueRange number, Class type) { - this.minimum = number.getMinimum().intValue(); - this.maximum = number.getMaximum().intValue(); - this.type = type; - } - - /* - * - */ - - public int getMinimum() { - return minimum; - } - - public int getMaximum() { - return maximum; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.COLLECTION_SIZE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - Collection collection = ((Collection) argument.asObject()); - int length = collection.size(); - if (length != 0) { - Object object = collection.iterator().next(); - if (!type.isInstance(object)) { - return false; - } - } - return length >= minimum && length <= maximum; - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } + private final int minimum; + private final int maximum; + + private final Class type; + + public CollectionSizeRange(int minimum, int maximum, Class type) { + this.minimum = minimum; + this.maximum = maximum; + this.type = type; + } + + public CollectionSizeRange(NumberValueRange number, Class type) { + this.minimum = number.getMinimum().intValue(); + this.maximum = number.getMaximum().intValue(); + this.type = type; + } + + /* + * + */ + + public int getMinimum() { + return minimum; + } + + public int getMaximum() { + return maximum; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.COLLECTION_SIZE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + Collection collection = ((Collection) argument.asObject()); + int length = collection.size(); + if (length != 0) { + Object object = collection.iterator().next(); + if (!type.isInstance(object)) { + return false; + } + } + return length >= minimum && length <= maximum; + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberChooseRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberChooseRange.java index 159ccde..1bebc7c 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberChooseRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberChooseRange.java @@ -11,109 +11,112 @@ public class NumberChooseRange extends BaseArgumentRange { - private final boolean blacklist; - private final List values; - - public NumberChooseRange(Object... values) { - this(false, values); - } - - public NumberChooseRange(boolean blacklist, Object... values) { - this.blacklist = blacklist; - this.values = asBigDecimal(values); - } - - public NumberChooseRange(List values) { - this(false, values); - } - - public NumberChooseRange(boolean blacklist, List values) { - this.blacklist = blacklist; - this.values = asBigDecimal(values); - } - - /* - * - */ - - public boolean isBlacklist() { - return blacklist; - } - - public List getValues() { - return values; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.NUMBER_CHOOSE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - BigDecimal compare = new BigDecimal(argument.asObject().toString()); - return values.stream().anyMatch(value -> value.compareTo(compare) == 0); - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } - - /* - * - */ - - public static List asBigDecimal(Object... objects) { - ArrayList list = new ArrayList<>(); - if (objects == null || objects.length == 0) - return list; - for (Object object : objects) { - try { - list.add(new BigDecimal(object.toString())); - } catch (NumberFormatException ignore) { - continue; - } - } - return list; - } - - public static List asBigDecimal(List objects) { - ArrayList list = new ArrayList<>(); - if (objects == null || objects.isEmpty()) - return list; - for (Object object : objects) { - try { - list.add(new BigDecimal(object.toString())); - } catch (NumberFormatException ignore) { - continue; - } - } - return list; - } + private final boolean blacklist; + private final List values; + + public NumberChooseRange(Object... values) { + this(false, values); + } + + public NumberChooseRange(boolean blacklist, Object... values) { + this.blacklist = blacklist; + this.values = asBigDecimal(values); + } + + public NumberChooseRange(List values) { + this(false, values); + } + + public NumberChooseRange(boolean blacklist, List values) { + this.blacklist = blacklist; + this.values = asBigDecimal(values); + } + + /* + * + */ + + public boolean isBlacklist() { + return blacklist; + } + + public List getValues() { + return values; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.NUMBER_CHOOSE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + BigDecimal compare = new BigDecimal(argument.asObject().toString()); + return values.stream().anyMatch(value -> value.compareTo(compare) == 0); + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } + + /* + * + */ + + public static List asBigDecimal(Object... objects) { + ArrayList list = new ArrayList<>(); + if (objects == null || objects.length == 0) { + return list; + } + for (Object object : objects) { + try { + list.add(new BigDecimal(object.toString())); + } catch (NumberFormatException ignore) { + continue; + } + } + return list; + } + + public static List asBigDecimal(List objects) { + ArrayList list = new ArrayList<>(); + if (objects == null || objects.isEmpty()) { + return list; + } + for (Object object : objects) { + try { + list.add(new BigDecimal(object.toString())); + } catch (NumberFormatException ignore) { + continue; + } + } + return list; + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberValueRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberValueRange.java index 77063ef..36114a2 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberValueRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/NumberValueRange.java @@ -10,120 +10,122 @@ public class NumberValueRange extends BaseArgumentRange { - private final BigDecimal minimum; - private final BigDecimal maximum; - - public NumberValueRange(int minimum, int maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(byte minimum, byte maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(short minimum, short maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(float minimum, float maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(double minimum, double maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(long minimum, long maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(BigInteger minimum, BigInteger maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(BigDecimal minimum, BigDecimal maximum) { - this.minimum = minimum; - this.maximum = maximum; - } - - public NumberValueRange(char minimum, char maximum) { - this.minimum = new BigDecimal(minimum); - this.maximum = new BigDecimal(maximum); - } - - public NumberValueRange(Number minimum, Number maximum) { - this.minimum = new BigDecimal(minimum.toString()); - this.maximum = new BigDecimal(maximum.toString()); - } - - public NumberValueRange(NumberValueRange number) { - this.minimum = number.getMinimum(); - this.maximum = number.getMaximum(); - } - - /* - * - */ - - public BigDecimal getMinimum() { - return minimum; - } - - public BigDecimal getMaximum() { - return maximum; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.NUMBER_VALUE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - Number number = (Number) argument.asObject(); - BigDecimal decimal; - if (!(number instanceof BigDecimal)) - decimal = new BigDecimal(number.toString()); - else - decimal = (BigDecimal) number; - return decimal.compareTo(minimum) >= 0 && decimal.compareTo(maximum) <= 0; - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } + private final BigDecimal minimum; + private final BigDecimal maximum; + + public NumberValueRange(int minimum, int maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(byte minimum, byte maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(short minimum, short maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(float minimum, float maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(double minimum, double maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(long minimum, long maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(BigInteger minimum, BigInteger maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(BigDecimal minimum, BigDecimal maximum) { + this.minimum = minimum; + this.maximum = maximum; + } + + public NumberValueRange(char minimum, char maximum) { + this.minimum = new BigDecimal(minimum); + this.maximum = new BigDecimal(maximum); + } + + public NumberValueRange(Number minimum, Number maximum) { + this.minimum = new BigDecimal(minimum.toString()); + this.maximum = new BigDecimal(maximum.toString()); + } + + public NumberValueRange(NumberValueRange number) { + this.minimum = number.getMinimum(); + this.maximum = number.getMaximum(); + } + + /* + * + */ + + public BigDecimal getMinimum() { + return minimum; + } + + public BigDecimal getMaximum() { + return maximum; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.NUMBER_VALUE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + Number number = (Number) argument.asObject(); + BigDecimal decimal; + if (!(number instanceof BigDecimal)) { + decimal = new BigDecimal(number.toString()); + } else { + decimal = (BigDecimal) number; + } + return decimal.compareTo(minimum) >= 0 && decimal.compareTo(maximum) <= 0; + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/StateRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/StateRange.java index d3bdc18..368eb91 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/StateRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/StateRange.java @@ -7,71 +7,73 @@ public class StateRange extends BaseArgumentRange { - private final boolean enabled; - private final boolean disallowed; - - public StateRange() { - this.enabled = false; - this.disallowed = false; - } - - public StateRange(boolean disallowed) { - this.enabled = true; - this.disallowed = disallowed; - } - - /* - * - */ - - public boolean isEnabled() { - return enabled; - } - - public boolean getDisallowed() { - return disallowed; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.STATE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - if (!enabled) - return true; - return ((boolean) argument.asObject() != disallowed); - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } + private final boolean enabled; + private final boolean disallowed; + + public StateRange() { + this.enabled = false; + this.disallowed = false; + } + + public StateRange(boolean disallowed) { + this.enabled = true; + this.disallowed = disallowed; + } + + /* + * + */ + + public boolean isEnabled() { + return enabled; + } + + public boolean getDisallowed() { + return disallowed; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.STATE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + if (!enabled) { + return true; + } + return ((boolean) argument.asObject() != disallowed); + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextChooseRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextChooseRange.java index 272a05f..c8b0210 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextChooseRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextChooseRange.java @@ -10,76 +10,77 @@ public class TextChooseRange extends BaseArgumentRange { - private final boolean blacklist; - private final List values; - - public TextChooseRange(CharSequence... values) { - this(false, values); - } - - public TextChooseRange(boolean blacklist, CharSequence... values) { - this(blacklist, Arrays.asList(values)); - } - - public TextChooseRange(List values) { - this(false, values); - } - - public TextChooseRange(boolean blacklist, List values) { - this.blacklist = blacklist; - this.values = values; - } - - /* - * - */ - - public boolean isBlacklist() { - return blacklist; - } - - public List getValues() { - return values; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.TEXT_CHOOSE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - return values.contains((CharSequence) argument.asObject()); - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } + private final boolean blacklist; + private final List values; + + public TextChooseRange(CharSequence... values) { + this(false, values); + } + + public TextChooseRange(boolean blacklist, CharSequence... values) { + this(blacklist, Arrays.asList(values)); + } + + public TextChooseRange(List values) { + this(false, values); + } + + public TextChooseRange(boolean blacklist, List values) { + this.blacklist = blacklist; + this.values = values; + } + + /* + * + */ + + public boolean isBlacklist() { + return blacklist; + } + + public List getValues() { + return values; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.TEXT_CHOOSE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + return values.contains(argument.asObject()); + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } } diff --git a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextSizeRange.java b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextSizeRange.java index 93a4fbf..c958038 100644 --- a/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextSizeRange.java +++ b/command/src/main/java/com/syntaxphoenix/syntaxapi/command/range/TextSizeRange.java @@ -7,70 +7,71 @@ public class TextSizeRange extends BaseArgumentRange { - private final int minimum; - private final int maximum; - - public TextSizeRange(int minimum, int maximum) { - this.minimum = minimum; - this.maximum = maximum; - } - - public TextSizeRange(NumberValueRange number) { - this.minimum = number.getMinimum().intValue(); - this.maximum = number.getMaximum().intValue(); - } - - /* - * - */ - - public int getMinimum() { - return minimum; - } - - public int getMaximum() { - return maximum; - } - - /* - * - */ - - @Override - public RangeType getType() { - return RangeType.TEXT_SIZE_RANGE; - } - - @Override - public Class getInputType() { - return getType().getInputType(); - } - - @Override - public boolean hasType(BaseArgument argument) { - return argument.getClassType().isAssignableFrom(getInputType()); - } - - @Override - public boolean isInRange(BaseArgument argument) { - if (!hasType(argument)) - return false; - int length = ((CharSequence) argument.asObject()).length(); - return length >= minimum && length <= maximum; - } - - /* - * - */ - - @Override - public String toString() { - return toString(ArgumentRangeSerializer.DEFAULT); - } - - @Override - public String toString(ArgumentRangeSerializer serializer) { - return serializer.toString(this); - } + private final int minimum; + private final int maximum; + + public TextSizeRange(int minimum, int maximum) { + this.minimum = minimum; + this.maximum = maximum; + } + + public TextSizeRange(NumberValueRange number) { + this.minimum = number.getMinimum().intValue(); + this.maximum = number.getMaximum().intValue(); + } + + /* + * + */ + + public int getMinimum() { + return minimum; + } + + public int getMaximum() { + return maximum; + } + + /* + * + */ + + @Override + public RangeType getType() { + return RangeType.TEXT_SIZE_RANGE; + } + + @Override + public Class getInputType() { + return getType().getInputType(); + } + + @Override + public boolean hasType(BaseArgument argument) { + return argument.getClassType().isAssignableFrom(getInputType()); + } + + @Override + public boolean isInRange(BaseArgument argument) { + if (!hasType(argument)) { + return false; + } + int length = ((CharSequence) argument.asObject()).length(); + return length >= minimum && length <= maximum; + } + + /* + * + */ + + @Override + public String toString() { + return toString(ArgumentRangeSerializer.DEFAULT); + } + + @Override + public String toString(ArgumentRangeSerializer serializer) { + return serializer.toString(this); + } } diff --git a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseConfig.java b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseConfig.java index df5c819..216dfae 100644 --- a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseConfig.java +++ b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseConfig.java @@ -9,16 +9,16 @@ */ public interface BaseConfig { - public void load(File file) throws Throwable; + public void load(File file) throws Throwable; - public void save(File file) throws Throwable; + public void save(File file) throws Throwable; - public default Optional asSection() { - BaseSection output = null; - if (this instanceof BaseSection) { - output = (BaseSection) this; - } - return Optional.ofNullable(output); - } + public default Optional asSection() { + BaseSection output = null; + if (this instanceof BaseSection) { + output = (BaseSection) this; + } + return Optional.ofNullable(output); + } } diff --git a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseSection.java b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseSection.java index 56b87ea..1aa2c11 100644 --- a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseSection.java +++ b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/BaseSection.java @@ -1,8 +1,8 @@ package com.syntaxphoenix.syntaxapi.config; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; /** * @author Lauriichen @@ -10,217 +10,217 @@ */ public abstract class BaseSection implements IBaseSection { - protected final SectionMap values = new SectionMap<>();; - private final String name; - - public BaseSection(String name) { - this.name = name; - } - - public Map getValues() { - return values; - } - - public Set getKeys() { - return values.keySet(); - } - - public String getName() { - return name; - } - - public boolean isValid() { - return !name.isEmpty(); - } - - public void clear() { - values.clear(); - } - - public boolean contains(String path) { - return get(path) != null; - } - - public boolean isInstance(String path, E value) { - Object object = get(path); - return object == null ? false : (value == null ? false : object.getClass().isAssignableFrom(value.getClass())); - } - - public boolean isInstance(String path, Class value) { - Object object = get(path); - return object == null ? false : (value == null ? false : object.getClass().isAssignableFrom(value)); - } - - @SuppressWarnings("unchecked") - public E check(String path, E value) { - Object current = get(path); - if (current != null) { - return (E) current; - } - set(path, value); - return value; - } - - public Object get(String path) { - if (!path.isEmpty()) { - return get(ConfigTools.getKeys(path)); - } - return null; - } - - @SuppressWarnings("unchecked") - public E get(String path, Class sample) { - if (!path.isEmpty()) { - return (E) get(ConfigTools.getKeys(path)); - } - return null; - } - - @SuppressWarnings("unchecked") - public E get(String path, E sample) { - if (!path.isEmpty()) { - return (E) get(ConfigTools.getKeys(path)); - } - return null; - } - - private Object get(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - BaseSection section; - if ((section = getSection(key[0])) != null) { - return section.get(ConfigTools.getNextKeys(key)); - } - } else { - return values.get(key[0]); - } - } - } - return null; - } - - public BaseSection getSection(String path) { - if (!path.isEmpty()) { - return getSection(ConfigTools.getKeys(path)); - } - return null; - } - - private BaseSection getSection(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - BaseSection section; - if ((section = getSection(key[0])) != null) { - return section.getSection(ConfigTools.getNextKeys(key)); - } - } else { - Object uncasted; - if ((uncasted = values.get(key[0])) instanceof BaseSection) { - return (BaseSection) uncasted; - } - } - } - } - return null; - } - - public BaseSection createSection(String path) { - if (!path.isEmpty()) { - return createSection(ConfigTools.getKeys(path)); - } - return null; - } - - private BaseSection createSection(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - BaseSection section; - if ((section = getSection(key[0])) == null) { - section = saveSection(initSection(key[0])); - } - return section.createSection(ConfigTools.getNextKeys(key)); - } else { - Object uncasted; - if (!((uncasted = get(key[0])) instanceof BaseSection)) { - uncasted = saveSection(initSection(key[0])); - } - return (BaseSection) uncasted; - } - } else { - BaseSection section = saveSection(initSection(key[0])); - if (key.length > 1) { - return section.createSection(ConfigTools.getNextKeys(key)); - } else { - return section; - } - } - } - return null; - } - - protected BaseSection saveSection(BaseSection section) { - set(section.getName(), section); - return section; - } - - public void set(String path, Object value) { - String[] keys = ConfigTools.getKeys(path); - String key = ConfigTools.getLastKey(keys); - set(key, ConfigTools.getKeysWithout(keys, key), value); - } - - public void set(String key, String[] path, Object value) { - if (path.length == 0) { - values.put(key, value); - } else { - BaseSection section = getSection(path); - if (section == null) { - section = createSection(path); - } - section.set(key, value); - } - } - - public SectionMap toMap() { - SectionMap output = new SectionMap<>(); - if (values.isEmpty()) { - return output; - } - Set> set = values.entrySet(); - for (Entry entry : set) { - Object out = entry.getValue(); - if (out instanceof BaseSection) { - if (isSectionInstance((BaseSection) out)) { - out = ((BaseSection) out).toMap(); - } - } - output.put(entry.getKey(), out); - } - return output; - } - - @SuppressWarnings("unchecked") - public void fromMap(SectionMap input) { - clear(); - Set> set = input.entrySet(); - if (set.isEmpty()) { - return; - } - for (Entry entry : set) { - Object obj = entry.getValue(); - if (obj instanceof SectionMap) { - createSection(entry.getKey()).fromMap((SectionMap) obj); - } else { - set(entry.getKey(), obj); - } - } - } - - protected abstract BaseSection initSection(String name); - - protected abstract boolean isSectionInstance(BaseSection section); + protected final SectionMap values = new SectionMap<>();; + private final String name; + + public BaseSection(String name) { + this.name = name; + } + + public Map getValues() { + return values; + } + + public Set getKeys() { + return values.keySet(); + } + + public String getName() { + return name; + } + + public boolean isValid() { + return !name.isEmpty(); + } + + public void clear() { + values.clear(); + } + + public boolean contains(String path) { + return get(path) != null; + } + + public boolean isInstance(String path, E value) { + Object object = get(path); + return object == null ? false : (value == null ? false : object.getClass().isAssignableFrom(value.getClass())); + } + + public boolean isInstance(String path, Class value) { + Object object = get(path); + return object == null ? false : (value == null ? false : object.getClass().isAssignableFrom(value)); + } + + @SuppressWarnings("unchecked") + public E check(String path, E value) { + Object current = get(path); + if (current != null) { + return (E) current; + } + set(path, value); + return value; + } + + public Object get(String path) { + if (!path.isEmpty()) { + return get(ConfigTools.getKeys(path)); + } + return null; + } + + @SuppressWarnings("unchecked") + public E get(String path, Class sample) { + if (!path.isEmpty()) { + return (E) get(ConfigTools.getKeys(path)); + } + return null; + } + + @SuppressWarnings("unchecked") + public E get(String path, E sample) { + if (!path.isEmpty()) { + return (E) get(ConfigTools.getKeys(path)); + } + return null; + } + + private Object get(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + BaseSection section; + if ((section = getSection(key[0])) != null) { + return section.get(ConfigTools.getNextKeys(key)); + } + } else { + return values.get(key[0]); + } + } + } + return null; + } + + public BaseSection getSection(String path) { + if (!path.isEmpty()) { + return getSection(ConfigTools.getKeys(path)); + } + return null; + } + + private BaseSection getSection(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + BaseSection section; + if ((section = getSection(key[0])) != null) { + return section.getSection(ConfigTools.getNextKeys(key)); + } + } else { + Object uncasted; + if ((uncasted = values.get(key[0])) instanceof BaseSection) { + return (BaseSection) uncasted; + } + } + } + } + return null; + } + + public BaseSection createSection(String path) { + if (!path.isEmpty()) { + return createSection(ConfigTools.getKeys(path)); + } + return null; + } + + private BaseSection createSection(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + BaseSection section; + if ((section = getSection(key[0])) == null) { + section = saveSection(initSection(key[0])); + } + return section.createSection(ConfigTools.getNextKeys(key)); + } else { + Object uncasted; + if (!((uncasted = get(key[0])) instanceof BaseSection)) { + uncasted = saveSection(initSection(key[0])); + } + return (BaseSection) uncasted; + } + } else { + BaseSection section = saveSection(initSection(key[0])); + if (key.length > 1) { + return section.createSection(ConfigTools.getNextKeys(key)); + } else { + return section; + } + } + } + return null; + } + + protected BaseSection saveSection(BaseSection section) { + set(section.getName(), section); + return section; + } + + public void set(String path, Object value) { + String[] keys = ConfigTools.getKeys(path); + String key = ConfigTools.getLastKey(keys); + set(key, ConfigTools.getKeysWithout(keys, key), value); + } + + public void set(String key, String[] path, Object value) { + if (path.length == 0) { + values.put(key, value); + } else { + BaseSection section = getSection(path); + if (section == null) { + section = createSection(path); + } + section.set(key, value); + } + } + + public SectionMap toMap() { + SectionMap output = new SectionMap<>(); + if (values.isEmpty()) { + return output; + } + Set> set = values.entrySet(); + for (Entry entry : set) { + Object out = entry.getValue(); + if (out instanceof BaseSection) { + if (isSectionInstance((BaseSection) out)) { + out = ((BaseSection) out).toMap(); + } + } + output.put(entry.getKey(), out); + } + return output; + } + + @SuppressWarnings("unchecked") + public void fromMap(SectionMap input) { + clear(); + Set> set = input.entrySet(); + if (set.isEmpty()) { + return; + } + for (Entry entry : set) { + Object obj = entry.getValue(); + if (obj instanceof SectionMap) { + createSection(entry.getKey()).fromMap((SectionMap) obj); + } else { + set(entry.getKey(), obj); + } + } + } + + protected abstract BaseSection initSection(String name); + + protected abstract boolean isSectionInstance(BaseSection section); } diff --git a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/ConfigTools.java b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/ConfigTools.java index ceada8f..931b777 100644 --- a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/ConfigTools.java +++ b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/ConfigTools.java @@ -8,45 +8,45 @@ */ public class ConfigTools { - public static String[] getKeys(String input) { - if (!input.contains(".")) { - return new String[] { - input - }; - } - return input.split("\\."); - } + public static String[] getKeys(String input) { + if (!input.contains(".")) { + return new String[] { + input + }; + } + return input.split("\\."); + } - public static String[] getNextKeys(String[] input) { - if (input.length == 1) { - return new String[0]; - } else { - String[] output = new String[input.length - 1]; - for (int x = 1; x < input.length; x++) { - output[x - 1] = input[x]; - } - return output; - } - } + public static String[] getNextKeys(String[] input) { + if (input.length == 1) { + return new String[0]; + } else { + String[] output = new String[input.length - 1]; + for (int x = 1; x < input.length; x++) { + output[x - 1] = input[x]; + } + return output; + } + } - public static String getLastKey(String[] input) { - if (input.length != 0) { - if (input.length == 1) { - return input[0]; - } - return input[input.length - 1]; - } - return ""; - } + public static String getLastKey(String[] input) { + if (input.length != 0) { + if (input.length == 1) { + return input[0]; + } + return input[input.length - 1]; + } + return ""; + } - public static String[] getKeysWithout(String[] input, String denied) { - ArrayList output = new ArrayList<>(); - for (int x = 0; x < input.length; x++) { - if (!input[x].equals(denied)) { - output.add(input[x]); - } - } - return output.toArray(new String[0]); - } + public static String[] getKeysWithout(String[] input, String denied) { + ArrayList output = new ArrayList<>(); + for (int x = 0; x < input.length; x++) { + if (!input[x].equals(denied)) { + output.add(input[x]); + } + } + return output.toArray(new String[0]); + } } diff --git a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/IBaseSection.java b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/IBaseSection.java index f7826c8..959c146 100644 --- a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/IBaseSection.java +++ b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/IBaseSection.java @@ -5,39 +5,39 @@ public interface IBaseSection { - public Map getValues(); + public Map getValues(); - public Set getKeys(); + public Set getKeys(); - public String getName(); + public String getName(); - public boolean isValid(); + public boolean isValid(); - public void clear(); + public void clear(); - public boolean contains(String path); + public boolean contains(String path); - public boolean isInstance(String path, E value); + public boolean isInstance(String path, E value); - public boolean isInstance(String path, Class value); + public boolean isInstance(String path, Class value); - public E check(String path, E value); + public E check(String path, E value); - public Object get(String path); + public Object get(String path); - public E get(String path, Class sample); + public E get(String path, Class sample); - public E get(String path, E sample); + public E get(String path, E sample); - public BaseSection getSection(String path); + public BaseSection getSection(String path); - public BaseSection createSection(String path); + public BaseSection createSection(String path); - public void set(String path, Object value); + public void set(String path, Object value); - public void set(String key, String[] path, Object value); + public void set(String key, String[] path, Object value); - public SectionMap toMap(); + public SectionMap toMap(); - public void fromMap(SectionMap input); + public void fromMap(SectionMap input); } diff --git a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/SectionMap.java b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/SectionMap.java index 2930ed9..68fec6a 100644 --- a/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/SectionMap.java +++ b/config/config-base/src/main/java/com/syntaxphoenix/syntaxapi/config/SectionMap.java @@ -4,10 +4,10 @@ public class SectionMap extends HashMap { - /** - * - */ + /** + * + */ - private static final long serialVersionUID = -8546634844301045074L; + private static final long serialVersionUID = -8546634844301045074L; } diff --git a/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfig.java b/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfig.java index be146c0..7d28de1 100644 --- a/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfig.java +++ b/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfig.java @@ -13,49 +13,49 @@ */ public class JsonConfig extends JsonConfigSection implements BaseConfig { - @Override - public void load(File file) throws IOException { - - if (file.exists()) { - - Scanner scanner = new Scanner(file); - StringBuilder builder = new StringBuilder(); - while (scanner.hasNextLine()) { - builder.append(scanner.nextLine()); - builder.append('\n'); - } - scanner.close(); - - String json = builder.toString(); - fromJsonString(json.substring(0, json.length() - 1)); - - } - - } - - @Override - public void save(File file) throws IOException { - - if (!file.exists()) { - String parentPath = file.getParent(); - if (parentPath != null && !parentPath.isEmpty()) { - File parent = file.getParentFile(); - if (parent.exists()) { - if (!parent.isDirectory()) { - parent.delete(); - parent.mkdirs(); - } - } else { - parent.mkdirs(); - } - } - file.createNewFile(); - } - - FileWriter writer = new FileWriter(file); - writer.write(toJsonString()); - writer.close(); - - } + @Override + public void load(File file) throws IOException { + + if (file.exists()) { + + Scanner scanner = new Scanner(file); + StringBuilder builder = new StringBuilder(); + while (scanner.hasNextLine()) { + builder.append(scanner.nextLine()); + builder.append('\n'); + } + scanner.close(); + + String json = builder.toString(); + fromJsonString(json.substring(0, json.length() - 1)); + + } + + } + + @Override + public void save(File file) throws IOException { + + if (!file.exists()) { + String parentPath = file.getParent(); + if (parentPath != null && !parentPath.isEmpty()) { + File parent = file.getParentFile(); + if (parent.exists()) { + if (!parent.isDirectory()) { + parent.delete(); + parent.mkdirs(); + } + } else { + parent.mkdirs(); + } + } + file.createNewFile(); + } + + FileWriter writer = new FileWriter(file); + writer.write(toJsonString()); + writer.close(); + + } } diff --git a/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfigSection.java b/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfigSection.java index 5e496cc..cb7cbe4 100644 --- a/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfigSection.java +++ b/config/config-json/src/main/java/com/syntaxphoenix/syntaxapi/config/json/JsonConfigSection.java @@ -19,132 +19,132 @@ */ public class JsonConfigSection extends BaseSection { - public JsonConfigSection() { - super(""); - } + public JsonConfigSection() { + super(""); + } - public JsonConfigSection(String name) { - super(name); - } + public JsonConfigSection(String name) { + super(name); + } - @Override - protected BaseSection initSection(String name) { - return new JsonConfigSection(name); - } + @Override + protected BaseSection initSection(String name) { + return new JsonConfigSection(name); + } - @Override - protected boolean isSectionInstance(BaseSection section) { - return section instanceof JsonConfigSection; - } + @Override + protected boolean isSectionInstance(BaseSection section) { + return section instanceof JsonConfigSection; + } - public void fromJson(JsonObject input) { - if (input.isJsonNull()) { - return; - } - Set> set = input.entrySet(); - if (!set.isEmpty()) { - for (Entry entry : set) { - JsonElement current = entry.getValue(); - if (current.isJsonNull()) { - continue; - } - if (current.isJsonObject()) { - JsonObject object = current.getAsJsonObject(); - if (object.get("class") == null) { - ((JsonConfigSection) createSection(entry.getKey())).fromJson(object); - } else { - Class clazz = ClassCache.getClass(object.get("class").getAsString()); - if (clazz == null) { - continue; - } - set(entry.getKey(), JsonTools.getConfiguredGson().fromJson(object.get("classValue"), clazz)); - } - continue; - } - if (current.isJsonPrimitive()) { - JsonPrimitive primitive = current.getAsJsonPrimitive(); - if (primitive.isBoolean()) { - set(entry.getKey(), primitive.getAsBoolean()); - continue; - } - if (primitive.isNumber()) { - Number number = primitive.getAsNumber(); - if (number instanceof LazilyParsedNumber) { - set(entry.getKey(), ValueIdentifier.identify(number.toString())); - continue; - } - if (number instanceof Byte) { - set(entry.getKey(), number.byteValue()); - continue; - } - if (number instanceof Short) { - set(entry.getKey(), number.shortValue()); - continue; - } - if (number instanceof Integer) { - set(entry.getKey(), number.intValue()); - continue; - } - if (number instanceof Long) { - set(entry.getKey(), number.longValue()); - continue; - } - if (number instanceof Float) { - set(entry.getKey(), number.floatValue()); - continue; - } - if (number instanceof Double) { - set(entry.getKey(), number.doubleValue()); - continue; - } - continue; - } - if (primitive.isString()) { - set(entry.getKey(), primitive.getAsString()); - continue; - } - set(entry.getKey(), ValueIdentifier.identify(JsonTools.getContent(primitive).toString())); - continue; - } - } - } - } + public void fromJson(JsonObject input) { + if (input.isJsonNull()) { + return; + } + Set> set = input.entrySet(); + if (!set.isEmpty()) { + for (Entry entry : set) { + JsonElement current = entry.getValue(); + if (current.isJsonNull()) { + continue; + } + if (current.isJsonObject()) { + JsonObject object = current.getAsJsonObject(); + if (object.get("class") == null) { + ((JsonConfigSection) createSection(entry.getKey())).fromJson(object); + } else { + Class clazz = ClassCache.getClass(object.get("class").getAsString()); + if (clazz == null) { + continue; + } + set(entry.getKey(), JsonTools.getConfiguredGson().fromJson(object.get("classValue"), clazz)); + } + continue; + } + if (current.isJsonPrimitive()) { + JsonPrimitive primitive = current.getAsJsonPrimitive(); + if (primitive.isBoolean()) { + set(entry.getKey(), primitive.getAsBoolean()); + continue; + } + if (primitive.isNumber()) { + Number number = primitive.getAsNumber(); + if (number instanceof LazilyParsedNumber) { + set(entry.getKey(), ValueIdentifier.identify(number.toString())); + continue; + } + if (number instanceof Byte) { + set(entry.getKey(), number.byteValue()); + continue; + } + if (number instanceof Short) { + set(entry.getKey(), number.shortValue()); + continue; + } + if (number instanceof Integer) { + set(entry.getKey(), number.intValue()); + continue; + } + if (number instanceof Long) { + set(entry.getKey(), number.longValue()); + continue; + } + if (number instanceof Float) { + set(entry.getKey(), number.floatValue()); + continue; + } + if (number instanceof Double) { + set(entry.getKey(), number.doubleValue()); + continue; + } + continue; + } + if (primitive.isString()) { + set(entry.getKey(), primitive.getAsString()); + continue; + } + set(entry.getKey(), ValueIdentifier.identify(JsonTools.getContent(primitive).toString())); + continue; + } + } + } + } - public void fromJsonString(String input) { - fromJson(JsonTools.readJson(input)); - } + public void fromJsonString(String input) { + fromJson(JsonTools.readJson(input)); + } - public JsonObject toJson() { - JsonObject object = new JsonObject(); - if (!values.isEmpty()) { - for (Entry entry : values.entrySet()) { - Object input = entry.getValue(); - if (input instanceof JsonConfigSection) { - object.add(entry.getKey(), ((JsonConfigSection) input).toJson()); - } else { - if (input instanceof Number) { - object.addProperty(entry.getKey(), (Number) input); - } else if (input instanceof Boolean) { - object.addProperty(entry.getKey(), (Boolean) input); - } else if (input instanceof Character) { - object.addProperty(entry.getKey(), (Character) input); - } else if (input instanceof String) { - object.addProperty(entry.getKey(), (String) input); - } else if (input instanceof Serializable) { - JsonObject serialized = new JsonObject(); - JsonElement element = JsonTools.getConfiguredGson().toJsonTree(input); - serialized.addProperty("class", input.getClass().getName().replace(".java", "").replace(".class", "")); - serialized.add("classValue", element); - object.add(entry.getKey(), serialized); - } - } - } - } - return object; - } + public JsonObject toJson() { + JsonObject object = new JsonObject(); + if (!values.isEmpty()) { + for (Entry entry : values.entrySet()) { + Object input = entry.getValue(); + if (input instanceof JsonConfigSection) { + object.add(entry.getKey(), ((JsonConfigSection) input).toJson()); + } else { + if (input instanceof Number) { + object.addProperty(entry.getKey(), (Number) input); + } else if (input instanceof Boolean) { + object.addProperty(entry.getKey(), (Boolean) input); + } else if (input instanceof Character) { + object.addProperty(entry.getKey(), (Character) input); + } else if (input instanceof String) { + object.addProperty(entry.getKey(), (String) input); + } else if (input instanceof Serializable) { + JsonObject serialized = new JsonObject(); + JsonElement element = JsonTools.getConfiguredGson().toJsonTree(input); + serialized.addProperty("class", input.getClass().getName().replace(".java", "").replace(".class", "")); + serialized.add("classValue", element); + object.add(entry.getKey(), serialized); + } + } + } + } + return object; + } - public String toJsonString() { - return JsonTools.getConfiguredGson().toJson(toJson()); - } + public String toJsonString() { + return JsonTools.getConfiguredGson().toJson(toJson()); + } } diff --git a/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfig.java b/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfig.java index d0423a2..b79d9a7 100644 --- a/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfig.java +++ b/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfig.java @@ -7,73 +7,73 @@ import java.io.IOException; import com.syntaxphoenix.syntaxapi.config.BaseConfig; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; import com.syntaxphoenix.syntaxapi.nbt.NbtNamedTag; import com.syntaxphoenix.syntaxapi.nbt.NbtTag; import com.syntaxphoenix.syntaxapi.nbt.NbtType; -import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; import com.syntaxphoenix.syntaxapi.nbt.tools.NbtDeserializer; import com.syntaxphoenix.syntaxapi.nbt.tools.NbtSerializer; public class NbtConfig extends NbtConfigSection implements BaseConfig { - private final NbtSerializer serializer; - private final NbtDeserializer deserializer; + private final NbtSerializer serializer; + private final NbtDeserializer deserializer; - public NbtConfig() { - this(true); - } + public NbtConfig() { + this(true); + } - public NbtConfig(boolean compressed) { - serializer = new NbtSerializer(compressed); - deserializer = new NbtDeserializer(compressed); - } + public NbtConfig(boolean compressed) { + serializer = new NbtSerializer(compressed); + deserializer = new NbtDeserializer(compressed); + } - @Override - public void load(File file) throws FileNotFoundException, IOException { + @Override + public void load(File file) throws FileNotFoundException, IOException { - if (!file.exists()) { - return; - } - FileInputStream stream = new FileInputStream(file); + if (!file.exists()) { + return; + } + FileInputStream stream = new FileInputStream(file); - NbtNamedTag tag = deserializer.fromStream(stream); + NbtNamedTag tag = deserializer.fromStream(stream); - stream.close(); + stream.close(); - NbtTag nbt = tag.getTag(); - if (nbt.getType() != NbtType.COMPOUND) { - return; - } + NbtTag nbt = tag.getTag(); + if (nbt.getType() != NbtType.COMPOUND) { + return; + } - fromNbt((NbtCompound) nbt); + fromNbt((NbtCompound) nbt); - } + } - @Override - public void save(File file) throws FileNotFoundException, IOException { + @Override + public void save(File file) throws FileNotFoundException, IOException { - if (!file.exists()) { - String parentPath = file.getParent(); - if (parentPath != null && !parentPath.isEmpty()) { - File parent = file.getParentFile(); - if (parent.exists()) { - if (!parent.isDirectory()) { - parent.delete(); - parent.mkdirs(); - } - } else { - parent.mkdirs(); - } - } - file.createNewFile(); - } + if (!file.exists()) { + String parentPath = file.getParent(); + if (parentPath != null && !parentPath.isEmpty()) { + File parent = file.getParentFile(); + if (parent.exists()) { + if (!parent.isDirectory()) { + parent.delete(); + parent.mkdirs(); + } + } else { + parent.mkdirs(); + } + } + file.createNewFile(); + } - FileOutputStream stream = new FileOutputStream(file); + FileOutputStream stream = new FileOutputStream(file); - serializer.toStream(new NbtNamedTag("root", asNbt()), stream); + serializer.toStream(new NbtNamedTag("root", asNbt()), stream); - stream.close(); + stream.close(); - } + } } diff --git a/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfigSection.java b/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfigSection.java index 2202bf1..24cbb2d 100644 --- a/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfigSection.java +++ b/config/config-nbt/src/main/java/com/syntaxphoenix/syntaxapi/config/nbt/NbtConfigSection.java @@ -4,215 +4,215 @@ import com.syntaxphoenix.syntaxapi.config.BaseSection; import com.syntaxphoenix.syntaxapi.config.ConfigTools; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; import com.syntaxphoenix.syntaxapi.nbt.NbtTag; import com.syntaxphoenix.syntaxapi.nbt.NbtType; import com.syntaxphoenix.syntaxapi.nbt.tools.NbtParser; import com.syntaxphoenix.syntaxapi.nbt.utils.NbtStorage; -import com.syntaxphoenix.syntaxapi.nbt.NbtByte; -import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; public class NbtConfigSection extends BaseSection implements NbtStorage { - public NbtConfigSection() { - super(""); - } - - public NbtConfigSection(String name) { - super(name); - } - - @Override - public NbtCompound asNbt() { - NbtCompound data = new NbtCompound(); - if (!values.isEmpty()) { - for (Entry entry : values.entrySet()) { - Object raw = entry.getValue(); - if (raw instanceof NbtConfigSection) { - data.set(entry.getKey(), ((NbtConfigSection) raw).asNbt()); - } else if (raw instanceof NbtTag) { - data.set(entry.getKey(), (NbtTag) raw); - } else { - NbtTag tag = NbtParser.fromObject(raw); - if (tag != null) { - data.set(entry.getKey(), tag); - } - } - } - } - data.set("section", true); - return data; - } - - @Override - public void fromNbt(NbtCompound data) { - values.clear(); - for (String key : data.getKeys()) { - NbtTag base = data.get(key); - if (base.getType() == NbtType.COMPOUND) { - NbtCompound compound = (NbtCompound) base; - if (compound.hasKey("section")) { - if (compound.getBoolean("section")) { - saveSection(initSection(key, compound)); - continue; - } - } - set(key, compound); - } else { - if (key.equals("section")) { - if (base.getType() == NbtType.BYTE) { - if (((NbtByte) base).getByteValue() == (byte) 0) { - continue; - } - } - } - set(key, base); - } - } - } - - @Override - public boolean contains(String path) { - return get(path) != null; - } - - public NbtTag check(String path, NbtTag value) { - NbtTag current = get(path); - if (current != null) { - return current; - } - set(path, value); - return value; - } - - @Override - public NbtTag get(String path) { - if (!path.isEmpty()) { - return get(ConfigTools.getKeys(path)); - } - return null; - } - - private NbtTag get(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - NbtConfigSection section; - if ((section = getSection(key[0])) != null) { - return section.get(ConfigTools.getNextKeys(key)); - } - } else { - return (NbtTag) values.get(key[0]); - } - } - } - return null; - } - - @Override - public NbtConfigSection getSection(String path) { - if (!path.isEmpty()) { - return getSection(ConfigTools.getKeys(path)); - } - return null; - } - - private NbtConfigSection getSection(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - NbtConfigSection section; - if ((section = getSection(key[0])) != null) { - return section.getSection(ConfigTools.getNextKeys(key)); - } - } else { - Object uncasted; - if ((uncasted = values.get(key[0])) instanceof NbtConfigSection) { - return (NbtConfigSection) uncasted; - } - } - } - } - return null; - } - - @Override - public NbtConfigSection createSection(String path) { - if (!path.isEmpty()) { - return createSection(ConfigTools.getKeys(path)); - } - return null; - } - - private NbtConfigSection createSection(String[] key) { - if (key.length != 0) { - if (values.containsKey(key[0])) { - if (key.length > 1) { - NbtConfigSection section; - if ((section = getSection(key[0])) == null) { - section = saveSection(initSection(key[0])); - } - return section.createSection(ConfigTools.getNextKeys(key)); - } else { - Object uncasted; - if (!((uncasted = get(key[0])) instanceof NbtConfigSection)) { - uncasted = saveSection(initSection(key[0])); - } - return (NbtConfigSection) uncasted; - } - } else { - NbtConfigSection section = saveSection(initSection(key[0])); - if (key.length > 1) { - return section.createSection(ConfigTools.getNextKeys(key)); - } else { - return section; - } - } - } - return null; - } - - public void set(String path, NbtTag value) { - String[] keys = ConfigTools.getKeys(path); - String key = ConfigTools.getLastKey(keys); - set(key, ConfigTools.getKeysWithout(keys, key), value); - } - - public void set(String key, String[] path, NbtTag value) { - if (path.length == 0) { - values.put(key, value); - } else { - NbtConfigSection section = getSection(path); - if (section == null) { - section = createSection(path); - } - section.set(key, value); - } - } - - @Override - protected NbtConfigSection initSection(String name) { - return new NbtConfigSection(name); - } - - protected NbtConfigSection initSection(String name, NbtCompound data) { - NbtConfigSection section = new NbtConfigSection(name); - section.fromNbt(data); - return section; - } - - @Override - protected boolean isSectionInstance(BaseSection section) { - return section instanceof NbtConfigSection; - } - - private NbtConfigSection saveSection(NbtConfigSection section) { - set(section.getName(), section.asNbt()); - return section; - } - - @Override - public String toString() { - return asNbt().toMSONString(); - } + public NbtConfigSection() { + super(""); + } + + public NbtConfigSection(String name) { + super(name); + } + + @Override + public NbtCompound asNbt() { + NbtCompound data = new NbtCompound(); + if (!values.isEmpty()) { + for (Entry entry : values.entrySet()) { + Object raw = entry.getValue(); + if (raw instanceof NbtConfigSection) { + data.set(entry.getKey(), ((NbtConfigSection) raw).asNbt()); + } else if (raw instanceof NbtTag) { + data.set(entry.getKey(), (NbtTag) raw); + } else { + NbtTag tag = NbtParser.fromObject(raw); + if (tag != null) { + data.set(entry.getKey(), tag); + } + } + } + } + data.set("section", true); + return data; + } + + @Override + public void fromNbt(NbtCompound data) { + values.clear(); + for (String key : data.getKeys()) { + NbtTag base = data.get(key); + if (base.getType() == NbtType.COMPOUND) { + NbtCompound compound = (NbtCompound) base; + if (compound.hasKey("section")) { + if (compound.getBoolean("section")) { + saveSection(initSection(key, compound)); + continue; + } + } + set(key, compound); + } else { + if (key.equals("section")) { + if (base.getType() == NbtType.BYTE) { + if (((NbtByte) base).getByteValue() == (byte) 0) { + continue; + } + } + } + set(key, base); + } + } + } + + @Override + public boolean contains(String path) { + return get(path) != null; + } + + public NbtTag check(String path, NbtTag value) { + NbtTag current = get(path); + if (current != null) { + return current; + } + set(path, value); + return value; + } + + @Override + public NbtTag get(String path) { + if (!path.isEmpty()) { + return get(ConfigTools.getKeys(path)); + } + return null; + } + + private NbtTag get(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + NbtConfigSection section; + if ((section = getSection(key[0])) != null) { + return section.get(ConfigTools.getNextKeys(key)); + } + } else { + return (NbtTag) values.get(key[0]); + } + } + } + return null; + } + + @Override + public NbtConfigSection getSection(String path) { + if (!path.isEmpty()) { + return getSection(ConfigTools.getKeys(path)); + } + return null; + } + + private NbtConfigSection getSection(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + NbtConfigSection section; + if ((section = getSection(key[0])) != null) { + return section.getSection(ConfigTools.getNextKeys(key)); + } + } else { + Object uncasted; + if ((uncasted = values.get(key[0])) instanceof NbtConfigSection) { + return (NbtConfigSection) uncasted; + } + } + } + } + return null; + } + + @Override + public NbtConfigSection createSection(String path) { + if (!path.isEmpty()) { + return createSection(ConfigTools.getKeys(path)); + } + return null; + } + + private NbtConfigSection createSection(String[] key) { + if (key.length != 0) { + if (values.containsKey(key[0])) { + if (key.length > 1) { + NbtConfigSection section; + if ((section = getSection(key[0])) == null) { + section = saveSection(initSection(key[0])); + } + return section.createSection(ConfigTools.getNextKeys(key)); + } else { + Object uncasted; + if (!((uncasted = get(key[0])) instanceof NbtConfigSection)) { + uncasted = saveSection(initSection(key[0])); + } + return (NbtConfigSection) uncasted; + } + } else { + NbtConfigSection section = saveSection(initSection(key[0])); + if (key.length > 1) { + return section.createSection(ConfigTools.getNextKeys(key)); + } else { + return section; + } + } + } + return null; + } + + public void set(String path, NbtTag value) { + String[] keys = ConfigTools.getKeys(path); + String key = ConfigTools.getLastKey(keys); + set(key, ConfigTools.getKeysWithout(keys, key), value); + } + + public void set(String key, String[] path, NbtTag value) { + if (path.length == 0) { + values.put(key, value); + } else { + NbtConfigSection section = getSection(path); + if (section == null) { + section = createSection(path); + } + section.set(key, value); + } + } + + @Override + protected NbtConfigSection initSection(String name) { + return new NbtConfigSection(name); + } + + protected NbtConfigSection initSection(String name, NbtCompound data) { + NbtConfigSection section = new NbtConfigSection(name); + section.fromNbt(data); + return section; + } + + @Override + protected boolean isSectionInstance(BaseSection section) { + return section instanceof NbtConfigSection; + } + + private NbtConfigSection saveSection(NbtConfigSection section) { + set(section.getName(), section.asNbt()); + return section; + } + + @Override + public String toString() { + return asNbt().toMSONString(); + } } \ No newline at end of file diff --git a/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfig.java b/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfig.java index f670041..fdf853c 100644 --- a/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfig.java +++ b/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfig.java @@ -8,49 +8,49 @@ public class TomlConfig extends TomlConfigSection implements BaseConfig { - @Override - public void load(File file) throws Throwable { - - if (file.exists()) { - - Scanner scanner = new Scanner(file); - StringBuilder builder = new StringBuilder(); - while (scanner.hasNextLine()) { - builder.append(scanner.nextLine()); - builder.append('\n'); - } - scanner.close(); - - String toml = builder.toString(); - fromTomlString(toml.substring(0, toml.length() - 1)); - - } - - } - - @Override - public void save(File file) throws Throwable { - - if (!file.exists()) { - String parentPath = file.getParent(); - if (parentPath != null && !parentPath.isEmpty()) { - File parent = file.getParentFile(); - if (parent.exists()) { - if (!parent.isDirectory()) { - parent.delete(); - parent.mkdirs(); - } - } else { - parent.mkdirs(); - } - } - file.createNewFile(); - } - - FileWriter writer = new FileWriter(file); - writer.write(toTomlString()); - writer.close(); - - } + @Override + public void load(File file) throws Throwable { + + if (file.exists()) { + + Scanner scanner = new Scanner(file); + StringBuilder builder = new StringBuilder(); + while (scanner.hasNextLine()) { + builder.append(scanner.nextLine()); + builder.append('\n'); + } + scanner.close(); + + String toml = builder.toString(); + fromTomlString(toml.substring(0, toml.length() - 1)); + + } + + } + + @Override + public void save(File file) throws Throwable { + + if (!file.exists()) { + String parentPath = file.getParent(); + if (parentPath != null && !parentPath.isEmpty()) { + File parent = file.getParentFile(); + if (parent.exists()) { + if (!parent.isDirectory()) { + parent.delete(); + parent.mkdirs(); + } + } else { + parent.mkdirs(); + } + } + file.createNewFile(); + } + + FileWriter writer = new FileWriter(file); + writer.write(toTomlString()); + writer.close(); + + } } diff --git a/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfigSection.java b/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfigSection.java index 59d0391..af3c8c4 100644 --- a/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfigSection.java +++ b/config/config-toml/src/main/java/com/syntaxphoenix/syntaxapi/config/toml/TomlConfigSection.java @@ -1,73 +1,73 @@ package com.syntaxphoenix.syntaxapi.config.toml; import java.io.IOException; -import java.util.Set; import java.util.HashMap; import java.util.Map.Entry; +import java.util.Set; import com.electronwill.toml.Toml; import com.syntaxphoenix.syntaxapi.config.BaseSection; public class TomlConfigSection extends BaseSection { - public TomlConfigSection() { - super(""); - } + public TomlConfigSection() { + super(""); + } - public TomlConfigSection(String name) { - super(name); - } + public TomlConfigSection(String name) { + super(name); + } - @Override - protected BaseSection initSection(String name) { - return new TomlConfigSection(name); - } + @Override + protected BaseSection initSection(String name) { + return new TomlConfigSection(name); + } - @Override - protected boolean isSectionInstance(BaseSection section) { - return section instanceof TomlConfigSection; - } + @Override + protected boolean isSectionInstance(BaseSection section) { + return section instanceof TomlConfigSection; + } - /* - * - * TO TOML - * - */ + /* + * + * TO TOML + * + */ - public String toTomlString() { - try { - return Toml.writeToString(toMap()); - } catch (IOException e) { - e.printStackTrace(); - } - return ""; - } + public String toTomlString() { + try { + return Toml.writeToString(toMap()); + } catch (IOException e) { + e.printStackTrace(); + } + return ""; + } - /* - * - * FROM TOML - * - */ + /* + * + * FROM TOML + * + */ - public void fromTomlString(String toml) { - fromMap((HashMap) Toml.read(toml)); - } + public void fromTomlString(String toml) { + fromMap((HashMap) Toml.read(toml)); + } - @SuppressWarnings("unchecked") - public void fromMap(HashMap input) { - clear(); - Set> set = input.entrySet(); - if (set.isEmpty()) { - return; - } - for (Entry entry : set) { - Object obj = entry.getValue(); - if (obj instanceof HashMap) { - ((TomlConfigSection) createSection(entry.getKey())).fromMap((HashMap) obj); - } else { - set(entry.getKey(), obj); - } - } - } + @SuppressWarnings("unchecked") + public void fromMap(HashMap input) { + clear(); + Set> set = input.entrySet(); + if (set.isEmpty()) { + return; + } + for (Entry entry : set) { + Object obj = entry.getValue(); + if (obj instanceof HashMap) { + ((TomlConfigSection) createSection(entry.getKey())).fromMap((HashMap) obj); + } else { + set(entry.getKey(), obj); + } + } + } } diff --git a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfig.java b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfig.java index 4204339..e37a13f 100644 --- a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfig.java +++ b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfig.java @@ -31,10 +31,11 @@ public void load(File file) throws IOException, RuntimeException { builder.append('\n'); } scanner.close(); - + String yaml = builder.toString(); - if (yaml.isEmpty()) + if (yaml.isEmpty()) { return; + } fromYamlString(yaml.substring(0, yaml.length() - 1)); diff --git a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfigSection.java b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfigSection.java index 0f17c46..db6bcb9 100644 --- a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfigSection.java +++ b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/YamlConfigSection.java @@ -2,7 +2,6 @@ import java.util.Map; import java.util.Map.Entry; - import java.util.Set; import org.yaml.snakeyaml.DumperOptions; diff --git a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/exceptions/YamlException.java b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/exceptions/YamlException.java index 8bfb608..7da102b 100644 --- a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/exceptions/YamlException.java +++ b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/exceptions/YamlException.java @@ -2,61 +2,61 @@ public class YamlException extends RuntimeException { - /** - * Constructs an YamlException with no detail message. - */ - public YamlException() { - super(); - } + /** + * Constructs an YamlException with no detail message. + */ + public YamlException() { + super(); + } - /** - * Constructs an YamlException with the specified detail message. - * - * @param s the detail message. - */ - public YamlException(String s) { - super(s); - } + /** + * Constructs an YamlException with the specified detail message. + * + * @param s the detail message. + */ + public YamlException(String s) { + super(s); + } - /** - * Constructs a new exception with the specified detail message and cause. - * - *

- * Note that the detail message associated with cause is not - * automatically incorporated in this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval by the - * {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public YamlException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new exception with the specified detail message and cause. + * + *

+ * Note that the detail message associated with cause is not + * automatically incorporated in this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval by the + * {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public YamlException(String message, Throwable cause) { + super(message, cause); + } - /** - * Constructs a new exception with the specified cause and a detail message of - * (cause==null ? null : cause.toString()) (which typically contains - * the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for - * example, {@link java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public YamlException(Throwable cause) { - super(cause); - } + /** + * Constructs a new exception with the specified cause and a detail message of + * (cause==null ? null : cause.toString()) (which typically contains + * the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for + * example, {@link java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public YamlException(Throwable cause) { + super(cause); + } - /** - * - */ - private static final long serialVersionUID = -3023398677172673915L; + /** + * + */ + private static final long serialVersionUID = -3023398677172673915L; } diff --git a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedConstructor.java b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedConstructor.java index 5ff0c08..ede4a2f 100644 --- a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedConstructor.java +++ b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedConstructor.java @@ -19,62 +19,62 @@ public class LinkedConstructor extends SafeConstructor { - public static final AbstractReflect SAFE_CONSTRUCT = new Reflect(SafeConstructor.class) - .searchMethod("merge", "mergeNode", MappingNode.class, boolean.class, Map.class, List.class); - - public LinkedConstructor() { - super(); - } - - @SuppressWarnings("unchecked") - @Override - protected void flattenMapping(MappingNode node) { - this.processDuplicateKeys(node); - if (node.isMerged()) { - node.setValue((List) SAFE_CONSTRUCT.run(this, "merge", node, true, new LinkedHashMap<>(), new LinkedList<>())); - } - - } - - @Override - protected void processDuplicateKeys(MappingNode node) { - List nodeValue = node.getValue(); - Map keys = new LinkedHashMap<>(nodeValue.size()); - TreeSet toRemove = new TreeSet<>(); - int i = 0; - - Iterator indicies2remove; - for (indicies2remove = nodeValue.iterator(); indicies2remove.hasNext(); ++i) { - NodeTuple tuple = indicies2remove.next(); - Node keyNode = tuple.getKeyNode(); - if (!keyNode.getTag().equals(Tag.MERGE)) { - Object key = this.constructObject(keyNode); - if (key != null) { - try { - key.hashCode(); - } catch (Exception var11) { - throw new YamlException("while constructing a mapping // " + node.getStartMark().toString() + " // found unacceptable key " + key - + " // " + tuple.getKeyNode().getStartMark().toString(), var11); - } - } - - Integer prevIndex = keys.put(key, i); - if (prevIndex != null) { - if (!this.isAllowDuplicateKeys()) { - throw new YamlException(node.getStartMark().toString() + " // " + key + " // " + tuple.getKeyNode().getStartMark()); - } - - toRemove.add(prevIndex); - } - } - } - - Iterator indicies2remove2 = toRemove.descendingIterator(); - - while (indicies2remove2.hasNext()) { - nodeValue.remove(indicies2remove2.next().intValue()); - } - - } + public static final AbstractReflect SAFE_CONSTRUCT = new Reflect(SafeConstructor.class).searchMethod("merge", "mergeNode", + MappingNode.class, boolean.class, Map.class, List.class); + + public LinkedConstructor() { + super(); + } + + @SuppressWarnings("unchecked") + @Override + protected void flattenMapping(MappingNode node) { + this.processDuplicateKeys(node); + if (node.isMerged()) { + node.setValue((List) SAFE_CONSTRUCT.run(this, "merge", node, true, new LinkedHashMap<>(), new LinkedList<>())); + } + + } + + @Override + protected void processDuplicateKeys(MappingNode node) { + List nodeValue = node.getValue(); + Map keys = new LinkedHashMap<>(nodeValue.size()); + TreeSet toRemove = new TreeSet<>(); + int i = 0; + + Iterator indicies2remove; + for (indicies2remove = nodeValue.iterator(); indicies2remove.hasNext(); ++i) { + NodeTuple tuple = indicies2remove.next(); + Node keyNode = tuple.getKeyNode(); + if (!keyNode.getTag().equals(Tag.MERGE)) { + Object key = this.constructObject(keyNode); + if (key != null) { + try { + key.hashCode(); + } catch (Exception var11) { + throw new YamlException("while constructing a mapping // " + node.getStartMark().toString() + + " // found unacceptable key " + key + " // " + tuple.getKeyNode().getStartMark().toString(), var11); + } + } + + Integer prevIndex = keys.put(key, i); + if (prevIndex != null) { + if (!this.isAllowDuplicateKeys()) { + throw new YamlException(node.getStartMark().toString() + " // " + key + " // " + tuple.getKeyNode().getStartMark()); + } + + toRemove.add(prevIndex); + } + } + } + + Iterator indicies2remove2 = toRemove.descendingIterator(); + + while (indicies2remove2.hasNext()) { + nodeValue.remove(indicies2remove2.next().intValue()); + } + + } } diff --git a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedRepresenter.java b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedRepresenter.java index 4b5c9b2..9d4c487 100644 --- a/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedRepresenter.java +++ b/config/config-yaml/src/main/java/com/syntaxphoenix/syntaxapi/config/yaml/utils/LinkedRepresenter.java @@ -12,20 +12,20 @@ public class LinkedRepresenter extends Representer { - public static final AbstractReflect BASE_REPRESENT = new Reflect(BaseRepresenter.class).searchField("objectMap", "representedObjects"); + public static final AbstractReflect BASE_REPRESENT = new Reflect(BaseRepresenter.class).searchField("objectMap", "representedObjects"); - public LinkedRepresenter() { - super(); - replaceMap(); - } + public LinkedRepresenter() { + super(); + replaceMap(); + } - public LinkedRepresenter(DumperOptions options) { - super(options); - replaceMap(); - } + public LinkedRepresenter(DumperOptions options) { + super(options); + replaceMap(); + } - private void replaceMap() { - BASE_REPRESENT.setFieldValue(this, "objectMap", new LinkedHashMap()); - } + private void replaceMap() { + BASE_REPRESENT.setFieldValue(this, "objectMap", new LinkedHashMap()); + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapter.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapter.java index 560ab80..fb203a1 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapter.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapter.java @@ -4,31 +4,31 @@ public abstract class DataAdapter { - private final Function builder; - private final Function extractor; + private final Function builder; + private final Function extractor; - private final Class primitiveType; - private final Class resultType; + private final Class primitiveType; + private final Class resultType; - public DataAdapter(Class primitiveType, Class resultType, Function builder, Function extractor) { - this.primitiveType = primitiveType; - this.resultType = resultType; - this.builder = builder; - this.extractor = extractor; - } + public DataAdapter(Class primitiveType, Class resultType, Function builder, Function extractor) { + this.primitiveType = primitiveType; + this.resultType = resultType; + this.builder = builder; + this.extractor = extractor; + } - public abstract Class getBaseType(); + public abstract Class getBaseType(); - protected I extract(B input) { - return resultType.isInstance(input) ? extractor.apply(resultType.cast(input)) : null; - } + protected I extract(B input) { + return resultType.isInstance(input) ? extractor.apply(resultType.cast(input)) : null; + } - protected R build(Object input) { - return primitiveType.isInstance(input) ? builder.apply(primitiveType.cast(input)) : null; - } + protected R build(Object input) { + return primitiveType.isInstance(input) ? builder.apply(primitiveType.cast(input)) : null; + } - public boolean isInstance(B base) { - return resultType.isInstance(base); - } + public boolean isInstance(B base) { + return resultType.isInstance(base); + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterContext.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterContext.java index c4a963f..ee91ff6 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterContext.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterContext.java @@ -2,6 +2,6 @@ public interface DataAdapterContext { - public IDataContainer newDataContainer(); + public IDataContainer newDataContainer(); } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterRegistry.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterRegistry.java index a7520fd..0bc7c06 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterRegistry.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataAdapterRegistry.java @@ -7,34 +7,35 @@ public abstract class DataAdapterRegistry { - private final ConcurrentHashMap, DataAdapter> adapters = new ConcurrentHashMap<>(); - - protected abstract DataAdapter buildAdapter(Class clazz); - - protected abstract DataAdapter createAdapter(Class primitiveType, Class resultType, Function builder, - Function extractor); - - public B wrap(Class type, T value) { - DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz)); - return adapter == null ? null : adapter.build(value); - } - - public T extract(Class type, B base) throws ClassCastException, IllegalArgumentException { - type = Primitives.fromPrimitive(type); - DataAdapter adapter = this.adapters.computeIfAbsent(type, (clazz) -> buildAdapter(clazz)); - if (adapter == null || !adapter.isInstance(base)) - return null; - Object foundValue = adapter.extract(base); - return type.isInstance(foundValue) ? type.cast(foundValue) : null; - } - - public boolean isInstanceOf(Class type, B base) { - DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz)); - return adapter == null ? null : adapter.isInstance(base); - } - - public boolean hasAdapter(Class type) { - return adapters.containsKey(Primitives.fromPrimitive(type)); - } + private final ConcurrentHashMap, DataAdapter> adapters = new ConcurrentHashMap<>(); + + protected abstract DataAdapter buildAdapter(Class clazz); + + protected abstract DataAdapter createAdapter(Class primitiveType, Class resultType, + Function builder, Function extractor); + + public B wrap(Class type, T value) { + DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz)); + return adapter == null ? null : adapter.build(value); + } + + public T extract(Class type, B base) throws ClassCastException, IllegalArgumentException { + type = Primitives.fromPrimitive(type); + DataAdapter adapter = this.adapters.computeIfAbsent(type, (clazz) -> buildAdapter(clazz)); + if (adapter == null || !adapter.isInstance(base)) { + return null; + } + Object foundValue = adapter.extract(base); + return type.isInstance(foundValue) ? type.cast(foundValue) : null; + } + + public boolean isInstanceOf(Class type, B base) { + DataAdapter adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz)); + return adapter == null ? null : adapter.isInstance(base); + } + + public boolean hasAdapter(Class type) { + return adapters.containsKey(Primitives.fromPrimitive(type)); + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataContainer.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataContainer.java index b7ba465..e8bf481 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataContainer.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataContainer.java @@ -5,54 +5,58 @@ public abstract class DataContainer implements IDataContainer { - public boolean has(String key) { - return get(key) != null; - } - - public boolean has(IKey key) { - return get(key) != null; - } - - public boolean has(String key, DataType type) { - Object obj = get(key); - if (obj == null) - return false; - if (type.isPrimitive(obj)) - return false; - return true; - } - - public boolean has(IKey key, DataType type) { - Object obj = get(key); - if (obj == null) - return false; - if (type.isPrimitive(obj)) - return false; - return true; - } - - public E get(String key, DataType type) { - return type.fromPrimitiveObj(getAdapterContext(), get(key)); - } - - public E get(IKey key, DataType type) { - return type.fromPrimitiveObj(getAdapterContext(), get(key)); - } - - public Object get(IKey key) { - return get(key.toString()); - } - - public void set(IKey key, E value, DataType type) { - set(key.toString(), value, type); - } - - public boolean remove(IKey key) { - return remove(key.toString()); - } - - public IKey[] getKeys() { - return getKeyspaces().stream().map(NamespacedKey::fromString).toArray(IKey[]::new); - } + public boolean has(String key) { + return get(key) != null; + } + + public boolean has(IKey key) { + return get(key) != null; + } + + public boolean has(String key, DataType type) { + Object obj = get(key); + if (obj == null) { + return false; + } + if (type.isPrimitive(obj)) { + return false; + } + return true; + } + + public boolean has(IKey key, DataType type) { + Object obj = get(key); + if (obj == null) { + return false; + } + if (type.isPrimitive(obj)) { + return false; + } + return true; + } + + public E get(String key, DataType type) { + return type.fromPrimitiveObj(getAdapterContext(), get(key)); + } + + public E get(IKey key, DataType type) { + return type.fromPrimitiveObj(getAdapterContext(), get(key)); + } + + public Object get(IKey key) { + return get(key.toString()); + } + + public void set(IKey key, E value, DataType type) { + set(key.toString(), value, type); + } + + public boolean remove(IKey key) { + return remove(key.toString()); + } + + public IKey[] getKeys() { + return getKeyspaces().stream().map(NamespacedKey::fromString).toArray(IKey[]::new); + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataFactory.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataFactory.java index dfd9892..6dbb7f3 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataFactory.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataFactory.java @@ -6,38 +6,38 @@ public abstract class DataFactory { - private final DataAdapterRegistry adapterRegistry; + private final DataAdapterRegistry adapterRegistry; - public DataFactory(DataAdapterRegistry adapterRegistry) { - this.adapterRegistry = adapterRegistry; - } + public DataFactory(DataAdapterRegistry adapterRegistry) { + this.adapterRegistry = adapterRegistry; + } - /* - * Get - */ + /* + * Get + */ - public DataAdapterRegistry getAdapaterRegistry() { - return adapterRegistry; - } + public DataAdapterRegistry getAdapaterRegistry() { + return adapterRegistry; + } - /* - * Serialize - */ + /* + * Serialize + */ - public abstract DataFactory toFile(DataContainer holder, File file); + public abstract DataFactory toFile(DataContainer holder, File file); - public abstract DataFactory toStream(DataContainer holder, OutputStream stream); + public abstract DataFactory toStream(DataContainer holder, OutputStream stream); - public abstract DataFactory toString(DataContainer holder, StringBuilder builder); + public abstract DataFactory toString(DataContainer holder, StringBuilder builder); - /* - * Deserialize - */ + /* + * Deserialize + */ - public abstract DataFactory fromFile(DataContainer holder, File file); + public abstract DataFactory fromFile(DataContainer holder, File file); - public abstract DataFactory fromStream(DataContainer holder, InputStream stream); + public abstract DataFactory fromStream(DataContainer holder, InputStream stream); - public abstract DataFactory fromString(DataContainer holder, String string); + public abstract DataFactory fromString(DataContainer holder, String string); } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataType.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataType.java index ed870f5..cee85a7 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataType.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataType.java @@ -2,42 +2,48 @@ public interface DataType

{ - public default boolean isComplex(Object object) { - return getComplex().isInstance(object); - } - - public default boolean isPrimitive(Object object) { - return getPrimitive().isInstance(object); - } - - public Class getComplex(); - - public Class

getPrimitive(); - - public P toPrimitive(DataAdapterContext context, C complex); - - public C fromPrimitive(DataAdapterContext context, P primitive); - - @SuppressWarnings("unchecked") - public default P toPrimitiveObj(DataAdapterContext context, Object complex) { - if (complex == null) - return null; - if (isComplex(complex)) - return toPrimitive(context, (C) complex); - if (isPrimitive(complex)) - return (P) complex; - return null; - } - - @SuppressWarnings("unchecked") - public default C fromPrimitiveObj(DataAdapterContext context, Object primitive) { - if (primitive == null) - return null; - if (isPrimitive(primitive)) - return fromPrimitive(context, (P) primitive); - if (isComplex(primitive)) - return (C) primitive; - return null; - } + public default boolean isComplex(Object object) { + return getComplex().isInstance(object); + } + + public default boolean isPrimitive(Object object) { + return getPrimitive().isInstance(object); + } + + public Class getComplex(); + + public Class

getPrimitive(); + + public P toPrimitive(DataAdapterContext context, C complex); + + public C fromPrimitive(DataAdapterContext context, P primitive); + + @SuppressWarnings("unchecked") + public default P toPrimitiveObj(DataAdapterContext context, Object complex) { + if (complex == null) { + return null; + } + if (isComplex(complex)) { + return toPrimitive(context, (C) complex); + } + if (isPrimitive(complex)) { + return (P) complex; + } + return null; + } + + @SuppressWarnings("unchecked") + public default C fromPrimitiveObj(DataAdapterContext context, Object primitive) { + if (primitive == null) { + return null; + } + if (isPrimitive(primitive)) { + return fromPrimitive(context, (P) primitive); + } + if (isComplex(primitive)) { + return (C) primitive; + } + return null; + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataTypeChain.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataTypeChain.java index 5164f12..dd83087 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataTypeChain.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/DataTypeChain.java @@ -7,171 +7,185 @@ public class DataTypeChain

implements DataType { - private final ArrayList> types = new ArrayList<>(); - - /* - * Contains - */ - - public boolean has(DataType type) { - return hasExact(type) || hasComplex(type.getComplex()); - } - - public boolean hasExact(DataType type) { - return types.contains(type); - } - - public boolean hasComplex(Class complex) { - return types.stream().anyMatch(type -> Objects.equals(type.getComplex(), complex)); - } - - /* - * Add - */ - - public DataTypeChain add(DataType type) { - if (type == null) - return this; - if (has(type)) - return this; - types.add(type); - return this; - } - - public DataTypeChain addAll(DataType... types) { - if (types == null) - return this; - for (int index = 0; index < types.length; index++) - add(types[index]); - return this; - } - - public DataTypeChain addAll(Iterable> types) { - if (types == null) - return this; - return addAll(types.iterator()); - } - - public DataTypeChain addAll(Iterator> types) { - if (types == null) - return this; - while (types.hasNext()) - add(types.next()); - return this; - } - - /* - * Remove - */ - - public DataTypeChain remove(DataType type) { - types.remove(type); - return this; - } - - public DataTypeChain removeAll(DataType... types) { - if (types == null) - return this; - for (int index = 0; index < types.length; index++) - remove(types[index]); - return this; - } - - public DataTypeChain removeAll(Iterable> types) { - if (types == null) - return this; - return removeAll(types.iterator()); - } - - public DataTypeChain removeAll(Iterator> types) { - if (types == null) - return this; - while (types.hasNext()) - remove(types.next()); - return this; - } - - /* - * Get - */ - - public DataType get(int index) { - return types.get(index); - } - - public DataType[] get(int start, int length) { - return types.subList(start, start + length).toArray(new DataType[0]); - } - - /* - * Other - */ - - public int size() { - return types.size(); - } - - public boolean isEmpty() { - return types.isEmpty(); - } - - public DataTypeChain clear() { - types.clear(); - return this; - } - - /* - * Cast - */ - - @SuppressWarnings("unchecked") - public Optional> asComplex(Class complex) { - return Optional.ofNullable(Objects.equals(getComplex(), complex) ? (DataTypeChain) this : null); - } - - @SuppressWarnings("unchecked") - public Optional> asPrimitive(Class primitive) { - return Optional.ofNullable(Objects.equals(getPrimitive(), primitive) ? (DataTypeChain) this : null); - } - - /* - * DataType - */ - - @SuppressWarnings("unchecked") - @Override - public Class getComplex() { - return isEmpty() ? null : (Class) types.get(size() - 1).getComplex(); - } - - @SuppressWarnings("unchecked") - @Override - public Class

getPrimitive() { - return isEmpty() ? null : (Class

) types.get(0).getPrimitive(); - } - - @SuppressWarnings("unchecked") - @Override - public C fromPrimitive(DataAdapterContext context, P primitive) { - Object output = primitive; - for (int index = size() - 1; index > -1; index--) { - if (output == null) - return null; - output = types.get(index).fromPrimitiveObj(context, output); - } - return isComplex(output) ? (C) output : null; - } - - @SuppressWarnings("unchecked") - @Override - public P toPrimitive(DataAdapterContext context, C complex) { - Object output = complex; - for (int index = size() - 1; index > -1; index--) { - if (output == null) - return null; - output = types.get(index).toPrimitiveObj(context, output); - } - return isPrimitive(output) ? (P) output : null; - } + private final ArrayList> types = new ArrayList<>(); + + /* + * Contains + */ + + public boolean has(DataType type) { + return hasExact(type) || hasComplex(type.getComplex()); + } + + public boolean hasExact(DataType type) { + return types.contains(type); + } + + public boolean hasComplex(Class complex) { + return types.stream().anyMatch(type -> Objects.equals(type.getComplex(), complex)); + } + + /* + * Add + */ + + public DataTypeChain add(DataType type) { + if (type == null) { + return this; + } + if (has(type)) { + return this; + } + types.add(type); + return this; + } + + public DataTypeChain addAll(DataType... types) { + if (types == null) { + return this; + } + for (int index = 0; index < types.length; index++) { + add(types[index]); + } + return this; + } + + public DataTypeChain addAll(Iterable> types) { + if (types == null) { + return this; + } + return addAll(types.iterator()); + } + + public DataTypeChain addAll(Iterator> types) { + if (types == null) { + return this; + } + while (types.hasNext()) { + add(types.next()); + } + return this; + } + + /* + * Remove + */ + + public DataTypeChain remove(DataType type) { + types.remove(type); + return this; + } + + public DataTypeChain removeAll(DataType... types) { + if (types == null) { + return this; + } + for (int index = 0; index < types.length; index++) { + remove(types[index]); + } + return this; + } + + public DataTypeChain removeAll(Iterable> types) { + if (types == null) { + return this; + } + return removeAll(types.iterator()); + } + + public DataTypeChain removeAll(Iterator> types) { + if (types == null) { + return this; + } + while (types.hasNext()) { + remove(types.next()); + } + return this; + } + + /* + * Get + */ + + public DataType get(int index) { + return types.get(index); + } + + public DataType[] get(int start, int length) { + return types.subList(start, start + length).toArray(new DataType[0]); + } + + /* + * Other + */ + + public int size() { + return types.size(); + } + + public boolean isEmpty() { + return types.isEmpty(); + } + + public DataTypeChain clear() { + types.clear(); + return this; + } + + /* + * Cast + */ + + @SuppressWarnings("unchecked") + public Optional> asComplex(Class complex) { + return Optional.ofNullable(Objects.equals(getComplex(), complex) ? (DataTypeChain) this : null); + } + + @SuppressWarnings("unchecked") + public Optional> asPrimitive(Class primitive) { + return Optional.ofNullable(Objects.equals(getPrimitive(), primitive) ? (DataTypeChain) this : null); + } + + /* + * DataType + */ + + @SuppressWarnings("unchecked") + @Override + public Class getComplex() { + return isEmpty() ? null : (Class) types.get(size() - 1).getComplex(); + } + + @SuppressWarnings("unchecked") + @Override + public Class

getPrimitive() { + return isEmpty() ? null : (Class

) types.get(0).getPrimitive(); + } + + @SuppressWarnings("unchecked") + @Override + public C fromPrimitive(DataAdapterContext context, P primitive) { + Object output = primitive; + for (int index = size() - 1; index > -1; index--) { + if (output == null) { + return null; + } + output = types.get(index).fromPrimitiveObj(context, output); + } + return isComplex(output) ? (C) output : null; + } + + @SuppressWarnings("unchecked") + @Override + public P toPrimitive(DataAdapterContext context, C complex) { + Object output = complex; + for (int index = size() - 1; index > -1; index--) { + if (output == null) { + return null; + } + output = types.get(index).toPrimitiveObj(context, output); + } + return isPrimitive(output) ? (P) output : null; + } } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/IDataContainer.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/IDataContainer.java index 8a4a99c..1cff33e 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/IDataContainer.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/IDataContainer.java @@ -6,42 +6,42 @@ public interface IDataContainer { - boolean has(String key); + boolean has(String key); - boolean has(IKey key); + boolean has(IKey key); - boolean has(String key, DataType type); + boolean has(String key, DataType type); - boolean has(IKey key, DataType type); + boolean has(IKey key, DataType type); - E get(String key, DataType type); + E get(String key, DataType type); - E get(IKey key, DataType type); + E get(IKey key, DataType type); - /* - * Abstract - */ + /* + * Abstract + */ - DataAdapterContext getAdapterContext(); + DataAdapterContext getAdapterContext(); - Object get(String key); + Object get(String key); - Object get(IKey key); + Object get(IKey key); - void set(String key, E value, DataType type); + void set(String key, E value, DataType type); - void set(IKey key, E value, DataType type); + void set(IKey key, E value, DataType type); - boolean remove(String key); + boolean remove(String key); - boolean remove(IKey key); + boolean remove(IKey key); - Set getKeyspaces(); + Set getKeyspaces(); - IKey[] getKeys(); + IKey[] getKeys(); - boolean isEmpty(); + boolean isEmpty(); - int size(); + int size(); } diff --git a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/PrimitiveDataType.java b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/PrimitiveDataType.java index d28b5c6..4fc3cb6 100644 --- a/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/PrimitiveDataType.java +++ b/data/data-base/src/main/java/com/syntaxphoenix/syntaxapi/data/PrimitiveDataType.java @@ -10,81 +10,81 @@ public class PrimitiveDataType

implements DataType { - public static final PrimitiveDataType BYTE = new PrimitiveDataType<>(Byte.class); - public static final PrimitiveDataType SHORT = new PrimitiveDataType<>(Short.class); - public static final PrimitiveDataType INTEGER = new PrimitiveDataType<>(Integer.class); - public static final PrimitiveDataType LONG = new PrimitiveDataType<>(Long.class); - - public static final PrimitiveDataType FLOAT = new PrimitiveDataType<>(Float.class); - public static final PrimitiveDataType DOUBLE = new PrimitiveDataType<>(Double.class); - - public static final PrimitiveDataType BIG_INTEGER = new PrimitiveDataType<>(BigInteger.class); - public static final PrimitiveDataType BIG_DECIMAL = new PrimitiveDataType<>(BigDecimal.class); - - public static final PrimitiveDataType BOOLEAN = new PrimitiveDataType<>(Boolean.class); - - public static final PrimitiveDataType STRING = new PrimitiveDataType<>(String.class); - - public static final PrimitiveDataType INT_ARRAY = new PrimitiveDataType<>(int[].class); - public static final PrimitiveDataType BYTE_ARRAY = new PrimitiveDataType<>(byte[].class); - public static final PrimitiveDataType LONG_ARRAY = new PrimitiveDataType<>(long[].class); - - public static final PrimitiveDataType DATA_HOLDER = new PrimitiveDataType<>(IDataContainer.class); - public static final PrimitiveDataType DATA_HOLDER_ARRAY = new PrimitiveDataType<>(IDataContainer[].class); - - public static final DataType[] PRIMITIVES = new PrimitiveDataType[] { - BYTE, - SHORT, - INTEGER, - LONG, - FLOAT, - DOUBLE, - BIG_INTEGER, - BIG_DECIMAL, - BOOLEAN, - STRING, - DATA_HOLDER, - DATA_HOLDER_ARRAY, - INT_ARRAY, - BYTE_ARRAY, - LONG_ARRAY - }; - - public static Optional> getPrimitive(Object object) { - Class clazz = Primitives.fromPrimitive(object.getClass()); - return Arrays.stream(PRIMITIVES).filter(type -> Objects.equals(clazz, type.getComplex())).findFirst(); - } - - /* - * - * - * - */ - - private final Class

primitiveType; - - private PrimitiveDataType(Class

primitiveType) { - this.primitiveType = primitiveType; - } - - @Override - public Class

getPrimitive() { - return primitiveType; - } - - @Override - public Class

getComplex() { - return primitiveType; - } - - @Override - public P toPrimitive(DataAdapterContext context, P complex) { - return complex; - } - - @Override - public P fromPrimitive(DataAdapterContext context, P primitive) { - return primitive; - } + public static final PrimitiveDataType BYTE = new PrimitiveDataType<>(Byte.class); + public static final PrimitiveDataType SHORT = new PrimitiveDataType<>(Short.class); + public static final PrimitiveDataType INTEGER = new PrimitiveDataType<>(Integer.class); + public static final PrimitiveDataType LONG = new PrimitiveDataType<>(Long.class); + + public static final PrimitiveDataType FLOAT = new PrimitiveDataType<>(Float.class); + public static final PrimitiveDataType DOUBLE = new PrimitiveDataType<>(Double.class); + + public static final PrimitiveDataType BIG_INTEGER = new PrimitiveDataType<>(BigInteger.class); + public static final PrimitiveDataType BIG_DECIMAL = new PrimitiveDataType<>(BigDecimal.class); + + public static final PrimitiveDataType BOOLEAN = new PrimitiveDataType<>(Boolean.class); + + public static final PrimitiveDataType STRING = new PrimitiveDataType<>(String.class); + + public static final PrimitiveDataType INT_ARRAY = new PrimitiveDataType<>(int[].class); + public static final PrimitiveDataType BYTE_ARRAY = new PrimitiveDataType<>(byte[].class); + public static final PrimitiveDataType LONG_ARRAY = new PrimitiveDataType<>(long[].class); + + public static final PrimitiveDataType DATA_HOLDER = new PrimitiveDataType<>(IDataContainer.class); + public static final PrimitiveDataType DATA_HOLDER_ARRAY = new PrimitiveDataType<>(IDataContainer[].class); + + public static final DataType[] PRIMITIVES = new PrimitiveDataType[] { + BYTE, + SHORT, + INTEGER, + LONG, + FLOAT, + DOUBLE, + BIG_INTEGER, + BIG_DECIMAL, + BOOLEAN, + STRING, + DATA_HOLDER, + DATA_HOLDER_ARRAY, + INT_ARRAY, + BYTE_ARRAY, + LONG_ARRAY + }; + + public static Optional> getPrimitive(Object object) { + Class clazz = Primitives.fromPrimitive(object.getClass()); + return Arrays.stream(PRIMITIVES).filter(type -> Objects.equals(clazz, type.getComplex())).findFirst(); + } + + /* + * + * + * + */ + + private final Class

primitiveType; + + private PrimitiveDataType(Class

primitiveType) { + this.primitiveType = primitiveType; + } + + @Override + public Class

getPrimitive() { + return primitiveType; + } + + @Override + public Class

getComplex() { + return primitiveType; + } + + @Override + public P toPrimitive(DataAdapterContext context, P complex) { + return complex; + } + + @Override + public P fromPrimitive(DataAdapterContext context, P primitive) { + return primitive; + } } diff --git a/data/data-nbtcontainer/pom.xml b/data/data-nbtcontainer/pom.xml index 21cc172..3798704 100644 --- a/data/data-nbtcontainer/pom.xml +++ b/data/data-nbtcontainer/pom.xml @@ -18,7 +18,7 @@ com.syntaxphoenix.syntaxapi data-base - 2.0.6 + 2.0.7 com.syntaxphoenix.syntaxapi diff --git a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapter.java b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapter.java index 0843677..a521467 100644 --- a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapter.java +++ b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapter.java @@ -9,200 +9,236 @@ import com.syntaxphoenix.syntaxapi.data.DataAdapter; import com.syntaxphoenix.syntaxapi.data.DataContainer; import com.syntaxphoenix.syntaxapi.data.IDataContainer; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigDecimal; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtByteArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtDouble; +import com.syntaxphoenix.syntaxapi.nbt.NbtFloat; +import com.syntaxphoenix.syntaxapi.nbt.NbtInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtIntArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtLong; +import com.syntaxphoenix.syntaxapi.nbt.NbtLongArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtShort; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; import com.syntaxphoenix.syntaxapi.utils.java.Primitives; public class NbtAdapter extends DataAdapter { - protected NbtAdapter(Class

primitiveType, Class resultType, Function builder, Function extractor) { - super(primitiveType, resultType, builder, extractor); - } - - @Override - public Class getBaseType() { - return NbtTag.class; - } - - /* - * - */ - - @SuppressWarnings({ - "rawtypes", - "unchecked" - }) - protected static DataAdapter createAdapter(NbtAdapterRegistry registry, Class type) { - type = Primitives.fromPrimitive(type); - - /* - * Numbers - */ - - if (Objects.equals(Boolean.class, type)) - return new NbtAdapter(Boolean.class, NbtByte.class, state -> new NbtByte((byte) (state ? 1 : 0)), - value -> value.getByteValue() == 1); - - if (Objects.equals(Byte.class, type)) - return new NbtAdapter(Byte.class, NbtByte.class, NbtByte::new, value -> value.getByteValue()); - - if (Objects.equals(Short.class, type)) - return new NbtAdapter(Short.class, NbtShort.class, NbtShort::new, value -> value.getShortValue()); - - if (Objects.equals(Integer.class, type)) - return new NbtAdapter(Integer.class, NbtInt.class, NbtInt::new, value -> value.getIntValue()); - - if (Objects.equals(Long.class, type)) - return new NbtAdapter(Long.class, NbtLong.class, NbtLong::new, value -> value.getLongValue()); - - if (Objects.equals(BigInteger.class, type)) - return new NbtAdapter(BigInteger.class, NbtBigInt.class, NbtBigInt::new, value -> value.getInteger()); - - if (Objects.equals(Float.class, type)) - return new NbtAdapter(Float.class, NbtFloat.class, NbtFloat::new, value -> value.getFloatValue()); - - if (Objects.equals(Double.class, type)) - return new NbtAdapter(Double.class, NbtDouble.class, NbtDouble::new, value -> value.getDoubleValue()); - - if (Objects.equals(BigDecimal.class, type)) - return new NbtAdapter(BigDecimal.class, NbtBigDecimal.class, NbtBigDecimal::new, value -> value.getDecimal()); - - /* - * String - */ - - if (Objects.equals(String.class, type)) - return new NbtAdapter(String.class, NbtString.class, NbtString::new, value -> value.getValue()); - - /* - * Number Arrays - */ - - if (Objects.equals(byte[].class, type)) - return new NbtAdapter(byte[].class, NbtByteArray.class, NbtByteArray::new, value -> value.getValue()); - - if (Objects.equals(int[].class, type)) - return new NbtAdapter(int[].class, NbtIntArray.class, NbtIntArray::new, value -> value.getValue()); - - if (Objects.equals(long[].class, type)) - return new NbtAdapter(long[].class, NbtLongArray.class, NbtLongArray::new, value -> value.getValue()); - - /* - * Complex Arrays - */ - - if (Objects.equals(IDataContainer[].class, type)) - return new NbtAdapter(IDataContainer[].class, NbtList.class, containers -> { - NbtList list = new NbtList<>(NbtType.COMPOUND); - for (IDataContainer container : containers) { - list.add(toNbtCompound(registry, container)); - } - return list; - }, list -> { - if (list.getElementType() != NbtType.COMPOUND) { - return new IDataContainer[0]; - } - NbtList nbtList = (NbtList) list; - ArrayList containers = new ArrayList<>(); - for (NbtTag tag : nbtList) { - containers.add(fromNbtCompound(registry, (NbtCompound) tag)); - } - return containers.toArray(new IDataContainer[0]); - }); - - if (Objects.equals(DataContainer[].class, type)) - return new NbtAdapter(DataContainer[].class, NbtList.class, containers -> { - NbtList list = new NbtList<>(NbtType.COMPOUND); - for (DataContainer container : containers) { - list.add(toNbtCompound(registry, container)); - } - return list; - }, list -> { - if (list.getElementType() != NbtType.COMPOUND) { - return new NbtContainer[0]; - } - NbtList nbtList = (NbtList) list; - ArrayList containers = new ArrayList<>(); - for (NbtTag tag : nbtList) { - containers.add(fromNbtCompound(registry, (NbtCompound) tag)); - } - return containers.toArray(new DataContainer[0]); - }); - - if (Objects.equals(NbtContainer[].class, type)) - return new NbtAdapter(NbtContainer[].class, NbtList.class, containers -> { - NbtList list = new NbtList<>(NbtType.COMPOUND); - for (NbtContainer container : containers) { - list.add(toNbtCompound(registry, container)); - } - return list; - }, list -> { - if (list.getElementType() != NbtType.COMPOUND) { - return new NbtContainer[0]; - } - NbtList nbtList = (NbtList) list; - ArrayList containers = new ArrayList<>(); - for (NbtTag tag : nbtList) { - containers.add(fromNbtCompound(registry, (NbtCompound) tag)); - } - return containers.toArray(new NbtContainer[0]); - }); - - /* - * Complex - */ - - if (Objects.equals(IDataContainer.class, type)) - return new NbtAdapter(IDataContainer.class, NbtCompound.class, container -> { - return toNbtCompound(registry, container); - }, compound -> { - return fromNbtCompound(registry, compound); - }); - - if (Objects.equals(DataContainer.class, type)) - return new NbtAdapter(DataContainer.class, NbtCompound.class, container -> { - return toNbtCompound(registry, container); - }, compound -> { - return fromNbtCompound(registry, compound); - }); - - if (Objects.equals(NbtContainer.class, type)) - return new NbtAdapter(NbtContainer.class, NbtCompound.class, container -> { - return toNbtCompound(registry, container); - }, compound -> { - return fromNbtCompound(registry, compound); - }); - - /* - * NbtTag - */ - - if (NbtTag.class.isAssignableFrom(type)) - return new NbtAdapter(NbtTag.class, NbtTag.class, tag -> tag, tag -> tag); - - return null; - } - - @SuppressWarnings({ - "unchecked", - "rawtypes" - }) - private static NbtCompound toNbtCompound(NbtAdapterRegistry registry, IDataContainer container) { - if (container instanceof NbtContainer) { - return ((NbtContainer) container).getRoot().clone(); - } - NbtCompound compound = new NbtCompound(); - for (String key : container.getKeyspaces()) { - Object object = container.get(key); - NbtTag tag = registry.wrap((Class) object.getClass(), object); - if (tag != null) { - compound.set(key, tag); - } - } - return compound; - } - - private static NbtContainer fromNbtCompound(NbtAdapterRegistry registry, NbtCompound compound) { - return new NbtContainer(compound.clone(), registry); - } + protected NbtAdapter(Class

primitiveType, Class resultType, Function builder, Function extractor) { + super(primitiveType, resultType, builder, extractor); + } + + @Override + public Class getBaseType() { + return NbtTag.class; + } + + /* + * + */ + + @SuppressWarnings({ + "rawtypes", + "unchecked" + }) + protected static DataAdapter createAdapter(NbtAdapterRegistry registry, Class type) { + type = Primitives.fromPrimitive(type); + + /* + * Numbers + */ + + if (Objects.equals(Boolean.class, type)) { + return new NbtAdapter(Boolean.class, NbtByte.class, state -> new NbtByte((byte) (state ? 1 : 0)), + value -> value.getByteValue() == 1); + } + + if (Objects.equals(Byte.class, type)) { + return new NbtAdapter(Byte.class, NbtByte.class, NbtByte::new, value -> value.getByteValue()); + } + + if (Objects.equals(Short.class, type)) { + return new NbtAdapter(Short.class, NbtShort.class, NbtShort::new, value -> value.getShortValue()); + } + + if (Objects.equals(Integer.class, type)) { + return new NbtAdapter(Integer.class, NbtInt.class, NbtInt::new, value -> value.getIntValue()); + } + + if (Objects.equals(Long.class, type)) { + return new NbtAdapter(Long.class, NbtLong.class, NbtLong::new, value -> value.getLongValue()); + } + + if (Objects.equals(BigInteger.class, type)) { + return new NbtAdapter(BigInteger.class, NbtBigInt.class, NbtBigInt::new, value -> value.getInteger()); + } + + if (Objects.equals(Float.class, type)) { + return new NbtAdapter(Float.class, NbtFloat.class, NbtFloat::new, value -> value.getFloatValue()); + } + + if (Objects.equals(Double.class, type)) { + return new NbtAdapter(Double.class, NbtDouble.class, NbtDouble::new, value -> value.getDoubleValue()); + } + + if (Objects.equals(BigDecimal.class, type)) { + return new NbtAdapter(BigDecimal.class, NbtBigDecimal.class, NbtBigDecimal::new, + value -> value.getDecimal()); + } + + /* + * String + */ + + if (Objects.equals(String.class, type)) { + return new NbtAdapter(String.class, NbtString.class, NbtString::new, value -> value.getValue()); + } + + /* + * Number Arrays + */ + + if (Objects.equals(byte[].class, type)) { + return new NbtAdapter(byte[].class, NbtByteArray.class, NbtByteArray::new, value -> value.getValue()); + } + + if (Objects.equals(int[].class, type)) { + return new NbtAdapter(int[].class, NbtIntArray.class, NbtIntArray::new, value -> value.getValue()); + } + + if (Objects.equals(long[].class, type)) { + return new NbtAdapter(long[].class, NbtLongArray.class, NbtLongArray::new, value -> value.getValue()); + } + + /* + * Complex Arrays + */ + + if (Objects.equals(IDataContainer[].class, type)) { + return new NbtAdapter(IDataContainer[].class, NbtList.class, containers -> { + NbtList list = new NbtList<>(NbtType.COMPOUND); + for (IDataContainer container : containers) { + list.add(toNbtCompound(registry, container)); + } + return list; + }, list -> { + if (list.getElementType() != NbtType.COMPOUND) { + return new IDataContainer[0]; + } + NbtList nbtList = list; + ArrayList containers = new ArrayList<>(); + for (NbtTag tag : nbtList) { + containers.add(fromNbtCompound(registry, (NbtCompound) tag)); + } + return containers.toArray(new IDataContainer[0]); + }); + } + + if (Objects.equals(DataContainer[].class, type)) { + return new NbtAdapter(DataContainer[].class, NbtList.class, containers -> { + NbtList list = new NbtList<>(NbtType.COMPOUND); + for (DataContainer container : containers) { + list.add(toNbtCompound(registry, container)); + } + return list; + }, list -> { + if (list.getElementType() != NbtType.COMPOUND) { + return new NbtContainer[0]; + } + NbtList nbtList = list; + ArrayList containers = new ArrayList<>(); + for (NbtTag tag : nbtList) { + containers.add(fromNbtCompound(registry, (NbtCompound) tag)); + } + return containers.toArray(new DataContainer[0]); + }); + } + + if (Objects.equals(NbtContainer[].class, type)) { + return new NbtAdapter(NbtContainer[].class, NbtList.class, containers -> { + NbtList list = new NbtList<>(NbtType.COMPOUND); + for (NbtContainer container : containers) { + list.add(toNbtCompound(registry, container)); + } + return list; + }, list -> { + if (list.getElementType() != NbtType.COMPOUND) { + return new NbtContainer[0]; + } + NbtList nbtList = list; + ArrayList containers = new ArrayList<>(); + for (NbtTag tag : nbtList) { + containers.add(fromNbtCompound(registry, (NbtCompound) tag)); + } + return containers.toArray(new NbtContainer[0]); + }); + } + + /* + * Complex + */ + + if (Objects.equals(IDataContainer.class, type)) { + return new NbtAdapter(IDataContainer.class, NbtCompound.class, container -> { + return toNbtCompound(registry, container); + }, compound -> { + return fromNbtCompound(registry, compound); + }); + } + + if (Objects.equals(DataContainer.class, type)) { + return new NbtAdapter(DataContainer.class, NbtCompound.class, container -> { + return toNbtCompound(registry, container); + }, compound -> { + return fromNbtCompound(registry, compound); + }); + } + + if (Objects.equals(NbtContainer.class, type)) { + return new NbtAdapter(NbtContainer.class, NbtCompound.class, container -> { + return toNbtCompound(registry, container); + }, compound -> { + return fromNbtCompound(registry, compound); + }); + } + + /* + * NbtTag + */ + + if (NbtTag.class.isAssignableFrom(type)) { + return new NbtAdapter(NbtTag.class, NbtTag.class, tag -> tag, tag -> tag); + } + + return null; + } + + @SuppressWarnings({ + "unchecked", + "rawtypes" + }) + private static NbtCompound toNbtCompound(NbtAdapterRegistry registry, IDataContainer container) { + if (container instanceof NbtContainer) { + return ((NbtContainer) container).getRoot().clone(); + } + NbtCompound compound = new NbtCompound(); + for (String key : container.getKeyspaces()) { + Object object = container.get(key); + NbtTag tag = registry.wrap((Class) object.getClass(), object); + if (tag != null) { + compound.set(key, tag); + } + } + return compound; + } + + private static NbtContainer fromNbtCompound(NbtAdapterRegistry registry, NbtCompound compound) { + return new NbtContainer(compound.clone(), registry); + } } diff --git a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapterRegistry.java b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapterRegistry.java index 1d65ab2..bd4ea26 100644 --- a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapterRegistry.java +++ b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtAdapterRegistry.java @@ -8,20 +8,20 @@ public class NbtAdapterRegistry extends DataAdapterRegistry { - public Object extract(NbtTag base) { - return extract(base.getType().getOwningClass(), base); - } + public Object extract(NbtTag base) { + return extract(base.getType().getOwningClass(), base); + } - @Override - protected NbtAdapter createAdapter(Class primitiveType, Class resultType, Function builder, - Function extractor) { - return new NbtAdapter<>(primitiveType, resultType, builder, extractor); - } + @Override + protected NbtAdapter createAdapter(Class primitiveType, Class resultType, Function builder, + Function extractor) { + return new NbtAdapter<>(primitiveType, resultType, builder, extractor); + } - @SuppressWarnings("unchecked") - @Override - protected DataAdapter buildAdapter(Class clazz) { - return (DataAdapter) NbtAdapter.createAdapter(this, clazz); - } + @SuppressWarnings("unchecked") + @Override + protected DataAdapter buildAdapter(Class clazz) { + return (DataAdapter) NbtAdapter.createAdapter(this, clazz); + } } diff --git a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtContainer.java b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtContainer.java index 14a40e1..c71e2bf 100644 --- a/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtContainer.java +++ b/data/data-nbtcontainer/src/main/java/com/syntaxphoenix/syntaxapi/data/container/nbt/NbtContainer.java @@ -12,91 +12,94 @@ public class NbtContainer extends DataContainer implements DataAdapterContext, NbtStorage { - private final NbtCompound root; - - private final NbtAdapterRegistry registry; - - public NbtContainer(NbtAdapterRegistry registry) { - this(new NbtCompound(), registry); - } - - protected NbtContainer(NbtCompound root, NbtAdapterRegistry registry) { - this.root = root; - this.registry = registry; - } - - @Override - public NbtContainer newDataContainer() { - return new NbtContainer(registry); - } - - @Override - public DataAdapterContext getAdapterContext() { - return this; - } - - public NbtAdapterRegistry getAdapterRegistry() { - return registry; - } - - public NbtCompound getRoot() { - return root; - } - - @Override - public Object get(String key) { - NbtTag tag = root.get(key); - if (tag == null) - return tag; - return registry.extract(tag); - } - - public void set(String key, NbtTag tag) { - if (tag == null) - return; - root.set(key, tag); - } - - @SuppressWarnings("unchecked") - public void set(String key, Object object) { - set(key, registry.wrap(Primitives.fromPrimitive((Class) object.getClass()), object)); - } - - @Override - public void set(String key, E value, DataType type) { - set(key, registry.wrap(type.getPrimitive(), type.toPrimitive(getAdapterContext(), value))); - } - - @Override - public boolean remove(String key) { - return root.remove(key) != null; - } - - @Override - public Set getKeyspaces() { - return root.getKeys(); - } - - @Override - public boolean isEmpty() { - return root.isEmpty(); - } - - @Override - public int size() { - return root.size(); - } - - @Override - public void fromNbt(NbtCompound nbt) { - root.clear(); - for (String key : nbt.getKeys()) - root.set(key, nbt.get(key)); - } - - @Override - public NbtCompound asNbt() { - return root.clone(); - } + private final NbtCompound root; + + private final NbtAdapterRegistry registry; + + public NbtContainer(NbtAdapterRegistry registry) { + this(new NbtCompound(), registry); + } + + protected NbtContainer(NbtCompound root, NbtAdapterRegistry registry) { + this.root = root; + this.registry = registry; + } + + @Override + public NbtContainer newDataContainer() { + return new NbtContainer(registry); + } + + @Override + public DataAdapterContext getAdapterContext() { + return this; + } + + public NbtAdapterRegistry getAdapterRegistry() { + return registry; + } + + public NbtCompound getRoot() { + return root; + } + + @Override + public Object get(String key) { + NbtTag tag = root.get(key); + if (tag == null) { + return tag; + } + return registry.extract(tag); + } + + public void set(String key, NbtTag tag) { + if (tag == null) { + return; + } + root.set(key, tag); + } + + @SuppressWarnings("unchecked") + public void set(String key, Object object) { + set(key, registry.wrap(Primitives.fromPrimitive((Class) object.getClass()), object)); + } + + @Override + public void set(String key, E value, DataType type) { + set(key, registry.wrap(type.getPrimitive(), type.toPrimitive(getAdapterContext(), value))); + } + + @Override + public boolean remove(String key) { + return root.remove(key) != null; + } + + @Override + public Set getKeyspaces() { + return root.getKeys(); + } + + @Override + public boolean isEmpty() { + return root.isEmpty(); + } + + @Override + public int size() { + return root.size(); + } + + @Override + public void fromNbt(NbtCompound nbt) { + root.clear(); + for (String key : nbt.getKeys()) { + root.set(key, nbt.get(key)); + } + } + + @Override + public NbtCompound asNbt() { + return root.clone(); + } } diff --git a/data/data-nbtcontainer/src/test/java/com/syntaxphoenix/syntaxapi/data/test/ContainerTest.java b/data/data-nbtcontainer/src/test/java/com/syntaxphoenix/syntaxapi/data/test/ContainerTest.java index f4dae9b..aa9ebb0 100644 --- a/data/data-nbtcontainer/src/test/java/com/syntaxphoenix/syntaxapi/data/test/ContainerTest.java +++ b/data/data-nbtcontainer/src/test/java/com/syntaxphoenix/syntaxapi/data/test/ContainerTest.java @@ -7,33 +7,33 @@ public class ContainerTest { - @Test - public void testData() { + @Test + public void testData() { - NbtAdapterRegistry registry = new NbtAdapterRegistry(); + NbtAdapterRegistry registry = new NbtAdapterRegistry(); - NbtContainer container = new NbtContainer(registry); + NbtContainer container = new NbtContainer(registry); - container.set(int.class.getSimpleName(), 9350485); - container.set(long.class.getSimpleName(), 93504850000000000L); - container.set(float.class.getSimpleName(), 9350485.45658F); - container.set(double.class.getSimpleName(), 93504850000.5465886456454864D); + container.set(int.class.getSimpleName(), 9350485); + container.set(long.class.getSimpleName(), 93504850000000000L); + container.set(float.class.getSimpleName(), 9350485.45658F); + container.set(double.class.getSimpleName(), 93504850000.5465886456454864D); - container.set(boolean.class.getSimpleName(), true); - container.set(String.class.getSimpleName(), "nice"); + container.set(boolean.class.getSimpleName(), true); + container.set(String.class.getSimpleName(), "nice"); - print(container, int.class); - print(container, long.class); - print(container, float.class); - print(container, double.class); + print(container, int.class); + print(container, long.class); + print(container, float.class); + print(container, double.class); - print(container, boolean.class); - print(container, String.class); + print(container, boolean.class); + print(container, String.class); - } + } - private void print(NbtContainer container, Class clazz) { - System.out.println(clazz.getSimpleName() + " => " + container.get(clazz.getSimpleName())); - } + private void print(NbtContainer container, Class clazz) { + System.out.println(clazz.getSimpleName() + " => " + container.get(clazz.getSimpleName())); + } } diff --git a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/AbstractProperties.java b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/AbstractProperties.java index 098207c..9dd0a8b 100644 --- a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/AbstractProperties.java +++ b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/AbstractProperties.java @@ -5,97 +5,97 @@ public abstract class AbstractProperties { - private final ArrayList> properties = new ArrayList<>(); - - public void setProperties(Property... properties) { - clearProperties(); - for (Property property : properties) { - setProperty(property); - } - } - - public void setProperty(Property property) { - Property remove; - if ((remove = findProperty(property.getKey())) != null) { - properties.remove(remove); - } - properties.add(property); - } - - public void addProperties(Property... properties) { - for (Property property : properties) { - addProperty(property); - } - } - - public void addProperty(Property property) { - if (!containsProperty(property.getKey())) { - properties.add(property); - } - } - - public void removeProperties(String... keys) { - for (String key : keys) { - removeProperty(key); - } - } - - public boolean removeProperty(String key) { - if (properties.isEmpty()) { - return false; - } - Optional> optional = properties.stream().filter(property -> property.getKey().equals(key)).findFirst(); - if (optional.isPresent()) { - return properties.remove(optional.get()); - } - return false; - } - - public Property findProperty(String key) { - if (properties.isEmpty()) { - return null; - } - Optional> optional = properties.stream().filter(property -> property.getKey().equals(key)).findFirst(); - if (optional.isPresent()) { - return optional.get(); - } - return null; - } - - public ArrayList> findProperties(String... keys) { - ArrayList> properties = new ArrayList<>(); - for (String key : keys) { - Property property; - if ((property = findProperty(key)) != null) { - properties.add(property); - } - } - return properties; - } - - public void clearProperties() { - properties.clear(); - } - - public boolean containsProperty(String key) { - return properties.stream().anyMatch(property -> property.getKey().equals(key)); - } - - public int getPropertyCount() { - return properties.size(); - } - - public boolean hasProperties() { - return !properties.isEmpty(); - } - - public Property[] getProperties() { - return properties.toArray(new Property[0]); - } - - /* - * - */ + private final ArrayList> properties = new ArrayList<>(); + + public void setProperties(Property... properties) { + clearProperties(); + for (Property property : properties) { + setProperty(property); + } + } + + public void setProperty(Property property) { + Property remove; + if ((remove = findProperty(property.getKey())) != null) { + properties.remove(remove); + } + properties.add(property); + } + + public void addProperties(Property... properties) { + for (Property property : properties) { + addProperty(property); + } + } + + public void addProperty(Property property) { + if (!containsProperty(property.getKey())) { + properties.add(property); + } + } + + public void removeProperties(String... keys) { + for (String key : keys) { + removeProperty(key); + } + } + + public boolean removeProperty(String key) { + if (properties.isEmpty()) { + return false; + } + Optional> optional = properties.stream().filter(property -> property.getKey().equals(key)).findFirst(); + if (optional.isPresent()) { + return properties.remove(optional.get()); + } + return false; + } + + public Property findProperty(String key) { + if (properties.isEmpty()) { + return null; + } + Optional> optional = properties.stream().filter(property -> property.getKey().equals(key)).findFirst(); + if (optional.isPresent()) { + return optional.get(); + } + return null; + } + + public ArrayList> findProperties(String... keys) { + ArrayList> properties = new ArrayList<>(); + for (String key : keys) { + Property property; + if ((property = findProperty(key)) != null) { + properties.add(property); + } + } + return properties; + } + + public void clearProperties() { + properties.clear(); + } + + public boolean containsProperty(String key) { + return properties.stream().anyMatch(property -> property.getKey().equals(key)); + } + + public int getPropertyCount() { + return properties.size(); + } + + public boolean hasProperties() { + return !properties.isEmpty(); + } + + public Property[] getProperties() { + return properties.toArray(new Property[0]); + } + + /* + * + */ // @Override // public NbtCompound asNbt() { diff --git a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Properties.java b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Properties.java index e92b4eb..5fd597b 100644 --- a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Properties.java +++ b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Properties.java @@ -8,6 +8,6 @@ */ public class Properties extends AbstractProperties implements Serializable { - private static final long serialVersionUID = 5806508173901340453L; + private static final long serialVersionUID = 5806508173901340453L; } \ No newline at end of file diff --git a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Property.java b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Property.java index 8e23e8f..4e9507c 100644 --- a/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Property.java +++ b/data/data-property/src/main/java/com/syntaxphoenix/syntaxapi/data/property/Property.java @@ -9,89 +9,89 @@ */ public class Property implements Serializable { - private static final long serialVersionUID = 8586167622486650403L; - private static final transient HashMap, Class> PRIMITIVE_OBJECT_TYPES = new HashMap<>(); - - static { - PRIMITIVE_OBJECT_TYPES.put(byte.class, Byte.class); - PRIMITIVE_OBJECT_TYPES.put(short.class, Short.class); - PRIMITIVE_OBJECT_TYPES.put(int.class, Integer.class); - PRIMITIVE_OBJECT_TYPES.put(long.class, Long.class); - PRIMITIVE_OBJECT_TYPES.put(float.class, Float.class); - PRIMITIVE_OBJECT_TYPES.put(double.class, Double.class); - PRIMITIVE_OBJECT_TYPES.put(boolean.class, Boolean.class); - } - - /* - * - */ - - private String key; - private E value; - - public Property(String key, E value) { - this.key = key; - this.value = value; - } - - @SuppressWarnings("unchecked") - public Property tryParse(Class clz) { - if (instanceOf(clz)) { - return (Property) this; - } else if (PRIMITIVE_OBJECT_TYPES.containsKey(clz)) { - Class clazz = PRIMITIVE_OBJECT_TYPES.get(clz); - if (instanceOf(clazz)) { - return (Property) this; - } - } - return null; - } - - public Property parseString() { - Property output; - if ((output = tryParse(String.class)) == null) { - output = new Property(key, value.toString()); - } - return output; - } - - public boolean instanceOf(Class clz) { - return clz.isInstance(value); - } - - public boolean isSerializable() { - return value.getClass().isAssignableFrom(Serializable.class); - } - - public String getHolderKey() { - return "%" + key + "%"; - } - - public String getKey() { - return key; - } - - @SuppressWarnings("unchecked") - public Class getValueOwner() { - return (Class) value.getClass(); - } - - public E getValue() { - return value; - } - - /* - * - * Creation - * - */ - - public static Property createObject(String key, Object value) { - return new Property(key, value); - } - - public static Property create(String key, T value) { - return new Property(key, value); - } + private static final long serialVersionUID = 8586167622486650403L; + private static final transient HashMap, Class> PRIMITIVE_OBJECT_TYPES = new HashMap<>(); + + static { + PRIMITIVE_OBJECT_TYPES.put(byte.class, Byte.class); + PRIMITIVE_OBJECT_TYPES.put(short.class, Short.class); + PRIMITIVE_OBJECT_TYPES.put(int.class, Integer.class); + PRIMITIVE_OBJECT_TYPES.put(long.class, Long.class); + PRIMITIVE_OBJECT_TYPES.put(float.class, Float.class); + PRIMITIVE_OBJECT_TYPES.put(double.class, Double.class); + PRIMITIVE_OBJECT_TYPES.put(boolean.class, Boolean.class); + } + + /* + * + */ + + private String key; + private E value; + + public Property(String key, E value) { + this.key = key; + this.value = value; + } + + @SuppressWarnings("unchecked") + public Property tryParse(Class clz) { + if (instanceOf(clz)) { + return (Property) this; + } else if (PRIMITIVE_OBJECT_TYPES.containsKey(clz)) { + Class clazz = PRIMITIVE_OBJECT_TYPES.get(clz); + if (instanceOf(clazz)) { + return (Property) this; + } + } + return null; + } + + public Property parseString() { + Property output; + if ((output = tryParse(String.class)) == null) { + output = new Property(key, value.toString()); + } + return output; + } + + public boolean instanceOf(Class clz) { + return clz.isInstance(value); + } + + public boolean isSerializable() { + return value.getClass().isAssignableFrom(Serializable.class); + } + + public String getHolderKey() { + return "%" + key + "%"; + } + + public String getKey() { + return key; + } + + @SuppressWarnings("unchecked") + public Class getValueOwner() { + return (Class) value.getClass(); + } + + public E getValue() { + return value; + } + + /* + * + * Creation + * + */ + + public static Property createObject(String key, Object value) { + return new Property(key, value); + } + + public static Property create(String key, T value) { + return new Property(key, value); + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Cancelable.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Cancelable.java index c0f62a8..62f5097 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Cancelable.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Cancelable.java @@ -6,8 +6,8 @@ */ public interface Cancelable { - public boolean isCancelled(); + public boolean isCancelled(); - public void setCancelled(boolean cancelled); + public void setCancelled(boolean cancelled); } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Event.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Event.java index 1085653..658bbc3 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Event.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/Event.java @@ -6,8 +6,8 @@ */ public abstract class Event { - public boolean isCancelable() { - return this instanceof Cancelable; - } + public boolean isCancelable() { + return this instanceof Cancelable; + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventAnalyser.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventAnalyser.java index 11ea849..7f93807 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventAnalyser.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventAnalyser.java @@ -8,48 +8,48 @@ public final class EventAnalyser { - private final EventListener listener; - private final AbstractReflect reflect; - - public EventAnalyser(EventListener listener) { - this.listener = listener; - this.reflect = new Reflect(listener.getClass()).searchMethodsByArguments("event", Event.class); - } - - public AbstractReflect getReflect() { - return reflect; - } - - public EventListener getListener() { - return listener; - } - - @SuppressWarnings("unchecked") - protected int registerEvents(EventManager manager) { - String base = "event-"; - int current = 0; - String name; - HashMap, EventExecutor> executors = new HashMap<>(); - while (reflect.containsMethod(name = (base + current))) { - current++; - Method method = reflect.getMethod(name); - EventHandler handler; - try { - handler = method.getAnnotation(EventHandler.class); - } catch (NullPointerException e) { - manager.getLogger().log(e); - continue; - } - Class clazz = (Class) method.getParameterTypes()[0]; - if (executors.containsKey(clazz)) { - executors.get(clazz).add(handler.priority(), new EventMethod(listener, method, handler.ignoreCancel())); - } else { - executors - .put(clazz, new EventExecutor(manager, listener, clazz).add(handler.priority(), new EventMethod(listener, method, handler.ignoreCancel()))); - } - } - manager.registerExecutors(executors.values()); - return current; - } + private final EventListener listener; + private final AbstractReflect reflect; + + public EventAnalyser(EventListener listener) { + this.listener = listener; + this.reflect = new Reflect(listener.getClass()).searchMethodsByArguments("event", Event.class); + } + + public AbstractReflect getReflect() { + return reflect; + } + + public EventListener getListener() { + return listener; + } + + @SuppressWarnings("unchecked") + protected int registerEvents(EventManager manager) { + String base = "event-"; + int current = 0; + String name; + HashMap, EventExecutor> executors = new HashMap<>(); + while (reflect.containsMethod(name = (base + current))) { + current++; + Method method = reflect.getMethod(name); + EventHandler handler; + try { + handler = method.getAnnotation(EventHandler.class); + } catch (NullPointerException e) { + manager.getLogger().log(e); + continue; + } + Class clazz = (Class) method.getParameterTypes()[0]; + if (executors.containsKey(clazz)) { + executors.get(clazz).add(handler.priority(), new EventMethod(listener, method, handler.ignoreCancel())); + } else { + executors.put(clazz, new EventExecutor(manager, listener, clazz).add(handler.priority(), + new EventMethod(listener, method, handler.ignoreCancel()))); + } + } + manager.registerExecutors(executors.values()); + return current; + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventCall.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventCall.java index 10f6230..55251c7 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventCall.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventCall.java @@ -11,128 +11,129 @@ public final class EventCall { - private final List executors; - private final EventManager manager; - private final Event event; + private final List executors; + private final EventManager manager; + private final Event event; - public EventCall(EventManager manager, Event event, List executors) { - this.executors = executors; - this.manager = manager; - this.event = event; + public EventCall(EventManager manager, Event event, List executors) { + this.executors = executors; + this.manager = manager; + this.event = event; - Collections.sort(executors); - } + Collections.sort(executors); + } - public final EventManager getManager() { - return manager; - } + public final EventManager getManager() { + return manager; + } - public final Event getEvent() { - return event; - } + public final Event getEvent() { + return event; + } - public final List getExecutors() { - return executors; - } + public final List getExecutors() { + return executors; + } - public Status execute() { - int count = 0; - if (executors.isEmpty()) { - Status status = new Status(count); - status.done(); - return status; - } - LinkedHashMap> listeners = new LinkedHashMap<>(); - for (EventPriority priority : EventPriority.values()) { - ArrayList methods = new ArrayList<>(); - for (EventExecutor executor : executors) { - methods.addAll(executor.getMethodsByPriority(priority)); - } - count += methods.size(); - listeners.put(priority, methods); - } - Status result = new Status(count); - return event instanceof Cancelable ? callCancelable(result, listeners) : call(result, listeners); - } + public Status execute() { + int count = 0; + if (executors.isEmpty()) { + Status status = new Status(count); + status.done(); + return status; + } + LinkedHashMap> listeners = new LinkedHashMap<>(); + for (EventPriority priority : EventPriority.values()) { + ArrayList methods = new ArrayList<>(); + for (EventExecutor executor : executors) { + methods.addAll(executor.getMethodsByPriority(priority)); + } + count += methods.size(); + listeners.put(priority, methods); + } + Status result = new Status(count); + return event instanceof Cancelable ? callCancelable(result, listeners) : call(result, listeners); + } - public Status executeAsync(ExecutorService service) { - int count = 0; - if (executors.isEmpty()) { - Status status = new Status(count); - status.done(); - return status; - } - LinkedHashMap> listeners = new LinkedHashMap<>(); - for (EventPriority priority : EventPriority.values()) { - ArrayList methods = new ArrayList<>(); - for (EventExecutor executor : executors) { - methods.addAll(executor.getMethodsByPriority(priority)); - } - count += methods.size(); - listeners.put(priority, methods); - } + public Status executeAsync(ExecutorService service) { + int count = 0; + if (executors.isEmpty()) { + Status status = new Status(count); + status.done(); + return status; + } + LinkedHashMap> listeners = new LinkedHashMap<>(); + for (EventPriority priority : EventPriority.values()) { + ArrayList methods = new ArrayList<>(); + for (EventExecutor executor : executors) { + methods.addAll(executor.getMethodsByPriority(priority)); + } + count += methods.size(); + listeners.put(priority, methods); + } - Status result = new Status(count); - service.submit(() -> { - if (event instanceof Cancelable) - callCancelable(result, listeners); - else - call(result, listeners); - }); - return result; - } + Status result = new Status(count); + service.submit(() -> { + if (event instanceof Cancelable) { + callCancelable(result, listeners); + } else { + call(result, listeners); + } + }); + return result; + } - private Status callCancelable(Status result, LinkedHashMap> listeners) { - Cancelable cancel = (Cancelable) event; - for (EventPriority priority : EventPriority.ORDERED_VALUES) { - ArrayList methods = listeners.get(priority); - if (methods.isEmpty()) { - continue; - } - for (EventMethod method : methods) { - if (cancel.isCancelled() && !method.ignoresCancel()) { - result.cancel(); - continue; - } - try { - method.execute(event); - result.success(); - } catch (Throwable throwable) { - result.failed(); - if (manager.hasLogger()) { - manager.getLogger().log(throwable); - } else { - System.out.println(Exceptions.stackTraceToString(throwable)); - } - } - } - } - result.done(); - return result; - } + private Status callCancelable(Status result, LinkedHashMap> listeners) { + Cancelable cancel = (Cancelable) event; + for (EventPriority priority : EventPriority.ORDERED_VALUES) { + ArrayList methods = listeners.get(priority); + if (methods.isEmpty()) { + continue; + } + for (EventMethod method : methods) { + if (cancel.isCancelled() && !method.ignoresCancel()) { + result.cancel(); + continue; + } + try { + method.execute(event); + result.success(); + } catch (Throwable throwable) { + result.failed(); + if (manager.hasLogger()) { + manager.getLogger().log(throwable); + } else { + System.out.println(Exceptions.stackTraceToString(throwable)); + } + } + } + } + result.done(); + return result; + } - private Status call(Status result, LinkedHashMap> listeners) { - for (EventPriority priority : EventPriority.ORDERED_VALUES) { - ArrayList methods = listeners.get(priority); - if (methods.isEmpty()) { - continue; - } - for (EventMethod method : methods) { - try { - method.execute(event); - result.success(); - } catch (Throwable throwable) { - result.failed(); - if (manager.hasLogger()) { - manager.getLogger().log(throwable); - } else { - System.out.println(Exceptions.stackTraceToString(throwable)); - } - } - } - } - result.done(); - return result; - } + private Status call(Status result, LinkedHashMap> listeners) { + for (EventPriority priority : EventPriority.ORDERED_VALUES) { + ArrayList methods = listeners.get(priority); + if (methods.isEmpty()) { + continue; + } + for (EventMethod method : methods) { + try { + method.execute(event); + result.success(); + } catch (Throwable throwable) { + result.failed(); + if (manager.hasLogger()) { + manager.getLogger().log(throwable); + } else { + System.out.println(Exceptions.stackTraceToString(throwable)); + } + } + } + } + result.done(); + return result; + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventExecutor.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventExecutor.java index 8d4213f..6273207 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventExecutor.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventExecutor.java @@ -7,73 +7,75 @@ public final class EventExecutor implements Comparable { - private final EnumMap> methods = new EnumMap<>(EventPriority.class); - private final Class event; - private final EventListener listener; - private final EventManager manager; + private final EnumMap> methods = new EnumMap<>(EventPriority.class); + private final Class event; + private final EventListener listener; + private final EventManager manager; - public EventExecutor(EventManager manager, EventListener listener, Class event) { - this.listener = listener; - this.manager = manager; - this.event = event; - } + public EventExecutor(EventManager manager, EventListener listener, Class event) { + this.listener = listener; + this.manager = manager; + this.event = event; + } - /* - * - */ + /* + * + */ - public final EventManager getManager() { - return manager; - } + public final EventManager getManager() { + return manager; + } - public final EventListener getListener() { - return listener; - } + public final EventListener getListener() { + return listener; + } - public final Class getEvent() { - return event; - } + public final Class getEvent() { + return event; + } - /* - * - */ + /* + * + */ - protected EventExecutor add(EventPriority priority, EventMethod method) { - ArrayList list = methods.get(priority); - if (list == null) { - methods.put(priority, list = new ArrayList<>()); - } else if (list.contains(method)) { - return this; - } - list.add(method); - return this; - } + protected EventExecutor add(EventPriority priority, EventMethod method) { + ArrayList list = methods.get(priority); + if (list == null) { + methods.put(priority, list = new ArrayList<>()); + } else if (list.contains(method)) { + return this; + } + list.add(method); + return this; + } - public List getMethodsByPriority(EventPriority priority) { - if (!methods.containsKey(priority)) { - return Collections.emptyList(); - } - return Collections.unmodifiableList(methods.get(priority)); - } + public List getMethodsByPriority(EventPriority priority) { + if (!methods.containsKey(priority)) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(methods.get(priority)); + } - public List getMethods() { - ArrayList output = new ArrayList<>(); - methods.forEach((priority, list) -> output.addAll(list)); - return output; - } + public List getMethods() { + ArrayList output = new ArrayList<>(); + methods.forEach((priority, list) -> output.addAll(list)); + return output; + } - /* - * - */ + /* + * + */ - @Override - public int compareTo(EventExecutor o) { - Class other = o.getEvent(); - if (event.equals(other)) - return 0; - if (event.isAssignableFrom(other)) - return -1; - return 1; - } + @Override + public int compareTo(EventExecutor o) { + Class other = o.getEvent(); + if (event.equals(other)) { + return 0; + } + if (event.isAssignableFrom(other)) { + return -1; + } + return 1; + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventHandler.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventHandler.java index c942107..305f131 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventHandler.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventHandler.java @@ -10,8 +10,8 @@ @Target(METHOD) public @interface EventHandler { - EventPriority priority() default EventPriority.NORMAL; + EventPriority priority() default EventPriority.NORMAL; - boolean ignoreCancel() default false; + boolean ignoreCancel() default false; } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventManager.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventManager.java index 5f23cc5..ceebf15 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventManager.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventManager.java @@ -21,217 +21,222 @@ public class EventManager { - private final LinkedHashMap, ArrayList> listeners = new LinkedHashMap<>(); - private final ILogger logger; - - private final ExecutorService service; - - public EventManager() { - this(null, null); - } - - public EventManager(ExecutorService service) { - this(null, service); - } - - public EventManager(ILogger logger) { - this(logger, null); - } - - public EventManager(ILogger logger, ExecutorService service) { - this.logger = logger; - this.service = service; - } - - /* - * Getter / Infos - */ - - public boolean hasLogger() { - return logger != null; - } - - public ILogger getLogger() { - return logger; - } - - public boolean isAsync() { - return service != null; - } - - public ExecutorService getExecutorService() { - return service; - } - - /* - * Event calls - */ - - public EventCall generateCall(Event event) { - return new EventCall(this, event, getExecutorsForEvent(event.getClass(), true)); - } - - public Status call(Event event) { - return call(generateCall(event)); - } - - public Status call(EventCall call) { - if (isAsync()) - return call.executeAsync(service); - else - return call.execute(); - } - - public Status callAsync(Event event, ExecutorService service) { - return callAsync(generateCall(event), service); - } - - public Status callAsync(EventCall call, ExecutorService service) { - return call.executeAsync(service); - } - - /* - * Registration - */ - - // Register - - public EventManager registerEvents(EventListener listener) { - EventAnalyser analyser = new EventAnalyser(listener); - analyser.registerEvents(this); - return this; - } - - public EventManager registerEvent(EventMethod method) { - if (!method.isValid()) { - return this; - } - EventExecutor executor = new EventExecutor(this, method.getListener(), method.getEvent()); - executor.add(method.hasEventHandler() ? method.getHandler().priority() : EventPriority.NORMAL, method); - registerExecutor(executor); - return this; - } - - public EventManager registerExecutors(Collection executors) { - executors.forEach(executor -> registerExecutor(executor)); - return this; - } - - public EventManager registerExecutor(EventExecutor executor) { - if (executor == null || executor.getMethods().isEmpty()) { - return this; - } - Class event = executor.getEvent(); - if (listeners.containsKey(event)) { - ArrayList executors = listeners.get(event); - if (!executors.contains(executor)) { - executors.add(executor); - } - } else if (!listeners.containsKey(event)) { - ArrayList executors = new ArrayList<>(); - executors.add(executor); - listeners.put(event, executors); - } - return this; - } - - // Unregister - - public EventManager unregisterEvent(Class event) { - listeners.remove(event); - return this; - } - - public EventManager unregisterEvents(Class listener) { - return unregisterExecutors(getExecutorsFromOwner(listener)); - } - - public EventManager unregisterEvents(EventListener listener) { - return unregisterExecutors(getExecutorsFromOwner(listener)); - } - - public EventManager unregisterExecutors(Iterable executors) { - return unregisterExecutors(executors.iterator()); - } - - public EventManager unregisterExecutors(Iterator executors) { - while (executors.hasNext()) - unregisterExecutor(executors.next()); - return this; - } - - public EventManager unregisterExecutors(EventExecutor... executors) { - for (EventExecutor executor : executors) - unregisterExecutor(executor); - return this; - } - - public EventManager unregisterExecutor(EventExecutor executor) { - ArrayList list = listeners.get(executor.getEvent()); - if (list != null && list.contains(executor)) - list.remove(executor); - return this; - } - - /* - * Owners - */ - - public List getOwners() { - return getExecutors().stream().collect(Collect.collectList((output, input) -> { - if (!output.contains(input.getListener())) - output.add(input.getListener()); - })); - } - - public List> getOwnerClasses() { - return getOwners().stream().collect(Collect.collectList((output, input) -> output.add(input.getClass()))); - } - - /* - * Events - */ - - public List> getEvents() { - return listeners.keySet().stream().collect(Collectors.toList()); - } - - /* - * Executors - */ - - public List getExecutors() { - return listeners.values().stream().collect(Collect.combineList()); - } - - public List getExecutorsFromOwner(EventListener listener) { - return getExecutors().stream().filter(executor -> executor.getListener() == listener).collect(Collectors.toList()); - } - - public List getExecutorsFromOwner(Class listener) { - return getExecutors().stream().filter(executor -> executor.getListener().getClass() == listener).collect(Collectors.toList()); - } - - public List getExecutorsForEvent(Class event) { - return getExecutorsForEvent(event, false); - } - - @SuppressWarnings("unchecked") - public List getExecutorsForEvent(Class event, boolean allowAssignableClasses) { - if (!allowAssignableClasses) { - if (!listeners.containsKey(event)) { - return new ArrayList<>(); - } - return (List) listeners.get(event).clone(); - } - ArrayList executors = new ArrayList<>(); - Set> keys = listeners.keySet(); - for (Class assign : keys) { - if (assign.isAssignableFrom(event)) { - executors.addAll(listeners.get(assign)); - } - } - return (List) executors.clone(); - } + private final LinkedHashMap, ArrayList> listeners = new LinkedHashMap<>(); + private final ILogger logger; + + private final ExecutorService service; + + public EventManager() { + this(null, null); + } + + public EventManager(ExecutorService service) { + this(null, service); + } + + public EventManager(ILogger logger) { + this(logger, null); + } + + public EventManager(ILogger logger, ExecutorService service) { + this.logger = logger; + this.service = service; + } + + /* + * Getter / Infos + */ + + public boolean hasLogger() { + return logger != null; + } + + public ILogger getLogger() { + return logger; + } + + public boolean isAsync() { + return service != null; + } + + public ExecutorService getExecutorService() { + return service; + } + + /* + * Event calls + */ + + public EventCall generateCall(Event event) { + return new EventCall(this, event, getExecutorsForEvent(event.getClass(), true)); + } + + public Status call(Event event) { + return call(generateCall(event)); + } + + public Status call(EventCall call) { + if (isAsync()) { + return call.executeAsync(service); + } else { + return call.execute(); + } + } + + public Status callAsync(Event event, ExecutorService service) { + return callAsync(generateCall(event), service); + } + + public Status callAsync(EventCall call, ExecutorService service) { + return call.executeAsync(service); + } + + /* + * Registration + */ + + // Register + + public EventManager registerEvents(EventListener listener) { + EventAnalyser analyser = new EventAnalyser(listener); + analyser.registerEvents(this); + return this; + } + + public EventManager registerEvent(EventMethod method) { + if (!method.isValid()) { + return this; + } + EventExecutor executor = new EventExecutor(this, method.getListener(), method.getEvent()); + executor.add(method.hasEventHandler() ? method.getHandler().priority() : EventPriority.NORMAL, method); + registerExecutor(executor); + return this; + } + + public EventManager registerExecutors(Collection executors) { + executors.forEach(executor -> registerExecutor(executor)); + return this; + } + + public EventManager registerExecutor(EventExecutor executor) { + if (executor == null || executor.getMethods().isEmpty()) { + return this; + } + Class event = executor.getEvent(); + if (listeners.containsKey(event)) { + ArrayList executors = listeners.get(event); + if (!executors.contains(executor)) { + executors.add(executor); + } + } else if (!listeners.containsKey(event)) { + ArrayList executors = new ArrayList<>(); + executors.add(executor); + listeners.put(event, executors); + } + return this; + } + + // Unregister + + public EventManager unregisterEvent(Class event) { + listeners.remove(event); + return this; + } + + public EventManager unregisterEvents(Class listener) { + return unregisterExecutors(getExecutorsFromOwner(listener)); + } + + public EventManager unregisterEvents(EventListener listener) { + return unregisterExecutors(getExecutorsFromOwner(listener)); + } + + public EventManager unregisterExecutors(Iterable executors) { + return unregisterExecutors(executors.iterator()); + } + + public EventManager unregisterExecutors(Iterator executors) { + while (executors.hasNext()) { + unregisterExecutor(executors.next()); + } + return this; + } + + public EventManager unregisterExecutors(EventExecutor... executors) { + for (EventExecutor executor : executors) { + unregisterExecutor(executor); + } + return this; + } + + public EventManager unregisterExecutor(EventExecutor executor) { + ArrayList list = listeners.get(executor.getEvent()); + if (list != null && list.contains(executor)) { + list.remove(executor); + } + return this; + } + + /* + * Owners + */ + + public List getOwners() { + return getExecutors().stream().collect(Collect.collectList((output, input) -> { + if (!output.contains(input.getListener())) { + output.add(input.getListener()); + } + })); + } + + public List> getOwnerClasses() { + return getOwners().stream().collect(Collect.collectList((output, input) -> output.add(input.getClass()))); + } + + /* + * Events + */ + + public List> getEvents() { + return listeners.keySet().stream().collect(Collectors.toList()); + } + + /* + * Executors + */ + + public List getExecutors() { + return listeners.values().stream().collect(Collect.combineList()); + } + + public List getExecutorsFromOwner(EventListener listener) { + return getExecutors().stream().filter(executor -> executor.getListener() == listener).collect(Collectors.toList()); + } + + public List getExecutorsFromOwner(Class listener) { + return getExecutors().stream().filter(executor -> executor.getListener().getClass() == listener).collect(Collectors.toList()); + } + + public List getExecutorsForEvent(Class event) { + return getExecutorsForEvent(event, false); + } + + @SuppressWarnings("unchecked") + public List getExecutorsForEvent(Class event, boolean allowAssignableClasses) { + if (!allowAssignableClasses) { + if (!listeners.containsKey(event)) { + return new ArrayList<>(); + } + return (List) listeners.get(event).clone(); + } + ArrayList executors = new ArrayList<>(); + Set> keys = listeners.keySet(); + for (Class assign : keys) { + if (assign.isAssignableFrom(event)) { + executors.addAll(listeners.get(assign)); + } + } + return (List) executors.clone(); + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventMethod.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventMethod.java index e753cb1..b49d019 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventMethod.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventMethod.java @@ -6,56 +6,55 @@ public class EventMethod { - private final EventListener listener; - private final boolean ignoreCancel; - private final Method method; - - public EventMethod(EventListener listener, Method method) { - this.listener = listener; - this.method = method; - this.ignoreCancel = hasEventHandler() ? getHandler().ignoreCancel() : false; - } - - public EventMethod(EventListener listener, Method method, boolean ignoreCancel) { - this.listener = listener; - this.method = method; - this.ignoreCancel = ignoreCancel; - } - - public boolean isValid() { - return ReflectionTools - .hasSameArguments(new Class[] { - Event.class - }, method.getParameterTypes()); - } - - public final boolean hasEventHandler() { - return getHandler() != null; - } - - @SuppressWarnings("unchecked") - public final Class getEvent() { - return (Class) method.getParameterTypes()[0]; - } - - public final EventHandler getHandler() { - return method.getAnnotation(EventHandler.class); - } - - public final boolean ignoresCancel() { - return ignoreCancel; - } - - public final Method getMethod() { - return method; - } - - public final EventListener getListener() { - return listener; - } - - public void execute(Event event) { - ReflectionTools.execute(listener, method, event); - } + private final EventListener listener; + private final boolean ignoreCancel; + private final Method method; + + public EventMethod(EventListener listener, Method method) { + this.listener = listener; + this.method = method; + this.ignoreCancel = hasEventHandler() ? getHandler().ignoreCancel() : false; + } + + public EventMethod(EventListener listener, Method method, boolean ignoreCancel) { + this.listener = listener; + this.method = method; + this.ignoreCancel = ignoreCancel; + } + + public boolean isValid() { + return ReflectionTools.hasSameArguments(new Class[] { + Event.class + }, method.getParameterTypes()); + } + + public final boolean hasEventHandler() { + return getHandler() != null; + } + + @SuppressWarnings("unchecked") + public final Class getEvent() { + return (Class) method.getParameterTypes()[0]; + } + + public final EventHandler getHandler() { + return method.getAnnotation(EventHandler.class); + } + + public final boolean ignoresCancel() { + return ignoreCancel; + } + + public final Method getMethod() { + return method; + } + + public final EventListener getListener() { + return listener; + } + + public void execute(Event event) { + ReflectionTools.execute(listener, method, event); + } } diff --git a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventPriority.java b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventPriority.java index 35b54b8..847adb8 100644 --- a/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventPriority.java +++ b/event/src/main/java/com/syntaxphoenix/syntaxapi/event/EventPriority.java @@ -6,30 +6,31 @@ public enum EventPriority { - LOWEST(-2), - LOW(-1), - NORMAL(0), - HIGH(1), - HIGHEST(2); + LOWEST(-2), + LOW(-1), + NORMAL(0), + HIGH(1), + HIGHEST(2); - /* - * - */ + /* + * + */ - public static final List ORDERED_VALUES = Collections.unmodifiableList(Arrays.asList(HIGHEST, HIGH, NORMAL, LOW, LOWEST)); + public static final List ORDERED_VALUES = Collections + .unmodifiableList(Arrays.asList(HIGHEST, HIGH, NORMAL, LOW, LOWEST)); - /* - * - */ + /* + * + */ - private int priority; + private int priority; - private EventPriority(int priority) { - this.priority = priority; - } + private EventPriority(int priority) { + this.priority = priority; + } - public int priority() { - return priority; - } + public int priority() { + return priority; + } } diff --git a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/DownloadFailedException.java b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/DownloadFailedException.java index 660ed03..9e8299d 100644 --- a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/DownloadFailedException.java +++ b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/DownloadFailedException.java @@ -2,60 +2,60 @@ public class DownloadFailedException extends RuntimeException { - /** - * Constructs an AddonException with no detail message. - */ - public DownloadFailedException() { - super(); - } + /** + * Constructs an AddonException with no detail message. + */ + public DownloadFailedException() { + super(); + } - /** - * Constructs an AddonException with the specified detail message. - * - * @param s the detail message. - */ - public DownloadFailedException(String s) { - super(s); - } + /** + * Constructs an AddonException with the specified detail message. + * + * @param s the detail message. + */ + public DownloadFailedException(String s) { + super(s); + } - /** - * Constructs a new exception with the specified detail message and cause. - * - *

- * Note that the detail message associated with cause is not - * automatically incorporated in this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval by the - * {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public DownloadFailedException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new exception with the specified detail message and cause. + * + *

+ * Note that the detail message associated with cause is not + * automatically incorporated in this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval by the + * {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public DownloadFailedException(String message, Throwable cause) { + super(message, cause); + } - /** - * Constructs a new exception with the specified cause and a detail message of - * (cause==null ? null : cause.toString()) (which typically contains - * the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for - * example, {@link java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public DownloadFailedException(Throwable cause) { - super(cause); - } + /** + * Constructs a new exception with the specified cause and a detail message of + * (cause==null ? null : cause.toString()) (which typically contains + * the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for + * example, {@link java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public DownloadFailedException(Throwable cause) { + super(cause); + } - /** - * - */ - private static final long serialVersionUID = -2199398677172673915L; + /** + * + */ + private static final long serialVersionUID = -2199398677172673915L; } diff --git a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/NotImplementedException.java b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/NotImplementedException.java index 4ff26e2..92b0f3f 100644 --- a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/NotImplementedException.java +++ b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/NotImplementedException.java @@ -2,62 +2,62 @@ public class NotImplementedException extends RuntimeException { - /** - * Constructs an NotImplementedException with no detail message. - */ - public NotImplementedException() { - super(); - } + /** + * Constructs an NotImplementedException with no detail message. + */ + public NotImplementedException() { + super(); + } - /** - * Constructs an NotImplementedException with the specified detail - * message. - * - * @param s the detail message. - */ - public NotImplementedException(String s) { - super(s); - } + /** + * Constructs an NotImplementedException with the specified detail + * message. + * + * @param s the detail message. + */ + public NotImplementedException(String s) { + super(s); + } - /** - * Constructs a new exception with the specified detail message and cause. - * - *

- * Note that the detail message associated with cause is not - * automatically incorporated in this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval by the - * {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public NotImplementedException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new exception with the specified detail message and cause. + * + *

+ * Note that the detail message associated with cause is not + * automatically incorporated in this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval by the + * {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public NotImplementedException(String message, Throwable cause) { + super(message, cause); + } - /** - * Constructs a new exception with the specified cause and a detail message of - * (cause==null ? null : cause.toString()) (which typically contains - * the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for - * example, {@link java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public NotImplementedException(Throwable cause) { - super(cause); - } + /** + * Constructs a new exception with the specified cause and a detail message of + * (cause==null ? null : cause.toString()) (which typically contains + * the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for + * example, {@link java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public NotImplementedException(Throwable cause) { + super(cause); + } - /** - * - */ + /** + * + */ - private static final long serialVersionUID = 6664615458135158429L; + private static final long serialVersionUID = 6664615458135158429L; } diff --git a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/ObjectLockedException.java b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/ObjectLockedException.java index de3d45e..334793e 100644 --- a/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/ObjectLockedException.java +++ b/exception/src/main/java/com/syntaxphoenix/syntaxapi/exception/ObjectLockedException.java @@ -2,61 +2,61 @@ public class ObjectLockedException extends RuntimeException { - /** - * Constructs an ObjectLockedException with no detail message. - */ - public ObjectLockedException() { - super(); - } + /** + * Constructs an ObjectLockedException with no detail message. + */ + public ObjectLockedException() { + super(); + } - /** - * Constructs an ObjectLockedException with the specified detail - * message. - * - * @param s the detail message. - */ - public ObjectLockedException(String s) { - super(s); - } + /** + * Constructs an ObjectLockedException with the specified detail + * message. + * + * @param s the detail message. + */ + public ObjectLockedException(String s) { + super(s); + } - /** - * Constructs a new exception with the specified detail message and cause. - * - *

- * Note that the detail message associated with cause is not - * automatically incorporated in this exception's detail message. - * - * @param message the detail message (which is saved for later retrieval by the - * {@link Throwable#getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value - * is permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public ObjectLockedException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new exception with the specified detail message and cause. + * + *

+ * Note that the detail message associated with cause is not + * automatically incorporated in this exception's detail message. + * + * @param message the detail message (which is saved for later retrieval by the + * {@link Throwable#getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value + * is permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public ObjectLockedException(String message, Throwable cause) { + super(message, cause); + } - /** - * Constructs a new exception with the specified cause and a detail message of - * (cause==null ? null : cause.toString()) (which typically contains - * the class and detail message of cause). This constructor is useful - * for exceptions that are little more than wrappers for other throwables (for - * example, {@link java.security.PrivilegedActionException}). - * - * @param cause the cause (which is saved for later retrieval by the - * {@link Throwable#getCause()} method). (A null value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.5 - */ - public ObjectLockedException(Throwable cause) { - super(cause); - } + /** + * Constructs a new exception with the specified cause and a detail message of + * (cause==null ? null : cause.toString()) (which typically contains + * the class and detail message of cause). This constructor is useful + * for exceptions that are little more than wrappers for other throwables (for + * example, {@link java.security.PrivilegedActionException}). + * + * @param cause the cause (which is saved for later retrieval by the + * {@link Throwable#getCause()} method). (A null value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + * @since 1.5 + */ + public ObjectLockedException(Throwable cause) { + super(cause); + } - /** - * - */ - private static final long serialVersionUID = -2199398677172673915L; + /** + * + */ + private static final long serialVersionUID = -2199398677172673915L; } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/AsyncLogger.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/AsyncLogger.java index 8244b32..defeefd 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/AsyncLogger.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/AsyncLogger.java @@ -10,169 +10,169 @@ public class AsyncLogger implements ILogger { - private final ExecutorService executor; - private final ILogger logger; - - public AsyncLogger(ILogger logger) { - this(Executors.newSingleThreadExecutor(), logger); - } - - public AsyncLogger(ExecutorService executor, ILogger logger) { - this.executor = executor; - this.logger = logger; - } - - /* - * - */ - - public ExecutorService getExecutor() { - return executor; - } - - public ILogger getLogger() { - return logger; - } - - /* - * - */ - - @Override - public AsyncLogger close() { - try { - executor.shutdown(); - executor.awaitTermination(60, TimeUnit.SECONDS); - } catch (InterruptedException e) { - logger.log(e); - } - logger.close(); - return this; - } - - /* - * - */ - - @Override - public AsyncLogger setThreadName(String name) { - logger.setThreadName(name); - return this; - } - - @Override - public String getThreadName() { - return logger.getThreadName(); - } - - @Override - public AsyncLogger setState(LoggerState state) { - logger.setState(state); - return this; - } - - @Override - public LoggerState getState() { - return logger.getState(); - } - - @Override - public AsyncLogger setCustom(BiConsumer custom) { - logger.setCustom(custom); - return this; - } - - @Override - public BiConsumer getCustom() { - return logger.getCustom(); - } - - @Override - public AsyncLogger setType(LogType type) { - logger.setType(type); - return this; - } - - @Override - public LogType getType(String typeId) { - return logger.getType(typeId); - } - - @Override - public ILogger setColored(boolean color) { - logger.setColored(color); - return this; - } - - @Override - public boolean isColored() { - return logger.isColored(); - } - - @Override - public LogTypeMap getTypeMap() { - return logger.getTypeMap(); - } - - /* - * - */ - - public AsyncLogger log(String message) { - queue(() -> logger.log(message)); - return this; - } - - public AsyncLogger log(LogTypeId type, String message) { - queue(() -> logger.log(type, message)); - return this; - } - - public AsyncLogger log(String typeId, String message) { - queue(() -> logger.log(typeId, message)); - return this; - } - - public AsyncLogger log(String... messages) { - queue(() -> logger.log(messages)); - return this; - } - - public AsyncLogger log(LogTypeId type, String... messages) { - queue(() -> logger.log(type, messages)); - return this; - } - - public AsyncLogger log(String typeId, String... messages) { - queue(() -> logger.log(typeId, messages)); - return this; - } - - public AsyncLogger log(Throwable throwable) { - queue(() -> logger.log(throwable)); - return this; - } - - public AsyncLogger log(LogTypeId type, Throwable throwable) { - queue(() -> logger.log(type, throwable)); - return this; - } - - public AsyncLogger log(String typeId, Throwable throwable) { - queue(() -> logger.log(typeId, throwable)); - return this; - } - - /* - * - */ - - private void queue(Runnable runnable) { - final String name = Thread.currentThread().getName(); - executor.submit(() -> { - logger.setThreadName(name); - runnable.run(); - }); - } + private final ExecutorService executor; + private final ILogger logger; + + public AsyncLogger(ILogger logger) { + this(Executors.newSingleThreadExecutor(), logger); + } + + public AsyncLogger(ExecutorService executor, ILogger logger) { + this.executor = executor; + this.logger = logger; + } + + /* + * + */ + + public ExecutorService getExecutor() { + return executor; + } + + public ILogger getLogger() { + return logger; + } + + /* + * + */ + + @Override + public AsyncLogger close() { + try { + executor.shutdown(); + executor.awaitTermination(60, TimeUnit.SECONDS); + } catch (InterruptedException e) { + logger.log(e); + } + logger.close(); + return this; + } + + /* + * + */ + + @Override + public AsyncLogger setThreadName(String name) { + logger.setThreadName(name); + return this; + } + + @Override + public String getThreadName() { + return logger.getThreadName(); + } + + @Override + public AsyncLogger setState(LoggerState state) { + logger.setState(state); + return this; + } + + @Override + public LoggerState getState() { + return logger.getState(); + } + + @Override + public AsyncLogger setCustom(BiConsumer custom) { + logger.setCustom(custom); + return this; + } + + @Override + public BiConsumer getCustom() { + return logger.getCustom(); + } + + @Override + public AsyncLogger setType(LogType type) { + logger.setType(type); + return this; + } + + @Override + public LogType getType(String typeId) { + return logger.getType(typeId); + } + + @Override + public ILogger setColored(boolean color) { + logger.setColored(color); + return this; + } + + @Override + public boolean isColored() { + return logger.isColored(); + } + + @Override + public LogTypeMap getTypeMap() { + return logger.getTypeMap(); + } + + /* + * + */ + + public AsyncLogger log(String message) { + queue(() -> logger.log(message)); + return this; + } + + public AsyncLogger log(LogTypeId type, String message) { + queue(() -> logger.log(type, message)); + return this; + } + + public AsyncLogger log(String typeId, String message) { + queue(() -> logger.log(typeId, message)); + return this; + } + + public AsyncLogger log(String... messages) { + queue(() -> logger.log(messages)); + return this; + } + + public AsyncLogger log(LogTypeId type, String... messages) { + queue(() -> logger.log(type, messages)); + return this; + } + + public AsyncLogger log(String typeId, String... messages) { + queue(() -> logger.log(typeId, messages)); + return this; + } + + public AsyncLogger log(Throwable throwable) { + queue(() -> logger.log(throwable)); + return this; + } + + public AsyncLogger log(LogTypeId type, Throwable throwable) { + queue(() -> logger.log(type, throwable)); + return this; + } + + public AsyncLogger log(String typeId, Throwable throwable) { + queue(() -> logger.log(typeId, throwable)); + return this; + } + + /* + * + */ + + private void queue(Runnable runnable) { + final String name = Thread.currentThread().getName(); + executor.submit(() -> { + logger.setThreadName(name); + runnable.run(); + }); + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/ILogger.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/ILogger.java index 6060c93..52c8e9c 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/ILogger.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/ILogger.java @@ -7,46 +7,46 @@ public interface ILogger { - public ILogger close(); + public ILogger close(); - public LogTypeMap getTypeMap(); + public LogTypeMap getTypeMap(); - public ILogger setCustom(BiConsumer custom); + public ILogger setCustom(BiConsumer custom); - public BiConsumer getCustom(); + public BiConsumer getCustom(); - public ILogger setType(LogType type); + public ILogger setType(LogType type); - public LogType getType(String typeId); + public LogType getType(String typeId); - public ILogger setState(LoggerState state); + public ILogger setState(LoggerState state); - public LoggerState getState(); + public LoggerState getState(); - public ILogger setThreadName(String name); + public ILogger setThreadName(String name); - public String getThreadName(); + public String getThreadName(); - public ILogger setColored(boolean color); + public ILogger setColored(boolean color); - public boolean isColored(); + public boolean isColored(); - public ILogger log(String message); + public ILogger log(String message); - public ILogger log(LogTypeId type, String message); + public ILogger log(LogTypeId type, String message); - public ILogger log(String typeId, String message); + public ILogger log(String typeId, String message); - public ILogger log(String... messages); + public ILogger log(String... messages); - public ILogger log(LogTypeId type, String... messages); + public ILogger log(LogTypeId type, String... messages); - public ILogger log(String typeId, String... messages); + public ILogger log(String typeId, String... messages); - public ILogger log(Throwable throwable); + public ILogger log(Throwable throwable); - public ILogger log(LogTypeId type, Throwable throwable); + public ILogger log(LogTypeId type, Throwable throwable); - public ILogger log(String typeId, Throwable throwable); + public ILogger log(String typeId, Throwable throwable); } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LogTypeId.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LogTypeId.java index 0b6a809..c152b5b 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LogTypeId.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LogTypeId.java @@ -2,13 +2,13 @@ public enum LogTypeId { - INFO, - WARNING, - ERROR, - DEBUG; - - public String id() { - return name().toLowerCase(); - } + INFO, + WARNING, + ERROR, + DEBUG; + + public String id() { + return name().toLowerCase(); + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LoggerState.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LoggerState.java index 0fecd2e..0e3ffff 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LoggerState.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/LoggerState.java @@ -2,88 +2,88 @@ public enum LoggerState { - NONE(), - STREAM(false, true, false), - EXTENDED_STREAM(true, true, false), - CUSTOM(false, false, true), - EXTENDED_CUSTOM(true, false, true), - STREAM_CUSTOM(false, true, true), - EXTENDED_STREAM_CUSTOM(true, true, true); + NONE(), + STREAM(false, true, false), + EXTENDED_STREAM(true, true, false), + CUSTOM(false, false, true), + EXTENDED_CUSTOM(true, false, true), + STREAM_CUSTOM(false, true, true), + EXTENDED_STREAM_CUSTOM(true, true, true); - private final boolean extended; - private final boolean stream; - private final boolean custom; - private final boolean logging; + private final boolean extended; + private final boolean stream; + private final boolean custom; + private final boolean logging; - private LoggerState(boolean extended, boolean stream, boolean custom) { - this.extended = extended; - this.stream = stream; - this.custom = custom; - this.logging = true; - } + private LoggerState(boolean extended, boolean stream, boolean custom) { + this.extended = extended; + this.stream = stream; + this.custom = custom; + this.logging = true; + } - private LoggerState() { - this.extended = false; - this.stream = false; - this.custom = false; - this.logging = false; - } + private LoggerState() { + this.extended = false; + this.stream = false; + this.custom = false; + this.logging = false; + } - public boolean useCustom() { - return custom; - } + public boolean useCustom() { + return custom; + } - public boolean useStream() { - return stream; - } + public boolean useStream() { + return stream; + } - public boolean extendedInfo() { - return extended; - } + public boolean extendedInfo() { + return extended; + } - public boolean isEnabled() { - return logging; - } + public boolean isEnabled() { + return logging; + } - public static LoggerState byName(String name) { - for (LoggerState state : values()) { - if (state.name().equalsIgnoreCase(name)) { - return state; - } - } - return LoggerState.NONE; - } + public static LoggerState byName(String name) { + for (LoggerState state : values()) { + if (state.name().equalsIgnoreCase(name)) { + return state; + } + } + return LoggerState.NONE; + } - public static LoggerState byOptions(boolean extended, boolean file, boolean console) { - if (extended) { - if (file) { - if (console) { - return LoggerState.EXTENDED_STREAM_CUSTOM; - } else { - return LoggerState.EXTENDED_STREAM; - } - } else { - if (console) { - return LoggerState.EXTENDED_CUSTOM; - } else { - return LoggerState.NONE; - } - } - } else { - if (file) { - if (console) { - return LoggerState.STREAM_CUSTOM; - } else { - return LoggerState.STREAM; - } - } else { - if (console) { - return LoggerState.CUSTOM; - } else { - return LoggerState.NONE; - } - } - } - } + public static LoggerState byOptions(boolean extended, boolean file, boolean console) { + if (extended) { + if (file) { + if (console) { + return LoggerState.EXTENDED_STREAM_CUSTOM; + } else { + return LoggerState.EXTENDED_STREAM; + } + } else { + if (console) { + return LoggerState.EXTENDED_CUSTOM; + } else { + return LoggerState.NONE; + } + } + } else { + if (file) { + if (console) { + return LoggerState.STREAM_CUSTOM; + } else { + return LoggerState.STREAM; + } + } else { + if (console) { + return LoggerState.CUSTOM; + } else { + return LoggerState.NONE; + } + } + } + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/SynLogger.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/SynLogger.java index b65c147..5bc0f06 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/SynLogger.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/SynLogger.java @@ -5,327 +5,339 @@ import java.util.Optional; import java.util.function.BiConsumer; -import com.syntaxphoenix.syntaxapi.logging.color.LogTypeMap; import com.syntaxphoenix.syntaxapi.logging.color.ColorTools; import com.syntaxphoenix.syntaxapi.logging.color.LogType; import com.syntaxphoenix.syntaxapi.logging.color.LogTypeColor; +import com.syntaxphoenix.syntaxapi.logging.color.LogTypeMap; import com.syntaxphoenix.syntaxapi.utils.java.Exceptions; import com.syntaxphoenix.syntaxapi.utils.java.Times; public final class SynLogger implements ILogger { - public static final String DEFAULT_FORMAT = "[%date% / %time%][%thread% => %type%] %message%"; - - /* - * - */ - - private LogTypeMap typeMap = new LogTypeMap(); - private boolean colored; - private String format; - - private BiConsumer custom; - private PrintStream stream; - - private LoggerState state = LoggerState.STREAM; - private String overrideThread; - - public SynLogger() { - this(System.out); - } - - public SynLogger(LoggerState state) { - this(System.out, state); - } - - public SynLogger(String format) { - this(System.out, format); - } - - public SynLogger(PrintStream file) { - this(file, DEFAULT_FORMAT); - } - - public SynLogger(String format, LoggerState state) { - this(System.out, format, state); - } - - public SynLogger(PrintStream stream, LoggerState state) { - this(stream, DEFAULT_FORMAT, state); - } - - public SynLogger(PrintStream stream, String format) { - setColored(true); - setFormat(format); - setStream(stream); - setDefaultTypes(); - } - - public SynLogger(PrintStream stream, String format, LoggerState state) { - setColored(true); - setFormat(format); - setStream(stream); - setState(state); - setDefaultTypes(); - } - - /* - * - */ - - @Override - public SynLogger close() { - if (stream != null) { - stream.close(); - stream = null; - } - return this; - } - - /* - * - */ - - @Override - public SynLogger setThreadName(String name) { - this.overrideThread = name; - return this; - } - - @Override - public String getThreadName() { - if (overrideThread == null) - return Thread.currentThread().getName(); - String name = overrideThread; - overrideThread = null; - return name; - } - - @Override - public SynLogger setCustom(BiConsumer custom) { - this.custom = custom; - return this; - } - - @Override - public BiConsumer getCustom() { - return custom; - } - - @Override - public SynLogger setState(LoggerState state) { - this.state = state; - return this; - } - - @Override - public LoggerState getState() { - return state; - } - - @Override - public SynLogger setColored(boolean colored) { - this.colored = colored; - return this; - } - - @Override - public boolean isColored() { - return colored; - } - - @Override - public SynLogger setType(LogType type) { - typeMap.override(type); - return this; - } - - @Override - public LogType getType(String typeId) { - Optional option = typeMap.tryGetById(typeId); - return option.isPresent() ? option.get() : LogTypeColor.DEFAULT; - } - - @Override - public LogTypeMap getTypeMap() { - return typeMap; - } - - /* - * - */ - - public SynLogger setStream(PrintStream stream) { - this.stream = stream; - return this; - } - - public PrintStream getStream() { - return stream; - } - - public SynLogger setFormat(String format) { - this.format = format; - return this; - } - - public String getFormat() { - return format; - } - - /* - * - */ - - public SynLogger setDefaultTypes() { - setType("debug", "#F000FF"); - setType("info", "#2FE4E7"); - setType("warning", "#E89102"); - setType("error", "#FF0000"); - return this; - } - - public SynLogger setType(String name, String hex) { - return setType(name, ColorTools.hex2rgb(hex)); - } - - public SynLogger setType(String name, Color color) { - return setType(new LogTypeColor(name, color)); - } - - /* - * - * - * - */ - - @Override - public SynLogger log(String message) { - return log(LogTypeId.INFO, message); - } - - @Override - public SynLogger log(LogTypeId type, String message) { - return log(type.id(), message); - } - - @Override - public SynLogger log(String typeId, String message) { - return log(getType(typeId), message); - } - - public SynLogger log(LogType type, String message) { - return println(type, - format - .replace("%date%", Times.getDate(".")) - .replace("%time%", Times.getTime(":")) - .replace("%thread%", getThreadName()) - .replace("%type%", type.getName()) - .replace("%message%", message)); - } - - /* - * - */ - - @Override - public SynLogger log(String... messages) { - return log(LogTypeId.INFO, messages); - } - - @Override - public SynLogger log(LogTypeId type, String... messages) { - return log(type.id(), messages); - } - - @Override - public SynLogger log(String typeId, String... messages) { - return log(getType(typeId), messages); - } - - public SynLogger log(LogType type, String... messages) { - if (messages == null || messages.length == 0) { - return this; - } - String thread = getThreadName(); - for (String message : messages) { - setThreadName(thread); - log(type, message); - } - return this; - } - - /* - * - */ - - @Override - public SynLogger log(Throwable throwable) { - return log(LogTypeId.ERROR, throwable); - } - - @Override - public SynLogger log(LogTypeId type, Throwable throwable) { - return log(type.id(), throwable); - } - - @Override - public SynLogger log(String typeId, Throwable throwable) { - return log(getType(typeId), throwable); - } - - public SynLogger log(LogType type, Throwable throwable) { - return log(type, Exceptions.stackTraceToStringArray(throwable)); - } - - /* - * - */ - - public SynLogger println(LogType type, String message) { - if (!colored) { - return println(message); - } - if (state.useCustom()) - if (custom != null) - custom.accept(true, type.asColorString(false) + message); - if (state.useStream()) - if (stream != null) - stream.println(type.asColorString(true) + message); - return this; - } - - public SynLogger println(String message) { - if (state.useCustom()) - if (custom != null) - custom.accept(true, message); - if (state.useStream()) - if (stream != null) - stream.println(message); - return this; - } - - public SynLogger print(LogType type, String message) { - if (!colored) { - return print(message); - } - if (state.useCustom()) - if (custom != null) - custom.accept(false, type.asColorString(false) + message); - if (state.useStream()) - if (stream != null) - stream.print(type.asColorString(true) + message); - return this; - } - - public SynLogger print(String message) { - if (state.useCustom()) - if (custom != null) - custom.accept(false, message); - if (state.useStream()) - if (stream != null) - stream.print(message); - return this; - } + public static final String DEFAULT_FORMAT = "[%date% / %time%][%thread% => %type%] %message%"; + + /* + * + */ + + private LogTypeMap typeMap = new LogTypeMap(); + private boolean colored; + private String format; + + private BiConsumer custom; + private PrintStream stream; + + private LoggerState state = LoggerState.STREAM; + private String overrideThread; + + public SynLogger() { + this(System.out); + } + + public SynLogger(LoggerState state) { + this(System.out, state); + } + + public SynLogger(String format) { + this(System.out, format); + } + + public SynLogger(PrintStream file) { + this(file, DEFAULT_FORMAT); + } + + public SynLogger(String format, LoggerState state) { + this(System.out, format, state); + } + + public SynLogger(PrintStream stream, LoggerState state) { + this(stream, DEFAULT_FORMAT, state); + } + + public SynLogger(PrintStream stream, String format) { + setColored(true); + setFormat(format); + setStream(stream); + setDefaultTypes(); + } + + public SynLogger(PrintStream stream, String format, LoggerState state) { + setColored(true); + setFormat(format); + setStream(stream); + setState(state); + setDefaultTypes(); + } + + /* + * + */ + + @Override + public SynLogger close() { + if (stream != null) { + stream.close(); + stream = null; + } + return this; + } + + /* + * + */ + + @Override + public SynLogger setThreadName(String name) { + this.overrideThread = name; + return this; + } + + @Override + public String getThreadName() { + if (overrideThread == null) { + return Thread.currentThread().getName(); + } + String name = overrideThread; + overrideThread = null; + return name; + } + + @Override + public SynLogger setCustom(BiConsumer custom) { + this.custom = custom; + return this; + } + + @Override + public BiConsumer getCustom() { + return custom; + } + + @Override + public SynLogger setState(LoggerState state) { + this.state = state; + return this; + } + + @Override + public LoggerState getState() { + return state; + } + + @Override + public SynLogger setColored(boolean colored) { + this.colored = colored; + return this; + } + + @Override + public boolean isColored() { + return colored; + } + + @Override + public SynLogger setType(LogType type) { + typeMap.override(type); + return this; + } + + @Override + public LogType getType(String typeId) { + Optional option = typeMap.tryGetById(typeId); + return option.isPresent() ? option.get() : LogTypeColor.DEFAULT; + } + + @Override + public LogTypeMap getTypeMap() { + return typeMap; + } + + /* + * + */ + + public SynLogger setStream(PrintStream stream) { + this.stream = stream; + return this; + } + + public PrintStream getStream() { + return stream; + } + + public SynLogger setFormat(String format) { + this.format = format; + return this; + } + + public String getFormat() { + return format; + } + + /* + * + */ + + public SynLogger setDefaultTypes() { + setType("debug", "#F000FF"); + setType("info", "#2FE4E7"); + setType("warning", "#E89102"); + setType("error", "#FF0000"); + return this; + } + + public SynLogger setType(String name, String hex) { + return setType(name, ColorTools.hex2rgb(hex)); + } + + public SynLogger setType(String name, Color color) { + return setType(new LogTypeColor(name, color)); + } + + /* + * + * + * + */ + + @Override + public SynLogger log(String message) { + return log(LogTypeId.INFO, message); + } + + @Override + public SynLogger log(LogTypeId type, String message) { + return log(type.id(), message); + } + + @Override + public SynLogger log(String typeId, String message) { + return log(getType(typeId), message); + } + + public SynLogger log(LogType type, String message) { + return println(type, format.replace("%date%", Times.getDate(".")).replace("%time%", Times.getTime(":")) + .replace("%thread%", getThreadName()).replace("%type%", type.getName()).replace("%message%", message)); + } + + /* + * + */ + + @Override + public SynLogger log(String... messages) { + return log(LogTypeId.INFO, messages); + } + + @Override + public SynLogger log(LogTypeId type, String... messages) { + return log(type.id(), messages); + } + + @Override + public SynLogger log(String typeId, String... messages) { + return log(getType(typeId), messages); + } + + public SynLogger log(LogType type, String... messages) { + if (messages == null || messages.length == 0) { + return this; + } + String thread = getThreadName(); + for (String message : messages) { + setThreadName(thread); + log(type, message); + } + return this; + } + + /* + * + */ + + @Override + public SynLogger log(Throwable throwable) { + return log(LogTypeId.ERROR, throwable); + } + + @Override + public SynLogger log(LogTypeId type, Throwable throwable) { + return log(type.id(), throwable); + } + + @Override + public SynLogger log(String typeId, Throwable throwable) { + return log(getType(typeId), throwable); + } + + public SynLogger log(LogType type, Throwable throwable) { + return log(type, Exceptions.stackTraceToStringArray(throwable)); + } + + /* + * + */ + + public SynLogger println(LogType type, String message) { + if (!colored) { + return println(message); + } + if (state.useCustom()) { + if (custom != null) { + custom.accept(true, type.asColorString(false) + message); + } + } + if (state.useStream()) { + if (stream != null) { + stream.println(type.asColorString(true) + message); + } + } + return this; + } + + public SynLogger println(String message) { + if (state.useCustom()) { + if (custom != null) { + custom.accept(true, message); + } + } + if (state.useStream()) { + if (stream != null) { + stream.println(message); + } + } + return this; + } + + public SynLogger print(LogType type, String message) { + if (!colored) { + return print(message); + } + if (state.useCustom()) { + if (custom != null) { + custom.accept(false, type.asColorString(false) + message); + } + } + if (state.useStream()) { + if (stream != null) { + stream.print(type.asColorString(true) + message); + } + } + return this; + } + + public SynLogger print(String message) { + if (state.useCustom()) { + if (custom != null) { + custom.accept(false, message); + } + } + if (state.useStream()) { + if (stream != null) { + stream.print(message); + } + } + return this; + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorProcessor.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorProcessor.java index 0e491e6..70d6013 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorProcessor.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorProcessor.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface ColorProcessor { - public String process(boolean stream, LogType type); + public String process(boolean stream, LogType type); } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorTools.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorTools.java index b28e21d..270d57f 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorTools.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/ColorTools.java @@ -4,39 +4,41 @@ public class ColorTools { - public static final String ANSI_FORMAT = "\033[r;g;bm"; - - public static Color hex2rgb(String hexHash) { - return hex2rgba(hexHash, 255); - } - - public static Color hex2rgba(String hexHash, int alpha) { - if (hexHash.startsWith("#")) - hexHash = hexHash.replace("#", ""); - if (hexHash.length() != 6) - return Color.BLACK; - String[] hex = hexHash.split("(?<=\\G..)"); - return hex2rgba(hex[0], hex[1], hex[2], alpha); - } - - public static Color hex2rgba(String red, String green, String blue) { - return hex2rgba(red, green, blue, 255); - } - - public static Color hex2rgba(String red, String green, String blue, int alpha) { - return rgba(Integer.parseInt(red, 16), Integer.parseInt(green, 16), Integer.parseInt(blue, 16), alpha); - } - - public static Color rgb(int red, int green, int blue) { - return rgba(red, green, blue, 255); - } - - public static Color rgba(int red, int green, int blue, int alpha) { - return new Color(red, green, blue, alpha); - } - - public static String toAnsiColor(Color color) { - return ANSI_FORMAT.replace("r", color.getRed() + "").replace("g", color.getGreen() + "").replace("b", color.getBlue() + ""); - } + public static final String ANSI_FORMAT = "\033[r;g;bm"; + + public static Color hex2rgb(String hexHash) { + return hex2rgba(hexHash, 255); + } + + public static Color hex2rgba(String hexHash, int alpha) { + if (hexHash.startsWith("#")) { + hexHash = hexHash.replace("#", ""); + } + if (hexHash.length() != 6) { + return Color.BLACK; + } + String[] hex = hexHash.split("(?<=\\G..)"); + return hex2rgba(hex[0], hex[1], hex[2], alpha); + } + + public static Color hex2rgba(String red, String green, String blue) { + return hex2rgba(red, green, blue, 255); + } + + public static Color hex2rgba(String red, String green, String blue, int alpha) { + return rgba(Integer.parseInt(red, 16), Integer.parseInt(green, 16), Integer.parseInt(blue, 16), alpha); + } + + public static Color rgb(int red, int green, int blue) { + return rgba(red, green, blue, 255); + } + + public static Color rgba(int red, int green, int blue, int alpha) { + return new Color(red, green, blue, alpha); + } + + public static String toAnsiColor(Color color) { + return ANSI_FORMAT.replace("r", color.getRed() + "").replace("g", color.getGreen() + "").replace("b", color.getBlue() + ""); + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogType.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogType.java index 84445a9..d602224 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogType.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogType.java @@ -6,60 +6,60 @@ public abstract class LogType { - private final String id; - private String name; + private final String id; + private String name; - /* - * - * - * - */ + /* + * + * + * + */ - public LogType(String id) { - this(id, Strings.firstLetterToUpperCase(id)); - } + public LogType(String id) { + this(id, Strings.firstLetterToUpperCase(id)); + } - public LogType(String id, String name) { - this.id = id.toLowerCase(); - this.name = name; - } + public LogType(String id, String name) { + this.id = id.toLowerCase(); + this.name = name; + } - /* - * - * - * - */ + /* + * + * + * + */ - public void setName(String name) { - this.name = (name == null || name.isEmpty()) ? this.name : name; - } + public void setName(String name) { + this.name = (name == null || name.isEmpty()) ? this.name : name; + } - /* - * - * - * - */ + /* + * + * + * + */ - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - /* - * - * - * - */ + /* + * + * + * + */ - public abstract ColorProcessor getColorProcessor(); + public abstract ColorProcessor getColorProcessor(); - public abstract Color asColor(); + public abstract Color asColor(); - public abstract String asColorString(); + public abstract String asColorString(); - public abstract String asColorString(boolean stream); + public abstract String asColorString(boolean stream); } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeColor.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeColor.java index c97ec55..82ac2d0 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeColor.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeColor.java @@ -4,70 +4,70 @@ public class LogTypeColor extends LogType { - public static final LogTypeColor DEFAULT = new LogTypeColor("info", "Info", ColorTools.hex2rgb("#474747")); - - public static final ColorProcessor PROCESSOR = (flag, type) -> type.asColorString(flag); - - /* - * - */ - - private Color color; - - /* - * - * - * - */ - - public LogTypeColor(String id) { - this(id, Color.BLACK); - } - - public LogTypeColor(String id, Color color) { - super(id); - this.color = color; - } - - public LogTypeColor(String id, String name, Color color) { - super(id, name); - this.color = color; - } - - /* - * - * - * - */ - - public void setColor(Color color) { - this.color = color == null ? this.color : color; - } - - /* - * - * - * - */ - - @Override - public ColorProcessor getColorProcessor() { - return PROCESSOR; - } - - @Override - public Color asColor() { - return color; - } - - @Override - public String asColorString() { - return ColorTools.toAnsiColor(asColor()); - } - - @Override - public String asColorString(boolean stream) { - return stream ? asColorString() : ""; - } + public static final LogTypeColor DEFAULT = new LogTypeColor("info", "Info", ColorTools.hex2rgb("#474747")); + + public static final ColorProcessor PROCESSOR = (flag, type) -> type.asColorString(flag); + + /* + * + */ + + private Color color; + + /* + * + * + * + */ + + public LogTypeColor(String id) { + this(id, Color.BLACK); + } + + public LogTypeColor(String id, Color color) { + super(id); + this.color = color; + } + + public LogTypeColor(String id, String name, Color color) { + super(id, name); + this.color = color; + } + + /* + * + * + * + */ + + public void setColor(Color color) { + this.color = color == null ? this.color : color; + } + + /* + * + * + * + */ + + @Override + public ColorProcessor getColorProcessor() { + return PROCESSOR; + } + + @Override + public Color asColor() { + return color; + } + + @Override + public String asColorString() { + return ColorTools.toAnsiColor(asColor()); + } + + @Override + public String asColorString(boolean stream) { + return stream ? asColorString() : ""; + } } diff --git a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeMap.java b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeMap.java index dbd5c0d..c47bdb0 100644 --- a/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeMap.java +++ b/logging/src/main/java/com/syntaxphoenix/syntaxapi/logging/color/LogTypeMap.java @@ -6,83 +6,83 @@ public class LogTypeMap { - private final ArrayList types = new ArrayList<>(); - - /* - * - * - * - */ - - public void register(final LogType type) { - if (contains(type)) { - return; - } - types.add(type); - } - - public void override(final LogType type) { - deleteById(type.getId()); - types.add(type); - } - - public void delete(final LogType type) { - if (contains(type)) { - types.remove(type); - } else { - deleteById(type.getId()); - } - } - - public void deleteById(final String id) { - Optional option = tryGetById(id); - if (option.isPresent()) { - delete(option.get()); - } - } - - /* - * - * - * - */ - - public LogType getById(String id) { - return tryGetById(id).get(); - } - - public LogType getByName(String name) { - return tryGetById(name).get(); - } - - public Optional tryGetById(String id) { - return tryGet(type -> type.getId().equals(id)); - } - - public Optional tryGetByName(String name) { - return tryGet(type -> type.getName().equals(name)); - } - - public Optional tryGet(Predicate predicate) { - return types.stream().filter(predicate).findFirst(); - } - - /* - * - * - * - */ - - public boolean contains(LogType type) { - return type == null ? false : types.contains(type); - } - - public boolean containsId(String id) { - return tryGetById(id).isPresent(); - } - - public boolean containsName(String name) { - return tryGetByName(name).isPresent(); - } + private final ArrayList types = new ArrayList<>(); + + /* + * + * + * + */ + + public void register(final LogType type) { + if (contains(type)) { + return; + } + types.add(type); + } + + public void override(final LogType type) { + deleteById(type.getId()); + types.add(type); + } + + public void delete(final LogType type) { + if (contains(type)) { + types.remove(type); + } else { + deleteById(type.getId()); + } + } + + public void deleteById(final String id) { + Optional option = tryGetById(id); + if (option.isPresent()) { + delete(option.get()); + } + } + + /* + * + * + * + */ + + public LogType getById(String id) { + return tryGetById(id).get(); + } + + public LogType getByName(String name) { + return tryGetById(name).get(); + } + + public Optional tryGetById(String id) { + return tryGet(type -> type.getId().equals(id)); + } + + public Optional tryGetByName(String name) { + return tryGet(type -> type.getName().equals(name)); + } + + public Optional tryGet(Predicate predicate) { + return types.stream().filter(predicate).findFirst(); + } + + /* + * + * + * + */ + + public boolean contains(LogType type) { + return type == null ? false : types.contains(type); + } + + public boolean containsId(String id) { + return tryGetById(id).isPresent(); + } + + public boolean containsName(String name) { + return tryGetByName(name).isPresent(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtAbstractList.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtAbstractList.java index 2dd50d5..d9f48f1 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtAbstractList.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtAbstractList.java @@ -8,122 +8,122 @@ public abstract class NbtAbstractList extends NbtTag implements List { - protected ArrayList list = new ArrayList<>(); - - @Override - public Iterator iterator() { - return list.iterator(); - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } - - @Override - public boolean add(T e) { - return list.add(e); - } - - @Override - public T get(int index) { - return list.get(index); - } - - @Override - public void add(int index, T element) { - list.add(index, element); - } - - @Override - public abstract NbtAbstractList clone(); - - @Override - public boolean contains(Object o) { - return list.contains(o); - } - - @Override - public Object[] toArray() { - return list.toArray(); - } - - @Override - public E[] toArray(E[] a) { - return list.toArray(a); - } - - @Override - public boolean remove(Object o) { - return list.remove(o); - } - - @Override - public boolean containsAll(Collection c) { - return list.containsAll(c); - } - - @Override - public boolean addAll(Collection c) { - return list.addAll(c); - } - - @Override - public boolean addAll(int index, Collection c) { - return list.addAll(index, c); - } - - @Override - public boolean removeAll(Collection c) { - return list.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return list.retainAll(c); - } - - @Override - public void clear() { - list.clear(); - } - - @Override - public T set(int index, T element) { - return list.set(index, element); - } - - @Override - public T remove(int index) { - return list.remove(index); - } - - @Override - public int indexOf(Object o) { - return list.indexOf(o); - } - - @Override - public int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } - - @Override - public ListIterator listIterator() { - return list.listIterator(); - } - - @Override - public ListIterator listIterator(int index) { - return list.listIterator(index); - } - - @Override - public abstract NbtAbstractList subList(int fromIndex, int toIndex); - - @Override - public List getValue() { - return list; - } + protected ArrayList list = new ArrayList<>(); + + @Override + public Iterator iterator() { + return list.iterator(); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public boolean add(T e) { + return list.add(e); + } + + @Override + public T get(int index) { + return list.get(index); + } + + @Override + public void add(int index, T element) { + list.add(index, element); + } + + @Override + public abstract NbtAbstractList clone(); + + @Override + public boolean contains(Object o) { + return list.contains(o); + } + + @Override + public Object[] toArray() { + return list.toArray(); + } + + @Override + public E[] toArray(E[] a) { + return list.toArray(a); + } + + @Override + public boolean remove(Object o) { + return list.remove(o); + } + + @Override + public boolean containsAll(Collection c) { + return list.containsAll(c); + } + + @Override + public boolean addAll(Collection c) { + return list.addAll(c); + } + + @Override + public boolean addAll(int index, Collection c) { + return list.addAll(index, c); + } + + @Override + public boolean removeAll(Collection c) { + return list.removeAll(c); + } + + @Override + public boolean retainAll(Collection c) { + return list.retainAll(c); + } + + @Override + public void clear() { + list.clear(); + } + + @Override + public T set(int index, T element) { + return list.set(index, element); + } + + @Override + public T remove(int index) { + return list.remove(index); + } + + @Override + public int indexOf(Object o) { + return list.indexOf(o); + } + + @Override + public int lastIndexOf(Object o) { + return list.lastIndexOf(o); + } + + @Override + public ListIterator listIterator() { + return list.listIterator(); + } + + @Override + public ListIterator listIterator(int index) { + return list.listIterator(index); + } + + @Override + public abstract NbtAbstractList subList(int fromIndex, int toIndex); + + @Override + public List getValue() { + return list; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigDecimal.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigDecimal.java index 5c8e488..68a417a 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigDecimal.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigDecimal.java @@ -6,50 +6,50 @@ public class NbtBigDecimal extends NbtString { - private BigDecimal bigDecimal; - - public NbtBigDecimal() { - - } - - public NbtBigDecimal(String value) { - super(Strings.isNumeric(value) ? value : "0"); - } - - public NbtBigDecimal(BigDecimal decimal) { - super(decimal.toString()); - this.bigDecimal = decimal; - } - - @Override - public boolean isBigInteger() { - return true; - } - - public BigDecimal getDecimal() { - return bigDecimal; - } - - @Override - public String getValue() { - return super.getValue(); - } - - @Override - public void setValue(String value) { - if (!Strings.isNumeric(value)) { - return; - } - setValue(new BigDecimal(value)); - } - - public void setValue(BigDecimal integer) { - super.setValue((bigDecimal = integer).toString()); - } - - @Override - public NbtString clone() { - return new NbtBigInt(bigDecimal.toString()); - } + private BigDecimal bigDecimal; + + public NbtBigDecimal() { + + } + + public NbtBigDecimal(String value) { + super(Strings.isNumeric(value) ? value : "0"); + } + + public NbtBigDecimal(BigDecimal decimal) { + super(decimal.toString()); + this.bigDecimal = decimal; + } + + @Override + public boolean isBigInteger() { + return true; + } + + public BigDecimal getDecimal() { + return bigDecimal; + } + + @Override + public String getValue() { + return super.getValue(); + } + + @Override + public void setValue(String value) { + if (!Strings.isNumeric(value)) { + return; + } + setValue(new BigDecimal(value)); + } + + public void setValue(BigDecimal integer) { + super.setValue((bigDecimal = integer).toString()); + } + + @Override + public NbtString clone() { + return new NbtBigInt(bigDecimal.toString()); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigInt.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigInt.java index 0a881e7..9f58745 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigInt.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtBigInt.java @@ -6,50 +6,50 @@ public class NbtBigInt extends NbtString { - private BigInteger bigInteger; - - public NbtBigInt() { - - } - - public NbtBigInt(String value) { - super(Strings.isNumeric(value) ? value : "0"); - } - - public NbtBigInt(BigInteger integer) { - super(integer.toString()); - this.bigInteger = integer; - } - - @Override - public boolean isBigInteger() { - return true; - } - - public BigInteger getInteger() { - return bigInteger; - } - - @Override - public String getValue() { - return super.getValue(); - } - - @Override - public void setValue(String value) { - if (!Strings.isNumeric(value)) { - return; - } - setValue(new BigInteger(value)); - } - - public void setValue(BigInteger integer) { - super.setValue((bigInteger = integer).toString()); - } - - @Override - public NbtString clone() { - return new NbtBigInt(bigInteger.toString()); - } + private BigInteger bigInteger; + + public NbtBigInt() { + + } + + public NbtBigInt(String value) { + super(Strings.isNumeric(value) ? value : "0"); + } + + public NbtBigInt(BigInteger integer) { + super(integer.toString()); + this.bigInteger = integer; + } + + @Override + public boolean isBigInteger() { + return true; + } + + public BigInteger getInteger() { + return bigInteger; + } + + @Override + public String getValue() { + return super.getValue(); + } + + @Override + public void setValue(String value) { + if (!Strings.isNumeric(value)) { + return; + } + setValue(new BigInteger(value)); + } + + public void setValue(BigInteger integer) { + super.setValue((bigInteger = integer).toString()); + } + + @Override + public NbtString clone() { + return new NbtBigInt(bigInteger.toString()); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByte.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByte.java index 246f984..94d349e 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByte.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByte.java @@ -5,63 +5,63 @@ */ public final class NbtByte extends NbtTag implements Cloneable, NbtNumber { - private byte value; - - public NbtByte() { - this.value = 0; - } - - public NbtByte(byte value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.byteValue(); - } - - @Override - public Byte getValue() { - return value; - } - - public byte getByteValue() { - return value; - } - - public void setByteValue(byte value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.BYTE; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtByte && equals((NbtByte) obj); - } - - public boolean equals(NbtByte tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Byte.hashCode(value); - } - - @Override - public String toMSONString() { - return Byte.toUnsignedInt(value) + "b"; - } - - @Override - public NbtByte clone() { - return new NbtByte(value); - } + private byte value; + + public NbtByte() { + this.value = 0; + } + + public NbtByte(byte value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.byteValue(); + } + + @Override + public Byte getValue() { + return value; + } + + public byte getByteValue() { + return value; + } + + public void setByteValue(byte value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.BYTE; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtByte && equals((NbtByte) obj); + } + + public boolean equals(NbtByte tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Byte.hashCode(value); + } + + @Override + public String toMSONString() { + return Byte.toUnsignedInt(value) + "b"; + } + + @Override + public NbtByte clone() { + return new NbtByte(value); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByteArray.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByteArray.java index 41e133e..8a93f07 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByteArray.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtByteArray.java @@ -7,63 +7,64 @@ */ public final class NbtByteArray extends NbtTag { - private final byte[] value; + private final byte[] value; - public NbtByteArray(byte[] value) { - this.value = value; - } + public NbtByteArray(byte[] value) { + this.value = value; + } - public NbtByteArray(Number[] numbers) { - this.value = new byte[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].byteValue(); - } + public NbtByteArray(Number[] numbers) { + this.value = new byte[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + value[i] = numbers[i].byteValue(); + } + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public byte[] getValue() { - return value; - } + @Override + public byte[] getValue() { + return value; + } - @Override - public NbtType getType() { - return NbtType.BYTE_ARRAY; - } + @Override + public NbtType getType() { + return NbtType.BYTE_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NbtByteArray && equals((NbtByteArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NbtByteArray && equals((NbtByteArray) obj); + } - public boolean equals(NbtByteArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NbtByteArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[B;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]).append('B'); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[B;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]).append('B'); + } + return stringbuilder.append(']').toString(); + } - @Override - public NbtByteArray clone() { - return new NbtByteArray(value.clone()); - } + @Override + public NbtByteArray clone() { + return new NbtByteArray(value.clone()); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtCompound.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtCompound.java index 522f72e..42f4262 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtCompound.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtCompound.java @@ -2,8 +2,14 @@ import java.math.BigDecimal; import java.math.BigInteger; -import java.util.*; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Set; import java.util.function.BiConsumer; import java.util.regex.Pattern; @@ -12,554 +18,574 @@ */ public final class NbtCompound extends NbtTag { - private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); - - private final Map value; - - public NbtCompound(Map value) { - this.value = new LinkedHashMap<>(value); - } - - public NbtCompound(NbtNamedTag... tags) { - this.value = new LinkedHashMap<>(); - - for (NbtNamedTag tag : tags) - this.value.put(tag.getName(), tag.getTag()); - } - - public NbtCompound() { - this.value = new LinkedHashMap<>(); - } - - // GETTERS - - /** - * Returns the size of this compound. - * - * @return the size of this compound - */ - public int size() { - return value.size(); - } - - @Override - public Map getValue() { - return value; - } - - @Override - public NbtType getType() { - return NbtType.COMPOUND; - } - - public void clear() { - value.clear(); - } - - @Override - public NbtCompound clone() { - NbtCompound compound = new NbtCompound(); - for (Entry entry : value.entrySet()) { - compound.set(entry.getKey(), entry.getValue().clone()); - } - return compound; - } - - /** - * Returns a tag number named with the given key. - * - * @param key the key - * @return a byte - * @throws NoSuchElementException if there is no tag with given name - */ - public NbtNumber getNumber(String key) { - if (!hasKey(key)) - return null; - NbtTag tag = get(key); - if (!(tag instanceof NbtNumber)) - return null; - return (NbtNumber) tag; - } - - /** - * Removes a value with given Key - * - * @param key the key - * @return value - */ - public NbtTag remove(String key) { - if (hasKey(key)) - return value.remove(key); - return null; - } - - /** - * Returns a tag named with the given key. - * - * @param key the key - * @return a byte - * @throws NoSuchElementException if there is no tag with given name - */ - public NbtTag get(String key) { - if (!hasKey(key)) - return null; - return value.get(key); - } - - /** - * Returns a byte named with the given key. - * - * @param key the key - * @return a byte - * @throws NoSuchElementException if there is no byte with given name - */ - public byte getByte(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtByte)) - return 0; - return ((NbtByte) tag).getValue(); - } - - /** - * Returns an short named with the given key. - * - * @param key the key - * @return an short - * @throws NoSuchElementException if there is no short with given name - */ - public short getShort(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtShort)) - return 0; - return ((NbtShort) tag).getValue(); - } - - /** - * Returns an int named with the given key. - * - * @param key the key - * @return an int - * @throws NoSuchElementException if there is no int with given name - */ - public int getInt(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtInt)) - return 0; - return ((NbtInt) tag).getValue(); - } - - /** - * Returns an int named with the given key. - * - * @param key the key - * @return an int - * @throws NoSuchElementException if there is no int with given name - */ - public BigInteger getBigInt(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtBigInt)) - return null; - return ((NbtBigInt) tag).getInteger(); - } - - /** - * Returns an long named with the given key. - * - * @param key the key - * @return an long - * @throws NoSuchElementException if there is no long with given name - */ - public long getLong(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtLong)) - return 0; - return ((NbtLong) tag).getValue(); - } - - /** - * Returns float named with the given key. - * - * @param key the key - * @return a float - * @throws NoSuchElementException if there is no float with given name - */ - public float getFloat(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtFloat)) - return 0; - return ((NbtFloat) tag).getValue(); - } - - /** - * Returns a double named with the given key. - * - * @param key the key - * @return a double - * @throws NoSuchElementException if there is no int with given name - */ - public double getDouble(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtDouble)) - return 0; - return ((NbtDouble) tag).getValue(); - } - - /** - * Returns a byte array named with the given key. - * - * @param key the key - * @return a byte array - * @throws NoSuchElementException if there is no int with given name - */ - public byte[] getByteArray(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtByteArray)) - return null; - return ((NbtByteArray) tag).getValue(); - } - - /** - * Returns a string named with the given key. - * - * @param key the key - * @return a string - * @throws NoSuchElementException if there is no int with given name - */ - public String getString(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtString)) - return null; - return ((NbtString) tag).getValue(); - } - - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no int with given name - */ - public List getList(String key) { - NbtList list = getTagList(key); - if (list == null) - return list; - return list.getValue(); - } - - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no list with given name - */ - public NbtList getTagList(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtList)) - return null; - return (NbtList) tag; - } - - /** - * Returns a list named with the given key. - * - * @param key the key - * @return a list - * @throws NoSuchElementException if there is no compound with given name - */ - public Map getCompoundMap(String key) { - return getCompound(key).getValue(); - } - - /** - * Returns a compound named with the given key. - * - * @param key the key - * @return a compound - * @throws NoSuchElementException if there is no compound with given name - */ - public NbtCompound getCompound(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtCompound)) - return null; - return (NbtCompound) tag; - } - - /** - * Returns an int array named with the given key. - * - * @param key the key - * @return a int array - * @throws NoSuchElementException if there is no int array with given name - */ - public int[] getIntArray(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtIntArray)) - return null; - return ((NbtIntArray) tag).getValue(); - } - - /** - * Returns a long array named with the given key. - * - * @param key the key - * @return a int array - * @throws NoSuchElementException if there is no int array with given name - */ - public long[] getLongArray(String key) { - NbtTag tag = value.get(key); - if (!(tag instanceof NbtLongArray)) - return null; - return ((NbtLongArray) tag).getValue(); - } - - /** - * Returns a boolean named with the given key. - * - * @param path the key - * @return a boolean - * @throws NoSuchElementException if there is no boolean with given name - */ - public boolean getBoolean(String path) { - byte byt = getByte(path); - if (byt == 0 || byt == 1) { - return byt == 1; - } - return false; - } - - /** - * Returns an immutable set containing all the keys in this compound. - * - * @return an immutable set - */ - public Set getKeys() { - return Collections.unmodifiableSet(value.keySet()); - } - - // PREDICATES - - /** - * Returns whether this compound is empty. - * - * @return whether this compound is empty - */ - public boolean isEmpty() { - return value.isEmpty(); - } - - /** - * Returns whether this compound tag contains the given key. - * - * @param key the given key - * @return true if the tag contains the given key - */ - public boolean hasKey(String key) { - return value.containsKey(key); - } - - /** - * Returns whether this compound tag contains the given key and its value is of - * a given type. - * - * @param key the given key - * @param type the type of the value - * @return true if the tag contains an entry with given key and of given type - */ - public boolean hasKey(String key, NbtType type) { - Objects.requireNonNull(type); - return value.containsKey(key) && value.get(key).getType() == type; - } - - /** - * Returns whether this compound tag contains the given key and its value is of - * a given type. - * - * @param key the given key - * @param type the type of the value - * @return true if the tag contains an entry with given key and of given type - */ - public boolean hasKeyOfType(String key, NbtType type) { - return hasKey(key, type); - } - - // MUTATORS - - /** - * Put the given name and its corresponding tag into the compound tag. - * - * @param name the tag name - * @param tag the tag value - */ - public void set(String name, NbtTag tag) { - this.value.put(name, tag); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, byte[] value) { - set(key, new NbtByteArray(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, byte value) { - set(key, new NbtByte(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param path the key - * @param bool the value - */ - public void set(String path, boolean bool) { - set(path, (byte) (bool ? 1 : 0)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, double value) { - set(key, new NbtDouble(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, float value) { - set(key, new NbtFloat(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, int[] value) { - set(key, new NbtIntArray(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, long[] value) { - set(key, new NbtLongArray(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, int value) { - set(key, new NbtInt(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, BigInteger value) { - set(key, new NbtBigInt(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, BigDecimal value) { - set(key, new NbtBigDecimal(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, long value) { - set(key, new NbtLong(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, short value) { - set(key, new NbtShort(value)); - } - - /** - * Put the given key and value into the compound tag. - * - * @param key they key - * @param value the value - */ - public void set(String key, String value) { - set(key, new NbtString(value)); - } - - // ITERATION - - /** - * Performs an action for every pair of keys and tags. - * - * @param action the action - */ - public void forEach(BiConsumer action) { - this.value.forEach(action::accept); - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtCompound && equals((NbtCompound) obj); - } - - public boolean equals(NbtCompound tag) { - return this.isEmpty() && tag.isEmpty() || this.value.equals(tag.value); - } - - @Override - public String toMSONString() { - StringBuilder builder = new StringBuilder("{"); - Set keys = this.value.keySet(); - - for (String key : keys) { - if (builder.length() > 1) { - builder.append(','); - } - builder.append(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)).append(':').append(this.value.get(key).toMSONString()); - } - - return builder.append("}").toString(); - } + private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); + + private final Map value; + + public NbtCompound(Map value) { + this.value = new LinkedHashMap<>(value); + } + + public NbtCompound(NbtNamedTag... tags) { + this.value = new LinkedHashMap<>(); + + for (NbtNamedTag tag : tags) { + this.value.put(tag.getName(), tag.getTag()); + } + } + + public NbtCompound() { + this.value = new LinkedHashMap<>(); + } + + // GETTERS + + /** + * Returns the size of this compound. + * + * @return the size of this compound + */ + public int size() { + return value.size(); + } + + @Override + public Map getValue() { + return value; + } + + @Override + public NbtType getType() { + return NbtType.COMPOUND; + } + + public void clear() { + value.clear(); + } + + @Override + public NbtCompound clone() { + NbtCompound compound = new NbtCompound(); + for (Entry entry : value.entrySet()) { + compound.set(entry.getKey(), entry.getValue().clone()); + } + return compound; + } + + /** + * Returns a tag number named with the given key. + * + * @param key the key + * @return a byte + * @throws NoSuchElementException if there is no tag with given name + */ + public NbtNumber getNumber(String key) { + if (!hasKey(key)) { + return null; + } + NbtTag tag = get(key); + if (!(tag instanceof NbtNumber)) { + return null; + } + return (NbtNumber) tag; + } + + /** + * Removes a value with given Key + * + * @param key the key + * @return value + */ + public NbtTag remove(String key) { + if (hasKey(key)) { + return value.remove(key); + } + return null; + } + + /** + * Returns a tag named with the given key. + * + * @param key the key + * @return a byte + * @throws NoSuchElementException if there is no tag with given name + */ + public NbtTag get(String key) { + if (!hasKey(key)) { + return null; + } + return value.get(key); + } + + /** + * Returns a byte named with the given key. + * + * @param key the key + * @return a byte + * @throws NoSuchElementException if there is no byte with given name + */ + public byte getByte(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtByte)) { + return 0; + } + return ((NbtByte) tag).getValue(); + } + + /** + * Returns an short named with the given key. + * + * @param key the key + * @return an short + * @throws NoSuchElementException if there is no short with given name + */ + public short getShort(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtShort)) { + return 0; + } + return ((NbtShort) tag).getValue(); + } + + /** + * Returns an int named with the given key. + * + * @param key the key + * @return an int + * @throws NoSuchElementException if there is no int with given name + */ + public int getInt(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtInt)) { + return 0; + } + return ((NbtInt) tag).getValue(); + } + + /** + * Returns an int named with the given key. + * + * @param key the key + * @return an int + * @throws NoSuchElementException if there is no int with given name + */ + public BigInteger getBigInt(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtBigInt)) { + return null; + } + return ((NbtBigInt) tag).getInteger(); + } + + /** + * Returns an long named with the given key. + * + * @param key the key + * @return an long + * @throws NoSuchElementException if there is no long with given name + */ + public long getLong(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtLong)) { + return 0; + } + return ((NbtLong) tag).getValue(); + } + + /** + * Returns float named with the given key. + * + * @param key the key + * @return a float + * @throws NoSuchElementException if there is no float with given name + */ + public float getFloat(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtFloat)) { + return 0; + } + return ((NbtFloat) tag).getValue(); + } + + /** + * Returns a double named with the given key. + * + * @param key the key + * @return a double + * @throws NoSuchElementException if there is no int with given name + */ + public double getDouble(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtDouble)) { + return 0; + } + return ((NbtDouble) tag).getValue(); + } + + /** + * Returns a byte array named with the given key. + * + * @param key the key + * @return a byte array + * @throws NoSuchElementException if there is no int with given name + */ + public byte[] getByteArray(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtByteArray)) { + return null; + } + return ((NbtByteArray) tag).getValue(); + } + + /** + * Returns a string named with the given key. + * + * @param key the key + * @return a string + * @throws NoSuchElementException if there is no int with given name + */ + public String getString(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtString)) { + return null; + } + return ((NbtString) tag).getValue(); + } + + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no int with given name + */ + public List getList(String key) { + NbtList list = getTagList(key); + if (list == null) { + return list; + } + return list.getValue(); + } + + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no list with given name + */ + public NbtList getTagList(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtList)) { + return null; + } + return (NbtList) tag; + } + + /** + * Returns a list named with the given key. + * + * @param key the key + * @return a list + * @throws NoSuchElementException if there is no compound with given name + */ + public Map getCompoundMap(String key) { + return getCompound(key).getValue(); + } + + /** + * Returns a compound named with the given key. + * + * @param key the key + * @return a compound + * @throws NoSuchElementException if there is no compound with given name + */ + public NbtCompound getCompound(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtCompound)) { + return null; + } + return (NbtCompound) tag; + } + + /** + * Returns an int array named with the given key. + * + * @param key the key + * @return a int array + * @throws NoSuchElementException if there is no int array with given name + */ + public int[] getIntArray(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtIntArray)) { + return null; + } + return ((NbtIntArray) tag).getValue(); + } + + /** + * Returns a long array named with the given key. + * + * @param key the key + * @return a int array + * @throws NoSuchElementException if there is no int array with given name + */ + public long[] getLongArray(String key) { + NbtTag tag = value.get(key); + if (!(tag instanceof NbtLongArray)) { + return null; + } + return ((NbtLongArray) tag).getValue(); + } + + /** + * Returns a boolean named with the given key. + * + * @param path the key + * @return a boolean + * @throws NoSuchElementException if there is no boolean with given name + */ + public boolean getBoolean(String path) { + byte byt = getByte(path); + if (byt == 0 || byt == 1) { + return byt == 1; + } + return false; + } + + /** + * Returns an immutable set containing all the keys in this compound. + * + * @return an immutable set + */ + public Set getKeys() { + return Collections.unmodifiableSet(value.keySet()); + } + + // PREDICATES + + /** + * Returns whether this compound is empty. + * + * @return whether this compound is empty + */ + public boolean isEmpty() { + return value.isEmpty(); + } + + /** + * Returns whether this compound tag contains the given key. + * + * @param key the given key + * @return true if the tag contains the given key + */ + public boolean hasKey(String key) { + return value.containsKey(key); + } + + /** + * Returns whether this compound tag contains the given key and its value is of + * a given type. + * + * @param key the given key + * @param type the type of the value + * @return true if the tag contains an entry with given key and of given type + */ + public boolean hasKey(String key, NbtType type) { + Objects.requireNonNull(type); + return value.containsKey(key) && value.get(key).getType() == type; + } + + /** + * Returns whether this compound tag contains the given key and its value is of + * a given type. + * + * @param key the given key + * @param type the type of the value + * @return true if the tag contains an entry with given key and of given type + */ + public boolean hasKeyOfType(String key, NbtType type) { + return hasKey(key, type); + } + + // MUTATORS + + /** + * Put the given name and its corresponding tag into the compound tag. + * + * @param name the tag name + * @param tag the tag value + */ + public void set(String name, NbtTag tag) { + this.value.put(name, tag); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, byte[] value) { + set(key, new NbtByteArray(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, byte value) { + set(key, new NbtByte(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param path the key + * @param bool the value + */ + public void set(String path, boolean bool) { + set(path, (byte) (bool ? 1 : 0)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, double value) { + set(key, new NbtDouble(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, float value) { + set(key, new NbtFloat(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, int[] value) { + set(key, new NbtIntArray(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, long[] value) { + set(key, new NbtLongArray(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, int value) { + set(key, new NbtInt(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, BigInteger value) { + set(key, new NbtBigInt(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, BigDecimal value) { + set(key, new NbtBigDecimal(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, long value) { + set(key, new NbtLong(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, short value) { + set(key, new NbtShort(value)); + } + + /** + * Put the given key and value into the compound tag. + * + * @param key they key + * @param value the value + */ + public void set(String key, String value) { + set(key, new NbtString(value)); + } + + // ITERATION + + /** + * Performs an action for every pair of keys and tags. + * + * @param action the action + */ + public void forEach(BiConsumer action) { + this.value.forEach(action::accept); + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtCompound && equals((NbtCompound) obj); + } + + public boolean equals(NbtCompound tag) { + return this.isEmpty() && tag.isEmpty() || this.value.equals(tag.value); + } + + @Override + public String toMSONString() { + StringBuilder builder = new StringBuilder("{"); + Set keys = this.value.keySet(); + + for (String key : keys) { + if (builder.length() > 1) { + builder.append(','); + } + builder.append(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)).append(':') + .append(this.value.get(key).toMSONString()); + } + + return builder.append("}").toString(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtDouble.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtDouble.java index 50e30da..52cd41e 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtDouble.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtDouble.java @@ -6,63 +6,63 @@ */ public final class NbtDouble extends NbtTag implements Cloneable, NbtNumber { - private double value; - - public NbtDouble() { - this.value = 0; - } - - public NbtDouble(double value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.doubleValue(); - } - - @Override - public Double getValue() { - return value; - } - - public double getDoubleValue() { - return value; - } - - public void setDoubleValue(double value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.DOUBLE; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtDouble && equals((NbtDouble) obj); - } - - public boolean equals(NbtDouble tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Double.hashCode(value); - } - - @Override - public String toMSONString() { - return value + "d"; - } - - @Override - public NbtDouble clone() { - return new NbtDouble(value); - } + private double value; + + public NbtDouble() { + this.value = 0; + } + + public NbtDouble(double value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.doubleValue(); + } + + @Override + public Double getValue() { + return value; + } + + public double getDoubleValue() { + return value; + } + + public void setDoubleValue(double value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.DOUBLE; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtDouble && equals((NbtDouble) obj); + } + + public boolean equals(NbtDouble tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Double.hashCode(value); + } + + @Override + public String toMSONString() { + return value + "d"; + } + + @Override + public NbtDouble clone() { + return new NbtDouble(value); + } } \ No newline at end of file diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtEnd.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtEnd.java index 07c7c31..98e15bf 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtEnd.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtEnd.java @@ -5,36 +5,35 @@ */ public final class NbtEnd extends NbtTag implements Cloneable { - public final static NbtEnd INSTANCE = new NbtEnd(); + public final static NbtEnd INSTANCE = new NbtEnd(); - private NbtEnd() { - } + private NbtEnd() {} - @Override - public Void getValue() { - return null; - } + @Override + public Void getValue() { + return null; + } - @Override - public NbtType getType() { - return NbtType.END; - } + @Override + public NbtType getType() { + return NbtType.END; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NbtEnd; - } + @Override + public boolean equals(Object obj) { + return obj instanceof NbtEnd; + } - @Override - public String toMSONString() { - return "END"; - } + @Override + public String toMSONString() { + return "END"; + } - @Override - public NbtEnd clone() { - return INSTANCE; - } + @Override + public NbtEnd clone() { + return INSTANCE; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtFloat.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtFloat.java index 04b3c71..4967a18 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtFloat.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtFloat.java @@ -5,63 +5,63 @@ */ public final class NbtFloat extends NbtTag implements Cloneable, NbtNumber { - private float value; - - public NbtFloat() { - this.value = 0; - } - - public NbtFloat(float value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.floatValue(); - } - - @Override - public Float getValue() { - return value; - } - - public float getFloatValue() { - return value; - } - - public void setFloatValue(float value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.FLOAT; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtFloat && equals((NbtFloat) obj); - } - - public boolean equals(NbtFloat tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Float.hashCode(value); - } - - @Override - public String toMSONString() { - return value + "f"; - } - - @Override - public NbtFloat clone() { - return new NbtFloat(value); - } + private float value; + + public NbtFloat() { + this.value = 0; + } + + public NbtFloat(float value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.floatValue(); + } + + @Override + public Float getValue() { + return value; + } + + public float getFloatValue() { + return value; + } + + public void setFloatValue(float value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.FLOAT; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtFloat && equals((NbtFloat) obj); + } + + public boolean equals(NbtFloat tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Float.hashCode(value); + } + + @Override + public String toMSONString() { + return value + "f"; + } + + @Override + public NbtFloat clone() { + return new NbtFloat(value); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtInt.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtInt.java index da55277..8ddebc6 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtInt.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtInt.java @@ -5,63 +5,63 @@ */ public final class NbtInt extends NbtTag implements Cloneable, NbtNumber { - private int value; - - public NbtInt() { - this.value = 0; - } - - public NbtInt(int value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.intValue(); - } - - @Override - public Integer getValue() { - return value; - } - - public int getIntValue() { - return value; - } - - public void setIntValue(int value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.INT; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtInt && equals((NbtInt) obj); - } - - public boolean equals(NbtInt tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Integer.hashCode(value); - } - - @Override - public String toMSONString() { - return Integer.toString(value); - } - - @Override - public NbtInt clone() { - return new NbtInt(value); - } + private int value; + + public NbtInt() { + this.value = 0; + } + + public NbtInt(int value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.intValue(); + } + + @Override + public Integer getValue() { + return value; + } + + public int getIntValue() { + return value; + } + + public void setIntValue(int value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.INT; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtInt && equals((NbtInt) obj); + } + + public boolean equals(NbtInt tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Integer.hashCode(value); + } + + @Override + public String toMSONString() { + return Integer.toString(value); + } + + @Override + public NbtInt clone() { + return new NbtInt(value); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtIntArray.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtIntArray.java index 5e2cc70..0399338 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtIntArray.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtIntArray.java @@ -8,68 +8,69 @@ */ public final class NbtIntArray extends NbtTag implements Cloneable { - private final int[] value; + private final int[] value; - /** - * Creates the tag with an empty name. - * - * @param value the value of the tag - */ - public NbtIntArray(int[] value) { - this.value = Objects.requireNonNull(value); - } + /** + * Creates the tag with an empty name. + * + * @param value the value of the tag + */ + public NbtIntArray(int[] value) { + this.value = Objects.requireNonNull(value); + } - public NbtIntArray(Number[] numbers) { - this.value = new int[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].intValue(); - } + public NbtIntArray(Number[] numbers) { + this.value = new int[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + value[i] = numbers[i].intValue(); + } + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public int[] getValue() { - return value; - } + @Override + public int[] getValue() { + return value; + } - @Override - public NbtType getType() { - return NbtType.INT_ARRAY; - } + @Override + public NbtType getType() { + return NbtType.INT_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NbtIntArray && equals((NbtIntArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NbtIntArray && equals((NbtIntArray) obj); + } - public boolean equals(NbtIntArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NbtIntArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[I;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[I;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]); + } + return stringbuilder.append(']').toString(); + } - @Override - public NbtIntArray clone() { - return new NbtIntArray(value.clone()); - } + @Override + public NbtIntArray clone() { + return new NbtIntArray(value.clone()); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtList.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtList.java index 7a3d256..f409fec 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtList.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtList.java @@ -11,253 +11,255 @@ */ public final class NbtList extends NbtAbstractList { - private NbtType type; + private NbtType type; - private NbtList(NbtType type, List list) { - addAll(list); - this.type = type; - } + private NbtList(NbtType type, List list) { + addAll(list); + this.type = type; + } - public NbtList(NbtType type) { - this.type = type; - } + public NbtList(NbtType type) { + this.type = type; + } - /** - * Creates the list with a type and a series of elements. - * - * @param list the value of the tag - */ - public NbtList(List list) { - if (list != null && !list.isEmpty()) { - addAll(list); - type = list.get(0).getType(); - } - } + /** + * Creates the list with a type and a series of elements. + * + * @param list the value of the tag + */ + public NbtList(List list) { + if (list != null && !list.isEmpty()) { + addAll(list); + type = list.get(0).getType(); + } + } - /** - * Creates the list with a type and a series of elements. - * - * @param array the value of the tag - */ - @SuppressWarnings("unchecked") - public NbtList(T... array) { - if (array.length == 0) { - return; - } - addAll(Arrays.asList(array)); - type = array[0].getType(); - } + /** + * Creates the list with a type and a series of elements. + * + * @param array the value of the tag + */ + @SuppressWarnings("unchecked") + public NbtList(T... array) { + if (array.length == 0) { + return; + } + addAll(Arrays.asList(array)); + type = array[0].getType(); + } - /** - * Creates an empty list with a type. - */ - public NbtList() { + /** + * Creates an empty list with a type. + */ + public NbtList() { - } + } - /** - * Add a Tag to the list - * - * @param element - tag that gets added - * - * @return if it had the same type or not - */ - @SuppressWarnings("unchecked") - public boolean addTag(NbtTag element) { - if (element != null) { - if (type == null) { - type = element.getType(); - } else if (element.getType() != type) { - return false; - } - } - return super.add((T) element); - } + /** + * Add a Tag to the list + * + * @param element - tag that gets added + * + * @return if it had the same type or not + */ + @SuppressWarnings("unchecked") + public boolean addTag(NbtTag element) { + if (element != null) { + if (type == null) { + type = element.getType(); + } else if (element.getType() != type) { + return false; + } + } + return super.add((T) element); + } - /** - * Add a Tag to the list at an specific index - * - * @param index - index at which the element should be inserted - * @param element - element to be inserted - * - * @return if it had the same type or not - */ - @SuppressWarnings("unchecked") - public boolean addTag(int index, NbtTag element) { - if (element != null) { - if (type == null) { - type = element.getType(); - } else if (element.getType() != type) { - return false; - } - } - super.add(index, (T) element); - return true; - } + /** + * Add a Tag to the list at an specific index + * + * @param index - index at which the element should be inserted + * @param element - element to be inserted + * + * @return if it had the same type or not + */ + @SuppressWarnings("unchecked") + public boolean addTag(int index, NbtTag element) { + if (element != null) { + if (type == null) { + type = element.getType(); + } else if (element.getType() != type) { + return false; + } + } + super.add(index, (T) element); + return true; + } - /** - * Add a Tag to the list - * - * @param element - element that gets added - * - * @return if it had the same type or not - */ - @Override - public boolean add(T element) { - if (element != null) { - if (type == null) { - type = element.getType(); - } else if (element.getType() != type) { - return false; - } - } - return super.add(element); - } + /** + * Add a Tag to the list + * + * @param element - element that gets added + * + * @return if it had the same type or not + */ + @Override + public boolean add(T element) { + if (element != null) { + if (type == null) { + type = element.getType(); + } else if (element.getType() != type) { + return false; + } + } + return super.add(element); + } - /** - * Add a Tag on a specific Index - * - * @param index - index at which the element should be inserted - * @param element - element to be inserted - */ - @Override - public void add(int index, T element) { - if (element != null) { - if (type == null) { - type = element.getType(); - } else if (element.getType() != type) { - return; - } - } - super.add(index, element); - } + /** + * Add a Tag on a specific Index + * + * @param index - index at which the element should be inserted + * @param element - element to be inserted + */ + @Override + public void add(int index, T element) { + if (element != null) { + if (type == null) { + type = element.getType(); + } else if (element.getType() != type) { + return; + } + } + super.add(index, element); + } - /** - * Adds all Tags of the collection into the list if they have the same type - * - * @param collection - that should be added - * - * @return if all values have been added or not - */ - @Override - public boolean addAll(Collection collection) { - if (collection.isEmpty()) { - return true; - } - int added = 0; - for (NbtTag tag : collection) { - if (addTag(tag)) - added++; - } - return added == collection.size(); - } + /** + * Adds all Tags of the collection into the list if they have the same type + * + * @param collection - that should be added + * + * @return if all values have been added or not + */ + @Override + public boolean addAll(Collection collection) { + if (collection.isEmpty()) { + return true; + } + int added = 0; + for (NbtTag tag : collection) { + if (addTag(tag)) { + added++; + } + } + return added == collection.size(); + } - /** - * Adds all Tags of the collection into the list starting at a specific index if - * they have the same type - * - * @param index - index where the values should be inserted - * @param collection - that should be inserted - * - * @return if all values have been added or not - */ - @Override - public boolean addAll(int index, Collection collection) { - if (collection.isEmpty()) { - return true; - } - int added = 0; - for (NbtTag tag : collection) { - if (addTag(index, tag)) { - added++; - index++; - } - } - return added == collection.size(); - } + /** + * Adds all Tags of the collection into the list starting at a specific index if + * they have the same type + * + * @param index - index where the values should be inserted + * @param collection - that should be inserted + * + * @return if all values have been added or not + */ + @Override + public boolean addAll(int index, Collection collection) { + if (collection.isEmpty()) { + return true; + } + int added = 0; + for (NbtTag tag : collection) { + if (addTag(index, tag)) { + added++; + index++; + } + } + return added == collection.size(); + } - /** - * Adds all Tags of the collection into the list if they have the same type - * - * @param collection that should be added - */ - public void addAllTags(Collection collection) { - if (collection.isEmpty()) { - return; - } - for (NbtTag tag : collection) { - addTag(tag); - } - } + /** + * Adds all Tags of the collection into the list if they have the same type + * + * @param collection that should be added + */ + public void addAllTags(Collection collection) { + if (collection.isEmpty()) { + return; + } + for (NbtTag tag : collection) { + addTag(tag); + } + } - /** - * Returns the size of this list. - * - * @return the size of this list - */ - @Override - public int size() { - return list.size(); - } + /** + * Returns the size of this list. + * + * @return the size of this list + */ + @Override + public int size() { + return list.size(); + } - @Override - public NbtType getType() { - return NbtType.LIST; - } + @Override + public NbtType getType() { + return NbtType.LIST; + } - /** - * Gets the type of elements in this list. - * - * @return The type of elements in this list. - */ - public NbtType getElementType() { - return type != null ? type : NbtType.COMPOUND; - } + /** + * Gets the type of elements in this list. + * + * @return The type of elements in this list. + */ + public NbtType getElementType() { + return type != null ? type : NbtType.COMPOUND; + } - @Override - public String toMSONString() { - StringBuilder builder = new StringBuilder("["); - Iterator iter = iterator(); + @Override + public String toMSONString() { + StringBuilder builder = new StringBuilder("["); + Iterator iter = iterator(); - boolean first = true; - while (iter.hasNext()) { - if (first) - first = false; - else - builder.append(','); - builder.append(iter.next().toMSONString()); - } + boolean first = true; + while (iter.hasNext()) { + if (first) { + first = false; + } else { + builder.append(','); + } + builder.append(iter.next().toMSONString()); + } - return builder.append("]").toString(); - } + return builder.append("]").toString(); + } - public static NbtList createFromType(NbtType type) { - return new NbtList<>(type); - } + public static NbtList createFromType(NbtType type) { + return new NbtList<>(type); + } - @SuppressWarnings("unchecked") - public static NbtList createFromTypeAndFill(NbtType type, Collection values) { - NbtList list = (NbtList) createFromType(type); - list.addAll(values); - return list; - } + @SuppressWarnings("unchecked") + public static NbtList createFromTypeAndFill(NbtType type, Collection values) { + NbtList list = (NbtList) createFromType(type); + list.addAll(values); + return list; + } - @SuppressWarnings("unchecked") - @Override - public NbtList clone() { - if (list.isEmpty()) { - return new NbtList(type); - } - List list = new ArrayList<>(); - for (T tag : this.list) { - list.add((T) tag.clone()); - } - return new NbtList(type, list); - } + @SuppressWarnings("unchecked") + @Override + public NbtList clone() { + if (list.isEmpty()) { + return new NbtList(type); + } + List list = new ArrayList<>(); + for (T tag : this.list) { + list.add((T) tag.clone()); + } + return new NbtList(type, list); + } - @Override - public NbtList subList(int fromIndex, int toIndex) { - return new NbtList(type, list.subList(fromIndex, toIndex)); - } + @Override + public NbtList subList(int fromIndex, int toIndex) { + return new NbtList(type, list.subList(fromIndex, toIndex)); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLong.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLong.java index e8bd454..ded4389 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLong.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLong.java @@ -5,63 +5,63 @@ */ public final class NbtLong extends NbtTag implements Cloneable, NbtNumber { - private long value; - - public NbtLong() { - this.value = 0; - } - - public NbtLong(long value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.longValue(); - } - - @Override - public Long getValue() { - return value; - } - - public long getLongValue() { - return value; - } - - public void setLongValue(long value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.LONG; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtLong && equals((NbtLong) obj); - } - - public boolean equals(NbtLong tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Long.hashCode(value); - } - - @Override - public String toMSONString() { - return value + "L"; - } - - @Override - public NbtLong clone() { - return new NbtLong(value); - } + private long value; + + public NbtLong() { + this.value = 0; + } + + public NbtLong(long value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.longValue(); + } + + @Override + public Long getValue() { + return value; + } + + public long getLongValue() { + return value; + } + + public void setLongValue(long value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.LONG; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtLong && equals((NbtLong) obj); + } + + public boolean equals(NbtLong tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Long.hashCode(value); + } + + @Override + public String toMSONString() { + return value + "L"; + } + + @Override + public NbtLong clone() { + return new NbtLong(value); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLongArray.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLongArray.java index 5619105..821b4d7 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLongArray.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtLongArray.java @@ -7,68 +7,69 @@ */ public final class NbtLongArray extends NbtTag { - private final long[] value; + private final long[] value; - /** - * Creates the tag with an empty name. - * - * @param value the value of the tag - */ - public NbtLongArray(long... value) { - this.value = value; - } + /** + * Creates the tag with an empty name. + * + * @param value the value of the tag + */ + public NbtLongArray(long... value) { + this.value = value; + } - public NbtLongArray(Number[] numbers) { - this.value = new long[numbers.length]; - for (int i = 0; i < numbers.length; i++) - value[i] = numbers[i].longValue(); - } + public NbtLongArray(Number[] numbers) { + this.value = new long[numbers.length]; + for (int i = 0; i < numbers.length; i++) { + value[i] = numbers[i].longValue(); + } + } - /** - * Returns the length of this array. - * - * @return the length of this array - */ - public int length() { - return value.length; - } + /** + * Returns the length of this array. + * + * @return the length of this array + */ + public int length() { + return value.length; + } - @Override - public long[] getValue() { - return value; - } + @Override + public long[] getValue() { + return value; + } - @Override - public NbtType getType() { - return NbtType.LONG_ARRAY; - } + @Override + public NbtType getType() { + return NbtType.LONG_ARRAY; + } - // MISC + // MISC - @Override - public boolean equals(Object obj) { - return obj instanceof NbtLongArray && equals((NbtLongArray) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof NbtLongArray && equals((NbtLongArray) obj); + } - public boolean equals(NbtLongArray tag) { - return Arrays.equals(this.value, tag.value); - } + public boolean equals(NbtLongArray tag) { + return Arrays.equals(this.value, tag.value); + } - @Override - public String toMSONString() { - StringBuilder stringbuilder = new StringBuilder("[I;"); - for (int i = 0; i < this.value.length; i++) { - if (i != 0) { - stringbuilder.append(','); - } - stringbuilder.append(this.value[i]); - } - return stringbuilder.append(']').toString(); - } + @Override + public String toMSONString() { + StringBuilder stringbuilder = new StringBuilder("[I;"); + for (int i = 0; i < this.value.length; i++) { + if (i != 0) { + stringbuilder.append(','); + } + stringbuilder.append(this.value[i]); + } + return stringbuilder.append(']').toString(); + } - @Override - public NbtLongArray clone() { - return new NbtLongArray(value.clone()); - } + @Override + public NbtLongArray clone() { + return new NbtLongArray(value.clone()); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNamedTag.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNamedTag.java index cbf2ad9..b35f5cc 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNamedTag.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNamedTag.java @@ -6,47 +6,47 @@ */ public class NbtNamedTag { - private final String name; - private final NbtTag tag; - - /** - * Constructs a new named tag. - * - * @param name the name - * @param tag the tag - */ - public NbtNamedTag(String name, NbtTag tag) { - this.name = name; - this.tag = tag; - } - - /** - * Returns the name of the tag. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Returns the tag. - * - * @return the tag - */ - public NbtTag getTag() { - return tag; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtNamedTag && equals((NbtNamedTag) obj); - } - - public boolean equals(NbtNamedTag tag) { - return this.name.equals(tag.name) && this.tag.equals(tag.tag); - } + private final String name; + private final NbtTag tag; + + /** + * Constructs a new named tag. + * + * @param name the name + * @param tag the tag + */ + public NbtNamedTag(String name, NbtTag tag) { + this.name = name; + this.tag = tag; + } + + /** + * Returns the name of the tag. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Returns the tag. + * + * @return the tag + */ + public NbtTag getTag() { + return tag; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtNamedTag && equals((NbtNamedTag) obj); + } + + public boolean equals(NbtNamedTag tag) { + return this.name.equals(tag.name) && this.tag.equals(tag.tag); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNumber.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNumber.java index f85d638..aee04fb 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNumber.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtNumber.java @@ -5,62 +5,62 @@ public interface NbtNumber { - public Number getValue(); + public Number getValue(); - public void setValue(Number number); + public void setValue(Number number); - public default byte asByte() { - return getValue().byteValue(); - } + public default byte asByte() { + return getValue().byteValue(); + } - public default short asShort() { - return getValue().shortValue(); - } + public default short asShort() { + return getValue().shortValue(); + } - public default int asInt() { - return getValue().intValue(); - } + public default int asInt() { + return getValue().intValue(); + } - public default float asFloat() { - return getValue().floatValue(); - } + public default float asFloat() { + return getValue().floatValue(); + } - public default long asLong() { - return getValue().longValue(); - } + public default long asLong() { + return getValue().longValue(); + } - public default double asDouble() { - return getValue().doubleValue(); - } + public default double asDouble() { + return getValue().doubleValue(); + } - public default BigInteger asBigInteger() { - return new BigInteger(getValue().toString()); - } + public default BigInteger asBigInteger() { + return new BigInteger(getValue().toString()); + } - public default BigDecimal asBigDecimal() { - return new BigDecimal(getValue().toString()); - } + public default BigDecimal asBigDecimal() { + return new BigDecimal(getValue().toString()); + } - public static NbtTag fromNumber(Number raw) { - if (raw instanceof Byte) { - return new NbtByte(raw.byteValue()); - } else if (raw instanceof Short) { - return new NbtShort(raw.shortValue()); - } else if (raw instanceof Integer) { - return new NbtInt(raw.intValue()); - } else if (raw instanceof Float) { - return new NbtFloat(raw.floatValue()); - } else if (raw instanceof Long) { - return new NbtLong(raw.longValue()); - } else if (raw instanceof Double) { - return new NbtDouble(raw.doubleValue()); - } else if (raw instanceof BigInteger) { - return new NbtBigInt((BigInteger) raw); - } else if (raw instanceof BigDecimal) { - return new NbtBigDecimal((BigDecimal) raw); - } else { - return new NbtInt(raw.intValue()); - } - } + public static NbtTag fromNumber(Number raw) { + if (raw instanceof Byte) { + return new NbtByte(raw.byteValue()); + } else if (raw instanceof Short) { + return new NbtShort(raw.shortValue()); + } else if (raw instanceof Integer) { + return new NbtInt(raw.intValue()); + } else if (raw instanceof Float) { + return new NbtFloat(raw.floatValue()); + } else if (raw instanceof Long) { + return new NbtLong(raw.longValue()); + } else if (raw instanceof Double) { + return new NbtDouble(raw.doubleValue()); + } else if (raw instanceof BigInteger) { + return new NbtBigInt((BigInteger) raw); + } else if (raw instanceof BigDecimal) { + return new NbtBigDecimal((BigDecimal) raw); + } else { + return new NbtInt(raw.intValue()); + } + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtShort.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtShort.java index a75e97b..62b4198 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtShort.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtShort.java @@ -5,63 +5,63 @@ */ public final class NbtShort extends NbtTag implements Cloneable, NbtNumber { - private short value; - - public NbtShort() { - this.value = 0; - } - - public NbtShort(short value) { - this.value = value; - } - - @Override - public void setValue(Number number) { - this.value = number.shortValue(); - } - - @Override - public Short getValue() { - return value; - } - - public short getShortValue() { - return value; - } - - public void setShortValue(short value) { - this.value = value; - } - - @Override - public NbtType getType() { - return NbtType.SHORT; - } - - // MISC - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtShort && equals((NbtShort) obj); - } - - public boolean equals(NbtShort tag) { - return this.value == tag.value; - } - - @Override - public int hashCode() { - return Short.hashCode(value); - } - - @Override - public String toMSONString() { - return value + "s"; - } - - @Override - public NbtShort clone() { - return new NbtShort(value); - } + private short value; + + public NbtShort() { + this.value = 0; + } + + public NbtShort(short value) { + this.value = value; + } + + @Override + public void setValue(Number number) { + this.value = number.shortValue(); + } + + @Override + public Short getValue() { + return value; + } + + public short getShortValue() { + return value; + } + + public void setShortValue(short value) { + this.value = value; + } + + @Override + public NbtType getType() { + return NbtType.SHORT; + } + + // MISC + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtShort && equals((NbtShort) obj); + } + + public boolean equals(NbtShort tag) { + return this.value == tag.value; + } + + @Override + public int hashCode() { + return Short.hashCode(value); + } + + @Override + public String toMSONString() { + return value + "s"; + } + + @Override + public NbtShort clone() { + return new NbtShort(value); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtString.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtString.java index eaa24a1..195fd77 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtString.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtString.java @@ -5,70 +5,70 @@ */ public class NbtString extends NbtTag implements Cloneable { - private String value; + private String value; - public NbtString() { - setValue(""); - } + public NbtString() { + setValue(""); + } - public NbtString(String value) { - setValue(value); - } + public NbtString(String value) { + setValue(value); + } - public boolean isBigInteger() { - return false; - } + public boolean isBigInteger() { + return false; + } - @Override - public String getValue() { - return value; - } + @Override + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } - @Override - public NbtType getType() { - return NbtType.STRING; - } + @Override + public NbtType getType() { + return NbtType.STRING; + } - // MISC + // MISC - @Override - public int hashCode() { - return value.hashCode(); - } + @Override + public int hashCode() { + return value.hashCode(); + } - @Override - public String toMSONString() { - return toMSONString(value); - } + @Override + public String toMSONString() { + return toMSONString(value); + } - @Override - public NbtString clone() { - return new NbtString(value); - } + @Override + public NbtString clone() { + return new NbtString(value); + } - // UTIL + // UTIL - /** - * Converts a regular string into a Mojangson string by surrounding it with - * quotes and escaping backslashes and quotes inside it. - * - * @param str the string - * @return the Mojangson string - */ - public static String toMSONString(String str) { - StringBuilder builder = new StringBuilder("\""); - char[] chars = str.toCharArray(); - for (char c : chars) { - if ((c == '\\') || (c == '"')) { - builder.append('\\'); - } - builder.append(c); - } - return builder.append('\"').toString(); - } + /** + * Converts a regular string into a Mojangson string by surrounding it with + * quotes and escaping backslashes and quotes inside it. + * + * @param str the string + * @return the Mojangson string + */ + public static String toMSONString(String str) { + StringBuilder builder = new StringBuilder("\""); + char[] chars = str.toCharArray(); + for (char c : chars) { + if ((c == '\\') || (c == '"')) { + builder.append('\\'); + } + builder.append(c); + } + return builder.append('\"').toString(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtTag.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtTag.java index aa0c0de..325e64d 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtTag.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtTag.java @@ -5,62 +5,62 @@ */ public abstract class NbtTag { - /** - * Gets the value of this tag. - * - * @return the value of this tag - */ - public abstract Object getValue(); + /** + * Gets the value of this tag. + * + * @return the value of this tag + */ + public abstract Object getValue(); - /** - * Returns the type of this tag. - * - * @return the type of this tag - */ - public abstract NbtType getType(); + /** + * Returns the type of this tag. + * + * @return the type of this tag + */ + public abstract NbtType getType(); - /** - * Convenience method for getting the id of this tag's type. - * - * @return the type id - */ - public byte getTypeId() { - return getType().getId(); - } + /** + * Convenience method for getting the id of this tag's type. + * + * @return the type id + */ + public byte getTypeId() { + return getType().getId(); + } - /** - * Returns a exact clone of this tag - * - * @return a exact clone of this tag - */ - public abstract NbtTag clone(); + /** + * Returns a exact clone of this tag + * + * @return a exact clone of this tag + */ + public abstract NbtTag clone(); - /** - * Returns a Mojangson string depicting this NBT tag. - * - * @return a Mojangson string depicting this NBT tag - */ - public abstract String toMSONString(); + /** + * Returns a Mojangson string depicting this NBT tag. + * + * @return a Mojangson string depicting this NBT tag + */ + public abstract String toMSONString(); - // MISC + // MISC - @Override - public boolean equals(Object obj) { - if (obj instanceof NbtTag) { - NbtTag tag = (NbtTag) obj; - return this.getType() == tag.getType() && this.getValue().equals(tag.getValue()); - } - return false; - } + @Override + public boolean equals(Object obj) { + if (obj instanceof NbtTag) { + NbtTag tag = (NbtTag) obj; + return this.getType() == tag.getType() && this.getValue().equals(tag.getValue()); + } + return false; + } - @Override - public int hashCode() { - return getValue().hashCode(); - } + @Override + public int hashCode() { + return getValue().hashCode(); + } - @Override - public String toString() { - return toMSONString(); - } + @Override + public String toString() { + return toMSONString(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtType.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtType.java index 4f08ec8..9eef989 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtType.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/NbtType.java @@ -17,234 +17,234 @@ *

*/ public enum NbtType { - /** - * Used to mark the end of compounds tags. May also be the type of empty list - * tags. - * - * @since NBT Version 19132 - */ - END("TAG_End", false, false, false, NbtEnd.class), - - /** - * A signed integer (8 bits). Sometimes used for booleans. (-128 to 127) - * - * @since NBT Version 19132 - */ - BYTE("TAG_Byte", true, true, false, NbtByte.class), - - /** - * A signed integer (16 bits). (-215 to 215-1) - * - * @since NBT Version 19132 - */ - SHORT("TAG_Short", true, true, false, NbtShort.class), - - /** - * A signed integer (32 bits). (-231 to 231-1) - * - * @since NBT Version 19132 - */ - INT("TAG_Int", true, true, false, NbtInt.class), - - /** - * A signed integer (64 bits). (-263 to 263-1) - * - * @since NBT Version 19132 - */ - LONG("TAG_Long", true, true, false, NbtLong.class), - - /** - * A signed (IEEE 754-2008) floating point number (32 bits). - * - * @since NBT Version 19132 - */ - FLOAT("TAG_Float", true, true, false, NbtFloat.class), - - /** - * A signed (IEEE 754-2008) floating point number (64 bits). - * - * @since NBT Version 19132 - */ - DOUBLE("TAG_Double", true, true, false, NbtDouble.class), - - /** - * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19132 - */ - BYTE_ARRAY("TAG_Byte_Array", false, false, true, NbtByteArray.class), - - /** - * UTF-8 encoded string. - * - * @since NBT Version 19132 - */ - STRING("TAG_String", true, false, false, NbtString.class), - - /** - * A list of unnamed tags of equal type. - * - * @since NBT Version 19132 - */ - LIST("TAG_List", false, false, false, NbtList.class), - - /** - * Compound of named tags followed by {@link #END}. - * - * @since NBT Version 19132 - */ - COMPOUND("TAG_Compound", false, false, false, NbtCompound.class), - - /** - * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19132 - */ - INT_ARRAY("TAG_Int_Array", false, false, true, NbtIntArray.class), - - /** - * An array of {@link #LONG} with maximum length of {@link Integer#MAX_VALUE}. - * - * @since NBT Version 19133 - */ - LONG_ARRAY("TAG_Long_Array", false, false, true, NbtLongArray.class); - - private final String name; - private final boolean numeric, primitive, array; - private final byte id; - private final Reflect owner; - - NbtType(String name, boolean primitive, boolean numeric, boolean array, Class owner) { - this.name = name; - this.id = (byte) ordinal(); - this.numeric = numeric; - this.primitive = primitive; - this.array = array; - this.owner = new Reflect(owner); - } - - /** - * Returns a new instance of the type - * - * @return the new instance - */ - public NbtTag init() { - return (NbtTag) owner.init(); - } - - /** - * Returns the type with the given id. - * - * @param id the id - * @return the type - */ - public static NbtType getById(byte id) { - return values()[id]; - } - - /** - *

- * Returns the id of this tag type. - *

- *

- * Although this method is currently equivalent to {@link #ordinal()}, it should - * always be used in its stead, since it is not guaranteed that this behavior - * will remain consistent. - *

- * - * @return the id - */ - public byte getId() { - return id; - } - - /** - * Return the type with the given owning class - * - * @param clazz the owning class - * @return the type or null - */ - public static NbtType getByClass(Class clazz) { - for (NbtType type : values()) { - if (type.getOwningClass().equals(clazz)) { - return type; - } - } - return null; - } - - /** - * Returns the owning class of this type. - * - * @return the owning class - */ - @SuppressWarnings("unchecked") - public Class getOwningClass() { - return (Class) owner.getOwner(); - } - - /** - * Returns the owning class of this type. - * - * @return the owning class - */ - public Reflect getOwner() { - return owner; - } - - /** - * Returns the name of this type. - * - * @return the name - */ - public String getName() { - return name; - } - - /** - * Returns the name of this type. {@link #getName()} - * - * @return the name - */ - @Override - public String toString() { - return getName(); - } - - /** - *

- * Returns whether this tag type is numeric. - *

- *

- * All tag types with payloads that are representable as a {@link Number} are - * compliant with this definition. - *

- * - * @return whether this type is numeric - */ - public boolean isNumeric() { - return numeric; - } - - /** - * Returns whether this tag type is primitive, meaning that it is not a - * {@link NbtByteArray}, {@link NbtIntArray}, {@link NbtList}, - * {@link NbtCompound} or {@link NbtEnd}. - * - * @return whether this type is numeric - */ - public boolean isPrimitive() { - return primitive; - } - - /** - * Returns whether this tag type is is an array type such as - * {@link NbtByteArray} or {@link NbtIntArray}. - * - * @return whether this type is an array type - */ - public boolean isArray() { - return array; - } + /** + * Used to mark the end of compounds tags. May also be the type of empty list + * tags. + * + * @since NBT Version 19132 + */ + END("TAG_End", false, false, false, NbtEnd.class), + + /** + * A signed integer (8 bits). Sometimes used for booleans. (-128 to 127) + * + * @since NBT Version 19132 + */ + BYTE("TAG_Byte", true, true, false, NbtByte.class), + + /** + * A signed integer (16 bits). (-215 to 215-1) + * + * @since NBT Version 19132 + */ + SHORT("TAG_Short", true, true, false, NbtShort.class), + + /** + * A signed integer (32 bits). (-231 to 231-1) + * + * @since NBT Version 19132 + */ + INT("TAG_Int", true, true, false, NbtInt.class), + + /** + * A signed integer (64 bits). (-263 to 263-1) + * + * @since NBT Version 19132 + */ + LONG("TAG_Long", true, true, false, NbtLong.class), + + /** + * A signed (IEEE 754-2008) floating point number (32 bits). + * + * @since NBT Version 19132 + */ + FLOAT("TAG_Float", true, true, false, NbtFloat.class), + + /** + * A signed (IEEE 754-2008) floating point number (64 bits). + * + * @since NBT Version 19132 + */ + DOUBLE("TAG_Double", true, true, false, NbtDouble.class), + + /** + * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19132 + */ + BYTE_ARRAY("TAG_Byte_Array", false, false, true, NbtByteArray.class), + + /** + * UTF-8 encoded string. + * + * @since NBT Version 19132 + */ + STRING("TAG_String", true, false, false, NbtString.class), + + /** + * A list of unnamed tags of equal type. + * + * @since NBT Version 19132 + */ + LIST("TAG_List", false, false, false, NbtList.class), + + /** + * Compound of named tags followed by {@link #END}. + * + * @since NBT Version 19132 + */ + COMPOUND("TAG_Compound", false, false, false, NbtCompound.class), + + /** + * An array of {@link #BYTE} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19132 + */ + INT_ARRAY("TAG_Int_Array", false, false, true, NbtIntArray.class), + + /** + * An array of {@link #LONG} with maximum length of {@link Integer#MAX_VALUE}. + * + * @since NBT Version 19133 + */ + LONG_ARRAY("TAG_Long_Array", false, false, true, NbtLongArray.class); + + private final String name; + private final boolean numeric, primitive, array; + private final byte id; + private final Reflect owner; + + NbtType(String name, boolean primitive, boolean numeric, boolean array, Class owner) { + this.name = name; + this.id = (byte) ordinal(); + this.numeric = numeric; + this.primitive = primitive; + this.array = array; + this.owner = new Reflect(owner); + } + + /** + * Returns a new instance of the type + * + * @return the new instance + */ + public NbtTag init() { + return (NbtTag) owner.init(); + } + + /** + * Returns the type with the given id. + * + * @param id the id + * @return the type + */ + public static NbtType getById(byte id) { + return values()[id]; + } + + /** + *

+ * Returns the id of this tag type. + *

+ *

+ * Although this method is currently equivalent to {@link #ordinal()}, it should + * always be used in its stead, since it is not guaranteed that this behavior + * will remain consistent. + *

+ * + * @return the id + */ + public byte getId() { + return id; + } + + /** + * Return the type with the given owning class + * + * @param clazz the owning class + * @return the type or null + */ + public static NbtType getByClass(Class clazz) { + for (NbtType type : values()) { + if (type.getOwningClass().equals(clazz)) { + return type; + } + } + return null; + } + + /** + * Returns the owning class of this type. + * + * @return the owning class + */ + @SuppressWarnings("unchecked") + public Class getOwningClass() { + return (Class) owner.getOwner(); + } + + /** + * Returns the owning class of this type. + * + * @return the owning class + */ + public Reflect getOwner() { + return owner; + } + + /** + * Returns the name of this type. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Returns the name of this type. {@link #getName()} + * + * @return the name + */ + @Override + public String toString() { + return getName(); + } + + /** + *

+ * Returns whether this tag type is numeric. + *

+ *

+ * All tag types with payloads that are representable as a {@link Number} are + * compliant with this definition. + *

+ * + * @return whether this type is numeric + */ + public boolean isNumeric() { + return numeric; + } + + /** + * Returns whether this tag type is primitive, meaning that it is not a + * {@link NbtByteArray}, {@link NbtIntArray}, {@link NbtList}, + * {@link NbtCompound} or {@link NbtEnd}. + * + * @return whether this type is numeric + */ + public boolean isPrimitive() { + return primitive; + } + + /** + * Returns whether this tag type is is an array type such as + * {@link NbtByteArray} or {@link NbtIntArray}. + * + * @return whether this type is an array type + */ + public boolean isArray() { + return array; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonDeserializer.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonDeserializer.java index 5ff6df5..9c1bd2f 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonDeserializer.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonDeserializer.java @@ -10,13 +10,13 @@ public class MojangsonDeserializer implements TextDeserializer { - @Override - public NbtNamedTag fromReader(Reader reader) throws IOException { - BufferedReader buffReader = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); + @Override + public NbtNamedTag fromReader(Reader reader) throws IOException { + BufferedReader buffReader = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - String mson = buffReader.lines().collect(Collectors.joining()); + String mson = buffReader.lines().collect(Collectors.joining()); - return MojangsonParser.parse(mson); - } + return MojangsonParser.parse(mson); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParseException.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParseException.java index be096e8..f7c808f 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParseException.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParseException.java @@ -4,25 +4,25 @@ public class MojangsonParseException extends IOException { - /** - * - */ - private static final long serialVersionUID = 3011813566487100293L; + /** + * + */ + private static final long serialVersionUID = 3011813566487100293L; - public MojangsonParseException(String msg, String content, int index) { - super(msg + " at: " + printErrorLoc(content, index)); - } + public MojangsonParseException(String msg, String content, int index) { + super(msg + " at: " + printErrorLoc(content, index)); + } - private static String printErrorLoc(String content, int index) { - StringBuilder builder = new StringBuilder(); - int i = Math.min(content.length(), index); - if (i > 35) { - builder.append("..."); - } - builder.append(content.substring(Math.max(0, i - 35), i)); - builder.append("<--[HERE]"); + private static String printErrorLoc(String content, int index) { + StringBuilder builder = new StringBuilder(); + int i = Math.min(content.length(), index); + if (i > 35) { + builder.append("..."); + } + builder.append(content.substring(Math.max(0, i - 35), i)); + builder.append("<--[HERE]"); - return builder.toString(); - } + return builder.toString(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParser.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParser.java index 39ac1e2..bf7b565 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParser.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonParser.java @@ -4,382 +4,404 @@ import java.util.List; import java.util.regex.Pattern; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigDecimal; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtByteArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtDouble; +import com.syntaxphoenix.syntaxapi.nbt.NbtFloat; +import com.syntaxphoenix.syntaxapi.nbt.NbtInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtIntArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtLong; +import com.syntaxphoenix.syntaxapi.nbt.NbtLongArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtNamedTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtShort; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; import com.syntaxphoenix.syntaxapi.utils.java.Strings; public final class MojangsonParser { - private static final Pattern DOUBLE_NS = Pattern.compile("[-+]?(?:[0-9]+[.]|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?", Pattern.CASE_INSENSITIVE), - DOUBLE_S = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE), - FLOAT = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?f", Pattern.CASE_INSENSITIVE), - BYTE = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)b", Pattern.CASE_INSENSITIVE), - LONG = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)l", Pattern.CASE_INSENSITIVE), - SHORT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)s", Pattern.CASE_INSENSITIVE), INT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)"); - - private final String str; - private int index; - - public static NbtNamedTag parse(String mson) throws MojangsonParseException { - return new MojangsonParser(mson).parseRootCompound(); - } - - private MojangsonParser(String str) { - this.str = str; - } - - // PARSE - - private NbtNamedTag parseRootCompound() throws MojangsonParseException { - String name; - NbtCompound result; - - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected key"); - } - if (currentChar() == '{') { - name = ""; - result = parseCompound(); - } else { - name = currentChar() == '"' ? parseQuotedString() : parseSimpleString(); - expectChar(':'); - result = parseCompound(); - } - - expectNoTrail(); - - return new NbtNamedTag(name, result); - } - - private String parseCompoundKey() throws MojangsonParseException { - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected key"); - } - return currentChar() == '"' ? parseQuotedString() : parseSimpleString(); - } - - private NbtTag parseStringOrLiteral() throws MojangsonParseException { - skipWhitespace(); - if (currentChar() == '"') - return new NbtString(parseQuotedString()); - String str = parseSimpleString(); - if (str.isEmpty()) - throw parseException("Expected value"); - return parseLiteral(str); - } - - private NbtTag parseLiteral(String str) { - try { - if (FLOAT.matcher(str).matches()) { - return new NbtFloat(Float.parseFloat(str.substring(0, str.length() - 1))); - } - if (BYTE.matcher(str).matches()) { - return new NbtByte(Byte.parseByte(str.substring(0, str.length() - 1))); - } - if (LONG.matcher(str).matches()) { - return new NbtLong(Long.parseLong(str.substring(0, str.length() - 1))); - } - if (SHORT.matcher(str).matches()) { - return new NbtShort(Short.parseShort(str.substring(0, str.length() - 1))); - } - if (INT.matcher(str).matches()) { - return new NbtInt(Integer.parseInt(str)); - } - if (DOUBLE_S.matcher(str).matches()) { - return new NbtDouble(Double.parseDouble(str.substring(0, str.length() - 1))); - } - if (DOUBLE_NS.matcher(str).matches()) { - return new NbtDouble(Double.parseDouble(str)); - } - if ("true".equalsIgnoreCase(str)) { - return new NbtByte((byte) 1); - } - if ("false".equalsIgnoreCase(str)) { - return new NbtByte((byte) 0); - } - } catch (NumberFormatException ex) { - } - if (Strings.isNumeric(str)) { - return new NbtBigInt(str); - } - if (Strings.isDecimal(str)) { - return new NbtBigDecimal(str); - } - return new NbtString(str); - } - - private String parseQuotedString() throws MojangsonParseException { - int j = ++this.index; - StringBuilder builder = null; - boolean escape = false; - - while (hasNext()) { - char c = nextChar(); - if (escape) { - if ((c != '\\') && (c != '"')) { - throw parseException("Invalid escape of '" + c + "'"); - } - escape = false; - } else { - if (c == '\\') { - escape = true; - if (builder != null) { - continue; - } - builder = new StringBuilder(this.str.substring(j, this.index - 1)); - continue; - } - if (c == '"') { - return builder == null ? this.str.substring(j, this.index - 1) : builder.toString(); - } - } - if (builder != null) { - builder.append(c); - } - } - throw parseException("Missing termination quote"); - } - - private String parseSimpleString() { - int j = this.index; - while (hasNext() && isSimpleChar(currentChar())) { - this.index += 1; - } - return this.str.substring(j, this.index); - } - - private NbtTag parseAnything() throws MojangsonParseException { - skipWhitespace(); - if (!hasNext()) - throw parseException("Expected value"); - - int c = currentChar(); - if (c == '{') - return parseCompound(); - else if (c == '[') - return parseDetectedArray(); - else - return parseStringOrLiteral(); - } - - private NbtTag parseDetectedArray() throws MojangsonParseException { - if (hasCharsLeft(2) && getChar(1) != '"' && getChar(2) == ';') { - return parseNumArray(); - } - return parseList(); - } - - private NbtCompound parseCompound() throws MojangsonParseException { - expectChar('{'); - - NbtCompound compound = new NbtCompound(); - - skipWhitespace(); - while ((hasNext()) && (currentChar() != '}')) { - String str = parseCompoundKey(); - if (str.isEmpty()) { - throw parseException("Expected non-empty key"); - } - expectChar(':'); - - compound.set(str, parseAnything()); - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected key"); - } - } - expectChar('}'); - - return compound; - } - - @SuppressWarnings("unchecked") - private NbtList parseList() throws MojangsonParseException { - expectChar('['); - - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected value"); - } - NbtList list = null; - ; - NbtType listType = null; - - while (currentChar() != ']') { - NbtTag element = parseAnything(); - NbtType elementType = element.getType(); - - if (listType == null) { - listType = elementType; - } else if (elementType != listType) { - throw parseException("Unable to insert " + elementType + " into ListTag of type " + listType); - } - if (list == null) { - list = (NbtList) NbtList.createFromType(elementType); - } - list.add(element); - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected value"); - } - } - expectChar(']'); - - return list; - } - - private NbtTag parseNumArray() throws MojangsonParseException { - expectChar('['); - char arrayType = nextChar(); - expectChar(';'); - // nextChar(); semicolon ignored by Mojang - - skipWhitespace(); - if (!hasNext()) { - throw parseException("Expected value"); - } - if (arrayType == 'B') - return new NbtByteArray(parseNumArray(NbtType.BYTE_ARRAY, NbtType.BYTE)); - else if (arrayType == 'L') - return new NbtLongArray(parseNumArray(NbtType.LONG_ARRAY, NbtType.LONG)); - else if (arrayType == 'I') - return new NbtIntArray(parseNumArray(NbtType.INT_ARRAY, NbtType.INT)); - throw parseException("Invalid array type '" + arrayType + "' found"); - } - - private Number[] parseNumArray(NbtType arrayType, NbtType primType) throws MojangsonParseException { - List result = new ArrayList<>(); - while (currentChar() != ']') { - NbtTag element = parseAnything(); - NbtType elementType = element.getType(); - - if (elementType != primType) { - throw parseException("Unable to insert " + elementType + " into " + arrayType); - } - if (primType == NbtType.BYTE) { - result.add(((NbtByte) element).getValue()); - } else if (primType == NbtType.LONG) { - result.add(((NbtLong) element).getValue()); - } else { - result.add(((NbtInt) element).getValue()); - } - if (!advanceToNextArrayElement()) { - break; - } - if (!hasNext()) { - throw parseException("Expected value"); - } - } - expectChar(']'); - - return result.toArray(new Number[result.size()]); - } - - // CHARACTER NAVIGATION - - private boolean advanceToNextArrayElement() { - skipWhitespace(); - if (hasNext() && currentChar() == ',') { - this.index += 1; - skipWhitespace(); - return true; - } - return false; - } - - private void skipWhitespace() { - while (hasNext() && Character.isWhitespace(currentChar())) { - this.index += 1; - } - } - - private boolean hasCharsLeft(int paramInt) { - return this.index + paramInt < this.str.length(); - } - - private boolean hasNext() { - return hasCharsLeft(0); - } - - /** - * Returns the character in the string at the current index plus a given offset. - * - * @param offset the offset - * @return the character at the offset - */ - private char getChar(int offset) { - return this.str.charAt(this.index + offset); - } - - /** - * Returns the current character. - * - * @return the current character - */ - private char currentChar() { - return getChar(0); - } - - /** - * Returns the current character and increments the index. - * - * @return the current character - */ - private char nextChar() { - return this.str.charAt(this.index++); - } - - // UTIL - - /** - * Verifies whether the current character is of given value and whether the - * parser can advance. If these conditions are met, the parser advances by one. - * If these conditions are not met, an exception is thrown. - * - * @param c the expected character - * @throws MojangsonParseException if {@link #currentChar()} does not equal - * {@code c} or if {@link #hasNext()} returns - * false - */ - private void expectChar(char c) throws MojangsonParseException { - skipWhitespace(); - - boolean hasNext = hasNext(); - if (hasNext && currentChar() == c) { - this.index += 1; - return; - } - throw new MojangsonParseException("Expected '" + c + "' but got '" + (hasNext ? Character.valueOf(currentChar()) : "") + "'", this.str, - this.index + 1); - } - - /** - * Verifies that the string has ended or that all characters from the next - * character on only consists of whitespace. - * - * @throws MojangsonParseException if the following characters contain a - * non-whitespace character - */ - private void expectNoTrail() throws MojangsonParseException { - skipWhitespace(); - if (hasNext()) { - this.index++; - throw parseException("Trailing data " + currentChar() + " found"); - } - } - - private MojangsonParseException parseException(String paramString) { - return new MojangsonParseException(paramString, this.str, this.index); - } - - private static boolean isSimpleChar(char paramChar) { - return (paramChar >= '0' && paramChar <= '9') || (paramChar >= 'A' && paramChar <= 'Z') || (paramChar >= 'a' && paramChar <= 'z') || paramChar == '_' - || paramChar == '-' || paramChar == '.' || paramChar == '+'; - } + private static final Pattern DOUBLE_NS = Pattern.compile("[-+]?(?:[0-9]+[.]|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?", + Pattern.CASE_INSENSITIVE), + DOUBLE_S = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?d", Pattern.CASE_INSENSITIVE), + FLOAT = Pattern.compile("[-+]?(?:[0-9]+[.]?|[0-9]*[.][0-9]+)(?:e[-+]?[0-9]+)?f", Pattern.CASE_INSENSITIVE), + BYTE = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)b", Pattern.CASE_INSENSITIVE), + LONG = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)l", Pattern.CASE_INSENSITIVE), + SHORT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)s", Pattern.CASE_INSENSITIVE), INT = Pattern.compile("[-+]?(?:0|[1-9][0-9]*)"); + + private final String str; + private int index; + + public static NbtNamedTag parse(String mson) throws MojangsonParseException { + return new MojangsonParser(mson).parseRootCompound(); + } + + private MojangsonParser(String str) { + this.str = str; + } + + // PARSE + + private NbtNamedTag parseRootCompound() throws MojangsonParseException { + String name; + NbtCompound result; + + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected key"); + } + if (currentChar() == '{') { + name = ""; + result = parseCompound(); + } else { + name = currentChar() == '"' ? parseQuotedString() : parseSimpleString(); + expectChar(':'); + result = parseCompound(); + } + + expectNoTrail(); + + return new NbtNamedTag(name, result); + } + + private String parseCompoundKey() throws MojangsonParseException { + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected key"); + } + return currentChar() == '"' ? parseQuotedString() : parseSimpleString(); + } + + private NbtTag parseStringOrLiteral() throws MojangsonParseException { + skipWhitespace(); + if (currentChar() == '"') { + return new NbtString(parseQuotedString()); + } + String str = parseSimpleString(); + if (str.isEmpty()) { + throw parseException("Expected value"); + } + return parseLiteral(str); + } + + private NbtTag parseLiteral(String str) { + try { + if (FLOAT.matcher(str).matches()) { + return new NbtFloat(Float.parseFloat(str.substring(0, str.length() - 1))); + } + if (BYTE.matcher(str).matches()) { + return new NbtByte(Byte.parseByte(str.substring(0, str.length() - 1))); + } + if (LONG.matcher(str).matches()) { + return new NbtLong(Long.parseLong(str.substring(0, str.length() - 1))); + } + if (SHORT.matcher(str).matches()) { + return new NbtShort(Short.parseShort(str.substring(0, str.length() - 1))); + } + if (INT.matcher(str).matches()) { + return new NbtInt(Integer.parseInt(str)); + } + if (DOUBLE_S.matcher(str).matches()) { + return new NbtDouble(Double.parseDouble(str.substring(0, str.length() - 1))); + } + if (DOUBLE_NS.matcher(str).matches()) { + return new NbtDouble(Double.parseDouble(str)); + } + if ("true".equalsIgnoreCase(str)) { + return new NbtByte((byte) 1); + } + if ("false".equalsIgnoreCase(str)) { + return new NbtByte((byte) 0); + } + } catch (NumberFormatException ex) { + } + if (Strings.isNumeric(str)) { + return new NbtBigInt(str); + } + if (Strings.isDecimal(str)) { + return new NbtBigDecimal(str); + } + return new NbtString(str); + } + + private String parseQuotedString() throws MojangsonParseException { + int j = ++this.index; + StringBuilder builder = null; + boolean escape = false; + + while (hasNext()) { + char c = nextChar(); + if (escape) { + if ((c != '\\') && (c != '"')) { + throw parseException("Invalid escape of '" + c + "'"); + } + escape = false; + } else { + if (c == '\\') { + escape = true; + if (builder != null) { + continue; + } + builder = new StringBuilder(this.str.substring(j, this.index - 1)); + continue; + } + if (c == '"') { + return builder == null ? this.str.substring(j, this.index - 1) : builder.toString(); + } + } + if (builder != null) { + builder.append(c); + } + } + throw parseException("Missing termination quote"); + } + + private String parseSimpleString() { + int j = this.index; + while (hasNext() && isSimpleChar(currentChar())) { + this.index += 1; + } + return this.str.substring(j, this.index); + } + + private NbtTag parseAnything() throws MojangsonParseException { + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected value"); + } + + int c = currentChar(); + if (c == '{') { + return parseCompound(); + } else if (c == '[') { + return parseDetectedArray(); + } else { + return parseStringOrLiteral(); + } + } + + private NbtTag parseDetectedArray() throws MojangsonParseException { + if (hasCharsLeft(2) && getChar(1) != '"' && getChar(2) == ';') { + return parseNumArray(); + } + return parseList(); + } + + private NbtCompound parseCompound() throws MojangsonParseException { + expectChar('{'); + + NbtCompound compound = new NbtCompound(); + + skipWhitespace(); + while ((hasNext()) && (currentChar() != '}')) { + String str = parseCompoundKey(); + if (str.isEmpty()) { + throw parseException("Expected non-empty key"); + } + expectChar(':'); + + compound.set(str, parseAnything()); + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected key"); + } + } + expectChar('}'); + + return compound; + } + + @SuppressWarnings("unchecked") + private NbtList parseList() throws MojangsonParseException { + expectChar('['); + + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected value"); + } + NbtList list = null; + ; + NbtType listType = null; + + while (currentChar() != ']') { + NbtTag element = parseAnything(); + NbtType elementType = element.getType(); + + if (listType == null) { + listType = elementType; + } else if (elementType != listType) { + throw parseException("Unable to insert " + elementType + " into ListTag of type " + listType); + } + if (list == null) { + list = (NbtList) NbtList.createFromType(elementType); + } + list.add(element); + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected value"); + } + } + expectChar(']'); + + return list; + } + + private NbtTag parseNumArray() throws MojangsonParseException { + expectChar('['); + char arrayType = nextChar(); + expectChar(';'); + // nextChar(); semicolon ignored by Mojang + + skipWhitespace(); + if (!hasNext()) { + throw parseException("Expected value"); + } + if (arrayType == 'B') { + return new NbtByteArray(parseNumArray(NbtType.BYTE_ARRAY, NbtType.BYTE)); + } else if (arrayType == 'L') { + return new NbtLongArray(parseNumArray(NbtType.LONG_ARRAY, NbtType.LONG)); + } else if (arrayType == 'I') { + return new NbtIntArray(parseNumArray(NbtType.INT_ARRAY, NbtType.INT)); + } + throw parseException("Invalid array type '" + arrayType + "' found"); + } + + private Number[] parseNumArray(NbtType arrayType, NbtType primType) throws MojangsonParseException { + List result = new ArrayList<>(); + while (currentChar() != ']') { + NbtTag element = parseAnything(); + NbtType elementType = element.getType(); + + if (elementType != primType) { + throw parseException("Unable to insert " + elementType + " into " + arrayType); + } + if (primType == NbtType.BYTE) { + result.add(((NbtByte) element).getValue()); + } else if (primType == NbtType.LONG) { + result.add(((NbtLong) element).getValue()); + } else { + result.add(((NbtInt) element).getValue()); + } + if (!advanceToNextArrayElement()) { + break; + } + if (!hasNext()) { + throw parseException("Expected value"); + } + } + expectChar(']'); + + return result.toArray(new Number[result.size()]); + } + + // CHARACTER NAVIGATION + + private boolean advanceToNextArrayElement() { + skipWhitespace(); + if (hasNext() && currentChar() == ',') { + this.index += 1; + skipWhitespace(); + return true; + } + return false; + } + + private void skipWhitespace() { + while (hasNext() && Character.isWhitespace(currentChar())) { + this.index += 1; + } + } + + private boolean hasCharsLeft(int paramInt) { + return this.index + paramInt < this.str.length(); + } + + private boolean hasNext() { + return hasCharsLeft(0); + } + + /** + * Returns the character in the string at the current index plus a given offset. + * + * @param offset the offset + * @return the character at the offset + */ + private char getChar(int offset) { + return this.str.charAt(this.index + offset); + } + + /** + * Returns the current character. + * + * @return the current character + */ + private char currentChar() { + return getChar(0); + } + + /** + * Returns the current character and increments the index. + * + * @return the current character + */ + private char nextChar() { + return this.str.charAt(this.index++); + } + + // UTIL + + /** + * Verifies whether the current character is of given value and whether the + * parser can advance. If these conditions are met, the parser advances by one. + * If these conditions are not met, an exception is thrown. + * + * @param c the expected character + * @throws MojangsonParseException if {@link #currentChar()} does not equal + * {@code c} or if {@link #hasNext()} returns + * false + */ + private void expectChar(char c) throws MojangsonParseException { + skipWhitespace(); + + boolean hasNext = hasNext(); + if (hasNext && currentChar() == c) { + this.index += 1; + return; + } + throw new MojangsonParseException("Expected '" + c + "' but got '" + (hasNext ? Character.valueOf(currentChar()) : "") + "'", + this.str, this.index + 1); + } + + /** + * Verifies that the string has ended or that all characters from the next + * character on only consists of whitespace. + * + * @throws MojangsonParseException if the following characters contain a + * non-whitespace character + */ + private void expectNoTrail() throws MojangsonParseException { + skipWhitespace(); + if (hasNext()) { + this.index++; + throw parseException("Trailing data " + currentChar() + " found"); + } + } + + private MojangsonParseException parseException(String paramString) { + return new MojangsonParseException(paramString, this.str, this.index); + } + + private static boolean isSimpleChar(char paramChar) { + return (paramChar >= '0' && paramChar <= '9') || (paramChar >= 'A' && paramChar <= 'Z') || (paramChar >= 'a' && paramChar <= 'z') + || paramChar == '_' || paramChar == '-' || paramChar == '.' || paramChar == '+'; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonSerializer.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonSerializer.java index fcd4ca7..cf8f5b5 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonSerializer.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonSerializer.java @@ -9,43 +9,43 @@ public class MojangsonSerializer implements TextSerializer { - private final boolean pretty; - - /** - * Constructs a new {@code MojangsonSerializer}. - * - * @param pretty whether to "pretty-print", adding whitespace, line breaks and - * indent - */ - public MojangsonSerializer(boolean pretty) { - this.pretty = pretty; - } - - /** - * Constructs a new {@code MojangsonSerializer} with disabled pretty-printing. - */ - public MojangsonSerializer() { - this(false); - } - - @Override - public void toWriter(NbtNamedTag nbt, Writer writer) throws IOException { - MojangsonWriter msonWriter = new MojangsonWriter(writer, pretty); - msonWriter.writeNamedTag(nbt); - msonWriter.endLn(); // end last line to comply with POSIX standard - msonWriter.flush(); - msonWriter.close(); - } - - @Override - public String toString(NbtNamedTag nbt) { - StringWriter stringWriter = new StringWriter(); - try { - toWriter(nbt, stringWriter); - } catch (IOException e) { - throw new AssertionError(e); - } - return stringWriter.toString(); - } + private final boolean pretty; + + /** + * Constructs a new {@code MojangsonSerializer}. + * + * @param pretty whether to "pretty-print", adding whitespace, line breaks and + * indent + */ + public MojangsonSerializer(boolean pretty) { + this.pretty = pretty; + } + + /** + * Constructs a new {@code MojangsonSerializer} with disabled pretty-printing. + */ + public MojangsonSerializer() { + this(false); + } + + @Override + public void toWriter(NbtNamedTag nbt, Writer writer) throws IOException { + MojangsonWriter msonWriter = new MojangsonWriter(writer, pretty); + msonWriter.writeNamedTag(nbt); + msonWriter.endLn(); // end last line to comply with POSIX standard + msonWriter.flush(); + msonWriter.close(); + } + + @Override + public String toString(NbtNamedTag nbt) { + StringWriter stringWriter = new StringWriter(); + try { + toWriter(nbt, stringWriter); + } catch (IOException e) { + throw new AssertionError(e); + } + return stringWriter.toString(); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonWriter.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonWriter.java index 50d77b8..3cdef9b 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonWriter.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/MojangsonWriter.java @@ -7,236 +7,249 @@ import java.util.Set; import java.util.regex.Pattern; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtNamedTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; public class MojangsonWriter extends Writer { - private static final String NEWLINE = System.getProperty("line.separator"), INDENT = " "; - - private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); - - private final Writer writer; - private final boolean pretty; - - private int indent = 0; - - /** - * Constructs a new writer. - * - * @param writer the writer - * @param pretty whether to "pretty-print", adding whitespace, line breaks and - * indent - */ - public MojangsonWriter(Writer writer, boolean pretty) { - this.writer = Objects.requireNonNull(writer); - this.pretty = pretty; - } - - /** - * Constructs a new writer with disabled pretty printing. - * - * @param writer the writer - */ - public MojangsonWriter(Writer writer) { - this(writer, false); - } - - public void writeNamedTag(String name, NbtTag root) throws IOException { - if (!name.isEmpty()) { - write((new NbtString(name).toMSONString())); - write(':'); - if (pretty) - write(' '); - } - - writeTag(root); - } - - public void writeNamedTag(NbtNamedTag nbt) throws IOException { - writeNamedTag(nbt.getName(), nbt.getTag()); - } - - public void writeTag(NbtTag tag) throws IOException { - if (!pretty) { - write(tag.toMSONString()); - return; - } - - NbtType type = tag.getType(); - if (type == NbtType.END || type.isPrimitive() || type.isArray()) { - writer.write(tag.toMSONString()); - } else if (type == NbtType.COMPOUND) { - writeCompound((NbtCompound) tag); - } else if (type == NbtType.LIST) { - writeList((NbtList) tag); - } else { - throw new AssertionError(type); - } - } - - private void writeCompound(NbtCompound compound) throws IOException { - if (!pretty) { - write(compound.toMSONString()); - return; - } - - write('{'); - - if (!compound.isEmpty()) { - boolean simple = isPrimitive(compound); - - if (!simple) { - indent++; - endLn(); - } - - Map map = compound.getValue(); - Set keys = map.keySet(); - boolean first = true; - - if (simple) - for (String key : keys) { - if (first) - first = false; - else - write(", "); - write(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)); - write(": "); - writeTag(map.get(key)); - } - else - for (String key : keys) { - if (first) - first = false; - else { - write(","); - endLn(); - } - write(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)); - write(": "); - writeTag(map.get(key)); - } - - if (!simple) { - indent--; - endLn(); - } - } - - write('}'); - } - - private void writeList(NbtList list) throws IOException { - if (!pretty) { - write(list.toMSONString()); - return; - } - - write('['); - - if (!list.isEmpty()) { - boolean simple = isPrimitive(list); - if (!simple) { - indent++; - endLn(); - } - - boolean first = true; - - if (simple) - for (NbtTag tag : list) { - if (first) - first = false; - else - write(", "); - writeTag(tag); - } - else - for (NbtTag tag : list) { - if (first) - first = false; - else { - write(","); - endLn(); - } - writeTag(tag); - } - - if (!simple) { - indent--; - endLn(); - } - } - - write(']'); - } - - /** - * Writes the indentation as many times as necessary. - * - * @throws IOException if an I/O error occurs - */ - protected void indent() throws IOException { - if (indent == 1) { - writer.write(INDENT); - } else if (indent > 0) { - for (int i = 0; i < indent; i++) - writer.append(INDENT); - } - } - - /** - * Ends the line with the native new line sequence. This will be CRLF on Windows - * and LF on most Unix systems. - * - * @throws IOException if an I/O error occurs - */ - protected void endLn() throws IOException { - writer.write(NEWLINE); - indent(); - } - - // WRITER IMPL - - @Override - public void write(int c) throws IOException { - writer.write(c); - } - - @Override - public void write(String str) throws IOException { - writer.write(str); - } - - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - writer.write(cbuf, off, len); - } - - @Override - public void flush() throws IOException { - writer.flush(); - } - - @Override - public void close() throws IOException { - writer.close(); - } - - // UTIL - - private static boolean isPrimitive(NbtList list) { - return list.isEmpty() || list.getElementType().isPrimitive(); - } - - private static boolean isPrimitive(NbtCompound compound) { - if (compound.isEmpty()) - return true; - for (NbtTag val : compound.getValue().values()) { - if (!val.getType().isPrimitive()) - return false; - } - return true; - } + private static final String NEWLINE = System.getProperty("line.separator"), INDENT = " "; + + private static final Pattern SIMPLE_STRING = Pattern.compile("[A-Za-z0-9._+-]+"); + + private final Writer writer; + private final boolean pretty; + + private int indent = 0; + + /** + * Constructs a new writer. + * + * @param writer the writer + * @param pretty whether to "pretty-print", adding whitespace, line breaks and + * indent + */ + public MojangsonWriter(Writer writer, boolean pretty) { + this.writer = Objects.requireNonNull(writer); + this.pretty = pretty; + } + + /** + * Constructs a new writer with disabled pretty printing. + * + * @param writer the writer + */ + public MojangsonWriter(Writer writer) { + this(writer, false); + } + + public void writeNamedTag(String name, NbtTag root) throws IOException { + if (!name.isEmpty()) { + write((new NbtString(name).toMSONString())); + write(':'); + if (pretty) { + write(' '); + } + } + + writeTag(root); + } + + public void writeNamedTag(NbtNamedTag nbt) throws IOException { + writeNamedTag(nbt.getName(), nbt.getTag()); + } + + public void writeTag(NbtTag tag) throws IOException { + if (!pretty) { + write(tag.toMSONString()); + return; + } + + NbtType type = tag.getType(); + if (type == NbtType.END || type.isPrimitive() || type.isArray()) { + writer.write(tag.toMSONString()); + } else if (type == NbtType.COMPOUND) { + writeCompound((NbtCompound) tag); + } else if (type == NbtType.LIST) { + writeList((NbtList) tag); + } else { + throw new AssertionError(type); + } + } + + private void writeCompound(NbtCompound compound) throws IOException { + if (!pretty) { + write(compound.toMSONString()); + return; + } + + write('{'); + + if (!compound.isEmpty()) { + boolean simple = isPrimitive(compound); + + if (!simple) { + indent++; + endLn(); + } + + Map map = compound.getValue(); + Set keys = map.keySet(); + boolean first = true; + + if (simple) { + for (String key : keys) { + if (first) { + first = false; + } else { + write(", "); + } + write(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)); + write(": "); + writeTag(map.get(key)); + } + } else { + for (String key : keys) { + if (first) { + first = false; + } else { + write(","); + endLn(); + } + write(SIMPLE_STRING.matcher(key).matches() ? key : NbtString.toMSONString(key)); + write(": "); + writeTag(map.get(key)); + } + } + + if (!simple) { + indent--; + endLn(); + } + } + + write('}'); + } + + private void writeList(NbtList list) throws IOException { + if (!pretty) { + write(list.toMSONString()); + return; + } + + write('['); + + if (!list.isEmpty()) { + boolean simple = isPrimitive(list); + if (!simple) { + indent++; + endLn(); + } + + boolean first = true; + + if (simple) { + for (NbtTag tag : list) { + if (first) { + first = false; + } else { + write(", "); + } + writeTag(tag); + } + } else { + for (NbtTag tag : list) { + if (first) { + first = false; + } else { + write(","); + endLn(); + } + writeTag(tag); + } + } + + if (!simple) { + indent--; + endLn(); + } + } + + write(']'); + } + + /** + * Writes the indentation as many times as necessary. + * + * @throws IOException if an I/O error occurs + */ + protected void indent() throws IOException { + if (indent == 1) { + writer.write(INDENT); + } else if (indent > 0) { + for (int i = 0; i < indent; i++) { + writer.append(INDENT); + } + } + } + + /** + * Ends the line with the native new line sequence. This will be CRLF on Windows + * and LF on most Unix systems. + * + * @throws IOException if an I/O error occurs + */ + protected void endLn() throws IOException { + writer.write(NEWLINE); + indent(); + } + + // WRITER IMPL + + @Override + public void write(int c) throws IOException { + writer.write(c); + } + + @Override + public void write(String str) throws IOException { + writer.write(str); + } + + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + writer.write(cbuf, off, len); + } + + @Override + public void flush() throws IOException { + writer.flush(); + } + + @Override + public void close() throws IOException { + writer.close(); + } + + // UTIL + + private static boolean isPrimitive(NbtList list) { + return list.isEmpty() || list.getElementType().isPrimitive(); + } + + private static boolean isPrimitive(NbtCompound compound) { + if (compound.isEmpty()) { + return true; + } + for (NbtTag val : compound.getValue().values()) { + if (!val.getType().isPrimitive()) { + return false; + } + } + return true; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtDeserializer.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtDeserializer.java index 262ac34..9854594 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtDeserializer.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtDeserializer.java @@ -9,37 +9,38 @@ public class NbtDeserializer implements Deserializer { - public static final NbtDeserializer COMPRESSED = new NbtDeserializer(true); - public static final NbtDeserializer UNCOMPRESSED = new NbtDeserializer(false); - - private final boolean compressed; - - /** - * Constructs a new NBT-Deserializer. - * - * @param compressed whether the input is g-zip compressed - */ - public NbtDeserializer(boolean compressed) { - this.compressed = compressed; - } - - /** - * Constructs a new NBT-Deserializer with enabled g-zip decompression. - */ - public NbtDeserializer() { - this(true); - } - - @Override - public NbtNamedTag fromStream(InputStream stream) throws IOException { - NbtInputStream nbtStream = compressed ? new NbtInputStream(new GZIPInputStream(stream)) : new NbtInputStream(stream); - - NbtNamedTag tag = nbtStream.readNamedTag(); - nbtStream.close(); - if (tag == null) - throw new IOException("failed to read NBT tag due to EOS"); - else - return tag; - } + public static final NbtDeserializer COMPRESSED = new NbtDeserializer(true); + public static final NbtDeserializer UNCOMPRESSED = new NbtDeserializer(false); + + private final boolean compressed; + + /** + * Constructs a new NBT-Deserializer. + * + * @param compressed whether the input is g-zip compressed + */ + public NbtDeserializer(boolean compressed) { + this.compressed = compressed; + } + + /** + * Constructs a new NBT-Deserializer with enabled g-zip decompression. + */ + public NbtDeserializer() { + this(true); + } + + @Override + public NbtNamedTag fromStream(InputStream stream) throws IOException { + NbtInputStream nbtStream = compressed ? new NbtInputStream(new GZIPInputStream(stream)) : new NbtInputStream(stream); + + NbtNamedTag tag = nbtStream.readNamedTag(); + nbtStream.close(); + if (tag == null) { + throw new IOException("failed to read NBT tag due to EOS"); + } else { + return tag; + } + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtInputStream.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtInputStream.java index 5e7ca94..319c8a4 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtInputStream.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtInputStream.java @@ -9,7 +9,23 @@ import java.util.List; import java.util.Map; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtByteArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtDouble; +import com.syntaxphoenix.syntaxapi.nbt.NbtEnd; +import com.syntaxphoenix.syntaxapi.nbt.NbtFloat; +import com.syntaxphoenix.syntaxapi.nbt.NbtInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtIntArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtLong; +import com.syntaxphoenix.syntaxapi.nbt.NbtLongArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtNamedTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtShort; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; import com.syntaxphoenix.syntaxapi.utils.java.Strings; /** @@ -18,204 +34,211 @@ */ public final class NbtInputStream extends DataInputStream { - private final static Charset UTF_8 = Charset.forName("UTF-8"); - - /** - * Creates a new {@code NBTInputStream}, which will source its data from the - * specified input stream. - * - * @param in the input stream - */ - public NbtInputStream(InputStream in) { - super(in); - } - - /** - *

- * Reads a tag and its name from the stream. - *

- *

- * Should the tag be of type {@link NbtType#COMPOUND} or {@link NbtType#LIST} - * will the full content (all elements in the compounds or list) be read. - *

- *

- * Null may be returned if the id of the tag can not be read due to the stream - * ending (expected end). If however the stream ends while reading either the - * tag name or the tag payload, an {@link IOException} is thrown (unexpected - * end). - *

- * - * @return the tag that was read or null if EOF is reached - * @throws IOException if an I/O error occurs - */ - public NbtNamedTag readNamedTag() throws IOException { - return readNamedTag(0); - } - - /** - *

- * Reads a tag and its name from the stream. - *

- *

- * Should the tag be of type {@link NbtType#COMPOUND} or {@link NbtType#LIST} - * will the full content (all elements in the compounds or list) be read. - *

- *

- * Null may be returned if the id of the tag can not be read due to the stream - * ending (expected end). If however the stream ends while reading either the - * tag name or the tag payload, an {@link IOException} is thrown (unexpected - * end). - *

- * - * @param depth the depth (used for recursive reading of lists or compounds) - * @return the tag that was read or null if EOF is reached - * @throws IOException if an I/O error occurs - */ - public NbtNamedTag readNamedTag(int depth) throws IOException { - int id = read(); - if (id == -1) - return null; - NbtType type = NbtType.getById((byte) id); - - String name = type != NbtType.END ? readString() : ""; - - return new NbtNamedTag(name, readTag(type, depth)); - } - - /** - *

- * Reads the payload of a tag given the type. - *

- *

- * This method accepts a depth parameter which in necessary for recursive - * reading of compounds and lists. - *

- *

- * The depth parameter indicates what depth the currently called function has, - * starting with 0 if this method in being called initially. - *

- *

- * Should this method be called while reading a compound or list, the depth will - * be 1. Should these compounds or lists contain further compounds and lists - * will the depth be 2 (and so on). - *

- * - * @param type the type - * @param depth the depth (used for recursive reading of lists or compounds) - * @return the tag - * @throws IOException if an I/O error occurs. - */ - public NbtTag readTag(NbtType type, int depth) throws IOException { - switch (type) { - case END: - return readTagEnd(depth); - case BYTE: - return new NbtByte(readByte()); - case SHORT: - return new NbtShort(readShort()); - case INT: - return new NbtInt(readInt()); - case LONG: - return new NbtLong(readLong()); - case FLOAT: - return new NbtFloat(readFloat()); - case DOUBLE: - return new NbtDouble(readDouble()); - case BYTE_ARRAY: - return readTagByteArray(); - case STRING: - return readTagString(); - case LIST: - return readTagList(depth); - case COMPOUND: - return readTagCompound(depth); - case INT_ARRAY: - return readTagIntArray(); - case LONG_ARRAY: - return readTagLongArray(); - default: - throw new IOException("invalid tag type: " + type); - } - } - - public NbtEnd readTagEnd(int depth) throws IOException { - if (depth == 0) - throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it."); - return NbtEnd.INSTANCE; - } - - public NbtByteArray readTagByteArray() throws IOException { - int length = readInt(); - byte[] bytes = new byte[length]; - readFully(bytes); - return new NbtByteArray(bytes); - } - - public NbtString readTagString() throws IOException { - String input = readString(); - if (Strings.isNumeric(input)) { - return new NbtBigInt(input); - } - return new NbtString(input); - } - - public NbtList readTagList(int depth) throws IOException { - NbtType elementType = NbtType.getById(readByte()); - int length = readInt(); - - if (elementType == NbtType.END && length > 0) - throw new IOException("List is of type TAG_End but not empty"); - - List tagList = new ArrayList<>(); - for (int i = 0; i < length; ++i) { - NbtTag tag = readTag(elementType, depth + 1); - tagList.add(tag); - } - - return NbtList.createFromTypeAndFill(elementType, tagList); - } - - public NbtCompound readTagCompound(int depth) throws IOException { - Map tagMap = new HashMap<>(); - while (true) { - NbtNamedTag namedTag = readNamedTag(depth + 1); - if (namedTag == null) - throw new IOException("NBT ends inside a list"); - - NbtTag tag = namedTag.getTag(); - if (tag instanceof NbtEnd) - break; - else - tagMap.put(namedTag.getName(), tag); - } - - return new NbtCompound(tagMap); - } - - public NbtIntArray readTagIntArray() throws IOException { - int length = readInt(); - int[] data = new int[length]; - for (int i = 0; i < length; i++) - data[i] = readInt(); - - return new NbtIntArray(data); - } - - public NbtLongArray readTagLongArray() throws IOException { - int length = readInt(); - long[] data = new long[length]; - for (int i = 0; i < length; i++) - data[i] = readLong(); - - return new NbtLongArray(data); - } - - public String readString() throws IOException { - int length = readUnsignedShort(); - byte[] bytes = new byte[length]; - readFully(bytes); - - return new String(bytes, UTF_8); - } + private final static Charset UTF_8 = Charset.forName("UTF-8"); + + /** + * Creates a new {@code NBTInputStream}, which will source its data from the + * specified input stream. + * + * @param in the input stream + */ + public NbtInputStream(InputStream in) { + super(in); + } + + /** + *

+ * Reads a tag and its name from the stream. + *

+ *

+ * Should the tag be of type {@link NbtType#COMPOUND} or {@link NbtType#LIST} + * will the full content (all elements in the compounds or list) be read. + *

+ *

+ * Null may be returned if the id of the tag can not be read due to the stream + * ending (expected end). If however the stream ends while reading either the + * tag name or the tag payload, an {@link IOException} is thrown (unexpected + * end). + *

+ * + * @return the tag that was read or null if EOF is reached + * @throws IOException if an I/O error occurs + */ + public NbtNamedTag readNamedTag() throws IOException { + return readNamedTag(0); + } + + /** + *

+ * Reads a tag and its name from the stream. + *

+ *

+ * Should the tag be of type {@link NbtType#COMPOUND} or {@link NbtType#LIST} + * will the full content (all elements in the compounds or list) be read. + *

+ *

+ * Null may be returned if the id of the tag can not be read due to the stream + * ending (expected end). If however the stream ends while reading either the + * tag name or the tag payload, an {@link IOException} is thrown (unexpected + * end). + *

+ * + * @param depth the depth (used for recursive reading of lists or compounds) + * @return the tag that was read or null if EOF is reached + * @throws IOException if an I/O error occurs + */ + public NbtNamedTag readNamedTag(int depth) throws IOException { + int id = read(); + if (id == -1) { + return null; + } + NbtType type = NbtType.getById((byte) id); + + String name = type != NbtType.END ? readString() : ""; + + return new NbtNamedTag(name, readTag(type, depth)); + } + + /** + *

+ * Reads the payload of a tag given the type. + *

+ *

+ * This method accepts a depth parameter which in necessary for recursive + * reading of compounds and lists. + *

+ *

+ * The depth parameter indicates what depth the currently called function has, + * starting with 0 if this method in being called initially. + *

+ *

+ * Should this method be called while reading a compound or list, the depth will + * be 1. Should these compounds or lists contain further compounds and lists + * will the depth be 2 (and so on). + *

+ * + * @param type the type + * @param depth the depth (used for recursive reading of lists or compounds) + * @return the tag + * @throws IOException if an I/O error occurs. + */ + public NbtTag readTag(NbtType type, int depth) throws IOException { + switch (type) { + case END: + return readTagEnd(depth); + case BYTE: + return new NbtByte(readByte()); + case SHORT: + return new NbtShort(readShort()); + case INT: + return new NbtInt(readInt()); + case LONG: + return new NbtLong(readLong()); + case FLOAT: + return new NbtFloat(readFloat()); + case DOUBLE: + return new NbtDouble(readDouble()); + case BYTE_ARRAY: + return readTagByteArray(); + case STRING: + return readTagString(); + case LIST: + return readTagList(depth); + case COMPOUND: + return readTagCompound(depth); + case INT_ARRAY: + return readTagIntArray(); + case LONG_ARRAY: + return readTagLongArray(); + default: + throw new IOException("invalid tag type: " + type); + } + } + + public NbtEnd readTagEnd(int depth) throws IOException { + if (depth == 0) { + throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it."); + } + return NbtEnd.INSTANCE; + } + + public NbtByteArray readTagByteArray() throws IOException { + int length = readInt(); + byte[] bytes = new byte[length]; + readFully(bytes); + return new NbtByteArray(bytes); + } + + public NbtString readTagString() throws IOException { + String input = readString(); + if (Strings.isNumeric(input)) { + return new NbtBigInt(input); + } + return new NbtString(input); + } + + public NbtList readTagList(int depth) throws IOException { + NbtType elementType = NbtType.getById(readByte()); + int length = readInt(); + + if (elementType == NbtType.END && length > 0) { + throw new IOException("List is of type TAG_End but not empty"); + } + + List tagList = new ArrayList<>(); + for (int i = 0; i < length; ++i) { + NbtTag tag = readTag(elementType, depth + 1); + tagList.add(tag); + } + + return NbtList.createFromTypeAndFill(elementType, tagList); + } + + public NbtCompound readTagCompound(int depth) throws IOException { + Map tagMap = new HashMap<>(); + while (true) { + NbtNamedTag namedTag = readNamedTag(depth + 1); + if (namedTag == null) { + throw new IOException("NBT ends inside a list"); + } + + NbtTag tag = namedTag.getTag(); + if (tag instanceof NbtEnd) { + break; + } else { + tagMap.put(namedTag.getName(), tag); + } + } + + return new NbtCompound(tagMap); + } + + public NbtIntArray readTagIntArray() throws IOException { + int length = readInt(); + int[] data = new int[length]; + for (int i = 0; i < length; i++) { + data[i] = readInt(); + } + + return new NbtIntArray(data); + } + + public NbtLongArray readTagLongArray() throws IOException { + int length = readInt(); + long[] data = new long[length]; + for (int i = 0; i < length; i++) { + data[i] = readLong(); + } + + return new NbtLongArray(data); + } + + public String readString() throws IOException { + int length = readUnsignedShort(); + byte[] bytes = new byte[length]; + readFully(bytes); + + return new String(bytes, UTF_8); + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtMatcher.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtMatcher.java index 62b176a..b04beb4 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtMatcher.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtMatcher.java @@ -3,100 +3,103 @@ import java.util.List; import java.util.Objects; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; import com.syntaxphoenix.syntaxapi.nbt.NbtTag; import com.syntaxphoenix.syntaxapi.nbt.NbtType; -import com.syntaxphoenix.syntaxapi.nbt.NbtList; public class NbtMatcher { - /** - * Check whether the pattern and the matching tag are completely identical. This - * will cause values which are present in the matching tag but not in the - * pattern tag to prevent a match. - */ - @SuppressWarnings("unused") - private final static int EXACT = 0b1, - /** - * Ignore values, only verify that the NBT tags match in types. - */ - TYPES_ONLY = 0b10; - - private final NbtTag pattern; - @SuppressWarnings("unused") - private final int flags; - - public NbtMatcher(NbtTag pattern, int flags) { - this.pattern = Objects.requireNonNull(pattern); - this.flags = flags; - } - - public boolean matches(NbtTag tag) { - return pattern.equals(tag); - } - - /** - *

- * Custom implementation of a {@link NbtType#LIST} tag which caches the type id, - * hash and emptiness. - *

- *

- * This custom list is optimized for being matched against a high quantity of - * other lists. - *

- */ - @SuppressWarnings("unused") - private static class NbtMatcherList extends NbtTag { - - private final int hash; - private final byte type; - private final boolean empty; - private final NbtTag[] value; - - public NbtMatcherList(NbtList tag) { - this.empty = tag.isEmpty(); - this.hash = tag.hashCode(); - this.type = tag.getTypeId(); - this.value = tag.getValue().toArray(new NbtTag[tag.size()]); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof NbtList && equals((NbtList) obj); - } - - @SuppressWarnings("unlikely-arg-type") - public boolean equals(NbtList tag) { - return this.empty && tag.isEmpty() || this.type == tag.getTypeId() && this.hash == tag.hashCode() && this.equals(tag.getValue()); - } - - public boolean equals(List tags) { - int index = 0; - for (NbtTag tag : tags) - if (!tag.equals(value[index++])) - return false; - return true; - } - - @Override - public Object getValue() { - return value; - } - - @Override - public NbtType getType() { - return NbtType.LIST; - } - - @Override - public String toMSONString() { - throw new UnsupportedOperationException(); - } - - @Override - public NbtMatcherList clone() { - return new NbtMatcherList(new NbtList<>(value)); - } - - } + /** + * Check whether the pattern and the matching tag are completely identical. This + * will cause values which are present in the matching tag but not in the + * pattern tag to prevent a match. + */ + @SuppressWarnings("unused") + private final static int EXACT = 0b1, + /** + * Ignore values, only verify that the NBT tags match in types. + */ + TYPES_ONLY = 0b10; + + private final NbtTag pattern; + @SuppressWarnings("unused") + private final int flags; + + public NbtMatcher(NbtTag pattern, int flags) { + this.pattern = Objects.requireNonNull(pattern); + this.flags = flags; + } + + public boolean matches(NbtTag tag) { + return pattern.equals(tag); + } + + /** + *

+ * Custom implementation of a {@link NbtType#LIST} tag which caches the type id, + * hash and emptiness. + *

+ *

+ * This custom list is optimized for being matched against a high quantity of + * other lists. + *

+ */ + @SuppressWarnings("unused") + private static class NbtMatcherList extends NbtTag { + + private final int hash; + private final byte type; + private final boolean empty; + private final NbtTag[] value; + + public NbtMatcherList(NbtList tag) { + this.empty = tag.isEmpty(); + this.hash = tag.hashCode(); + this.type = tag.getTypeId(); + this.value = tag.getValue().toArray(new NbtTag[tag.size()]); + } + + @Override + public boolean equals(Object obj) { + return obj instanceof NbtList && equals((NbtList) obj); + } + + @SuppressWarnings("unlikely-arg-type") + public boolean equals(NbtList tag) { + return this.empty && tag.isEmpty() + || this.type == tag.getTypeId() && this.hash == tag.hashCode() && this.equals(tag.getValue()); + } + + public boolean equals(List tags) { + int index = 0; + for (NbtTag tag : tags) { + if (!tag.equals(value[index++])) { + return false; + } + } + return true; + } + + @Override + public Object getValue() { + return value; + } + + @Override + public NbtType getType() { + return NbtType.LIST; + } + + @Override + public String toMSONString() { + throw new UnsupportedOperationException(); + } + + @Override + public NbtMatcherList clone() { + return new NbtMatcherList(new NbtList<>(value)); + } + + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtOutputStream.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtOutputStream.java index 0fdbd2e..5858ea5 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtOutputStream.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtOutputStream.java @@ -7,7 +7,21 @@ import java.util.List; import java.util.Map; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtByteArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtDouble; +import com.syntaxphoenix.syntaxapi.nbt.NbtFloat; +import com.syntaxphoenix.syntaxapi.nbt.NbtInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtIntArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtLong; +import com.syntaxphoenix.syntaxapi.nbt.NbtLongArray; +import com.syntaxphoenix.syntaxapi.nbt.NbtNamedTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtShort; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; /** * An NBTInputStream extends {@link DataOutputStream} by allowing to write named @@ -15,187 +29,191 @@ */ public final class NbtOutputStream extends DataOutputStream { - private final static Charset UTF_8 = Charset.forName("UTF-8"); - - private final static int END_ID = NbtType.END.getId(); - - /** - * Creates a new {@code NBTOutputStream}, which will write data to the specified - * underlying output stream. - * - * @param out the output stream - */ - public NbtOutputStream(OutputStream out) { - super(out); - } - - /** - * Writes a tag. - * - * @param name the name of the tag - * @param tag the tag to write - * @throws IOException if an I/O error occurs - */ - public void writeNamedTag(String name, NbtTag tag) throws IOException { - if (tag == null) { - return; - } - - int typeId = tag.getType().getId(); - byte[] nameBytes = name.getBytes(UTF_8); - - writeByte(typeId); - writeShort(nameBytes.length); - write(nameBytes); - - if (typeId == END_ID) - throw new IOException("Named TAG_End not permitted."); - - writeTag(tag); - } - - /** - * Writes a tag. - * - * @param tag the tag to write - * @throws IOException if an I/O error occurs - */ - public void writeNamedTag(NbtNamedTag tag) throws IOException { - writeNamedTag(tag.getName(), tag.getTag()); - } - - /** - * Writes a tag payload. - * - * @param tag the tag - * @throws IOException if an I/O error occurs - */ - public void writeTag(NbtTag tag) throws IOException { - switch (tag.getType()) { - case END: - break; - case BYTE: - writeByte(((NbtByte) tag).getByteValue()); - break; - case SHORT: - writeShort(((NbtShort) tag).getShortValue()); - break; - case INT: - writeInt(((NbtInt) tag).getIntValue()); - break; - case LONG: - writeLong(((NbtLong) tag).getLongValue()); - break; - case FLOAT: - writeFloat(((NbtFloat) tag).getFloatValue()); - break; - case DOUBLE: - writeDouble(((NbtDouble) tag).getDoubleValue()); - break; - case BYTE_ARRAY: - writeTagByteArray((NbtByteArray) tag); - break; - case STRING: - writeTagString((NbtString) tag); - break; - case LIST: - writeTagList((NbtList) tag); - break; - case COMPOUND: - writeTagCompound((NbtCompound) tag); - break; - case INT_ARRAY: - writeTagIntArray((NbtIntArray) tag); - break; - case LONG_ARRAY: - writeTagLongArray((NbtLongArray) tag); - break; - default: - throw new IOException("invalid tag type: " + tag.getType()); - } - } - - /** - * Writes a {@code TAG_String} tag. - * - * @param tag the tag. - * @throws IOException if an I/O error occurs - */ - public void writeTagString(NbtString tag) throws IOException { - byte[] bytes = tag.getValue().getBytes(UTF_8); - writeShort(bytes.length); - write(bytes); - } - - /** - * Writes a {@code TAG_Byte_Array} tag. - * - * @param tag the tag - * @throws IOException if an I/O error occurs - */ - public void writeTagByteArray(NbtByteArray tag) throws IOException { - byte[] bytes = tag.getValue(); - writeInt(bytes.length); - write(bytes); - } - - /** - * Writes a {@code TAG_List} tag. - * - * @param tag the tag. - * @throws IOException if an I/O error occurs - */ - public void writeTagList(NbtList tag) throws IOException { - NbtType type = tag.getElementType(); - List tags = tag.getValue(); - int size = tags.size(); - - writeByte(type.getId()); - writeInt(size); - - if (tags.isEmpty()) { - return; - } - - for (NbtTag element : tags) - writeTag(element); - } - - /** - * Writes a {@code TAG_Compound} tag. - * - * @param tag the tag - * @throws IOException if an I/O error occurs - */ - public void writeTagCompound(NbtCompound tag) throws IOException { - for (Map.Entry entry : tag.getValue().entrySet()) { - writeNamedTag(entry.getKey(), entry.getValue()); - } - writeByte(END_ID); - } - - /** - * Writes a {@code TAG_Int_Array} tag. - * - * @param tag the tag - * @throws IOException if an I/O error occurs - */ - public void writeTagIntArray(NbtIntArray tag) throws IOException { - writeInt(tag.length()); - for (int aData : tag.getValue()) - writeInt(aData); - } - - /** - * Writes a {@code TAG_Long_Array} tag. - * - * @param tag the tag - * @throws IOException if an I/O error occurs - */ - public void writeTagLongArray(NbtLongArray tag) throws IOException { - writeInt(tag.length()); - for (long aData : tag.getValue()) - writeLong(aData); - } + private final static Charset UTF_8 = Charset.forName("UTF-8"); + + private final static int END_ID = NbtType.END.getId(); + + /** + * Creates a new {@code NBTOutputStream}, which will write data to the specified + * underlying output stream. + * + * @param out the output stream + */ + public NbtOutputStream(OutputStream out) { + super(out); + } + + /** + * Writes a tag. + * + * @param name the name of the tag + * @param tag the tag to write + * @throws IOException if an I/O error occurs + */ + public void writeNamedTag(String name, NbtTag tag) throws IOException { + if (tag == null) { + return; + } + + int typeId = tag.getType().getId(); + byte[] nameBytes = name.getBytes(UTF_8); + + writeByte(typeId); + writeShort(nameBytes.length); + write(nameBytes); + + if (typeId == END_ID) { + throw new IOException("Named TAG_End not permitted."); + } + + writeTag(tag); + } + + /** + * Writes a tag. + * + * @param tag the tag to write + * @throws IOException if an I/O error occurs + */ + public void writeNamedTag(NbtNamedTag tag) throws IOException { + writeNamedTag(tag.getName(), tag.getTag()); + } + + /** + * Writes a tag payload. + * + * @param tag the tag + * @throws IOException if an I/O error occurs + */ + public void writeTag(NbtTag tag) throws IOException { + switch (tag.getType()) { + case END: + break; + case BYTE: + writeByte(((NbtByte) tag).getByteValue()); + break; + case SHORT: + writeShort(((NbtShort) tag).getShortValue()); + break; + case INT: + writeInt(((NbtInt) tag).getIntValue()); + break; + case LONG: + writeLong(((NbtLong) tag).getLongValue()); + break; + case FLOAT: + writeFloat(((NbtFloat) tag).getFloatValue()); + break; + case DOUBLE: + writeDouble(((NbtDouble) tag).getDoubleValue()); + break; + case BYTE_ARRAY: + writeTagByteArray((NbtByteArray) tag); + break; + case STRING: + writeTagString((NbtString) tag); + break; + case LIST: + writeTagList((NbtList) tag); + break; + case COMPOUND: + writeTagCompound((NbtCompound) tag); + break; + case INT_ARRAY: + writeTagIntArray((NbtIntArray) tag); + break; + case LONG_ARRAY: + writeTagLongArray((NbtLongArray) tag); + break; + default: + throw new IOException("invalid tag type: " + tag.getType()); + } + } + + /** + * Writes a {@code TAG_String} tag. + * + * @param tag the tag. + * @throws IOException if an I/O error occurs + */ + public void writeTagString(NbtString tag) throws IOException { + byte[] bytes = tag.getValue().getBytes(UTF_8); + writeShort(bytes.length); + write(bytes); + } + + /** + * Writes a {@code TAG_Byte_Array} tag. + * + * @param tag the tag + * @throws IOException if an I/O error occurs + */ + public void writeTagByteArray(NbtByteArray tag) throws IOException { + byte[] bytes = tag.getValue(); + writeInt(bytes.length); + write(bytes); + } + + /** + * Writes a {@code TAG_List} tag. + * + * @param tag the tag. + * @throws IOException if an I/O error occurs + */ + public void writeTagList(NbtList tag) throws IOException { + NbtType type = tag.getElementType(); + List tags = tag.getValue(); + int size = tags.size(); + + writeByte(type.getId()); + writeInt(size); + + if (tags.isEmpty()) { + return; + } + + for (NbtTag element : tags) { + writeTag(element); + } + } + + /** + * Writes a {@code TAG_Compound} tag. + * + * @param tag the tag + * @throws IOException if an I/O error occurs + */ + public void writeTagCompound(NbtCompound tag) throws IOException { + for (Map.Entry entry : tag.getValue().entrySet()) { + writeNamedTag(entry.getKey(), entry.getValue()); + } + writeByte(END_ID); + } + + /** + * Writes a {@code TAG_Int_Array} tag. + * + * @param tag the tag + * @throws IOException if an I/O error occurs + */ + public void writeTagIntArray(NbtIntArray tag) throws IOException { + writeInt(tag.length()); + for (int aData : tag.getValue()) { + writeInt(aData); + } + } + + /** + * Writes a {@code TAG_Long_Array} tag. + * + * @param tag the tag + * @throws IOException if an I/O error occurs + */ + public void writeTagLongArray(NbtLongArray tag) throws IOException { + writeInt(tag.length()); + for (long aData : tag.getValue()) { + writeLong(aData); + } + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtParser.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtParser.java index 87222c5..e97893f 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtParser.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtParser.java @@ -21,141 +21,141 @@ public class NbtParser { - public static final MojangsonDeserializer DESERIALIZER = new MojangsonDeserializer(); - public static final MojangsonSerializer SERIALIZER = new MojangsonSerializer(true); + public static final MojangsonDeserializer DESERIALIZER = new MojangsonDeserializer(); + public static final MojangsonSerializer SERIALIZER = new MojangsonSerializer(true); - /** - * Convert nbt to mson - * - * @param tag - NbtTag that should be converted - * - * @return resulting mson string - */ - public static String toPrettyMson(NbtNamedTag tag) { - return SERIALIZER.toString(tag); - } + /** + * Convert nbt to mson + * + * @param tag - NbtTag that should be converted + * + * @return resulting mson string + */ + public static String toPrettyMson(NbtNamedTag tag) { + return SERIALIZER.toString(tag); + } - /** - * Convert mson to nbt - * - * @param mson - mson string that should be converted - * - * @return resulting NbtTag - */ - public static NbtNamedTag fromPrettyMson(String mson) { - try { - return DESERIALIZER.fromString(mson); - } catch (IOException e) { - return null; - } - } + /** + * Convert mson to nbt + * + * @param mson - mson string that should be converted + * + * @return resulting NbtTag + */ + public static NbtNamedTag fromPrettyMson(String mson) { + try { + return DESERIALIZER.fromString(mson); + } catch (IOException e) { + return null; + } + } - /** - * Analyzes and tries to convert an Object to nbt - * - * @param raw - not analyzed or converted object that should be converted to nbt - * - * @return NbtTag or null depending on if it was successful or not - */ - @SuppressWarnings("unchecked") - public static NbtTag fromObject(Object raw) { - if (raw instanceof Number) { - return NbtNumber.fromNumber((Number) raw); - } else if (raw instanceof String) { - String input = (String) raw; - if (Strings.isNumeric(input)) { - return new NbtBigInt(input); - } else if (Strings.isDecimal(input)) { - return new NbtBigDecimal(input); - } - return new NbtString(input); - } else if (raw instanceof List) { - List> list = fromList((List) raw); - if (list.size() == 1) { - return list.get(0); - } - return listsToList(list); - } else if (raw instanceof Map) { - return fromMap((Map) raw); - } else if (raw instanceof NbtTag) { - return (NbtTag) raw; - } - return null; - } + /** + * Analyzes and tries to convert an Object to nbt + * + * @param raw - not analyzed or converted object that should be converted to nbt + * + * @return NbtTag or null depending on if it was successful or not + */ + @SuppressWarnings("unchecked") + public static NbtTag fromObject(Object raw) { + if (raw instanceof Number) { + return NbtNumber.fromNumber((Number) raw); + } else if (raw instanceof String) { + String input = (String) raw; + if (Strings.isNumeric(input)) { + return new NbtBigInt(input); + } else if (Strings.isDecimal(input)) { + return new NbtBigDecimal(input); + } + return new NbtString(input); + } else if (raw instanceof List) { + List> list = fromList((List) raw); + if (list.size() == 1) { + return list.get(0); + } + return listsToList(list); + } else if (raw instanceof Map) { + return fromMap((Map) raw); + } else if (raw instanceof NbtTag) { + return (NbtTag) raw; + } + return null; + } - /** - * Trying to convert a List to NbtList's - * - * @param list - list of objects that should be converted - * - * @return list of NbtList's based on their type - */ - @SuppressWarnings("unchecked") - public static List> fromList(List list) { - List> output = new ArrayList<>(); - if (list == null || list.isEmpty()) { - output.add(new NbtList<>()); - return output; - } - HashMap> sort = new HashMap<>(); - for (Object obj : list) { - NbtTag tag = fromObject(obj); - NbtType type = tag.getType(); - if (sort.containsKey(type)) { - sort.get(type).add(tag); - } else { - NbtList nbt = (NbtList) NbtList.createFromType(type); - nbt.add(tag); - sort.put(type, nbt); - } - } - output.addAll(sort.values()); - return output; - } + /** + * Trying to convert a List to NbtList's + * + * @param list - list of objects that should be converted + * + * @return list of NbtList's based on their type + */ + @SuppressWarnings("unchecked") + public static List> fromList(List list) { + List> output = new ArrayList<>(); + if (list == null || list.isEmpty()) { + output.add(new NbtList<>()); + return output; + } + HashMap> sort = new HashMap<>(); + for (Object obj : list) { + NbtTag tag = fromObject(obj); + NbtType type = tag.getType(); + if (sort.containsKey(type)) { + sort.get(type).add(tag); + } else { + NbtList nbt = (NbtList) NbtList.createFromType(type); + nbt.add(tag); + sort.put(type, nbt); + } + } + output.addAll(sort.values()); + return output; + } - /** - * Trying to convert a Map to an NbtCompound - * - * @param map - Map that should be converted to an NbtCompound - * - * @return resulting NbtCompound tag - */ - public static NbtCompound fromMap(Map map) { - NbtCompound compound = new NbtCompound(); - if (map == null || map.isEmpty()) { - return compound; - } - Set> set = map.entrySet(); - for (Entry entry : set) { - Object raw = entry.getKey(); - if (!(raw instanceof String)) { - continue; - } - String key = (String) raw; - NbtTag input = fromObject(entry.getValue()); - if (input != null) { - compound.set(key, input); - } - } - return compound; - } + /** + * Trying to convert a Map to an NbtCompound + * + * @param map - Map that should be converted to an NbtCompound + * + * @return resulting NbtCompound tag + */ + public static NbtCompound fromMap(Map map) { + NbtCompound compound = new NbtCompound(); + if (map == null || map.isEmpty()) { + return compound; + } + Set> set = map.entrySet(); + for (Entry entry : set) { + Object raw = entry.getKey(); + if (!(raw instanceof String)) { + continue; + } + String key = (String) raw; + NbtTag input = fromObject(entry.getValue()); + if (input != null) { + compound.set(key, input); + } + } + return compound; + } - /** - * Convert a List of NbtList's to an NbtList of NbtList's - * - * @param lists - lists that should be converted - * - * @return NbtList containing all NbtList's - */ - public static NbtList> listsToList(List> lists) { - NbtList> list = new NbtList<>(); - if (lists == null || lists.isEmpty()) { - return list; - } - for (NbtList input : lists) { - list.add(input); - } - return list; - } + /** + * Convert a List of NbtList's to an NbtList of NbtList's + * + * @param lists - lists that should be converted + * + * @return NbtList containing all NbtList's + */ + public static NbtList> listsToList(List> lists) { + NbtList> list = new NbtList<>(); + if (lists == null || lists.isEmpty()) { + return list; + } + for (NbtList input : lists) { + list.add(input); + } + return list; + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtSerializer.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtSerializer.java index 56b72a8..da43d2b 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtSerializer.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtSerializer.java @@ -9,42 +9,42 @@ public class NbtSerializer implements Serializer { - public static final NbtSerializer COMPRESSED = new NbtSerializer(true); - public static final NbtSerializer UNCOMPRESSED = new NbtSerializer(true); - - private final boolean compress; - - /** - * Constructs a new NBT-Serializer. - * - * @param compress whether to use gzip compression. - */ - public NbtSerializer(boolean compress) { - this.compress = compress; - } - - /** - * Constructs a new NBT-Serializer with enabled gzip compression. - */ - public NbtSerializer() { - this(true); - } - - @Override - public void toStream(NbtNamedTag tag, OutputStream stream) throws IOException { - if (compress) { - GZIPOutputStream gzipStream = new GZIPOutputStream(stream); - NbtOutputStream nbtStream = new NbtOutputStream(gzipStream); - nbtStream.writeNamedTag(tag); - gzipStream.finish(); - nbtStream.flush(); - nbtStream.close(); - } else { - NbtOutputStream output = new NbtOutputStream(stream); - output.writeNamedTag(tag); - output.flush(); - output.close(); - } - } + public static final NbtSerializer COMPRESSED = new NbtSerializer(true); + public static final NbtSerializer UNCOMPRESSED = new NbtSerializer(true); + + private final boolean compress; + + /** + * Constructs a new NBT-Serializer. + * + * @param compress whether to use gzip compression. + */ + public NbtSerializer(boolean compress) { + this.compress = compress; + } + + /** + * Constructs a new NBT-Serializer with enabled gzip compression. + */ + public NbtSerializer() { + this(true); + } + + @Override + public void toStream(NbtNamedTag tag, OutputStream stream) throws IOException { + if (compress) { + GZIPOutputStream gzipStream = new GZIPOutputStream(stream); + NbtOutputStream nbtStream = new NbtOutputStream(gzipStream); + nbtStream.writeNamedTag(tag); + gzipStream.finish(); + nbtStream.flush(); + nbtStream.close(); + } else { + NbtOutputStream output = new NbtOutputStream(stream); + output.writeNamedTag(tag); + output.flush(); + output.close(); + } + } } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtLoadable.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtLoadable.java index 547b69d..570bdc0 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtLoadable.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtLoadable.java @@ -4,6 +4,6 @@ public interface NbtLoadable { - public void fromNbt(E nbt); + public void fromNbt(E nbt); } diff --git a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtSaveable.java b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtSaveable.java index 98934ee..ee2997e 100644 --- a/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtSaveable.java +++ b/nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/utils/NbtSaveable.java @@ -4,6 +4,6 @@ public interface NbtSaveable { - public E asNbt(); + public E asNbt(); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/AsyncSocketServer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/AsyncSocketServer.java index 04f4e8e..17bde6d 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/AsyncSocketServer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/AsyncSocketServer.java @@ -9,92 +9,93 @@ public abstract class AsyncSocketServer extends SocketServer { - private final ExecutorService service; - - public AsyncSocketServer() { - this((ThreadFactory) null); - } - - public AsyncSocketServer(ThreadFactory factory) { - this(factory, Executors.newCachedThreadPool(factory)); - } - - public AsyncSocketServer(ExecutorService service) { - this(DEFAULT_PORT, service); - } - - public AsyncSocketServer(ThreadFactory factory, ExecutorService service) { - this(DEFAULT_PORT, factory, service); - } - - public AsyncSocketServer(int port) { - this(port, (ThreadFactory) null); - } - - public AsyncSocketServer(int port, ThreadFactory factory) { - this(port, factory, Executors.newCachedThreadPool(factory)); - } - - public AsyncSocketServer(int port, ExecutorService service) { - super(port); - this.service = service; - } - - public AsyncSocketServer(int port, ThreadFactory factory, ExecutorService service) { - super(port, factory); - this.service = service; - } - - public AsyncSocketServer(int port, InetAddress address) { - this(port, address, (ThreadFactory) null); - } - - public AsyncSocketServer(int port, InetAddress address, ThreadFactory factory) { - this(port, address, factory, factory == null ? Executors.newCachedThreadPool() : Executors.newCachedThreadPool(factory)); - } - - public AsyncSocketServer(int port, InetAddress address, ExecutorService service) { - super(port, address); - this.service = service; - } - - public AsyncSocketServer(int port, InetAddress address, ThreadFactory factory, ExecutorService service) { - super(port, address, factory); - this.service = service; - } - - /* - * - */ - - public final ExecutorService getExecutorSerivce() { - return service; - } - - /* - * - */ - - @Override - protected void handleClient(Socket socket) throws Throwable { - service.execute(() -> { - try { - handleClientAsync(socket); - } catch (Throwable throwable) { - try { - if (!socket.isClosed()) - socket.close(); - } catch (IOException e) { - } - handleExceptionAsync(throwable); - } - }); - } - - protected void handleExceptionAsync(Throwable throwable) { - throwable.printStackTrace(); - } - - protected abstract void handleClientAsync(Socket socket) throws Throwable; + private final ExecutorService service; + + public AsyncSocketServer() { + this((ThreadFactory) null); + } + + public AsyncSocketServer(ThreadFactory factory) { + this(factory, Executors.newCachedThreadPool(factory)); + } + + public AsyncSocketServer(ExecutorService service) { + this(DEFAULT_PORT, service); + } + + public AsyncSocketServer(ThreadFactory factory, ExecutorService service) { + this(DEFAULT_PORT, factory, service); + } + + public AsyncSocketServer(int port) { + this(port, (ThreadFactory) null); + } + + public AsyncSocketServer(int port, ThreadFactory factory) { + this(port, factory, Executors.newCachedThreadPool(factory)); + } + + public AsyncSocketServer(int port, ExecutorService service) { + super(port); + this.service = service; + } + + public AsyncSocketServer(int port, ThreadFactory factory, ExecutorService service) { + super(port, factory); + this.service = service; + } + + public AsyncSocketServer(int port, InetAddress address) { + this(port, address, (ThreadFactory) null); + } + + public AsyncSocketServer(int port, InetAddress address, ThreadFactory factory) { + this(port, address, factory, factory == null ? Executors.newCachedThreadPool() : Executors.newCachedThreadPool(factory)); + } + + public AsyncSocketServer(int port, InetAddress address, ExecutorService service) { + super(port, address); + this.service = service; + } + + public AsyncSocketServer(int port, InetAddress address, ThreadFactory factory, ExecutorService service) { + super(port, address, factory); + this.service = service; + } + + /* + * + */ + + public final ExecutorService getExecutorSerivce() { + return service; + } + + /* + * + */ + + @Override + protected void handleClient(Socket socket) throws Throwable { + service.execute(() -> { + try { + handleClientAsync(socket); + } catch (Throwable throwable) { + try { + if (!socket.isClosed()) { + socket.close(); + } + } catch (IOException e) { + } + handleExceptionAsync(throwable); + } + }); + } + + protected void handleExceptionAsync(Throwable throwable) { + throwable.printStackTrace(); + } + + protected abstract void handleClientAsync(Socket socket) throws Throwable; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/SocketServer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/SocketServer.java index 28b600b..7a44125 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/SocketServer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/SocketServer.java @@ -12,141 +12,145 @@ public abstract class SocketServer { - public static final int DEFAULT_PORT = 80; + public static final int DEFAULT_PORT = 80; + + /* + * + */ - /* - * - */ - - private final ExecutorService serverThread; - private final InetAddress address; - private final int port; - - private ServerSocket serverSocket; - - public SocketServer() { - this(DEFAULT_PORT); - } - - public SocketServer(ThreadFactory factory) { - this(DEFAULT_PORT, factory); - } - - public SocketServer(int port) { - this(port, null, null); - } - - public SocketServer(int port, ThreadFactory factory) { - this(port, null, factory); - } - - public SocketServer(int port, InetAddress address) { - this(port, address, null); - } - - public SocketServer(int port, InetAddress address, ThreadFactory factory) { - this.port = port; - this.address = address; - this.serverThread = factory == null ? Executors.newSingleThreadExecutor() : Executors.newSingleThreadExecutor(factory); - } - - /* - * - */ - - public final void applyName(String name) { - this.serverThread.submit(() -> Thread.currentThread().setName(name)); - } - - /* - * - */ - - public final ExecutorService getServerThread() { - return serverThread; - } - - public final int getPort() { - return port; - } - - public final ServerSocket getSocket() { - return serverSocket; - } - - /* - * - */ - - public void start() throws IOException { - if (serverSocket != null) - return; - - serverSocket = address == null ? new ServerSocket(port) : new ServerSocket(port, 50, address); - serverThread.submit(() -> { - try { - handleServer(); - } catch (Throwable throwable) { - handleException(throwable); - } - }); - } - - public void stop() throws IOException { - if (serverSocket == null) - return; - - serverSocket.close(); - serverSocket = null; - } - - public boolean isStarted() { - return serverSocket != null; - } - - /* - * - */ - - protected void handleException(Throwable throwable) { - throwable.printStackTrace(); - } - - protected void handleServer() { - - while (serverSocket != null) { - - Socket clientSocket = null; - try { - clientSocket = serverSocket.accept(); - } catch (Throwable throwable) { - handleException(throwable); - } - - if (clientSocket == null) - continue; - boolean open = true; - try { - handleClient(clientSocket); - } catch (Throwable throwable) { - handleException(throwable); - open = false; - } - - if (open) - continue; - try { - clientSocket.close(); - } catch (Throwable throwable) { - handleException(throwable); - } - - } - - } - - protected void handleClient(Socket socket) throws Throwable { - throw new NotImplementedException(); - } + private final ExecutorService serverThread; + private final InetAddress address; + private final int port; + + private ServerSocket serverSocket; + + public SocketServer() { + this(DEFAULT_PORT); + } + + public SocketServer(ThreadFactory factory) { + this(DEFAULT_PORT, factory); + } + + public SocketServer(int port) { + this(port, null, null); + } + + public SocketServer(int port, ThreadFactory factory) { + this(port, null, factory); + } + + public SocketServer(int port, InetAddress address) { + this(port, address, null); + } + + public SocketServer(int port, InetAddress address, ThreadFactory factory) { + this.port = port; + this.address = address; + this.serverThread = factory == null ? Executors.newSingleThreadExecutor() : Executors.newSingleThreadExecutor(factory); + } + + /* + * + */ + + public final void applyName(String name) { + this.serverThread.submit(() -> Thread.currentThread().setName(name)); + } + + /* + * + */ + + public final ExecutorService getServerThread() { + return serverThread; + } + + public final int getPort() { + return port; + } + + public final ServerSocket getSocket() { + return serverSocket; + } + + /* + * + */ + + public void start() throws IOException { + if (serverSocket != null) { + return; + } + + serverSocket = address == null ? new ServerSocket(port) : new ServerSocket(port, 50, address); + serverThread.submit(() -> { + try { + handleServer(); + } catch (Throwable throwable) { + handleException(throwable); + } + }); + } + + public void stop() throws IOException { + if (serverSocket == null) { + return; + } + + serverSocket.close(); + serverSocket = null; + } + + public boolean isStarted() { + return serverSocket != null; + } + + /* + * + */ + + protected void handleException(Throwable throwable) { + throwable.printStackTrace(); + } + + protected void handleServer() { + + while (serverSocket != null) { + + Socket clientSocket = null; + try { + clientSocket = serverSocket.accept(); + } catch (Throwable throwable) { + handleException(throwable); + } + + if (clientSocket == null) { + continue; + } + boolean open = true; + try { + handleClient(clientSocket); + } catch (Throwable throwable) { + handleException(throwable); + open = false; + } + + if (open) { + continue; + } + try { + clientSocket.close(); + } catch (Throwable throwable) { + handleException(throwable); + } + + } + + } + + protected void handleClient(Socket socket) throws Throwable { + throw new NotImplementedException(); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Answer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Answer.java index 0242922..c8ddc0a 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Answer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Answer.java @@ -11,161 +11,166 @@ public abstract class Answer { - public static final List BLOCKED = Arrays.asList("Content-Type", "Server", "Date", "Content-Length", "Set-Cookie"); - - protected final HashMap headers = new HashMap<>(); - protected final ArrayList cookies = new ArrayList<>(); - protected final NamedType type; - - protected int code = 404; - - public Answer(NamedType type) { - this.type = type; - } - - /* - * Getter - */ - - public String header(String key) { - return headers.get(key); - } - - public NamedType type() { - return type; - } - - public int code() { - return code; - } - - /* - * Setter - */ - - public Answer code(int code) { - this.code = code; - return this; - } - - public Answer header(String key, Object value) { - return header(key, value.toString()); - } - - public Answer header(String key, String value) { - synchronized (headers) { - if (value != null) - headers.put(key, value); - else - headers.remove(key); - } - return this; - } - - public Answer addCookie(String key, Object value) { - return addCookie(Cookie.of(key, value)); - } - - public Answer addCookie(Cookie cookie) { - synchronized (cookies) { - if (!cookies.contains(cookie)) - cookies.add(cookie); - } - return this; - } - - public Answer removeCookie(Cookie cookie) { - synchronized (cookies) { - cookies.remove(cookie); - } - return this; - } - - public Answer removeCookie(String key) { - synchronized (cookies) { - cookies.stream().filter(cookie -> cookie.getName().equals(key)).findFirst().ifPresent(cookie -> cookies.remove(cookie)); - } - return this; - } - - /* - * Response Management - */ - - public Answer clearHeaders() { - synchronized (headers) { - headers.clear(); - } - return this; - } - - public Answer clearCookies() { - synchronized (cookies) { - cookies.clear(); - } - return this; - } - - public abstract boolean hasResponse(); - - public abstract E getResponse(); - - public abstract Answer clearResponse(); - - /* - * Serialize answer - */ - - public abstract byte[] serializeResponse(); - - protected byte[] serializeString(String input) { - return input.getBytes(StandardCharsets.UTF_8); - } - - /* - * Send answer - */ - - public Answer write(HttpWriter writer) throws IOException { - if (type == null) - return this; - - byte[] data = null; - int length = 0; - - if (hasResponse()) { - - data = serializeResponse(); - length = data.length; - - } - - writer.write(code).writeServer().writeDate().writeLength(length); - - Set> headers; - synchronized (this.headers) { - headers = this.headers.entrySet(); - } - for (Entry header : headers) { - if (BLOCKED.contains(header.getKey())) - continue; - writer.write(header); - } - - Cookie[] cookie; - synchronized (cookies) { - cookie = cookies.toArray(new Cookie[0]); - } - writer.writeCookies(cookie).writeType(type.type()); - - writer.line(); - - if (data != null) - writer.write(data); - - writer.clear(); - - return this; - } + public static final List BLOCKED = Arrays.asList("Content-Type", "Server", "Date", "Content-Length", "Set-Cookie"); + + protected final HashMap headers = new HashMap<>(); + protected final ArrayList cookies = new ArrayList<>(); + protected final NamedType type; + + protected int code = 404; + + public Answer(NamedType type) { + this.type = type; + } + + /* + * Getter + */ + + public String header(String key) { + return headers.get(key); + } + + public NamedType type() { + return type; + } + + public int code() { + return code; + } + + /* + * Setter + */ + + public Answer code(int code) { + this.code = code; + return this; + } + + public Answer header(String key, Object value) { + return header(key, value.toString()); + } + + public Answer header(String key, String value) { + synchronized (headers) { + if (value != null) { + headers.put(key, value); + } else { + headers.remove(key); + } + } + return this; + } + + public Answer addCookie(String key, Object value) { + return addCookie(Cookie.of(key, value)); + } + + public Answer addCookie(Cookie cookie) { + synchronized (cookies) { + if (!cookies.contains(cookie)) { + cookies.add(cookie); + } + } + return this; + } + + public Answer removeCookie(Cookie cookie) { + synchronized (cookies) { + cookies.remove(cookie); + } + return this; + } + + public Answer removeCookie(String key) { + synchronized (cookies) { + cookies.stream().filter(cookie -> cookie.getName().equals(key)).findFirst().ifPresent(cookie -> cookies.remove(cookie)); + } + return this; + } + + /* + * Response Management + */ + + public Answer clearHeaders() { + synchronized (headers) { + headers.clear(); + } + return this; + } + + public Answer clearCookies() { + synchronized (cookies) { + cookies.clear(); + } + return this; + } + + public abstract boolean hasResponse(); + + public abstract E getResponse(); + + public abstract Answer clearResponse(); + + /* + * Serialize answer + */ + + public abstract byte[] serializeResponse(); + + protected byte[] serializeString(String input) { + return input.getBytes(StandardCharsets.UTF_8); + } + + /* + * Send answer + */ + + public Answer write(HttpWriter writer) throws IOException { + if (type == null) { + return this; + } + + byte[] data = null; + int length = 0; + + if (hasResponse()) { + + data = serializeResponse(); + length = data.length; + + } + + writer.write(code).writeServer().writeDate().writeLength(length); + + Set> headers; + synchronized (this.headers) { + headers = this.headers.entrySet(); + } + for (Entry header : headers) { + if (BLOCKED.contains(header.getKey())) { + continue; + } + writer.write(header); + } + + Cookie[] cookie; + synchronized (cookies) { + cookie = cookies.toArray(new Cookie[0]); + } + writer.writeCookies(cookie).writeType(type.type()); + + writer.line(); + + if (data != null) { + writer.write(data); + } + + writer.clear(); + + return this; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentDeserializer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentDeserializer.java index b3619e5..b13991b 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentDeserializer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentDeserializer.java @@ -3,10 +3,10 @@ @FunctionalInterface public interface ContentDeserializer { - /* - * - */ + /* + * + */ - public RequestData process(String value); + public RequestData process(String value); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentSerializer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentSerializer.java index d426e0f..29e2146 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentSerializer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentSerializer.java @@ -3,10 +3,10 @@ @FunctionalInterface public interface ContentSerializer { - /* - * - */ + /* + * + */ - public String process(RequestData parameters); + public String process(RequestData parameters); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentToUrlModifier.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentToUrlModifier.java index 5f1a2f1..0fd1c1c 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentToUrlModifier.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentToUrlModifier.java @@ -7,11 +7,12 @@ @FunctionalInterface public interface ContentToUrlModifier { - public static final ContentToUrlModifier URL_ENCODED = (url, content, serializer) -> { - if (serializer != null && content != null) - UrlReflection.applyQuery(url, '?' + serializer.process(content)); - }; + public static final ContentToUrlModifier URL_ENCODED = (url, content, serializer) -> { + if (serializer != null && content != null) { + UrlReflection.applyQuery(url, '?' + serializer.process(content)); + } + }; - public void apply(URL url, RequestData content, ContentSerializer serializer); + public void apply(URL url, RequestData content, ContentSerializer serializer); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentType.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentType.java index 8164467..2724ce2 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentType.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ContentType.java @@ -4,142 +4,146 @@ public interface ContentType extends NamedType { - /* - * Interfaces - */ - - public ContentSerializer serializer(); - - public ContentDeserializer deserializer(); - - public ContentToUrlModifier urlModifier(); - - /* - * Defaults - */ - - public default boolean supportsUrlModification() { - return urlModifier() != null; - } - - public default void modifyUrl(URL url, RequestData object) { - ContentToUrlModifier modifier = urlModifier(); - if (modifier != null) - modifier.apply(url, object, serializer()); - } - - public default String serialize(RequestData object) { - ContentSerializer serializer = serializer(); - if (serializer == null) - return ""; - return serializer.process(object); - } - - public default RequestData deserialize(String value) { - ContentDeserializer deserializer = deserializer(); - if (deserializer == null) - return null; - return deserializer.process(value); - } - - /* - * Builder - */ - - public static ContentType build(String type) { - return new ContentType() { - @Override - public String type() { - return type; - } - - @Override - public ContentDeserializer deserializer() { - return null; - } - - @Override - public ContentSerializer serializer() { - return null; - } - - @Override - public ContentToUrlModifier urlModifier() { - return null; - } - }; - } - - public static ContentType build(String type, ContentType content) { - return new ContentType() { - @Override - public String type() { - return type; - } - - @Override - public ContentDeserializer deserializer() { - return content.deserializer(); - } - - @Override - public ContentSerializer serializer() { - return content.serializer(); - } - - @Override - public ContentToUrlModifier urlModifier() { - return content.urlModifier(); - } - }; - } - - public static ContentType build(String type, ContentSerializer serializer, ContentDeserializer deserializer) { - return new ContentType() { - @Override - public String type() { - return type; - } - - @Override - public ContentDeserializer deserializer() { - return deserializer; - } - - @Override - public ContentSerializer serializer() { - return serializer; - } - - @Override - public ContentToUrlModifier urlModifier() { - return null; - } - }; - } - - public static ContentType build(String type, ContentSerializer serializer, ContentDeserializer deserializer, ContentToUrlModifier modifier) { - return new ContentType() { - @Override - public String type() { - return type; - } - - @Override - public ContentDeserializer deserializer() { - return deserializer; - } - - @Override - public ContentSerializer serializer() { - return serializer; - } - - @Override - public ContentToUrlModifier urlModifier() { - return modifier; - } - }; - } + /* + * Interfaces + */ + + public ContentSerializer serializer(); + + public ContentDeserializer deserializer(); + + public ContentToUrlModifier urlModifier(); + + /* + * Defaults + */ + + public default boolean supportsUrlModification() { + return urlModifier() != null; + } + + public default void modifyUrl(URL url, RequestData object) { + ContentToUrlModifier modifier = urlModifier(); + if (modifier != null) { + modifier.apply(url, object, serializer()); + } + } + + public default String serialize(RequestData object) { + ContentSerializer serializer = serializer(); + if (serializer == null) { + return ""; + } + return serializer.process(object); + } + + public default RequestData deserialize(String value) { + ContentDeserializer deserializer = deserializer(); + if (deserializer == null) { + return null; + } + return deserializer.process(value); + } + + /* + * Builder + */ + + public static ContentType build(String type) { + return new ContentType() { + @Override + public String type() { + return type; + } + + @Override + public ContentDeserializer deserializer() { + return null; + } + + @Override + public ContentSerializer serializer() { + return null; + } + + @Override + public ContentToUrlModifier urlModifier() { + return null; + } + }; + } + + public static ContentType build(String type, ContentType content) { + return new ContentType() { + @Override + public String type() { + return type; + } + + @Override + public ContentDeserializer deserializer() { + return content.deserializer(); + } + + @Override + public ContentSerializer serializer() { + return content.serializer(); + } + + @Override + public ContentToUrlModifier urlModifier() { + return content.urlModifier(); + } + }; + } + + public static ContentType build(String type, ContentSerializer serializer, ContentDeserializer deserializer) { + return new ContentType() { + @Override + public String type() { + return type; + } + + @Override + public ContentDeserializer deserializer() { + return deserializer; + } + + @Override + public ContentSerializer serializer() { + return serializer; + } + + @Override + public ContentToUrlModifier urlModifier() { + return null; + } + }; + } + + public static ContentType build(String type, ContentSerializer serializer, ContentDeserializer deserializer, + ContentToUrlModifier modifier) { + return new ContentType() { + @Override + public String type() { + return type; + } + + @Override + public ContentDeserializer deserializer() { + return deserializer; + } + + @Override + public ContentSerializer serializer() { + return serializer; + } + + @Override + public ContentToUrlModifier urlModifier() { + return modifier; + } + }; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Cookie.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Cookie.java index 38220ff..3d94040 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Cookie.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Cookie.java @@ -4,43 +4,43 @@ public class Cookie { - public static Cookie of(String key, Object value) { - return new Cookie(key, value); - } - - private final HashMap properties = new HashMap<>(); - private final String name; - private final Object value; - - private Cookie(String name, Object value) { - this.name = name; - this.value = value; - } - - public String getName() { - return name; - } - - public Object getValue() { - return value; - } - - public HashMap getProperties() { - return properties; - } - - public Cookie add(String key, Object value) { - properties.put(key, value); - return this; - } - - public Cookie add(String key) { - return add(key, null); - } - - public Cookie remove(String key) { - properties.remove(key); - return this; - } + public static Cookie of(String key, Object value) { + return new Cookie(key, value); + } + + private final HashMap properties = new HashMap<>(); + private final String name; + private final Object value; + + private Cookie(String name, Object value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public Object getValue() { + return value; + } + + public HashMap getProperties() { + return properties; + } + + public Cookie add(String key, Object value) { + properties.put(key, value); + return this; + } + + public Cookie add(String key) { + return add(key, null); + } + + public Cookie remove(String key) { + properties.remove(key); + return this; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/CustomRequestData.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/CustomRequestData.java index 1c1928e..8065b82 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/CustomRequestData.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/CustomRequestData.java @@ -2,22 +2,22 @@ public class CustomRequestData extends RequestData { - private final Class type; - private final E value; + private final Class type; + private final E value; - public CustomRequestData(Class type, E value) { - this.type = type; - this.value = value; - } + public CustomRequestData(Class type, E value) { + this.type = type; + this.value = value; + } @Override - public Class getType() { - return type; - } + public Class getType() { + return type; + } - @Override - public E getValue() { - return value; - } + @Override + public E getValue() { + return value; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultDeserializers.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultDeserializers.java index 45b51ba..ff894fa 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultDeserializers.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultDeserializers.java @@ -5,32 +5,33 @@ public class DefaultDeserializers { - /* - * Default deserializers - */ - - public static final ContentSerializer PLAIN = null; - - /* - * Json deserializers - */ - - public static final JsonContentDeserializer JSON = value -> JsonTools.readJson(value); - - public static final JsonContentDeserializer URL_ENCODED = value -> { - JsonObject output = new JsonObject(); - String[] entries = (value = value.replaceFirst("\\?", "")).contains("&") ? value.split("&") - : new String[] { - value - }; - for (int index = 0; index < entries.length; index++) { - String current = entries[index]; - if (!current.contains("=")) - continue; - String[] entry = current.split("=", 2); - output.addProperty(entry[0], entry[1]); - } - return output; - }; + /* + * Default deserializers + */ + + public static final ContentSerializer PLAIN = null; + + /* + * Json deserializers + */ + + public static final JsonContentDeserializer JSON = value -> JsonTools.readJson(value); + + public static final JsonContentDeserializer URL_ENCODED = value -> { + JsonObject output = new JsonObject(); + String[] entries = (value = value.replaceFirst("\\?", "")).contains("&") ? value.split("&") + : new String[] { + value + }; + for (int index = 0; index < entries.length; index++) { + String current = entries[index]; + if (!current.contains("=")) { + continue; + } + String[] entry = current.split("=", 2); + output.addProperty(entry[0], entry[1]); + } + return output; + }; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultSerializers.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultSerializers.java index 897110b..1e7559f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultSerializers.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/DefaultSerializers.java @@ -8,36 +8,37 @@ public class DefaultSerializers { - /* - * Default serializers - */ - - public static final ContentSerializer PLAIN = null; - - /* - * Json serializers - */ - - public static final JsonContentSerializer JSON = parameters -> parameters.toString(); - - public static final JsonContentSerializer URL_ENCODED = parameters -> { - if (parameters.entrySet().isEmpty()) - return ""; - - StringBuilder builder = new StringBuilder(); - - try { - for (Entry parameter : parameters.entrySet()) { - builder.append(URLEncoder.encode(parameter.getKey(), "UTF-8")); - builder.append('='); - builder.append(URLEncoder.encode(parameter.getValue().getAsString(), "UTF-8")); - builder.append('&'); - } - } catch (UnsupportedEncodingException ignore) { - } - - String value = builder.toString(); - return value.substring(0, value.length() - 1); - }; + /* + * Default serializers + */ + + public static final ContentSerializer PLAIN = null; + + /* + * Json serializers + */ + + public static final JsonContentSerializer JSON = parameters -> parameters.toString(); + + public static final JsonContentSerializer URL_ENCODED = parameters -> { + if (parameters.entrySet().isEmpty()) { + return ""; + } + + StringBuilder builder = new StringBuilder(); + + try { + for (Entry parameter : parameters.entrySet()) { + builder.append(URLEncoder.encode(parameter.getKey(), "UTF-8")); + builder.append('='); + builder.append(URLEncoder.encode(parameter.getValue().getAsString(), "UTF-8")); + builder.append('&'); + } + } catch (UnsupportedEncodingException ignore) { + } + + String value = builder.toString(); + return value.substring(0, value.length() - 1); + }; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/FileAnswer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/FileAnswer.java index f1f7433..53c78f7 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/FileAnswer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/FileAnswer.java @@ -4,29 +4,29 @@ public abstract class FileAnswer extends NamedAnswer implements Refreshable { - protected final File file; - - public FileAnswer(File file, NamedType type) { - super(type); - this.file = file; - refresh(); - } - - @Override - public FileAnswer setResponse(String response) { - return this; - } - - public File getFile() { - return file; - } - - @Override - public FileAnswer refresh() { - this.response = readFile(); - return this; - } - - protected abstract String readFile(); + protected final File file; + + public FileAnswer(File file, NamedType type) { + super(type); + this.file = file; + refresh(); + } + + @Override + public FileAnswer setResponse(String response) { + return this; + } + + public File getFile() { + return file; + } + + @Override + public FileAnswer refresh() { + this.response = readFile(); + return this; + } + + protected abstract String readFile(); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpSender.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpSender.java index 4931361..d293b01 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpSender.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpSender.java @@ -5,20 +5,20 @@ public class HttpSender { - private final Socket client; - private final BufferedReader input; + private final Socket client; + private final BufferedReader input; - public HttpSender(Socket client, BufferedReader input) { - this.client = client; - this.input = input; - } + public HttpSender(Socket client, BufferedReader input) { + this.client = client; + this.input = input; + } - public Socket getClient() { - return client; - } + public Socket getClient() { + return client; + } - public BufferedReader getInput() { - return input; - } + public BufferedReader getInput() { + return input; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpServer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpServer.java index 00d8daf..e335f4f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpServer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpServer.java @@ -114,8 +114,9 @@ public HttpServer addType(RequestType type) { } public HttpServer addTypes(RequestType... types) { - for (int index = 0; index < types.length; index++) + for (int index = 0; index < types.length; index++) { supported.add(types[index]); + } return this; } @@ -125,8 +126,9 @@ public HttpServer removeType(RequestType type) { } public HttpServer removeTypes(RequestType... types) { - for (int index = 0; index < types.length; index++) + for (int index = 0; index < types.length; index++) { supported.remove(types[index]); + } return this; } @@ -174,12 +176,14 @@ protected void handleClientAsync(Socket socket) throws Throwable { ReceivedRequest request = new ReceivedRequest(RequestType.fromString(info[0]), path); - if (parameters != null) + if (parameters != null) { request.parseParameters(parameters); + } while ((line = reader.readLine()) != null) { - if (line.isEmpty()) + if (line.isEmpty()) { break; + } request.parseHeader(line); } @@ -196,13 +200,15 @@ protected void handleClientAsync(Socket socket) throws Throwable { RequestState state = gate.acceptRequest(writer, request); if (state.accepted()) { if (request.hasHeader("expect")) { - if (((String) request.getHeader("expect")).contains("100-continue")) + if (((String) request.getHeader("expect")).contains("100-continue")) { new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.CONTINUE).write(writer); + } } } else { - if (!state.message()) + if (!state.message()) { new NamedAnswer(StandardNamedType.PLAIN).setResponse("Method or contenttype is not supported") .code(ResponseCode.BAD_REQUEST).write(writer); + } reader.close(); writer.close(); socket.close(); @@ -210,9 +216,10 @@ protected void handleClientAsync(Socket socket) throws Throwable { } } else { if (request.hasHeader("expect")) { - if (((String) request.getHeader("expect")).contains("100-continue")) + if (((String) request.getHeader("expect")).contains("100-continue")) { new NamedAnswer(StandardNamedType.PLAIN).setResponse("No content length given!").code(ResponseCode.LENGTH_REQUIRED) .write(writer); + } } } @@ -221,8 +228,9 @@ protected void handleClientAsync(Socket socket) throws Throwable { */ RequestContent content = RequestContent.UNNEEDED; - if (validator != null) + if (validator != null) { content = validator.parseContent(writer, request); + } if (!content.ignore()) { @@ -270,8 +278,9 @@ protected void handleClientAsync(Socket socket) throws Throwable { reader.close(); writer.close(); socket.close(); - if (execution.hasThrowable()) + if (execution.hasThrowable()) { throw execution.getThrowable(); + } } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpWriter.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpWriter.java index 42513ae..e13f449 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpWriter.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/HttpWriter.java @@ -9,122 +9,120 @@ public class HttpWriter { - private final PrintStream output; - - public HttpWriter(PrintStream output) { - this.output = output; - } - - /* - * - */ - - public PrintStream getStream() { - return output; - } - - /* - * - */ - - public HttpWriter write(int code) { - getStream().println("HTTP/1.1 " + code + ' ' + ResponseCode.getName(code)); - return this; - } - - /* - * - */ - - public HttpWriter writeServer() { - return write("Server", "Java SyntaxPhoenix HTTP Server from Lauriichan : 1.0"); - } - - public HttpWriter writeDate() { - return write("Date", new Date()); - } - - public HttpWriter writeLength(int length) { - return write("Content-Length", length); - } - - public HttpWriter writeType(ContentType type) { - return writeType(type.type()); - } - - public HttpWriter writeType(String type) { - return write("Content-Type", type + "; charset=UTF-8"); - } - - public HttpWriter writeCookies(Cookie... cookies) { - for (int index = 0; index < cookies.length; index++) - writeCookie(cookies[index]); - return this; - } - - public HttpWriter writeCookie(Cookie cookie) { - StringBuilder builder = new StringBuilder(); - builder.append(cookie.getName()); - builder.append('='); - builder.append(cookie.getValue()); - HashMap properties = cookie.getProperties(); - if (!properties.isEmpty()) { - synchronized (properties) { - builder.append("; "); - builder - .append(properties - .entrySet() - .stream() - .map(entry -> entry.getValue() == null ? entry.getKey() : entry.getKey() + '=' + entry.getValue()) - .collect(Collectors.joining("; "))); - } - } - return write("Set-Cookie", builder.toString()); - } - - /* - * - */ - - public HttpWriter write(Entry entry) { - return write(entry.getKey(), entry.getValue()); - } - - public HttpWriter write(String key, Object value) { - return write(key, value.toString()); - } - - public HttpWriter write(String key, String value) { - getStream().println(key + ": " + value); - return this; - } - - /* - * - */ - - public HttpWriter write(byte[] buffer) throws IOException { - getStream().write(buffer); - return this; - } - - public HttpWriter line() { - getStream().println(); - return this; - } - - /* - * - */ - - public HttpWriter clear() { - getStream().flush(); - return this; - } - - public HttpWriter close() { - getStream().close(); - return this; - } + private final PrintStream output; + + public HttpWriter(PrintStream output) { + this.output = output; + } + + /* + * + */ + + public PrintStream getStream() { + return output; + } + + /* + * + */ + + public HttpWriter write(int code) { + getStream().println("HTTP/1.1 " + code + ' ' + ResponseCode.getName(code)); + return this; + } + + /* + * + */ + + public HttpWriter writeServer() { + return write("Server", "Java SyntaxPhoenix HTTP Server from Lauriichan : 1.0"); + } + + public HttpWriter writeDate() { + return write("Date", new Date()); + } + + public HttpWriter writeLength(int length) { + return write("Content-Length", length); + } + + public HttpWriter writeType(ContentType type) { + return writeType(type.type()); + } + + public HttpWriter writeType(String type) { + return write("Content-Type", type + "; charset=UTF-8"); + } + + public HttpWriter writeCookies(Cookie... cookies) { + for (int index = 0; index < cookies.length; index++) { + writeCookie(cookies[index]); + } + return this; + } + + public HttpWriter writeCookie(Cookie cookie) { + StringBuilder builder = new StringBuilder(); + builder.append(cookie.getName()); + builder.append('='); + builder.append(cookie.getValue()); + HashMap properties = cookie.getProperties(); + if (!properties.isEmpty()) { + synchronized (properties) { + builder.append("; "); + builder.append(properties.entrySet().stream() + .map(entry -> entry.getValue() == null ? entry.getKey() : entry.getKey() + '=' + entry.getValue()) + .collect(Collectors.joining("; "))); + } + } + return write("Set-Cookie", builder.toString()); + } + + /* + * + */ + + public HttpWriter write(Entry entry) { + return write(entry.getKey(), entry.getValue()); + } + + public HttpWriter write(String key, Object value) { + return write(key, value.toString()); + } + + public HttpWriter write(String key, String value) { + getStream().println(key + ": " + value); + return this; + } + + /* + * + */ + + public HttpWriter write(byte[] buffer) throws IOException { + getStream().write(buffer); + return this; + } + + public HttpWriter line() { + getStream().println(); + return this; + } + + /* + * + */ + + public HttpWriter clear() { + getStream().flush(); + return this; + } + + public HttpWriter close() { + getStream().close(); + return this; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonAnswer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonAnswer.java index 16b9e61..f1ade3b 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonAnswer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonAnswer.java @@ -5,94 +5,96 @@ public class JsonAnswer extends Answer { - private JsonObject object = new JsonObject(); - - /* - * - */ - - public JsonAnswer(ContentType type) { - super(type); - } - - /* - * - */ - - public JsonElement respond(String key) { - return object.get(key); - } - - /* - * - */ - - public JsonAnswer code(int code) { - super.code(code); - return this; - } - - public JsonAnswer header(String key, Object value) { - super.header(key, value); - return this; - } - - public JsonAnswer header(String key, String value) { - super.header(key, value); - return this; - } - - public JsonAnswer respond(String key, String value) { - if (value != null) - object.addProperty(key, value); - else - object.remove(key); - return this; - } - - public JsonAnswer respond(String key, JsonElement element) { - if (element != null) - object.add(key, element); - else - object.remove(key); - return this; - } - - public JsonAnswer respond(JsonObject object) { - this.object = object; - return this; - } - - /* - * - */ - - public JsonAnswer clearHeaders() { - clearHeaders(); - return this; - } - - public JsonAnswer clearResponse() { - object = new JsonObject(); - return this; - } - - /* - * - */ - - public boolean hasResponse() { - return !object.keySet().isEmpty(); - } - - @Override - public JsonObject getResponse() { - return object; - } - - @Override - public byte[] serializeResponse() { - return serializeString(object.toString()); - } + private JsonObject object = new JsonObject(); + + /* + * + */ + + public JsonAnswer(ContentType type) { + super(type); + } + + /* + * + */ + + public JsonElement respond(String key) { + return object.get(key); + } + + /* + * + */ + + public JsonAnswer code(int code) { + super.code(code); + return this; + } + + public JsonAnswer header(String key, Object value) { + super.header(key, value); + return this; + } + + public JsonAnswer header(String key, String value) { + super.header(key, value); + return this; + } + + public JsonAnswer respond(String key, String value) { + if (value != null) { + object.addProperty(key, value); + } else { + object.remove(key); + } + return this; + } + + public JsonAnswer respond(String key, JsonElement element) { + if (element != null) { + object.add(key, element); + } else { + object.remove(key); + } + return this; + } + + public JsonAnswer respond(JsonObject object) { + this.object = object; + return this; + } + + /* + * + */ + + public JsonAnswer clearHeaders() { + clearHeaders(); + return this; + } + + public JsonAnswer clearResponse() { + object = new JsonObject(); + return this; + } + + /* + * + */ + + public boolean hasResponse() { + return !object.keySet().isEmpty(); + } + + @Override + public JsonObject getResponse() { + return object; + } + + @Override + public byte[] serializeResponse() { + return serializeString(object.toString()); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentDeserializer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentDeserializer.java index 3655487..d7b466b 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentDeserializer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentDeserializer.java @@ -4,11 +4,11 @@ public interface JsonContentDeserializer extends ContentDeserializer { - @Override - default RequestData process(String value) { - return new CustomRequestData<>(JsonObject.class, parse(value)); - } + @Override + default RequestData process(String value) { + return new CustomRequestData<>(JsonObject.class, parse(value)); + } - public JsonObject parse(String value); + public JsonObject parse(String value); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentSerializer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentSerializer.java index eaf50a3..6546cd0 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentSerializer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/JsonContentSerializer.java @@ -5,12 +5,12 @@ @FunctionalInterface public interface JsonContentSerializer extends ContentSerializer { - @Override - default String process(RequestData parameters) { - Object value = parameters.getValue(); - return value instanceof JsonObject ? process((JsonObject) value) : null; - } + @Override + default String process(RequestData parameters) { + Object value = parameters.getValue(); + return value instanceof JsonObject ? process((JsonObject) value) : null; + } - public String process(JsonObject object); + public String process(JsonObject object); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedAnswer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedAnswer.java index 96f3d84..cfc6e9f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedAnswer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedAnswer.java @@ -2,36 +2,36 @@ public class NamedAnswer extends Answer { - protected String response; - - public NamedAnswer(NamedType type) { - super(type); - } - - @Override - public boolean hasResponse() { - return response != null; - } - - @Override - public String getResponse() { - return response; - } - - public NamedAnswer setResponse(String response) { - this.response = response; - return this; - } - - @Override - public NamedAnswer clearResponse() { - this.response = null; - return this; - } - - @Override - public byte[] serializeResponse() { - return serializeString(response); - } + protected String response; + + public NamedAnswer(NamedType type) { + super(type); + } + + @Override + public boolean hasResponse() { + return response != null; + } + + @Override + public String getResponse() { + return response; + } + + public NamedAnswer setResponse(String response) { + this.response = response; + return this; + } + + @Override + public NamedAnswer clearResponse() { + this.response = null; + return this; + } + + @Override + public byte[] serializeResponse() { + return serializeString(response); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedType.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedType.java index 70c6bcd..c367430 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedType.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/NamedType.java @@ -3,10 +3,10 @@ @FunctionalInterface public interface NamedType { - public String type(); + public String type(); - public default boolean has(String extension) { - return false; - } + public default boolean has(String extension) { + return false; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/PathHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/PathHandler.java index c64c64e..c582a57 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/PathHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/PathHandler.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface PathHandler { - public void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception; + public void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ReceivedRequest.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ReceivedRequest.java index 68f81dd..2cb870f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ReceivedRequest.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ReceivedRequest.java @@ -8,175 +8,184 @@ public class ReceivedRequest { - protected final HashMap headers = new HashMap<>(); - protected final HashMap cookies = new HashMap<>(); - protected final HashMap parameters = new HashMap<>(); - - protected final RequestType type; - protected final String[] path; - protected final String fullPath; - - private RequestData data; - - public ReceivedRequest(RequestType type, String[] path) { - this.type = type; - this.path = path; - this.fullPath = SimpleConversion.toPath(path); - } - - ReceivedRequest(RequestType type, String fullPath) { - this.type = type; - this.path = SimpleConversion.fromPath(fullPath); - this.fullPath = fullPath; - } - - /* - * Parse parameters - */ - - public final ReceivedRequest parseParameters(String... parameters) { - for (int index = 0; index < parameters.length; index++) - parseParameter(parameters[index].trim()); - return this; - } - - public final ReceivedRequest parseParameter(String parameter) { - if (!parameter.contains("=")) - return this; - String[] array = parameter.split("=", 2); - parameters.put(array[0], ValueIdentifier.identify(array[1])); - return this; - } - - /* - * Parameters - */ - - public final HashMap getParams() { - return parameters; - } - - public final Object getParam(String key) { - return parameters.get(key); - } - - public final boolean hasParam(String key) { - return parameters.containsKey(key); - } - - /* - * Parse cookies - */ - - public final ReceivedRequest parseCookies(String cookies) { - if (!cookies.contains(";")) { - return parseCookie(cookies.trim()); - } - String[] array = cookies.split(";"); - for (int index = 0; index < array.length; index++) - parseCookie(array[index].trim()); - return this; - } - - public final ReceivedRequest parseCookie(String cookie) { - if (!cookie.contains("=")) - return this; - String[] array = cookie.split("="); - cookies.put(array[0], ValueIdentifier.identify(array[1])); - return this; - } - - /* - * Cookies - */ - - public final HashMap getCookies() { - return cookies; - } - - public final Object getCookie(String key) { - return cookies.get(key); - } - - public final boolean hasCookie(String key) { - return cookies.containsKey(key); - } - - /* - * Parse headers - */ - - public final ReceivedRequest parseHeaders(Iterable headers) { - return parseHeaders(headers.iterator()); - } - - public final ReceivedRequest parseHeaders(Iterator headers) { - while (headers.hasNext()) - parseHeader(headers.next()); - return this; - } - - public final ReceivedRequest parseHeaders(String... headers) { - if (headers == null || headers.length == 0) - return this; - for (String header : headers) - parseHeader(header); - return this; - } - - public final ReceivedRequest parseHeader(String header) { - if (!header.contains(":")) - return this; - String[] parts = header.split(":", 2); - if ((parts[0] = parts[0].toLowerCase()).equalsIgnoreCase("Cookie")) - return parseCookies(parts[1]); - headers.put(parts[0].toLowerCase(), ValueIdentifier.identify(parts[1].trim())); - return this; - } - - /* - * Headers - */ - - public final HashMap getHeaders() { - return headers; - } - - public final Object getHeader(String key) { - return headers.get(key.toLowerCase()); - } - - public final boolean hasHeader(String key) { - return headers.containsKey(key.toLowerCase()); - } - - /* - * Setter - */ - - public final ReceivedRequest setData(RequestData data) { - this.data = data; - return this; - } - - /* - * Getter - */ - - public final RequestData getData() { - return data; - } - - public final RequestType getType() { - return type; - } - - public final String[] getPath() { - return path; - } - - public final String getPathAsString() { - return fullPath; - } + protected final HashMap headers = new HashMap<>(); + protected final HashMap cookies = new HashMap<>(); + protected final HashMap parameters = new HashMap<>(); + + protected final RequestType type; + protected final String[] path; + protected final String fullPath; + + private RequestData data; + + public ReceivedRequest(RequestType type, String[] path) { + this.type = type; + this.path = path; + this.fullPath = SimpleConversion.toPath(path); + } + + ReceivedRequest(RequestType type, String fullPath) { + this.type = type; + this.path = SimpleConversion.fromPath(fullPath); + this.fullPath = fullPath; + } + + /* + * Parse parameters + */ + + public final ReceivedRequest parseParameters(String... parameters) { + for (int index = 0; index < parameters.length; index++) { + parseParameter(parameters[index].trim()); + } + return this; + } + + public final ReceivedRequest parseParameter(String parameter) { + if (!parameter.contains("=")) { + return this; + } + String[] array = parameter.split("=", 2); + parameters.put(array[0], ValueIdentifier.identify(array[1])); + return this; + } + + /* + * Parameters + */ + + public final HashMap getParams() { + return parameters; + } + + public final Object getParam(String key) { + return parameters.get(key); + } + + public final boolean hasParam(String key) { + return parameters.containsKey(key); + } + + /* + * Parse cookies + */ + + public final ReceivedRequest parseCookies(String cookies) { + if (!cookies.contains(";")) { + return parseCookie(cookies.trim()); + } + String[] array = cookies.split(";"); + for (int index = 0; index < array.length; index++) { + parseCookie(array[index].trim()); + } + return this; + } + + public final ReceivedRequest parseCookie(String cookie) { + if (!cookie.contains("=")) { + return this; + } + String[] array = cookie.split("="); + cookies.put(array[0], ValueIdentifier.identify(array[1])); + return this; + } + + /* + * Cookies + */ + + public final HashMap getCookies() { + return cookies; + } + + public final Object getCookie(String key) { + return cookies.get(key); + } + + public final boolean hasCookie(String key) { + return cookies.containsKey(key); + } + + /* + * Parse headers + */ + + public final ReceivedRequest parseHeaders(Iterable headers) { + return parseHeaders(headers.iterator()); + } + + public final ReceivedRequest parseHeaders(Iterator headers) { + while (headers.hasNext()) { + parseHeader(headers.next()); + } + return this; + } + + public final ReceivedRequest parseHeaders(String... headers) { + if (headers == null || headers.length == 0) { + return this; + } + for (String header : headers) { + parseHeader(header); + } + return this; + } + + public final ReceivedRequest parseHeader(String header) { + if (!header.contains(":")) { + return this; + } + String[] parts = header.split(":", 2); + if ((parts[0] = parts[0].toLowerCase()).equalsIgnoreCase("Cookie")) { + return parseCookies(parts[1]); + } + headers.put(parts[0].toLowerCase(), ValueIdentifier.identify(parts[1].trim())); + return this; + } + + /* + * Headers + */ + + public final HashMap getHeaders() { + return headers; + } + + public final Object getHeader(String key) { + return headers.get(key.toLowerCase()); + } + + public final boolean hasHeader(String key) { + return headers.containsKey(key.toLowerCase()); + } + + /* + * Setter + */ + + public final ReceivedRequest setData(RequestData data) { + this.data = data; + return this; + } + + /* + * Getter + */ + + public final RequestData getData() { + return data; + } + + public final RequestType getType() { + return type; + } + + public final String[] getPath() { + return path; + } + + public final String getPathAsString() { + return fullPath; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RedirectRequestHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RedirectRequestHandler.java index bca519e..12b494f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RedirectRequestHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RedirectRequestHandler.java @@ -8,106 +8,106 @@ public class RedirectRequestHandler implements RequestHandler, PathHandler { - private final HashMap paths = new HashMap<>(); - private PathHandler main; - - @Override - public boolean handleRequest(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { - redirectPath(sender, writer, data); - return true; - } - - @Override - public void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { - if (data.getPath().length == 1) { - if (main == null) { - new NamedAnswer(StandardNamedType.PLAIN).setResponse("Not Found").code(ResponseCode.NOT_FOUND).write(writer); - return; - } - main.handlePath(sender, writer, data); - return; - } - redirectPath(sender, writer, new PathedReceivedRequest(data)); - } - - /* - * Manage paths - */ - - public RedirectRequestHandler setDefault(PathHandler handler) { - this.main = handler; - return this; - } - - public RedirectRequestHandler set(String path, PathHandler handler) { - Objects.requireNonNull(path, "Path cannot be null!"); - if (handler == null) { - paths.remove(path); - return this; - } - paths.put(path, handler); - return this; - } - - public RedirectRequestHandler set(PathHandler handler, String... path) { - return set(path(path), handler); - } - - public RedirectRequestHandler delete(String... path) { - return set(path(path), null); - } - - public PathHandler getDefault() { - return main; - } - - public PathHandler get(String... path) { - return paths.get(path(path)); - } - - protected String path(String... path) { - return Objects.requireNonNull(path, "Path cannot be null!").length == 1 ? path[0] : SimpleConversion.toPath(path); - } - - /* - * Redirect to correct path - */ - - protected void redirectPath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { - PathHandler handler = paths.get(data.getPathAsString()); - if (handler == null) { - if (main == null) { - new NamedAnswer(StandardNamedType.PLAIN).setResponse("Not Found").code(ResponseCode.NOT_FOUND).write(writer); - return; - } - main.handlePath(sender, writer, data); - return; - } - handler.handlePath(sender, writer, data); - } - - /* - * Path conversion class - */ - - public static class PathedReceivedRequest extends ReceivedRequest { - - public PathedReceivedRequest(ReceivedRequest request) { - this(Arrays.subArray(size -> new String[size], request.getPath(), 1), request); - } - - public PathedReceivedRequest(String path, ReceivedRequest request) { - super(request.getType(), path); - getHeaders().putAll(request.getHeaders()); - setData(request.getData()); - } - - public PathedReceivedRequest(String path[], ReceivedRequest request) { - super(request.getType(), path); - getHeaders().putAll(request.getHeaders()); - setData(request.getData()); - } - - } + private final HashMap paths = new HashMap<>(); + private PathHandler main; + + @Override + public boolean handleRequest(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { + redirectPath(sender, writer, data); + return true; + } + + @Override + public void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { + if (data.getPath().length == 1) { + if (main == null) { + new NamedAnswer(StandardNamedType.PLAIN).setResponse("Not Found").code(ResponseCode.NOT_FOUND).write(writer); + return; + } + main.handlePath(sender, writer, data); + return; + } + redirectPath(sender, writer, new PathedReceivedRequest(data)); + } + + /* + * Manage paths + */ + + public RedirectRequestHandler setDefault(PathHandler handler) { + this.main = handler; + return this; + } + + public RedirectRequestHandler set(String path, PathHandler handler) { + Objects.requireNonNull(path, "Path cannot be null!"); + if (handler == null) { + paths.remove(path); + return this; + } + paths.put(path, handler); + return this; + } + + public RedirectRequestHandler set(PathHandler handler, String... path) { + return set(path(path), handler); + } + + public RedirectRequestHandler delete(String... path) { + return set(path(path), null); + } + + public PathHandler getDefault() { + return main; + } + + public PathHandler get(String... path) { + return paths.get(path(path)); + } + + protected String path(String... path) { + return Objects.requireNonNull(path, "Path cannot be null!").length == 1 ? path[0] : SimpleConversion.toPath(path); + } + + /* + * Redirect to correct path + */ + + protected void redirectPath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { + PathHandler handler = paths.get(data.getPathAsString()); + if (handler == null) { + if (main == null) { + new NamedAnswer(StandardNamedType.PLAIN).setResponse("Not Found").code(ResponseCode.NOT_FOUND).write(writer); + return; + } + main.handlePath(sender, writer, data); + return; + } + handler.handlePath(sender, writer, data); + } + + /* + * Path conversion class + */ + + public static class PathedReceivedRequest extends ReceivedRequest { + + public PathedReceivedRequest(ReceivedRequest request) { + this(Arrays.subArray(size -> new String[size], request.getPath(), 1), request); + } + + public PathedReceivedRequest(String path, ReceivedRequest request) { + super(request.getType(), path); + getHeaders().putAll(request.getHeaders()); + setData(request.getData()); + } + + public PathedReceivedRequest(String path[], ReceivedRequest request) { + super(request.getType(), path); + getHeaders().putAll(request.getHeaders()); + setData(request.getData()); + } + + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Refreshable.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Refreshable.java index 329ba81..1c4c382 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Refreshable.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Refreshable.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface Refreshable { - public E refresh(); + public E refresh(); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Request.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Request.java index 07eadd3..4e9f89c 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Request.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Request.java @@ -39,26 +39,29 @@ public Request modifyUrl(boolean modifyUrl) { } public Request header(String key, String value) { - if (value != null) + if (value != null) { headers.put(key, value); - else + } else { headers.remove(key); + } return this; } public Request parameter(String key, String value) { - if (value != null) + if (value != null) { parameters.addProperty(key, value); - else + } else { parameters.remove(key); + } return this; } public Request parameter(String key, JsonElement element) { - if (element != null) + if (element != null) { parameters.add(key, element); - else + } else { parameters.remove(key); + } return this; } @@ -163,8 +166,9 @@ public Response execute(URL url, ContentType content) throws IOException { byte[] response = new byte[0]; - if (stream != null) + if (stream != null) { response = Streams.toByteArray(stream); + } return new Response(connection.getResponseCode(), response, connection.getHeaderFields()); diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestContent.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestContent.java index bd318f2..f1a7a21 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestContent.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestContent.java @@ -2,30 +2,30 @@ public enum RequestContent { - UNNEEDED, - NEEDED; + UNNEEDED, + NEEDED; - private boolean message = false; + private boolean message = false; - public boolean message() { - return message; - } + public boolean message() { + return message; + } - public RequestContent message(boolean message) { - this.message = message; - return this; - } + public RequestContent message(boolean message) { + this.message = message; + return this; + } - public boolean ignore() { - return this == UNNEEDED; - } + public boolean ignore() { + return this == UNNEEDED; + } - public boolean accepted() { - return this == NEEDED && !message(); - } + public boolean accepted() { + return this == NEEDED && !message(); + } - public boolean denied() { - return this == NEEDED && message(); - } + public boolean denied() { + return this == NEEDED && message(); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestData.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestData.java index 9b9a485..47681ea 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestData.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestData.java @@ -4,6 +4,6 @@ public abstract class RequestData { public abstract Class getType(); - public abstract T getValue(); + public abstract T getValue(); } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestExecution.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestExecution.java index 100957a..2fddf3a 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestExecution.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestExecution.java @@ -2,41 +2,41 @@ public enum RequestExecution { - CLOSE(true), - THROW(true), - OPEN(false); + CLOSE(true), + THROW(true), + OPEN(false); - private final boolean close; + private final boolean close; - private RequestExecution(boolean close) { - this.close = close; - } + private RequestExecution(boolean close) { + this.close = close; + } - private Throwable throwable; + private Throwable throwable; - private RequestExecution setThrowable(Throwable throwable) { - this.throwable = throwable; - return this; - } + private RequestExecution setThrowable(Throwable throwable) { + this.throwable = throwable; + return this; + } - public Throwable getThrowable() { - return throwable; - } + public Throwable getThrowable() { + return throwable; + } - public boolean hasThrowable() { - return throwable != null; - } + public boolean hasThrowable() { + return throwable != null; + } - public boolean close() { - return close; - } + public boolean close() { + return close; + } - public static RequestExecution of(boolean close) { - return close ? CLOSE : OPEN; - } + public static RequestExecution of(boolean close) { + return close ? CLOSE : OPEN; + } - public static RequestExecution error(Throwable throwable) { - return RequestExecution.THROW.setThrowable(throwable); - } + public static RequestExecution error(Throwable throwable) { + return RequestExecution.THROW.setThrowable(throwable); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestGate.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestGate.java index f2d3579..a6a72a7 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestGate.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestGate.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface RequestGate { - public RequestState acceptRequest(HttpWriter writer, ReceivedRequest request) throws Exception; + public RequestState acceptRequest(HttpWriter writer, ReceivedRequest request) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestHandler.java index 2248592..ac29d39 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestHandler.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface RequestHandler { - public boolean handleRequest(HttpSender sender, HttpWriter writer, ReceivedRequest request) throws Exception; + public boolean handleRequest(HttpSender sender, HttpWriter writer, ReceivedRequest request) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestSerializer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestSerializer.java index 5b45df0..2d6de6f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestSerializer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestSerializer.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface RequestSerializer { - public RequestData serialize(String data) throws Exception; + public RequestData serialize(String data) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestState.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestState.java index 0e2c66b..970ab45 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestState.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestState.java @@ -2,26 +2,26 @@ public enum RequestState { - ACCEPTED, - DENIED; + ACCEPTED, + DENIED; - private boolean message = false; + private boolean message = false; - public boolean message() { - return message; - } + public boolean message() { + return message; + } - public RequestState message(boolean message) { - this.message = message; - return this; - } + public RequestState message(boolean message) { + this.message = message; + return this; + } - public boolean accepted() { - return this == ACCEPTED; - } + public boolean accepted() { + return this == ACCEPTED; + } - public boolean denied() { - return this == DENIED; - } + public boolean denied() { + return this == DENIED; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestType.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestType.java index 15bf2a2..731995c 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestType.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestType.java @@ -2,37 +2,39 @@ public enum RequestType { - GET, - HEAD, - PUT(true), - POST(true), - DELETE(true), - OPTIONS(true), - PATCH(true), - CONNECT, - TRACE, - NONE; - - private final boolean output; - - private RequestType() { - output = false; - } - - private RequestType(boolean state) { - output = state; - } - - public boolean hasOutput() { - return output; - } - - public static RequestType fromString(String value) { - value = value.toUpperCase(); - for (RequestType type : values()) - if (type.name().equals(value)) - return type; - return NONE; - } + GET, + HEAD, + PUT(true), + POST(true), + DELETE(true), + OPTIONS(true), + PATCH(true), + CONNECT, + TRACE, + NONE; + + private final boolean output; + + private RequestType() { + output = false; + } + + private RequestType(boolean state) { + output = state; + } + + public boolean hasOutput() { + return output; + } + + public static RequestType fromString(String value) { + value = value.toUpperCase(); + for (RequestType type : values()) { + if (type.name().equals(value)) { + return type; + } + } + return NONE; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestValidator.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestValidator.java index f02be7f..ed9c2fa 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestValidator.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/RequestValidator.java @@ -3,8 +3,9 @@ @FunctionalInterface public interface RequestValidator { - public static final RequestValidator DEFAULT_VALIDATOR = (writer, request) -> RequestContent.NEEDED.message(!request.hasHeader("Content-Length")); + public static final RequestValidator DEFAULT_VALIDATOR = (writer, request) -> RequestContent.NEEDED + .message(!request.hasHeader("Content-Length")); - public RequestContent parseContent(HttpWriter writer, ReceivedRequest request) throws Exception; + public RequestContent parseContent(HttpWriter writer, ReceivedRequest request) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Response.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Response.java index a2c2c20..bbd157b 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Response.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/Response.java @@ -13,68 +13,69 @@ public class Response { - private final JsonObject headers; - private final int responseCode; - private final byte[] response; - - public Response(int responseCode, byte[] response, Map> headerMap) { - this.responseCode = responseCode; - this.response = response; - this.headers = headerMap.entrySet().stream().collect(JsonTools.toJsonObject()); - } - - /* - * Header management - */ - - public boolean has(String header) { - return headers.has(header.toLowerCase()); - } - - public boolean hasMultiple(String header) { - if (!has(header)) - return false; - return get(header).isJsonArray(); - } - - public JsonElement get(String header) { - return headers.get(header); - } - - public JsonArray getMultiple(String header) { - return headers.get(header).getAsJsonArray(); - } - - public String getAsString(String header) { - return get(header).getAsString(); - } - - /* - * Getters - */ - - public int getCode() { - return responseCode; - } - - public byte[] getResponseBytes() { - return response; - } - - public String getResponse() { - try { - return Streams.toString(new ByteArrayInputStream(response)); - } catch (IOException e) { - return new String(response); - } - } - - public JsonObject getResponseAsJson() { - return JsonTools.readJson(getResponse()); - } - - public JsonObject getResponseHeaders() { - return headers; - } + private final JsonObject headers; + private final int responseCode; + private final byte[] response; + + public Response(int responseCode, byte[] response, Map> headerMap) { + this.responseCode = responseCode; + this.response = response; + this.headers = headerMap.entrySet().stream().collect(JsonTools.toJsonObject()); + } + + /* + * Header management + */ + + public boolean has(String header) { + return headers.has(header.toLowerCase()); + } + + public boolean hasMultiple(String header) { + if (!has(header)) { + return false; + } + return get(header).isJsonArray(); + } + + public JsonElement get(String header) { + return headers.get(header); + } + + public JsonArray getMultiple(String header) { + return headers.get(header).getAsJsonArray(); + } + + public String getAsString(String header) { + return get(header).getAsString(); + } + + /* + * Getters + */ + + public int getCode() { + return responseCode; + } + + public byte[] getResponseBytes() { + return response; + } + + public String getResponse() { + try { + return Streams.toString(new ByteArrayInputStream(response)); + } catch (IOException e) { + return new String(response); + } + } + + public JsonObject getResponseAsJson() { + return JsonTools.readJson(getResponse()); + } + + public JsonObject getResponseHeaders() { + return headers; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ResponseCode.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ResponseCode.java index 3946663..0ac8576 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ResponseCode.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/ResponseCode.java @@ -7,121 +7,125 @@ public final class ResponseCode { - /** - * - * Informations - * - */ - - public static final int CONTINUE = 100; - public static final int SWITCHING_PROTOCOLS = 101; - public static final int PROCESSING = 102; - - /** - * - * Succeeded Operations - * - */ - - public static final int OK = 200; - public static final int CREATED = 201; - public static final int ACCEPTED = 202; - public static final int NON_AUTHORITATIVE_INFORMATION = 203; - public static final int NO_CONTENT = 204; - public static final int RESET_CONTENT = 205; - public static final int PARTIAL_CONTENT = 206; - public static final int MULTI_STATUS = 207; - public static final int ALREADY_REPORTED = 208; - public static final int IM_USED = 226; - - /** - * - * Redirects - * - */ - - public static final int MULTIPLE_CHOICES = 300; - public static final int MOVED_PERMANENTLY = 301; - public static final int FOUND_MOVE_TEMPORARILLY = 302; - public static final int SEE_OTHER = 303; - public static final int NOT_MODIFIED = 304; - public static final int USE_PROXY = 305; - public static final int TEMPORARY_REDIRECT = 307; - public static final int PERMANENT_REDIRECT = 308; - - /** - * - * Client Errors - * - */ - - public static final int BAD_REQUEST = 400; - public static final int UNAUTHORIZED = 401; - public static final int PAYMENT_REQUIRED = 402; - public static final int FORBIDDEN = 403; - public static final int NOT_FOUND = 404; - public static final int METHOD_NOT_ALLOWED = 405; - public static final int NOT_ACCEPTABLE = 406; - public static final int PROXY_AUTHENTICATION_REQUIRED = 407; - public static final int REQUEST_TIMOEOUT = 408; - public static final int CONFLICT = 409; - public static final int GONE = 410; - public static final int LENGTH_REQUIRED = 411; - public static final int PRECONDITION_FAILED = 412; - public static final int REQUEST_ENTITY_TOO_LARGE = 413; - public static final int URI_TOO_LONG = 414; - public static final int UNSUPPORTED_MEDIA_TYPE = 415; - public static final int REQUESTED_RANGE_NOT_SATISFIABLE = 416; - public static final int EXPECTATION_FAILED = 417; - public static final int POLICY_NOT_FULFILLED = 420; - public static final int MISDIRECTED_REQUEST = 421; - public static final int UNPROCESSABLE_ENTITY = 422; - public static final int LOCKED = 423; - public static final int FAILED_DEPENDENCY = 424; - public static final int UPGRADE_REQUIRED = 426; - public static final int PRECONDITION_REQUIRED = 428; - public static final int TOO_MANY_REQUESTS = 429; - public static final int REQUEST_HEADER_FIELDS_TOO_LARGE = 431; - public static final int UNAVAILABLE_FOR_LEGAL_REASONS = 451; - - /** - * - * Server Errors - * - */ - - public static final int INTERNAL_SERVER_ERROR = 500; - public static final int NOT_IMPLEMENTED = 501; - public static final int BAD_GATEWAY = 502; - public static final int SERVICE_UNAVAILABLE = 503; - public static final int GATEWAY_TIMEOUT = 504; - public static final int HTTP_VERSION_NOT_SUPPORTED = 505; - public static final int VARIANT_ALSO_NEGOTIATES = 506; - public static final int INSUFFICIENT_STORAGE = 507; - public static final int LOOP_DETECTED = 508; - public static final int BANDWITH_LIMIT_EXCEEDED = 509; - public static final int NOT_EXTENDED = 510; - public static final int NETWORK_AUTHENTICATION_REQUIRED = 511; - - /* - * - */ - - public static final String getName(int code) { - Field[] fields = ResponseCode.class.getFields(); - for (Field field : fields) - if (((int) ReflectionTools.getValue(field)) == code) - return format(field.getName()); - return ""; - } - - private static final String format(String name) { - if (!name.contains("_")) - return Strings.firstLetterToUpperCase(name); - String[] parts = name.split("_"); - for (int index = 0; index < parts.length; index++) - parts[index] = Strings.firstLetterToUpperCase(parts[index]); - return String.join(" ", parts); - } + /** + * + * Informations + * + */ + + public static final int CONTINUE = 100; + public static final int SWITCHING_PROTOCOLS = 101; + public static final int PROCESSING = 102; + + /** + * + * Succeeded Operations + * + */ + + public static final int OK = 200; + public static final int CREATED = 201; + public static final int ACCEPTED = 202; + public static final int NON_AUTHORITATIVE_INFORMATION = 203; + public static final int NO_CONTENT = 204; + public static final int RESET_CONTENT = 205; + public static final int PARTIAL_CONTENT = 206; + public static final int MULTI_STATUS = 207; + public static final int ALREADY_REPORTED = 208; + public static final int IM_USED = 226; + + /** + * + * Redirects + * + */ + + public static final int MULTIPLE_CHOICES = 300; + public static final int MOVED_PERMANENTLY = 301; + public static final int FOUND_MOVE_TEMPORARILLY = 302; + public static final int SEE_OTHER = 303; + public static final int NOT_MODIFIED = 304; + public static final int USE_PROXY = 305; + public static final int TEMPORARY_REDIRECT = 307; + public static final int PERMANENT_REDIRECT = 308; + + /** + * + * Client Errors + * + */ + + public static final int BAD_REQUEST = 400; + public static final int UNAUTHORIZED = 401; + public static final int PAYMENT_REQUIRED = 402; + public static final int FORBIDDEN = 403; + public static final int NOT_FOUND = 404; + public static final int METHOD_NOT_ALLOWED = 405; + public static final int NOT_ACCEPTABLE = 406; + public static final int PROXY_AUTHENTICATION_REQUIRED = 407; + public static final int REQUEST_TIMOEOUT = 408; + public static final int CONFLICT = 409; + public static final int GONE = 410; + public static final int LENGTH_REQUIRED = 411; + public static final int PRECONDITION_FAILED = 412; + public static final int REQUEST_ENTITY_TOO_LARGE = 413; + public static final int URI_TOO_LONG = 414; + public static final int UNSUPPORTED_MEDIA_TYPE = 415; + public static final int REQUESTED_RANGE_NOT_SATISFIABLE = 416; + public static final int EXPECTATION_FAILED = 417; + public static final int POLICY_NOT_FULFILLED = 420; + public static final int MISDIRECTED_REQUEST = 421; + public static final int UNPROCESSABLE_ENTITY = 422; + public static final int LOCKED = 423; + public static final int FAILED_DEPENDENCY = 424; + public static final int UPGRADE_REQUIRED = 426; + public static final int PRECONDITION_REQUIRED = 428; + public static final int TOO_MANY_REQUESTS = 429; + public static final int REQUEST_HEADER_FIELDS_TOO_LARGE = 431; + public static final int UNAVAILABLE_FOR_LEGAL_REASONS = 451; + + /** + * + * Server Errors + * + */ + + public static final int INTERNAL_SERVER_ERROR = 500; + public static final int NOT_IMPLEMENTED = 501; + public static final int BAD_GATEWAY = 502; + public static final int SERVICE_UNAVAILABLE = 503; + public static final int GATEWAY_TIMEOUT = 504; + public static final int HTTP_VERSION_NOT_SUPPORTED = 505; + public static final int VARIANT_ALSO_NEGOTIATES = 506; + public static final int INSUFFICIENT_STORAGE = 507; + public static final int LOOP_DETECTED = 508; + public static final int BANDWITH_LIMIT_EXCEEDED = 509; + public static final int NOT_EXTENDED = 510; + public static final int NETWORK_AUTHENTICATION_REQUIRED = 511; + + /* + * + */ + + public static final String getName(int code) { + Field[] fields = ResponseCode.class.getFields(); + for (Field field : fields) { + if (((int) ReflectionTools.getValue(field)) == code) { + return format(field.getName()); + } + } + return ""; + } + + private static final String format(String name) { + if (!name.contains("_")) { + return Strings.firstLetterToUpperCase(name); + } + String[] parts = name.split("_"); + for (int index = 0; index < parts.length; index++) { + parts[index] = Strings.firstLetterToUpperCase(parts[index]); + } + return String.join(" ", parts); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SimpleFileAnswer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SimpleFileAnswer.java index 04092f2..97208a0 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SimpleFileAnswer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SimpleFileAnswer.java @@ -8,17 +8,17 @@ public class SimpleFileAnswer extends FileAnswer { - public SimpleFileAnswer(File file, NamedType type) { - super(file, type); - } + public SimpleFileAnswer(File file, NamedType type) { + super(file, type); + } - @Override - public String readFile() { - try { - return Streams.toString(new FileInputStream(file)); - } catch (IOException e) { - return ""; - } - } + @Override + public String readFile() { + try { + return Streams.toString(new FileInputStream(file)); + } catch (IOException e) { + return ""; + } + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SpecialSerializers.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SpecialSerializers.java index f0c6b58..8f8e3a5 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SpecialSerializers.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/SpecialSerializers.java @@ -8,106 +8,108 @@ public class SpecialSerializers { - /* - * Default serializers - */ + /* + * Default serializers + */ - /* - * Json serializers - */ + /* + * Json serializers + */ - public static final JsonContentSerializer PLAIN = new JsonContentSerializer() { + public static final JsonContentSerializer PLAIN = new JsonContentSerializer() { - private final char[] CHARS = new char[] { - ':', - ' ', - '\t', - '\n', - '-' - }; - private final String NULL = "null"; - private final String NEXT = "==>"; + private final char[] CHARS = new char[] { + ':', + ' ', + '\t', + '\n', + '-' + }; + private final String NULL = "null"; + private final String NEXT = "==>"; - public String process(JsonObject parameters) { - StringBuilder builder = new StringBuilder(); + public String process(JsonObject parameters) { + StringBuilder builder = new StringBuilder(); - append(builder, parameters, 0); + append(builder, parameters, 0); - return builder.toString(); - } + return builder.toString(); + } - private boolean append(StringBuilder builder, JsonObject object, int depth) { + private boolean append(StringBuilder builder, JsonObject object, int depth) { - for (Entry entry : object.entrySet()) { + for (Entry entry : object.entrySet()) { - JsonElement element = entry.getValue(); + JsonElement element = entry.getValue(); - for (int current = 0; current < depth; current++) - builder.append(CHARS[2]); + for (int current = 0; current < depth; current++) { + builder.append(CHARS[2]); + } - builder.append(entry.getKey()); - builder.append(CHARS[0]); - builder.append(CHARS[1]); + builder.append(entry.getKey()); + builder.append(CHARS[0]); + builder.append(CHARS[1]); - if (element == null || element.isJsonNull()) { - builder.append(NULL); - continue; - } + if (element == null || element.isJsonNull()) { + builder.append(NULL); + continue; + } - if (element.isJsonPrimitive()) { - builder.append(element.getAsString()); - continue; - } + if (element.isJsonPrimitive()) { + builder.append(element.getAsString()); + continue; + } - builder.append(CHARS[3]); + builder.append(CHARS[3]); - if (element.isJsonArray()) { - append(builder, element.getAsJsonArray(), depth + 1); - continue; - } + if (element.isJsonArray()) { + append(builder, element.getAsJsonArray(), depth + 1); + continue; + } - append(builder, element.getAsJsonObject(), depth + 1); + append(builder, element.getAsJsonObject(), depth + 1); - } + } - return true; - } + return true; + } - private boolean append(StringBuilder builder, JsonArray array, int depth) { + private boolean append(StringBuilder builder, JsonArray array, int depth) { - for (JsonElement element : array) { + for (JsonElement element : array) { - for (int current = 0; current < depth; current++) - builder.append(CHARS[2]); + for (int current = 0; current < depth; current++) { + builder.append(CHARS[2]); + } - builder.append(CHARS[4]); - builder.append(CHARS[0]); + builder.append(CHARS[4]); + builder.append(CHARS[0]); - if (element == null || element.isJsonNull()) { - builder.append(NULL); - continue; - } + if (element == null || element.isJsonNull()) { + builder.append(NULL); + continue; + } - if (element.isJsonPrimitive()) { - builder.append(element.getAsString()); - continue; - } + if (element.isJsonPrimitive()) { + builder.append(element.getAsString()); + continue; + } - builder.append(NEXT); - builder.append(CHARS[3]); + builder.append(NEXT); + builder.append(CHARS[3]); - if (element.isJsonArray()) { - append(builder, element.getAsJsonArray(), depth + 1); - continue; - } + if (element.isJsonArray()) { + append(builder, element.getAsJsonArray(), depth + 1); + continue; + } - append(builder, element.getAsJsonObject(), depth + 1); + append(builder, element.getAsJsonObject(), depth + 1); - } + } - return true; - } + return true; + } - }; + }; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardContentType.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardContentType.java index 0c15744..5dd0c48 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardContentType.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardContentType.java @@ -2,64 +2,68 @@ public enum StandardContentType implements ContentType { - URL_ENCODED("application/x-www-form-urlencoded", DefaultSerializers.URL_ENCODED, DefaultDeserializers.URL_ENCODED, ContentToUrlModifier.URL_ENCODED), - PLAIN_SPECIAL("text/plain", SpecialSerializers.PLAIN, null), - JSON("application/json", DefaultSerializers.JSON, DefaultDeserializers.JSON); + URL_ENCODED("application/x-www-form-urlencoded", DefaultSerializers.URL_ENCODED, DefaultDeserializers.URL_ENCODED, + ContentToUrlModifier.URL_ENCODED), + PLAIN_SPECIAL("text/plain", SpecialSerializers.PLAIN, null), + JSON("application/json", DefaultSerializers.JSON, DefaultDeserializers.JSON); - private final String type; + private final String type; - private final ContentSerializer serializer; - private final ContentDeserializer deserializer; + private final ContentSerializer serializer; + private final ContentDeserializer deserializer; - private final ContentToUrlModifier urlModifier; + private final ContentToUrlModifier urlModifier; - private StandardContentType(String type, ContentSerializer serializer, ContentDeserializer deserializer, ContentToUrlModifier urlModifier) { - this.type = type; - this.serializer = serializer; - this.deserializer = deserializer; - this.urlModifier = urlModifier; - } + private StandardContentType(String type, ContentSerializer serializer, ContentDeserializer deserializer, + ContentToUrlModifier urlModifier) { + this.type = type; + this.serializer = serializer; + this.deserializer = deserializer; + this.urlModifier = urlModifier; + } - private StandardContentType(String type, ContentSerializer serializer, ContentDeserializer deserializer) { - this.type = type; - this.serializer = serializer; - this.deserializer = deserializer; - this.urlModifier = null; - } + private StandardContentType(String type, ContentSerializer serializer, ContentDeserializer deserializer) { + this.type = type; + this.serializer = serializer; + this.deserializer = deserializer; + this.urlModifier = null; + } - /* - * Getter - */ + /* + * Getter + */ - @Override - public String type() { - return type; - } + @Override + public String type() { + return type; + } - @Override - public ContentSerializer serializer() { - return serializer; - } + @Override + public ContentSerializer serializer() { + return serializer; + } - @Override - public ContentDeserializer deserializer() { - return deserializer; - } + @Override + public ContentDeserializer deserializer() { + return deserializer; + } - @Override - public ContentToUrlModifier urlModifier() { - return urlModifier; - } + @Override + public ContentToUrlModifier urlModifier() { + return urlModifier; + } - /* - * static Getter - */ + /* + * static Getter + */ - public static StandardContentType fromString(String value) { - for (StandardContentType type : values()) - if (type.type().equals(value)) - return type; - return null; - } + public static StandardContentType fromString(String value) { + for (StandardContentType type : values()) { + if (type.type().equals(value)) { + return type; + } + } + return null; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardNamedType.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardNamedType.java index 119f9d5..c117311 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardNamedType.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/StandardNamedType.java @@ -5,36 +5,38 @@ public enum StandardNamedType implements NamedType { - PLAIN("text/plain", "txt"), - JAVA_SCRIPT("text/javascript", "js"), - XML("text/xml", "xml"), - CSS("text/css", "css"), - HTML("text/html", "htm", "html", "shtml"); - - private final String type; - private final List extensions; - - private StandardNamedType(String type, String... extensions) { - this.type = type; - this.extensions = Arrays.asList(extensions); - } - - @Override - public String type() { - return type; - } - - @Override - public boolean has(String extension) { - return extensions.contains(extension.contains(".") ? extension.substring(1) : extension); - } - - public static StandardNamedType parse(String extension) { - StandardNamedType[] types = values(); - for (int index = 0; index < types.length; index++) - if (types[index].has(extension)) - return types[index]; - return null; - } + PLAIN("text/plain", "txt"), + JAVA_SCRIPT("text/javascript", "js"), + XML("text/xml", "xml"), + CSS("text/css", "css"), + HTML("text/html", "htm", "html", "shtml"); + + private final String type; + private final List extensions; + + private StandardNamedType(String type, String... extensions) { + this.type = type; + this.extensions = Arrays.asList(extensions); + } + + @Override + public String type() { + return type; + } + + @Override + public boolean has(String extension) { + return extensions.contains(extension.contains(".") ? extension.substring(1) : extension); + } + + public static StandardNamedType parse(String extension) { + StandardNamedType[] types = values(); + for (int index = 0; index < types.length; index++) { + if (types[index].has(extension)) { + return types[index]; + } + } + return null; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/IWebPathHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/IWebPathHandler.java index 091c7c8..d6590d0 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/IWebPathHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/IWebPathHandler.java @@ -9,6 +9,6 @@ @FunctionalInterface public interface IWebPathHandler { - public void handlePath(File directory, HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception; + public void handlePath(File directory, HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception; } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathAdapter.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathAdapter.java index cc9704b..9f80a3e 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathAdapter.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathAdapter.java @@ -10,17 +10,17 @@ public class WebPathAdapter implements PathHandler { - private final Container directory; - private final IWebPathHandler handler; + private final Container directory; + private final IWebPathHandler handler; - public WebPathAdapter(Container directory, IWebPathHandler handler) { - this.directory = directory; - this.handler = handler; - } + public WebPathAdapter(Container directory, IWebPathHandler handler) { + this.directory = directory; + this.handler = handler; + } - @Override - public final void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { - handler.handlePath(directory.get(), sender, writer, data); - } + @Override + public final void handlePath(HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { + handler.handlePath(directory.get(), sender, writer, data); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathHandler.java index daa95e0..efb8176 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebPathHandler.java @@ -12,32 +12,32 @@ public class WebPathHandler implements IWebPathHandler { - @Override - public void handlePath(File directory, HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { - File file = new File(directory, data.getPathAsString()); - if (!file.exists()) { - new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); - return; - } - - if (!file.isFile()) { - file = new File(file, "index.html"); - if (!file.exists()) { - new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); - return; - } - new SimpleFileAnswer(file, StandardNamedType.HTML).code(ResponseCode.OK).write(writer); - return; - } - - StandardNamedType type = StandardNamedType.parse(data.getPath()[data.getPath().length - 1]); - if (type == null) { - new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); - return; - } - - new SimpleFileAnswer(file, type).code(ResponseCode.OK).write(writer); - - } + @Override + public void handlePath(File directory, HttpSender sender, HttpWriter writer, ReceivedRequest data) throws Exception { + File file = new File(directory, data.getPathAsString()); + if (!file.exists()) { + new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); + return; + } + + if (!file.isFile()) { + file = new File(file, "index.html"); + if (!file.exists()) { + new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); + return; + } + new SimpleFileAnswer(file, StandardNamedType.HTML).code(ResponseCode.OK).write(writer); + return; + } + + StandardNamedType type = StandardNamedType.parse(data.getPath()[data.getPath().length - 1]); + if (type == null) { + new NamedAnswer(StandardNamedType.PLAIN).code(ResponseCode.NOT_FOUND).write(writer); + return; + } + + new SimpleFileAnswer(file, type).code(ResponseCode.OK).write(writer); + + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebRedirectHandler.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebRedirectHandler.java index 2107918..c769a0f 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebRedirectHandler.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebRedirectHandler.java @@ -8,49 +8,49 @@ public class WebRedirectHandler extends RedirectRequestHandler implements WebHandler { - private final Container directory = Container.of(); - - public WebRedirectHandler(File file) { - directory.replace(file); - } - - public WebRedirectHandler setDirectory(File directory) { - this.directory.replace(directory); - return this; - } - - public Container getDirectory() { - return directory; - } - - public WebRedirectHandler set(IWebPathHandler pathHandler, String... path) { - set(new WebPathAdapter(directory, pathHandler), path); - return this; - } - - public WebRedirectHandler set(WebPathAdapter pathAdapter, String... path) { - set(pathAdapter, path); - return this; - } - - public WebRedirectHandler set(String path, IWebPathHandler pathHandler) { - set(path, new WebPathAdapter(directory, pathHandler)); - return this; - } - - public WebRedirectHandler set(String path, WebPathAdapter pathAdapter) { - set(path, (PathHandler) pathAdapter); - return this; - } - - public WebRedirectHandler setDefault(IWebPathHandler pathHandler) { - setDefault(new WebPathAdapter(directory, pathHandler)); - return this; - } - - public WebRedirectHandler setDefault(WebPathAdapter pathAdapter) { - setDefault((PathHandler) pathAdapter); - return this; - } + private final Container directory = Container.of(); + + public WebRedirectHandler(File file) { + directory.replace(file); + } + + public WebRedirectHandler setDirectory(File directory) { + this.directory.replace(directory); + return this; + } + + public Container getDirectory() { + return directory; + } + + public WebRedirectHandler set(IWebPathHandler pathHandler, String... path) { + set(new WebPathAdapter(directory, pathHandler), path); + return this; + } + + public WebRedirectHandler set(WebPathAdapter pathAdapter, String... path) { + set(pathAdapter, path); + return this; + } + + public WebRedirectHandler set(String path, IWebPathHandler pathHandler) { + set(path, new WebPathAdapter(directory, pathHandler)); + return this; + } + + public WebRedirectHandler set(String path, WebPathAdapter pathAdapter) { + set(path, (PathHandler) pathAdapter); + return this; + } + + public WebRedirectHandler setDefault(IWebPathHandler pathHandler) { + setDefault(new WebPathAdapter(directory, pathHandler)); + return this; + } + + public WebRedirectHandler setDefault(WebPathAdapter pathAdapter) { + setDefault((PathHandler) pathAdapter); + return this; + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebServer.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebServer.java index 140a07b..f651786 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebServer.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/net/http/web/WebServer.java @@ -15,87 +15,85 @@ public class WebServer extends HttpServer { - private WebHandler handler; - - public WebServer() { - super(); - } - - public WebServer(ThreadFactory factory) { - super(factory); - } - - public WebServer(ExecutorService service) { - super(service); - } - - public WebServer(ThreadFactory factory, ExecutorService service) { - super(factory, service); - } - - public WebServer(int port) { - super(port); - } - - public WebServer(int port, ThreadFactory factory) { - super(port, factory); - } - - public WebServer(int port, ExecutorService service) { - super(port, service); - } - - public WebServer(int port, ThreadFactory factory, ExecutorService service) { - super(port, factory, service); - } - - public WebServer(int port, InetAddress address) { - super(port, address); - } - - public WebServer(int port, InetAddress address, ThreadFactory factory) { - super(port, address, factory); - } - - public WebServer(int port, InetAddress address, ExecutorService service) { - super(port, address, service); - } - - public WebServer(int port, InetAddress address, ThreadFactory factory, ExecutorService service) { - super(port, address, factory, service); - } - - /* - * Getter - */ - - public WebHandler getHandler() { - return handler; - } - - /* - * Setter - */ - - public void setHandler(WebHandler handler) { - this.handler = handler; - } - - /* - * Handle HttpRequest - */ - - @Override - protected RequestExecution handleHttpRequest(HttpSender sender, HttpWriter writer, ReceivedRequest request) throws Exception { - try { - return RequestExecution.of(handler.handleRequest(sender, writer, request)); - } catch (Exception e) { - new NamedAnswer(StandardNamedType.PLAIN) - .setResponse("Something went wrong handling your request!") - .code(ResponseCode.INTERNAL_SERVER_ERROR) - .write(writer); - throw e; - } - } + private WebHandler handler; + + public WebServer() { + super(); + } + + public WebServer(ThreadFactory factory) { + super(factory); + } + + public WebServer(ExecutorService service) { + super(service); + } + + public WebServer(ThreadFactory factory, ExecutorService service) { + super(factory, service); + } + + public WebServer(int port) { + super(port); + } + + public WebServer(int port, ThreadFactory factory) { + super(port, factory); + } + + public WebServer(int port, ExecutorService service) { + super(port, service); + } + + public WebServer(int port, ThreadFactory factory, ExecutorService service) { + super(port, factory, service); + } + + public WebServer(int port, InetAddress address) { + super(port, address); + } + + public WebServer(int port, InetAddress address, ThreadFactory factory) { + super(port, address, factory); + } + + public WebServer(int port, InetAddress address, ExecutorService service) { + super(port, address, service); + } + + public WebServer(int port, InetAddress address, ThreadFactory factory, ExecutorService service) { + super(port, address, factory, service); + } + + /* + * Getter + */ + + public WebHandler getHandler() { + return handler; + } + + /* + * Setter + */ + + public void setHandler(WebHandler handler) { + this.handler = handler; + } + + /* + * Handle HttpRequest + */ + + @Override + protected RequestExecution handleHttpRequest(HttpSender sender, HttpWriter writer, ReceivedRequest request) throws Exception { + try { + return RequestExecution.of(handler.handleRequest(sender, writer, request)); + } catch (Exception e) { + new NamedAnswer(StandardNamedType.PLAIN).setResponse("Something went wrong handling your request!") + .code(ResponseCode.INTERNAL_SERVER_ERROR).write(writer); + throw e; + } + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/SimpleConversion.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/SimpleConversion.java index fd04fd5..551a8df 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/SimpleConversion.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/SimpleConversion.java @@ -2,22 +2,22 @@ public class SimpleConversion { - public static String toPath(String[] path) { - return toPath(path, "/"); - } + public static String toPath(String[] path) { + return toPath(path, "/"); + } - public static String toPath(String[] path, String joiner) { - if (path == null || path.length == 0) { - return ""; - } - if (path[0].isEmpty()) { - return ""; - } - return String.join(joiner, path); - } + public static String toPath(String[] path, String joiner) { + if (path == null || path.length == 0) { + return ""; + } + if (path[0].isEmpty()) { + return ""; + } + return String.join(joiner, path); + } - public static String[] fromPath(String path) { - return path == null ? new String[0] : path.split("/"); - } + public static String[] fromPath(String path) { + return path == null ? new String[0] : path.split("/"); + } } diff --git a/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/UrlReflection.java b/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/UrlReflection.java index 0d9d87e..4d03f57 100644 --- a/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/UrlReflection.java +++ b/net/src/main/java/com/syntaxphoenix/syntaxapi/utils/net/UrlReflection.java @@ -8,13 +8,13 @@ public class UrlReflection { - public static final AbstractReflect URL_REFLECT = new Reflect(URL.class).searchField("query", "query").searchField("file", "file"); + public static final AbstractReflect URL_REFLECT = new Reflect(URL.class).searchField("query", "query").searchField("file", "file"); - public static void applyQuery(URL url, String query) { - Objects.requireNonNull(url); - Objects.requireNonNull(query); - URL_REFLECT.setFieldValue(url, "file", url.getPath() + query); - URL_REFLECT.setFieldValue(url, "query", query.startsWith("?") ? query.replaceFirst("\\?", "") : query); - } + public static void applyQuery(URL url, String query) { + Objects.requireNonNull(url); + Objects.requireNonNull(query); + URL_REFLECT.setFieldValue(url, "file", url.getPath() + query); + URL_REFLECT.setFieldValue(url, "query", query.startsWith("?") ? query.replaceFirst("\\?", "") : query); + } } diff --git a/net/src/test/java/net/test/RestHandler.java b/net/src/test/java/net/test/RestHandler.java index 1dc4d6f..a5321c2 100644 --- a/net/src/test/java/net/test/RestHandler.java +++ b/net/src/test/java/net/test/RestHandler.java @@ -12,7 +12,8 @@ public class RestHandler implements RequestHandler { @Override public boolean handleRequest(HttpSender sender, HttpWriter writer, ReceivedRequest request) throws Exception { - new JsonAnswer(StandardContentType.JSON).header("buildNumber", 0).respond("info", "Message received!").code(ResponseCode.OK).write(writer); + new JsonAnswer(StandardContentType.JSON).header("buildNumber", 0).respond("info", "Message received!").code(ResponseCode.OK) + .write(writer); return true; } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/Keys.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/Keys.java index 5780205..fd723b3 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/Keys.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/Keys.java @@ -2,120 +2,123 @@ public class Keys { - public static final Keys DEFAULT = new Keys(); - - public static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - public static final String NUMBERS = "0123456789"; - - public static final int DEFAULT_STRING_LENGTH = ALPHABET.length(); - public static final int DEFAULT_INT_LENGTH = ((Integer.MAX_VALUE + "").length() - 1); - public static final int DEFAULT_LONG_LENGTH = ((Long.MAX_VALUE + "").length() - 1); - - /* - * - */ - - private final RandomNumberGenerator RANDOM; - - /* - * - */ - - public Keys() { - this(System.currentTimeMillis()); - } - - public Keys(long seed) { - this(NumberGeneratorType.MURMUR.create(seed)); - } - - public Keys(RandomNumberGenerator generator) { - RANDOM = generator; - } - - /* - * - */ - - public final String makeKey() { - return makeKey(DEFAULT_STRING_LENGTH); - } - - public String makeKey(int length) { - char[] chars = new char[length]; - for (int current = 0; current < length; ++current) - chars[current] = ALPHABET.charAt(RANDOM.nextInt(DEFAULT_STRING_LENGTH)); - return String.valueOf(chars); - } - - /* - * - */ - - public Integer makeInt() { - return makeInt(DEFAULT_INT_LENGTH); - } - - public Integer makeInt(int length) { - char[] chars = new char[length]; - for (int current = 0; current < length; ++current) - chars[current] = NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length())); - return Integer.valueOf(String.valueOf(chars)); - } - - /* - * - */ - - public Long makeLong() { - return makeLong(DEFAULT_LONG_LENGTH); - } - - public Long makeLong(int length) { - char[] chars = new char[length]; - for (int current = 0; current < length; ++current) - chars[current] = NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length())); - return Long.valueOf(String.valueOf(chars)); - } - - // - // - // Static keys stuff - // - // To prevent old methods from breaking. - // - // - - public static final String generateKey() { - return DEFAULT.makeKey(); - } - - public static final String generateKey(int length) { - return DEFAULT.makeKey(length); - } - - // - // - // - - public static final Integer generateInt() { - return DEFAULT.makeInt(); - } - - public static final Integer generateInt(int length) { - return DEFAULT.makeInt(length); - } - - // - // - // - - public static final Long generateLong() { - return DEFAULT.makeLong(); - } - - public static final Long generateLong(int length) { - return DEFAULT.makeLong(length); - } + public static final Keys DEFAULT = new Keys(); + + public static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + public static final String NUMBERS = "0123456789"; + + public static final int DEFAULT_STRING_LENGTH = ALPHABET.length(); + public static final int DEFAULT_INT_LENGTH = ((Integer.MAX_VALUE + "").length() - 1); + public static final int DEFAULT_LONG_LENGTH = ((Long.MAX_VALUE + "").length() - 1); + + /* + * + */ + + private final RandomNumberGenerator RANDOM; + + /* + * + */ + + public Keys() { + this(System.currentTimeMillis()); + } + + public Keys(long seed) { + this(NumberGeneratorType.MURMUR.create(seed)); + } + + public Keys(RandomNumberGenerator generator) { + RANDOM = generator; + } + + /* + * + */ + + public final String makeKey() { + return makeKey(DEFAULT_STRING_LENGTH); + } + + public String makeKey(int length) { + char[] chars = new char[length]; + for (int current = 0; current < length; ++current) { + chars[current] = ALPHABET.charAt(RANDOM.nextInt(DEFAULT_STRING_LENGTH)); + } + return String.valueOf(chars); + } + + /* + * + */ + + public Integer makeInt() { + return makeInt(DEFAULT_INT_LENGTH); + } + + public Integer makeInt(int length) { + char[] chars = new char[length]; + for (int current = 0; current < length; ++current) { + chars[current] = NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length())); + } + return Integer.valueOf(String.valueOf(chars)); + } + + /* + * + */ + + public Long makeLong() { + return makeLong(DEFAULT_LONG_LENGTH); + } + + public Long makeLong(int length) { + char[] chars = new char[length]; + for (int current = 0; current < length; ++current) { + chars[current] = NUMBERS.charAt(RANDOM.nextInt(NUMBERS.length())); + } + return Long.valueOf(String.valueOf(chars)); + } + + // + // + // Static keys stuff + // + // To prevent old methods from breaking. + // + // + + public static final String generateKey() { + return DEFAULT.makeKey(); + } + + public static final String generateKey(int length) { + return DEFAULT.makeKey(length); + } + + // + // + // + + public static final Integer generateInt() { + return DEFAULT.makeInt(); + } + + public static final Integer generateInt(int length) { + return DEFAULT.makeInt(length); + } + + // + // + // + + public static final Long generateLong() { + return DEFAULT.makeLong(); + } + + public static final Long generateLong(int length) { + return DEFAULT.makeLong(length); + } } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/LinearCongruentialGenerator.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/LinearCongruentialGenerator.java index d3457ba..a55ca35 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/LinearCongruentialGenerator.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/LinearCongruentialGenerator.java @@ -2,225 +2,230 @@ public class LinearCongruentialGenerator extends RandomNumberGenerator { - private long seed; - private int state; - - private int multiplier = 87454568; - private int increment = 3214561; - private int modulu = 2 ^ 31; - - public LinearCongruentialGenerator() { - setSeed(System.currentTimeMillis()); - } - - public LinearCongruentialGenerator(long seed) { - setSeed(System.currentTimeMillis()); - } - - /* - * - */ - - public void setSeed(long seed) { - this.seed = seed; - this.state = Math.toIntExact(seed >> 32); - } - - public long getSeed() { - return seed; - } - - /* - * - */ - - @Override - public void setCompressedState(long state) { - this.state = Math.toIntExact(seed); - } - - @Override - public long getCompressedState() { - return state; - } - - /* - * - */ - - public int getMultipliert() { - return multiplier; - } - - public void setMultiplier(int multiplier) { - this.multiplier = multiplier; - checkVariables(); - } - - /* - * - */ - - public int getIncrement() { - return increment; - } - - public void setIncrement(int increment) { - this.increment = increment; - checkVariables(); - } - - /* - * - */ - - public int getModulu() { - return modulu; - } - - public void setModulu(int modulu) { - this.modulu = modulu; - checkVariables(); - } - - /* - * - * - * - */ - - @Override - public boolean nextBoolean() { - return next(1) == 0; - } - - /* - * - */ - - @Override - public short nextShort() { - return (short) next(16); - } - - @Override - public short nextShort(short bound) { - return nextShort((short) 0, bound); - } - - @Override - public short nextShort(short min, short max) { - if (max <= min) { - return min; - } - return (short) (min + Math.abs((int) (nextShort() % (max - min)))); - } - - /* - * - */ - - @Override - public int nextInt() { - return state = ((multiplier * state) + increment) % modulu; - } - - @Override - public int nextInt(int bound) { - return nextInt(0, bound); - } - - @Override - public int nextInt(int min, int max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextInt() % (max - min)); - } - - /* - * - */ - - @Override - public long nextLong() { - return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); - } - - @Override - public long nextLong(long bound) { - return nextLong(0L, bound); - } - - @Override - public long nextLong(long min, long max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextLong() % (max - min)); - } - - /* - * - */ - - @Override - public float nextFloat() { - return (float) (((double) nextInt() - -2147483648.0) / 4294967295.0); - } - - @Override - public float nextFloat(float bound) { - return nextFloat(0, bound); - } - - @Override - public float nextFloat(float min, float max) { - if (max <= min) { - return min; - } - return min + (nextFloat() * (max - min)); - } - - /* - * - */ - - @Override - public double nextDouble() { - return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; - } - - @Override - public double nextDouble(double bound) { - return nextDouble(0, bound); - } - - @Override - public double nextDouble(double min, double max) { - if (max <= min) { - return min; - } - return min + (nextDouble() * (max - min)); - } - - /* - * - * - * - */ - - private void checkVariables() { - if (modulu <= 0) - modulu = 1; - if (multiplier <= 0) - multiplier = 1; - if (increment < 0) - increment = 0; - if (multiplier > modulu) - multiplier = modulu != 1 ? modulu - 1 : 1; - if (increment > modulu) - increment = modulu - 1; - } + private long seed; + private int state; + + private int multiplier = 87454568; + private int increment = 3214561; + private int modulu = 2 ^ 31; + + public LinearCongruentialGenerator() { + setSeed(System.currentTimeMillis()); + } + + public LinearCongruentialGenerator(long seed) { + setSeed(System.currentTimeMillis()); + } + + /* + * + */ + + public void setSeed(long seed) { + this.seed = seed; + this.state = Math.toIntExact(seed >> 32); + } + + public long getSeed() { + return seed; + } + + /* + * + */ + + @Override + public void setCompressedState(long state) { + this.state = Math.toIntExact(seed); + } + + @Override + public long getCompressedState() { + return state; + } + + /* + * + */ + + public int getMultipliert() { + return multiplier; + } + + public void setMultiplier(int multiplier) { + this.multiplier = multiplier; + checkVariables(); + } + + /* + * + */ + + public int getIncrement() { + return increment; + } + + public void setIncrement(int increment) { + this.increment = increment; + checkVariables(); + } + + /* + * + */ + + public int getModulu() { + return modulu; + } + + public void setModulu(int modulu) { + this.modulu = modulu; + checkVariables(); + } + + /* + * + * + * + */ + + @Override + public boolean nextBoolean() { + return next(1) == 0; + } + + /* + * + */ + + @Override + public short nextShort() { + return (short) next(16); + } + + @Override + public short nextShort(short bound) { + return nextShort((short) 0, bound); + } + + @Override + public short nextShort(short min, short max) { + if (max <= min) { + return min; + } + return (short) (min + Math.abs(nextShort() % (max - min))); + } + + /* + * + */ + + @Override + public int nextInt() { + return state = ((multiplier * state) + increment) % modulu; + } + + @Override + public int nextInt(int bound) { + return nextInt(0, bound); + } + + @Override + public int nextInt(int min, int max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextInt() % (max - min)); + } + + /* + * + */ + + @Override + public long nextLong() { + return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); + } + + @Override + public long nextLong(long bound) { + return nextLong(0L, bound); + } + + @Override + public long nextLong(long min, long max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextLong() % (max - min)); + } + + /* + * + */ + + @Override + public float nextFloat() { + return (float) ((nextInt() - -2147483648.0) / 4294967295.0); + } + + @Override + public float nextFloat(float bound) { + return nextFloat(0, bound); + } + + @Override + public float nextFloat(float min, float max) { + if (max <= min) { + return min; + } + return min + (nextFloat() * (max - min)); + } + + /* + * + */ + + @Override + public double nextDouble() { + return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; + } + + @Override + public double nextDouble(double bound) { + return nextDouble(0, bound); + } + + @Override + public double nextDouble(double min, double max) { + if (max <= min) { + return min; + } + return min + (nextDouble() * (max - min)); + } + + /* + * + * + * + */ + + private void checkVariables() { + if (modulu <= 0) { + modulu = 1; + } + if (multiplier <= 0) { + multiplier = 1; + } + if (increment < 0) { + increment = 0; + } + if (multiplier > modulu) { + multiplier = modulu != 1 ? modulu - 1 : 1; + } + if (increment > modulu) { + increment = modulu - 1; + } + } } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/MurmurHashGenerator.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/MurmurHashGenerator.java index e98d273..2f91e05 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/MurmurHashGenerator.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/MurmurHashGenerator.java @@ -2,188 +2,189 @@ public class MurmurHashGenerator extends RandomNumberGenerator { - private long iterations = 0L; - private long seed; - - public MurmurHashGenerator() { - this.seed = System.currentTimeMillis(); - } - - public MurmurHashGenerator(long seed) { - this.seed = seed; - } - - /* - * - */ - - public void setSeed(long seed) { - this.seed = seed; - this.iterations = 0L; - } - - public long getSeed() { - return seed; - } - - /* - * - */ - - @Override - public void setCompressedState(long state) { - seed = state & -1; - iterations = state >> 32 & -1; - } - - @Override - public long getCompressedState() { - return seed | iterations << 32; - } - - /* - * - * - * - */ - - @Override - public boolean nextBoolean() { - return next(1) == 0; - } - - /* - * - */ - - @Override - public short nextShort() { - return (short) next(16); - } - - @Override - public short nextShort(short bound) { - return nextShort((short) 0, bound); - } - - @Override - public short nextShort(short min, short max) { - if (max <= min) { - return min; - } - return (short) (min + Math.abs((int) (nextShort() % (max - min)))); - } - - /* - * - */ - - @Override - public int nextInt() { - if (iterations == Long.MAX_VALUE) - iterations = 0L; - int output = generateInt(seed, iterations++); - return output; - } - - @Override - public int nextInt(int bound) { - return nextInt(0, bound); - } - - @Override - public int nextInt(int min, int max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextInt() % (max - min)); - } - - /* - * - */ - - @Override - public long nextLong() { - return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); - } - - @Override - public long nextLong(long bound) { - return nextLong(0L, bound); - } - - @Override - public long nextLong(long min, long max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextLong() % (max - min)); - } - - /* - * - */ - - @Override - public float nextFloat() { - return (float) (((double) nextInt() - -2147483648.0) / 4294967295.0); - } - - @Override - public float nextFloat(float bound) { - return nextFloat(0, bound); - } - - @Override - public float nextFloat(float min, float max) { - if (max <= min) { - return min; - } - return min + (nextFloat() * (max - min)); - } - - /* - * - */ - - @Override - public double nextDouble() { - return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; - } - - @Override - public double nextDouble(double bound) { - return nextDouble(0, bound); - } - - @Override - public double nextDouble(double min, double max) { - if (max <= min) { - return min; - } - return min + (nextDouble() * (max - min)); - } - - /* - * - * - * - */ - - public static int generateInt(long seed, long input) { - long num = input * 3432918353L; - num = (num << 15 | num >> 17); - num *= 461845907L; - long num2 = seed ^ num; - num2 = (num2 << 13 | num2 >> 19); - num2 = num2 * 5L + 3864292196L; - num2 ^= 2834544218L; - num2 ^= num2 >> 16; - num2 *= 2246822507L; - num2 ^= num2 >> 13; - num2 *= 3266489909L; - return (int) (num2 ^ num2 >> 16); - } + private long iterations = 0L; + private long seed; + + public MurmurHashGenerator() { + this.seed = System.currentTimeMillis(); + } + + public MurmurHashGenerator(long seed) { + this.seed = seed; + } + + /* + * + */ + + public void setSeed(long seed) { + this.seed = seed; + this.iterations = 0L; + } + + public long getSeed() { + return seed; + } + + /* + * + */ + + @Override + public void setCompressedState(long state) { + seed = state & -1; + iterations = state >> 32 & -1; + } + + @Override + public long getCompressedState() { + return seed | iterations << 32; + } + + /* + * + * + * + */ + + @Override + public boolean nextBoolean() { + return next(1) == 0; + } + + /* + * + */ + + @Override + public short nextShort() { + return (short) next(16); + } + + @Override + public short nextShort(short bound) { + return nextShort((short) 0, bound); + } + + @Override + public short nextShort(short min, short max) { + if (max <= min) { + return min; + } + return (short) (min + Math.abs(nextShort() % (max - min))); + } + + /* + * + */ + + @Override + public int nextInt() { + if (iterations == Long.MAX_VALUE) { + iterations = 0L; + } + int output = generateInt(seed, iterations++); + return output; + } + + @Override + public int nextInt(int bound) { + return nextInt(0, bound); + } + + @Override + public int nextInt(int min, int max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextInt() % (max - min)); + } + + /* + * + */ + + @Override + public long nextLong() { + return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); + } + + @Override + public long nextLong(long bound) { + return nextLong(0L, bound); + } + + @Override + public long nextLong(long min, long max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextLong() % (max - min)); + } + + /* + * + */ + + @Override + public float nextFloat() { + return (float) ((nextInt() - -2147483648.0) / 4294967295.0); + } + + @Override + public float nextFloat(float bound) { + return nextFloat(0, bound); + } + + @Override + public float nextFloat(float min, float max) { + if (max <= min) { + return min; + } + return min + (nextFloat() * (max - min)); + } + + /* + * + */ + + @Override + public double nextDouble() { + return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; + } + + @Override + public double nextDouble(double bound) { + return nextDouble(0, bound); + } + + @Override + public double nextDouble(double min, double max) { + if (max <= min) { + return min; + } + return min + (nextDouble() * (max - min)); + } + + /* + * + * + * + */ + + public static int generateInt(long seed, long input) { + long num = input * 3432918353L; + num = (num << 15 | num >> 17); + num *= 461845907L; + long num2 = seed ^ num; + num2 = (num2 << 13 | num2 >> 19); + num2 = num2 * 5L + 3864292196L; + num2 ^= 2834544218L; + num2 ^= num2 >> 16; + num2 *= 2246822507L; + num2 ^= num2 >> 13; + num2 *= 3266489909L; + return (int) (num2 ^ num2 >> 16); + } } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/NumberGeneratorType.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/NumberGeneratorType.java index 00594b9..48b0483 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/NumberGeneratorType.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/NumberGeneratorType.java @@ -5,27 +5,27 @@ public enum NumberGeneratorType { - LINEAR(LinearCongruentialGenerator.class), - PERMUTED(PermutedCongruentialGenerator.class), - MURMUR(MurmurHashGenerator.class); + LINEAR(LinearCongruentialGenerator.class), + PERMUTED(PermutedCongruentialGenerator.class), + MURMUR(MurmurHashGenerator.class); - private final AbstractReflect NUMBER_GENERATOR; + private final AbstractReflect NUMBER_GENERATOR; - private NumberGeneratorType(Class clazz) { - this.NUMBER_GENERATOR = new Reflect(clazz).searchConstructor("seed", long.class); - } + private NumberGeneratorType(Class clazz) { + this.NUMBER_GENERATOR = new Reflect(clazz).searchConstructor("seed", long.class); + } - @SuppressWarnings("unchecked") - public Class getGeneratorClass() { - return (Class) NUMBER_GENERATOR.getOwner(); - } + @SuppressWarnings("unchecked") + public Class getGeneratorClass() { + return (Class) NUMBER_GENERATOR.getOwner(); + } - public RandomNumberGenerator create() { - return (RandomNumberGenerator) NUMBER_GENERATOR.init(); - } + public RandomNumberGenerator create() { + return (RandomNumberGenerator) NUMBER_GENERATOR.init(); + } - public RandomNumberGenerator create(long seed) { - return (RandomNumberGenerator) NUMBER_GENERATOR.init("seed", seed); - } + public RandomNumberGenerator create(long seed) { + return (RandomNumberGenerator) NUMBER_GENERATOR.init("seed", seed); + } } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/PermutedCongruentialGenerator.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/PermutedCongruentialGenerator.java index 3a9b702..41c2944 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/PermutedCongruentialGenerator.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/PermutedCongruentialGenerator.java @@ -2,211 +2,213 @@ public class PermutedCongruentialGenerator extends RandomNumberGenerator { - private long state; - private long seed; - - private long multiplier = 645; - private long increment = 2583; - - public PermutedCongruentialGenerator() { - setSeed(System.currentTimeMillis()); - } - - public PermutedCongruentialGenerator(long seed) { - setSeed(seed); - } - - /* - * - */ - - @Override - public void setSeed(long seed) { - this.seed = seed; - this.state = seed; - } - - @Override - public long getSeed() { - return seed; - } - - /* - * - */ - - @Override - public void setCompressedState(long state) { - this.state = state; - } - - @Override - public long getCompressedState() { - return state; - } - - /* - * - */ - - public long getMultiplier() { - return multiplier; - } - - public void setMultiplier(long multiplier) { - this.multiplier = multiplier; - checkVariables(); - } - - /* - * - */ - - public long getIncrement() { - return increment; - } - - public void setIncrement(long increment) { - this.increment = increment; - checkVariables(); - } - - /* - * - * - * - */ - - @Override - public boolean nextBoolean() { - return next(1) == 0; - } - - /* - * - */ - - @Override - public short nextShort() { - return (short) next(16); - } - - @Override - public short nextShort(short bound) { - return nextShort((short) 0, bound); - } - - @Override - public short nextShort(short min, short max) { - if (max <= min) { - return min; - } - return (short) (min + Math.abs((int) (nextShort() % (max - min)))); - } - - /* - * - */ - - @Override - public int nextInt() { - long number = state; - long count = number >> 59; - state = number * multiplier + increment; - number ^= number >> 18; - return (int) (((int) number) >> count | number << (-count & 31)); - } - - @Override - public int nextInt(int bound) { - return nextInt(0, bound); - } - - @Override - public int nextInt(int min, int max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextInt() % (max - min)); - } - - /* - * - */ - - @Override - public long nextLong() { - return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); - } - - @Override - public long nextLong(long bound) { - return nextLong(0L, bound); - } - - @Override - public long nextLong(long min, long max) { - if (max <= min) { - return min; - } - return min + Math.abs(nextLong() % (max - min)); - } - - /* - * - */ - - @Override - public float nextFloat() { - return (float) (((double) nextInt() - -2147483648.0) / 4294967295.0); - } - - @Override - public float nextFloat(float bound) { - return nextFloat(0, bound); - } - - @Override - public float nextFloat(float min, float max) { - if (max <= min) { - return min; - } - return min + (nextFloat() * (max - min)); - } - - /* - * - */ - - @Override - public double nextDouble() { - return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; - } - - @Override - public double nextDouble(double bound) { - return nextDouble(0, bound); - } - - @Override - public double nextDouble(double min, double max) { - if (max <= min) { - return min; - } - return min + (nextDouble() * (max - min)); - } - - /* - * - * - * - */ - - private void checkVariables() { - if (multiplier <= 0) - multiplier = 1; - if (increment < 0) - increment = 0; - } + private long state; + private long seed; + + private long multiplier = 645; + private long increment = 2583; + + public PermutedCongruentialGenerator() { + setSeed(System.currentTimeMillis()); + } + + public PermutedCongruentialGenerator(long seed) { + setSeed(seed); + } + + /* + * + */ + + @Override + public void setSeed(long seed) { + this.seed = seed; + this.state = seed; + } + + @Override + public long getSeed() { + return seed; + } + + /* + * + */ + + @Override + public void setCompressedState(long state) { + this.state = state; + } + + @Override + public long getCompressedState() { + return state; + } + + /* + * + */ + + public long getMultiplier() { + return multiplier; + } + + public void setMultiplier(long multiplier) { + this.multiplier = multiplier; + checkVariables(); + } + + /* + * + */ + + public long getIncrement() { + return increment; + } + + public void setIncrement(long increment) { + this.increment = increment; + checkVariables(); + } + + /* + * + * + * + */ + + @Override + public boolean nextBoolean() { + return next(1) == 0; + } + + /* + * + */ + + @Override + public short nextShort() { + return (short) next(16); + } + + @Override + public short nextShort(short bound) { + return nextShort((short) 0, bound); + } + + @Override + public short nextShort(short min, short max) { + if (max <= min) { + return min; + } + return (short) (min + Math.abs(nextShort() % (max - min))); + } + + /* + * + */ + + @Override + public int nextInt() { + long number = state; + long count = number >> 59; + state = number * multiplier + increment; + number ^= number >> 18; + return (int) (((int) number) >> count | number << (-count & 31)); + } + + @Override + public int nextInt(int bound) { + return nextInt(0, bound); + } + + @Override + public int nextInt(int min, int max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextInt() % (max - min)); + } + + /* + * + */ + + @Override + public long nextLong() { + return ((long) nextInt()) << 32 | (nextInt() & 0xffffffffL); + } + + @Override + public long nextLong(long bound) { + return nextLong(0L, bound); + } + + @Override + public long nextLong(long min, long max) { + if (max <= min) { + return min; + } + return min + Math.abs(nextLong() % (max - min)); + } + + /* + * + */ + + @Override + public float nextFloat() { + return (float) ((nextInt() - -2147483648.0) / 4294967295.0); + } + + @Override + public float nextFloat(float bound) { + return nextFloat(0, bound); + } + + @Override + public float nextFloat(float min, float max) { + if (max <= min) { + return min; + } + return min + (nextFloat() * (max - min)); + } + + /* + * + */ + + @Override + public double nextDouble() { + return (((long) (next(26)) << 27) + next(27)) * 0x1.0p-53; + } + + @Override + public double nextDouble(double bound) { + return nextDouble(0, bound); + } + + @Override + public double nextDouble(double min, double max) { + if (max <= min) { + return min; + } + return min + (nextDouble() * (max - min)); + } + + /* + * + * + * + */ + + private void checkVariables() { + if (multiplier <= 0) { + multiplier = 1; + } + if (increment < 0) { + increment = 0; + } + } } diff --git a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/RandomNumberGenerator.java b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/RandomNumberGenerator.java index 3ff51cf..573041c 100644 --- a/random/src/main/java/com/syntaxphoenix/syntaxapi/random/RandomNumberGenerator.java +++ b/random/src/main/java/com/syntaxphoenix/syntaxapi/random/RandomNumberGenerator.java @@ -2,82 +2,82 @@ public abstract class RandomNumberGenerator { - public abstract void setSeed(long seed); + public abstract void setSeed(long seed); - public abstract long getSeed(); + public abstract long getSeed(); - /* - * - */ + /* + * + */ - public abstract void setCompressedState(long state); + public abstract void setCompressedState(long state); - public abstract long getCompressedState(); + public abstract long getCompressedState(); - /* - * - * - * - */ + /* + * + * + * + */ - public abstract boolean nextBoolean(); + public abstract boolean nextBoolean(); - /* - * - */ + /* + * + */ - public abstract short nextShort(); + public abstract short nextShort(); - public abstract short nextShort(short bound); + public abstract short nextShort(short bound); - public abstract short nextShort(short min, short max); + public abstract short nextShort(short min, short max); - /* - * - */ + /* + * + */ - public abstract int nextInt(); + public abstract int nextInt(); - public abstract int nextInt(int bound); + public abstract int nextInt(int bound); - public abstract int nextInt(int min, int max); + public abstract int nextInt(int min, int max); - /* - * - */ + /* + * + */ - public abstract long nextLong(); + public abstract long nextLong(); - public abstract long nextLong(long bound); + public abstract long nextLong(long bound); - public abstract long nextLong(long min, long max); + public abstract long nextLong(long min, long max); - /* - * - */ + /* + * + */ - public abstract float nextFloat(); + public abstract float nextFloat(); - public abstract float nextFloat(float bound); + public abstract float nextFloat(float bound); - public abstract float nextFloat(float min, float max); + public abstract float nextFloat(float min, float max); - /* - * - */ + /* + * + */ - public abstract double nextDouble(); + public abstract double nextDouble(); - public abstract double nextDouble(double bound); + public abstract double nextDouble(double bound); - public abstract double nextDouble(double min, double max); + public abstract double nextDouble(double min, double max); - /* - * - */ + /* + * + */ - protected int next(int bits) { - return nextInt() >>> (32 - bits); - } + protected int next(int bits) { + return nextInt() >>> (32 - bits); + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/AbstractReflectCache.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/AbstractReflectCache.java index 5b4ad94..1691b65 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/AbstractReflectCache.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/AbstractReflectCache.java @@ -5,40 +5,40 @@ public abstract class AbstractReflectCache { - protected final HashMap cache = new HashMap<>(); - - public void clear() { - cache.values().forEach(ClassCache::uncache); - } - - public Optional get(String name) { - return Optional.ofNullable(cache.get(name)); - } - - public boolean has(String name) { - return cache.containsKey(name); - } - - public R create(String name, String path) { - if (has(name)) { - return cache.get(name); - } - R reflect = create(path); - cache.put(name, reflect); - return reflect; - } - - public R create(String name, Class clazz) { - if (has(name)) { - return cache.get(name); - } - R reflect = create(clazz); - cache.put(name, reflect); - return reflect; - } - - protected abstract R create(Class clazz); - - protected abstract R create(String path); + protected final HashMap cache = new HashMap<>(); + + public void clear() { + cache.values().forEach(ClassCache::uncache); + } + + public Optional get(String name) { + return Optional.ofNullable(cache.get(name)); + } + + public boolean has(String name) { + return cache.containsKey(name); + } + + public R create(String name, String path) { + if (has(name)) { + return cache.get(name); + } + R reflect = create(path); + cache.put(name, reflect); + return reflect; + } + + public R create(String name, Class clazz) { + if (has(name)) { + return cache.get(name); + } + R reflect = create(clazz); + cache.put(name, reflect); + return reflect; + } + + protected abstract R create(Class clazz); + + protected abstract R create(String path); } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClassCache.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClassCache.java index 324433e..eda264c 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClassCache.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClassCache.java @@ -6,37 +6,39 @@ public class ClassCache { - public static final HashMap> CLASSES = new HashMap<>(); + public static final HashMap> CLASSES = new HashMap<>(); - public static Optional> getOptionalClass(String classPath) { - if (CLASSES.containsKey(classPath)) { - return Optional.of(CLASSES.get(classPath)); - } - try { - Class clazz = Class.forName(classPath); - if (clazz != null) { - CLASSES.put(classPath, clazz); - return Optional.of(clazz); - } - return Optional.empty(); - } catch (ClassNotFoundException e) { - return Optional.empty(); - } - } + public static Optional> getOptionalClass(String classPath) { + if (CLASSES.containsKey(classPath)) { + return Optional.of(CLASSES.get(classPath)); + } + try { + Class clazz = Class.forName(classPath); + if (clazz != null) { + CLASSES.put(classPath, clazz); + return Optional.of(clazz); + } + return Optional.empty(); + } catch (ClassNotFoundException e) { + return Optional.empty(); + } + } - public static Class getClass(String classPath) { - Optional> option = getOptionalClass(classPath); - return option.orElse(null); - } + public static Class getClass(String classPath) { + Optional> option = getOptionalClass(classPath); + return option.orElse(null); + } - public static void uncache(AbstractReflect reflect) { - Class search = reflect.getOwner(); - reflect.delete(); - if (CLASSES.isEmpty()) - return; - Optional>> option = CLASSES.entrySet().stream().filter(entry -> entry.getValue().equals(search)).findFirst(); - if (option.isPresent()) - CLASSES.remove(option.get().getKey()); - } + public static void uncache(AbstractReflect reflect) { + Class search = reflect.getOwner(); + reflect.delete(); + if (CLASSES.isEmpty()) { + return; + } + Optional>> option = CLASSES.entrySet().stream().filter(entry -> entry.getValue().equals(search)).findFirst(); + if (option.isPresent()) { + CLASSES.remove(option.get().getKey()); + } + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClasspathAccess.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClasspathAccess.java index ad557d3..ea51d95 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClasspathAccess.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ClasspathAccess.java @@ -9,104 +9,106 @@ public class ClasspathAccess { - private static final HashMap CLASSPATHS = new HashMap<>(); + private static final HashMap CLASSPATHS = new HashMap<>(); - public static ClasspathAccess of(String name) { - File directory = getClasspath(name); - if (directory == null) - return null; - String pathString = directory.getPath(); - if (CLASSPATHS.containsKey(pathString)) - return CLASSPATHS.get(pathString); - ClasspathAccess access = new ClasspathAccess(pathString, directory); - CLASSPATHS.put(pathString, access); - return access; - } + public static ClasspathAccess of(String name) { + File directory = getClasspath(name); + if (directory == null) { + return null; + } + String pathString = directory.getPath(); + if (CLASSPATHS.containsKey(pathString)) { + return CLASSPATHS.get(pathString); + } + ClasspathAccess access = new ClasspathAccess(pathString, directory); + CLASSPATHS.put(pathString, access); + return access; + } - public static ClasspathAccess of(String name, ClassLoader... loaders) { - File directory = getClasspath(name); - if (directory == null) - return null; - String pathString = directory.getPath(); - if (CLASSPATHS.containsKey(pathString)) - return CLASSPATHS.get(pathString); - ClasspathAccess access = new ClasspathAccess(pathString, directory); - CLASSPATHS.put(pathString, access); - return access; - } + public static ClasspathAccess of(String name, ClassLoader... loaders) { + File directory = getClasspath(name); + if (directory == null) { + return null; + } + String pathString = directory.getPath(); + if (CLASSPATHS.containsKey(pathString)) { + return CLASSPATHS.get(pathString); + } + ClasspathAccess access = new ClasspathAccess(pathString, directory); + CLASSPATHS.put(pathString, access); + return access; + } - /* - * - */ + /* + * + */ - private static File getClasspath(String packageName, ClassLoader... loaders) { - File directory = null; - try { - File[] files = ReflectionTools.getUrlAsFiles(ReflectionHelper.forPackage(packageName, loaders)); - if (files.length == 0) - return null; - directory = files[0]; - } catch (URISyntaxException e) { - } - if (directory == null) - return null; - return directory; - } + private static File getClasspath(String packageName, ClassLoader... loaders) { + File directory = null; + try { + File[] files = ReflectionTools.getUrlAsFiles(ReflectionHelper.forPackage(packageName, loaders)); + if (files.length == 0) { + return null; + } + directory = files[0]; + } catch (URISyntaxException e) { + } + if (directory == null) { + return null; + } + return directory; + } - /* - * - */ + /* + * + */ - protected final HashMap packages = new HashMap<>(); - protected final String classPath; - protected final File directory; + protected final HashMap packages = new HashMap<>(); + protected final String classPath; + protected final File directory; - private ClasspathAccess(String classPath, File directory) { - this.classPath = classPath; - this.directory = directory; - } + private ClasspathAccess(String classPath, File directory) { + this.classPath = classPath; + this.directory = directory; + } - public Optional getOptionalPackage(String packageName) { - synchronized (packages) { - if (packages.containsKey(packageName)) - return Optional.of(packages.get(packageName)); - } - String[] path = packageName.split("\\."); - ArrayList files = new ArrayList<>(); - File[] directories = Arrays - .stream(directory.listFiles(file -> file.isDirectory())) - .filter(file -> !file.getName().equals("META-INF")) - .toArray(File[]::new); - files.add(directories); - for (int index = 0; index < (path.length - 1); index++) { - files - .add(directories = Arrays - .stream(directories) - .map(file -> file.listFiles(current -> current.isDirectory())) - .flatMap(array -> Arrays.stream(array)) - .toArray(File[]::new)); - } - int pathLength = classPath.length() + 1; - String filter = packageName.replace('.', '\\'); - Optional option = files.stream().flatMap(array -> Arrays.stream(array)).filter(file -> { - String filePath = file.getPath(); - return filter.equals(filePath.substring(pathLength, filePath.length())); - }).findFirst(); - if (!option.isPresent()) - return Optional.empty(); - PackageAccess access = new PackageAccess(this, packageName, option.get()); - packages.put(packageName, access); - return Optional.of(access); - } + public Optional getOptionalPackage(String packageName) { + synchronized (packages) { + if (packages.containsKey(packageName)) { + return Optional.of(packages.get(packageName)); + } + } + String[] path = packageName.split("\\."); + ArrayList files = new ArrayList<>(); + File[] directories = Arrays.stream(directory.listFiles(file -> file.isDirectory())) + .filter(file -> !file.getName().equals("META-INF")).toArray(File[]::new); + files.add(directories); + for (int index = 0; index < (path.length - 1); index++) { + files.add(directories = Arrays.stream(directories).map(file -> file.listFiles(current -> current.isDirectory())) + .flatMap(array -> Arrays.stream(array)).toArray(File[]::new)); + } + int pathLength = classPath.length() + 1; + String filter = packageName.replace('.', '\\'); + Optional option = files.stream().flatMap(array -> Arrays.stream(array)).filter(file -> { + String filePath = file.getPath(); + return filter.equals(filePath.substring(pathLength, filePath.length())); + }).findFirst(); + if (!option.isPresent()) { + return Optional.empty(); + } + PackageAccess access = new PackageAccess(this, packageName, option.get()); + packages.put(packageName, access); + return Optional.of(access); + } - public PackageAccess getPackage(String packageName) { - return getOptionalPackage(packageName).orElse(null); - } + public PackageAccess getPackage(String packageName) { + return getOptionalPackage(packageName).orElse(null); + } - public PackageAccess[] getCachedPackages() { - synchronized (packages) { - return packages.values().toArray(new PackageAccess[0]); - } - } + public PackageAccess[] getCachedPackages() { + synchronized (packages) { + return packages.values().toArray(new PackageAccess[0]); + } + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/PackageAccess.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/PackageAccess.java index 7f4859f..1a98f48 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/PackageAccess.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/PackageAccess.java @@ -6,60 +6,62 @@ public class PackageAccess { - public static final Class[] EMPTY = new Class[0]; + public static final Class[] EMPTY = new Class[0]; - public static PackageAccess of(String packageName) { - return ClasspathAccess.of(packageName).getPackage(packageName); - } + public static PackageAccess of(String packageName) { + return ClasspathAccess.of(packageName).getPackage(packageName); + } - protected final HashMap> classes = new HashMap<>(); - protected final ClasspathAccess classpath; - protected final String packageName; + protected final HashMap> classes = new HashMap<>(); + protected final ClasspathAccess classpath; + protected final String packageName; - PackageAccess(ClasspathAccess classpath, String packageName, File externalPackage) { - this.classpath = classpath; - this.packageName = packageName; - scan(externalPackage); - } + PackageAccess(ClasspathAccess classpath, String packageName, File externalPackage) { + this.classpath = classpath; + this.packageName = packageName; + scan(externalPackage); + } - /* - * Scanning for classes - */ + /* + * Scanning for classes + */ - private void scan(File exteneralPackage) { - if (exteneralPackage == null) - return; - File[] files = exteneralPackage.listFiles(file -> file.getName().endsWith(".class")); - for (int index = 0; index < files.length; index++) { - String name = files[index].getName().split("\\.")[0]; - Optional> option = ClassCache.getOptionalClass(packageName + '.' + name); - if (option.isPresent()) - classes.put(name, option.get()); - } - } + private void scan(File exteneralPackage) { + if (exteneralPackage == null) { + return; + } + File[] files = exteneralPackage.listFiles(file -> file.getName().endsWith(".class")); + for (int index = 0; index < files.length; index++) { + String name = files[index].getName().split("\\.")[0]; + Optional> option = ClassCache.getOptionalClass(packageName + '.' + name); + if (option.isPresent()) { + classes.put(name, option.get()); + } + } + } - /* - * - */ + /* + * + */ - public ClasspathAccess getClasspath() { - return classpath; - } + public ClasspathAccess getClasspath() { + return classpath; + } - public boolean hasClasses() { - return !classes.isEmpty(); - } + public boolean hasClasses() { + return !classes.isEmpty(); + } - public Class[] getClasses() { - return classes.isEmpty() ? EMPTY : classes.values().toArray(new Class[0]); - } + public Class[] getClasses() { + return classes.isEmpty() ? EMPTY : classes.values().toArray(new Class[0]); + } - public Class getClass(String name) { - return classes.get(name); - } + public Class getClass(String name) { + return classes.get(name); + } - public Optional> getOptionalClass(String name) { - return Optional.ofNullable(classes.get(name)); - } + public Optional> getOptionalClass(String name) { + return Optional.ofNullable(classes.get(name)); + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/Reflect.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/Reflect.java index 8c736c8..a0fea82 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/Reflect.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/Reflect.java @@ -2,12 +2,12 @@ public class Reflect extends AbstractReflect { - public Reflect(String classPath) { - super(classPath); - } + public Reflect(String classPath) { + super(classPath); + } - public Reflect(Class owner) { - super(owner); - } + public Reflect(Class owner) { + super(owner); + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectCache.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectCache.java index d85373e..fe0b49f 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectCache.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectCache.java @@ -2,14 +2,14 @@ public class ReflectCache extends AbstractReflectCache { - @Override - protected Reflect create(Class clazz) { - return new Reflect(clazz); - } - - @Override - protected Reflect create(String path) { - return new Reflect(path); - } + @Override + protected Reflect create(Class clazz) { + return new Reflect(clazz); + } + + @Override + protected Reflect create(String path) { + return new Reflect(path); + } } diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionHelper.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionHelper.java index 54b3820..a9b113c 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionHelper.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionHelper.java @@ -23,373 +23,376 @@ */ public final class ReflectionHelper { - /** - * Gets the current thread context class loader. - * {@code Thread.currentThread().getContextClassLoader()}. - * - * @return the context class loader, may be null - */ - public static ClassLoader contextClassLoader() { - return Thread.currentThread().getContextClassLoader(); - } + /** + * Gets the current thread context class loader. + * {@code Thread.currentThread().getContextClassLoader()}. + * + * @return the context class loader, may be null + */ + public static ClassLoader contextClassLoader() { + return Thread.currentThread().getContextClassLoader(); + } - /** - * Gets the class loader of this library. - * {@code ClassCache.class.getClassLoader()}. - * - * @return the static library class loader, may be null - */ - public static ClassLoader staticClassLoader() { - return ClassCache.class.getClassLoader(); - } + /** + * Gets the class loader of this library. + * {@code ClassCache.class.getClassLoader()}. + * + * @return the static library class loader, may be null + */ + public static ClassLoader staticClassLoader() { + return ClassCache.class.getClassLoader(); + } - /** - * Returns an array of class Loaders initialized from the specified array. - *

- * If the input is null or empty, it defaults to both - * {@link #contextClassLoader()} and {@link #staticClassLoader()} - * - * @param classLoaders the classLoaders provided - * - * @return the array of class loaders, not null - */ - public static ClassLoader[] classLoaders(ClassLoader... classLoaders) { - if (classLoaders != null && classLoaders.length != 0) { - return classLoaders; - } else { - ClassLoader contextClassLoader = contextClassLoader(), staticClassLoader = staticClassLoader(); - return contextClassLoader != null ? staticClassLoader != null && contextClassLoader != staticClassLoader ? new ClassLoader[] { - contextClassLoader, - staticClassLoader - } - : new ClassLoader[] { - contextClassLoader - } : new ClassLoader[] {}; + /** + * Returns an array of class Loaders initialized from the specified array. + *

+ * If the input is null or empty, it defaults to both + * {@link #contextClassLoader()} and {@link #staticClassLoader()} + * + * @param classLoaders the classLoaders provided + * + * @return the array of class loaders, not null + */ + public static ClassLoader[] classLoaders(ClassLoader... classLoaders) { + if (classLoaders != null && classLoaders.length != 0) { + return classLoaders; + } else { + ClassLoader contextClassLoader = contextClassLoader(), staticClassLoader = staticClassLoader(); + return contextClassLoader != null ? staticClassLoader != null && contextClassLoader != staticClassLoader ? new ClassLoader[] { + contextClassLoader, + staticClassLoader + } + : new ClassLoader[] { + contextClassLoader + } : new ClassLoader[] {}; - } - } + } + } - /** - * Returns a distinct collection of URLs based on a package name. - *

- * This searches for the package name as a resource, using - * {@link ClassLoader#getResources(String)}. For example, - * {@code forPackage(org.reflections)} effectively returns URLs from the - * classpath containing packages starting with {@code org.reflections}. - *

- * If the optional {@link ClassLoader}s are not specified, then both - * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for - * {@link ClassLoader#getResources(String)}. - *

- * The returned URLs retainsthe order of the given {@code classLoaders}. - * - * @param classLoaders the classLoaders provided - * @param name the package name - * - * @return the collection of URLs, not null - */ - public static Collection forPackage(String name, ClassLoader... classLoaders) { - return forResource(resourceName(name), classLoaders); - } + /** + * Returns a distinct collection of URLs based on a package name. + *

+ * This searches for the package name as a resource, using + * {@link ClassLoader#getResources(String)}. For example, + * {@code forPackage(org.reflections)} effectively returns URLs from the + * classpath containing packages starting with {@code org.reflections}. + *

+ * If the optional {@link ClassLoader}s are not specified, then both + * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for + * {@link ClassLoader#getResources(String)}. + *

+ * The returned URLs retainsthe order of the given {@code classLoaders}. + * + * @param classLoaders the classLoaders provided + * @param name the package name + * + * @return the collection of URLs, not null + */ + public static Collection forPackage(String name, ClassLoader... classLoaders) { + return forResource(resourceName(name), classLoaders); + } - /** - * Returns a distinct collection of URLs based on a resource. - *

- * This searches for the resource name, using - * {@link ClassLoader#getResources(String)}. For example, - * {@code forResource(test.properties)} effectively returns URLs from the - * classpath containing files of that name. - *

- * If the optional {@link ClassLoader}s are not specified, then both - * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for - * {@link ClassLoader#getResources(String)}. - *

- * The returned URLs retains the order of the given {@code classLoaders}. - * - * @param classLoaders the classLoaders provided - * @param resourceName the resource name - * - * @return the collection of URLs, not null - */ - public static Collection forResource(String resourceName, ClassLoader... classLoaders) { - final List result = new ArrayList<>(); - final ClassLoader[] loaders = classLoaders(classLoaders); - for (ClassLoader classLoader : loaders) { - try { - final Enumeration urls = classLoader.getResources(resourceName); - while (urls.hasMoreElements()) { - final URL url = urls.nextElement(); - int index = url.toExternalForm().lastIndexOf(resourceName); - if (index != -1) { - // Add old url as contextUrl to support exotic url handlers - result.add(new URL(url, url.toExternalForm().substring(0, index))); - } else { - result.add(url); - } - } - } catch (IOException e) { - // Ignore for now - // TODO: Add logger - } - } - return distinctUrls(result); - } + /** + * Returns a distinct collection of URLs based on a resource. + *

+ * This searches for the resource name, using + * {@link ClassLoader#getResources(String)}. For example, + * {@code forResource(test.properties)} effectively returns URLs from the + * classpath containing files of that name. + *

+ * If the optional {@link ClassLoader}s are not specified, then both + * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for + * {@link ClassLoader#getResources(String)}. + *

+ * The returned URLs retains the order of the given {@code classLoaders}. + * + * @param classLoaders the classLoaders provided + * @param resourceName the resource name + * + * @return the collection of URLs, not null + */ + public static Collection forResource(String resourceName, ClassLoader... classLoaders) { + final List result = new ArrayList<>(); + final ClassLoader[] loaders = classLoaders(classLoaders); + for (ClassLoader classLoader : loaders) { + try { + final Enumeration urls = classLoader.getResources(resourceName); + while (urls.hasMoreElements()) { + final URL url = urls.nextElement(); + int index = url.toExternalForm().lastIndexOf(resourceName); + if (index != -1) { + // Add old url as contextUrl to support exotic url handlers + result.add(new URL(url, url.toExternalForm().substring(0, index))); + } else { + result.add(url); + } + } + } catch (IOException e) { + // Ignore for now + // TODO: Add logger + } + } + return distinctUrls(result); + } - /** - * Returns the URL that contains a {@code Class}. - *

- * This searches for the class using {@link ClassLoader#getResource(String)}. - *

- * If the optional {@link ClassLoader}s are not specified, then both - * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for - * {@link ClassLoader#getResources(String)}. - * - * @param classLoaders the classLoaders provided - * @param aClass the class which the url should be get for - * - * @return the URL containing the class, null if not found - */ - public static URL forClass(Class aClass, ClassLoader... classLoaders) { - final ClassLoader[] loaders = classLoaders(classLoaders); - final String resourceName = aClass.getName().replace(".", "/") + ".class"; - for (ClassLoader classLoader : loaders) { - try { - final URL url = classLoader.getResource(resourceName); - if (url != null) { - final String normalizedUrl = url - .toExternalForm() - .substring(0, url.toExternalForm().lastIndexOf(aClass.getPackage().getName().replace(".", "/"))); - return new URL(normalizedUrl); - } - } catch (MalformedURLException e) { - // Ignore for now - // TODO: Add logger - } - } - return null; - } + /** + * Returns the URL that contains a {@code Class}. + *

+ * This searches for the class using {@link ClassLoader#getResource(String)}. + *

+ * If the optional {@link ClassLoader}s are not specified, then both + * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for + * {@link ClassLoader#getResources(String)}. + * + * @param classLoaders the classLoaders provided + * @param aClass the class which the url should be get for + * + * @return the URL containing the class, null if not found + */ + public static URL forClass(Class aClass, ClassLoader... classLoaders) { + final ClassLoader[] loaders = classLoaders(classLoaders); + final String resourceName = aClass.getName().replace(".", "/") + ".class"; + for (ClassLoader classLoader : loaders) { + try { + final URL url = classLoader.getResource(resourceName); + if (url != null) { + final String normalizedUrl = url.toExternalForm().substring(0, + url.toExternalForm().lastIndexOf(aClass.getPackage().getName().replace(".", "/"))); + return new URL(normalizedUrl); + } + } catch (MalformedURLException e) { + // Ignore for now + // TODO: Add logger + } + } + return null; + } - /** - * Returns a distinct collection of URLs based on URLs derived from class - * loaders. - *

- * This finds the URLs using {@link URLClassLoader#getURLs()} using both - * {@link #contextClassLoader()} and {@link #staticClassLoader()}. - *

- * The returned URLs retains the order of the given {@code classLoaders}. - * - * @return the collection of URLs, not null - */ - public static Collection forClassLoader() { - return forClassLoader(classLoaders()); - } + /** + * Returns a distinct collection of URLs based on URLs derived from class + * loaders. + *

+ * This finds the URLs using {@link URLClassLoader#getURLs()} using both + * {@link #contextClassLoader()} and {@link #staticClassLoader()}. + *

+ * The returned URLs retains the order of the given {@code classLoaders}. + * + * @return the collection of URLs, not null + */ + public static Collection forClassLoader() { + return forClassLoader(classLoaders()); + } - /** - * Returns a distinct collection of URLs based on URLs derived from class - * loaders. - *

- * This finds the URLs using {@link URLClassLoader#getURLs()} using the - * specified class loader, searching up the parent hierarchy. - *

- * If the optional {@link ClassLoader}s are not specified, then both - * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for - * {@link ClassLoader#getResources(String)}. - *

- * The returned URLs retains the order of the given {@code classLoaders}. - * - * @param classLoaders the classLoaders provided - * - * @return the collection of URLs, not null - */ - public static Collection forClassLoader(ClassLoader... classLoaders) { - final Collection result = new ArrayList<>(); - final ClassLoader[] loaders = classLoaders(classLoaders); - for (ClassLoader classLoader : loaders) { - while (classLoader != null) { - if (classLoader instanceof URLClassLoader) { - URL[] urls = ((URLClassLoader) classLoader).getURLs(); - if (urls != null) { - result.addAll(Arrays.asList(urls)); - } - } - classLoader = classLoader.getParent(); - } - } - return distinctUrls(result); - } + /** + * Returns a distinct collection of URLs based on URLs derived from class + * loaders. + *

+ * This finds the URLs using {@link URLClassLoader#getURLs()} using the + * specified class loader, searching up the parent hierarchy. + *

+ * If the optional {@link ClassLoader}s are not specified, then both + * {@link #contextClassLoader()} and {@link #staticClassLoader()} are used for + * {@link ClassLoader#getResources(String)}. + *

+ * The returned URLs retains the order of the given {@code classLoaders}. + * + * @param classLoaders the classLoaders provided + * + * @return the collection of URLs, not null + */ + public static Collection forClassLoader(ClassLoader... classLoaders) { + final Collection result = new ArrayList<>(); + final ClassLoader[] loaders = classLoaders(classLoaders); + for (ClassLoader classLoader : loaders) { + while (classLoader != null) { + if (classLoader instanceof URLClassLoader) { + URL[] urls = ((URLClassLoader) classLoader).getURLs(); + if (urls != null) { + result.addAll(Arrays.asList(urls)); + } + } + classLoader = classLoader.getParent(); + } + } + return distinctUrls(result); + } - /** - * Returns a distinct collection of URLs based on the {@code java.class.path} - * system property. - *

- * This finds the URLs using the {@code java.class.path} system property. - *

- * The returned collection of URLs retains the classpath order. - * - * @return the collection of URLs, not null - */ - public static Collection forJavaClassPath() { - Collection urls = new ArrayList<>(); - String javaClassPath = System.getProperty("java.class.path"); - if (javaClassPath != null) { - for (String path : javaClassPath.split(File.pathSeparator)) { - try { - urls.add(new File(path).toURI().toURL()); - } catch (Exception e) { - // Ignore for now - // TODO: Add logger - } - } - } - return distinctUrls(urls); - } + /** + * Returns a distinct collection of URLs based on the {@code java.class.path} + * system property. + *

+ * This finds the URLs using the {@code java.class.path} system property. + *

+ * The returned collection of URLs retains the classpath order. + * + * @return the collection of URLs, not null + */ + public static Collection forJavaClassPath() { + Collection urls = new ArrayList<>(); + String javaClassPath = System.getProperty("java.class.path"); + if (javaClassPath != null) { + for (String path : javaClassPath.split(File.pathSeparator)) { + try { + urls.add(new File(path).toURI().toURL()); + } catch (Exception e) { + // Ignore for now + // TODO: Add logger + } + } + } + return distinctUrls(urls); + } - /** - * Returns a distinct collection of URLs based on URLs derived from class - * loaders expanded with Manifest information. - *

- * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that - * defines additional jar files to be included on the classpath. This method - * finds the jar files using the {@link #contextClassLoader()} and - * {@link #staticClassLoader()}, before searching for any additional manifest - * classpaths. - * - * @return the collection of URLs, not null - */ - public static Collection forManifest() { - return forManifest(forClassLoader()); - } + /** + * Returns a distinct collection of URLs based on URLs derived from class + * loaders expanded with Manifest information. + *

+ * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that + * defines additional jar files to be included on the classpath. This method + * finds the jar files using the {@link #contextClassLoader()} and + * {@link #staticClassLoader()}, before searching for any additional manifest + * classpaths. + * + * @return the collection of URLs, not null + */ + public static Collection forManifest() { + return forManifest(forClassLoader()); + } - /** - * Returns a distinct collection of URLs from a single URL based on the Manifest - * information. - *

- * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that - * defines additional jar files to be included on the classpath. This method - * takes a single URL, tries to resolve it as a jar file, and if so, adds any - * additional manifest classpaths. The returned collection of URLs will always - * contain the input URL. - * - * @param url the manifest url - * - * @return the collection of URLs, not null - */ - @SuppressWarnings("resource") - public static Collection forManifest(final URL url) { - final Collection result = new ArrayList<>(); - result.add(url); - try { - final String part = cleanPath(url); - File jarFile = new File(part); - JarFile myJar = new JarFile(part); - URL validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), part); - if (validUrl != null) { - result.add(validUrl); - } - final Manifest manifest = myJar.getManifest(); - if (manifest != null) { - final String classPath = manifest.getMainAttributes().getValue(new Attributes.Name("Class-Path")); - if (classPath != null) { - for (String jar : classPath.split(" ")) { - validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), jar); - if (validUrl != null) { - result.add(validUrl); - } - } - } - } - } catch (IOException e) { - // don't do anything, we're going on the assumption it is a jar, which could be - // wrong - } - return distinctUrls(result); - } + /** + * Returns a distinct collection of URLs from a single URL based on the Manifest + * information. + *

+ * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that + * defines additional jar files to be included on the classpath. This method + * takes a single URL, tries to resolve it as a jar file, and if so, adds any + * additional manifest classpaths. The returned collection of URLs will always + * contain the input URL. + * + * @param url the manifest url + * + * @return the collection of URLs, not null + */ + @SuppressWarnings("resource") + public static Collection forManifest(final URL url) { + final Collection result = new ArrayList<>(); + result.add(url); + try { + final String part = cleanPath(url); + File jarFile = new File(part); + JarFile myJar = new JarFile(part); + URL validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), part); + if (validUrl != null) { + result.add(validUrl); + } + final Manifest manifest = myJar.getManifest(); + if (manifest != null) { + final String classPath = manifest.getMainAttributes().getValue(new Attributes.Name("Class-Path")); + if (classPath != null) { + for (String jar : classPath.split(" ")) { + validUrl = tryToGetValidUrl(jarFile.getPath(), new File(part).getParent(), jar); + if (validUrl != null) { + result.add(validUrl); + } + } + } + } + } catch (IOException e) { + // don't do anything, we're going on the assumption it is a jar, which could be + // wrong + } + return distinctUrls(result); + } - /** - * Returns a distinct collection of URLs by expanding the specified URLs with - * Manifest information. - *

- * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that - * defines additional jar files to be included on the classpath. This method - * takes each URL in turn, tries to resolve it as a jar file, and if so, adds - * any additional manifest classpaths. The returned collection of URLs will - * always contain all the input URLs. - *

- * The returned URLs retains the input order. - * - * @param urls the manifest urls - * - * @return the collection of URLs, not null - */ - public static Collection forManifest(final Iterable urls) { - Collection result = new ArrayList<>(); - // determine if any of the URLs are JARs, and get any dependencies - for (URL url : urls) { - result.addAll(forManifest(url)); - } - return distinctUrls(result); - } + /** + * Returns a distinct collection of URLs by expanding the specified URLs with + * Manifest information. + *

+ * The {@code MANIFEST.MF} file can contain a {@code Class-Path} entry that + * defines additional jar files to be included on the classpath. This method + * takes each URL in turn, tries to resolve it as a jar file, and if so, adds + * any additional manifest classpaths. The returned collection of URLs will + * always contain all the input URLs. + *

+ * The returned URLs retains the input order. + * + * @param urls the manifest urls + * + * @return the collection of URLs, not null + */ + public static Collection forManifest(final Iterable urls) { + Collection result = new ArrayList<>(); + // determine if any of the URLs are JARs, and get any dependencies + for (URL url : urls) { + result.addAll(forManifest(url)); + } + return distinctUrls(result); + } - // a little bit cryptic... - static URL tryToGetValidUrl(String workingDir, String path, String filename) { - try { - if (new File(filename).exists()) - return new File(filename).toURI().toURL(); - if (new File(path + File.separator + filename).exists()) - return new File(path + File.separator + filename).toURI().toURL(); - if (new File(workingDir + File.separator + filename).exists()) - return new File(workingDir + File.separator + filename).toURI().toURL(); - if (new File(new URL(filename).getFile()).exists()) - return new File(new URL(filename).getFile()).toURI().toURL(); - } catch (MalformedURLException e) { - // don't do anything, we're going on the assumption it is a jar, which could be - // wrong - } - return null; - } + // a little bit cryptic... + static URL tryToGetValidUrl(String workingDir, String path, String filename) { + try { + if (new File(filename).exists()) { + return new File(filename).toURI().toURL(); + } + if (new File(path + File.separator + filename).exists()) { + return new File(path + File.separator + filename).toURI().toURL(); + } + if (new File(workingDir + File.separator + filename).exists()) { + return new File(workingDir + File.separator + filename).toURI().toURL(); + } + if (new File(new URL(filename).getFile()).exists()) { + return new File(new URL(filename).getFile()).toURI().toURL(); + } + } catch (MalformedURLException e) { + // don't do anything, we're going on the assumption it is a jar, which could be + // wrong + } + return null; + } - /** - * Cleans the URL. - * - * @param url the URL to clean, not null - * @return the path, not null - */ - public static String cleanPath(final URL url) { - String path = url.getPath(); - try { - path = URLDecoder.decode(path, "UTF-8"); - } catch (UnsupportedEncodingException e) { - /**/ } - if (path.startsWith("jar:")) { - path = path.substring("jar:".length()); - } - if (path.startsWith("file:")) { - path = path.substring("file:".length()); - } - if (path.endsWith("!/")) { - path = path.substring(0, path.lastIndexOf("!/")) + "/"; - } - return path; - } + /** + * Cleans the URL. + * + * @param url the URL to clean, not null + * @return the path, not null + */ + public static String cleanPath(final URL url) { + String path = url.getPath(); + try { + path = URLDecoder.decode(path, "UTF-8"); + } catch (UnsupportedEncodingException e) { + /**/ } + if (path.startsWith("jar:")) { + path = path.substring("jar:".length()); + } + if (path.startsWith("file:")) { + path = path.substring("file:".length()); + } + if (path.endsWith("!/")) { + path = path.substring(0, path.lastIndexOf("!/")) + "/"; + } + return path; + } - private static String resourceName(String name) { - if (name != null) { - String resourceName = name.replace(".", "/"); - resourceName = resourceName.replace("\\", "/"); - if (resourceName.startsWith("/")) { - resourceName = resourceName.substring(1); - } - return resourceName; - } - return null; - } + private static String resourceName(String name) { + if (name != null) { + String resourceName = name.replace(".", "/"); + resourceName = resourceName.replace("\\", "/"); + if (resourceName.startsWith("/")) { + resourceName = resourceName.substring(1); + } + return resourceName; + } + return null; + } - // http://michaelscharf.blogspot.co.il/2006/11/javaneturlequals-and-hashcode-make.html - private static Collection distinctUrls(Collection urls) { - Map distinct = new LinkedHashMap<>(urls.size()); - for (URL url : urls) { - distinct.put(url.toExternalForm(), url); - } - return distinct.values(); - } + // http://michaelscharf.blogspot.co.il/2006/11/javaneturlequals-and-hashcode-make.html + private static Collection distinctUrls(Collection urls) { + Map distinct = new LinkedHashMap<>(urls.size()); + for (URL url : urls) { + distinct.put(url.toExternalForm(), url); + } + return distinct.values(); + } } \ No newline at end of file diff --git a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionTools.java b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionTools.java index 4521343..b6d277a 100644 --- a/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionTools.java +++ b/reflection/src/main/java/com/syntaxphoenix/syntaxapi/reflection/ReflectionTools.java @@ -11,102 +11,105 @@ public class ReflectionTools { - public static Object getValue(Field field, Object source) { - if (field != null) { - boolean access = field.isAccessible(); - if (!access) { - field.setAccessible(true); - } - Object output = null; - try { - output = field.get(source); - } catch (IllegalArgumentException | IllegalAccessException e) { - if (!access) { - field.setAccessible(access); - } - e.printStackTrace(); - } - if (!access) { - field.setAccessible(access); - } - return output; - } - return null; - } + public static Object getValue(Field field, Object source) { + if (field != null) { + boolean access = field.isAccessible(); + if (!access) { + field.setAccessible(true); + } + Object output = null; + try { + output = field.get(source); + } catch (IllegalArgumentException | IllegalAccessException e) { + if (!access) { + field.setAccessible(access); + } + e.printStackTrace(); + } + if (!access) { + field.setAccessible(access); + } + return output; + } + return null; + } - public static Object getValue(Field field) { - return getValue(field, null); - } + public static Object getValue(Field field) { + return getValue(field, null); + } - public static boolean hasSameArguments(Class[] compare1, Class[] compare2) { - if (compare1.length == 0 && compare2.length == 0) { - return true; - } else if (compare1.length != compare2.length) { - return false; - } - for (Class arg1 : compare1) { - boolean found = true; - for (Class arg2 : compare2) { - if (!arg1.isAssignableFrom(arg2)) { - found = false; - break; - } - } - if (!found) { - return false; - } - } - return true; - } + public static boolean hasSameArguments(Class[] compare1, Class[] compare2) { + if (compare1.length == 0 && compare2.length == 0) { + return true; + } else if (compare1.length != compare2.length) { + return false; + } + for (Class arg1 : compare1) { + boolean found = true; + for (Class arg2 : compare2) { + if (!arg1.isAssignableFrom(arg2)) { + found = false; + break; + } + } + if (!found) { + return false; + } + } + return true; + } - /* - * - */ + /* + * + */ - public static File[] getUrlAsFiles(Collection collection) throws URISyntaxException { - if (collection.isEmpty()) - return new File[0]; - ArrayList files = new ArrayList<>(); - for (URL url : collection) - files.add(new File(url.toURI().getPath())); - return files.toArray(new File[0]); - } + public static File[] getUrlAsFiles(Collection collection) throws URISyntaxException { + if (collection.isEmpty()) { + return new File[0]; + } + ArrayList files = new ArrayList<>(); + for (URL url : collection) { + files.add(new File(url.toURI().getPath())); + } + return files.toArray(new File[0]); + } - /* - * - */ + /* + * + */ - public static Object execute(Object source, Method method, Object... arguments) { - if (method != null) { - boolean access; - if (!(access = method.isAccessible())) { - method.setAccessible(true); - } - try { - return method.invoke(source, arguments); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - if (!access) { - method.setAccessible(access); - } - e.printStackTrace(); - } - if (!access) { - method.setAccessible(access); - } - } - return null; - } + public static Object execute(Object source, Method method, Object... arguments) { + if (method != null) { + boolean access; + if (!(access = method.isAccessible())) { + method.setAccessible(true); + } + try { + return method.invoke(source, arguments); + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + if (!access) { + method.setAccessible(access); + } + e.printStackTrace(); + } + if (!access) { + method.setAccessible(access); + } + } + return null; + } - public static int countSuperTypesTill(Class type, Class superType) { - int count = 0; - Class currentType = type; - while (!superType.equals(currentType)) { - currentType = currentType.getSuperclass(); - count++; - if (currentType == null) - break; - } - return count; - } + public static int countSuperTypesTill(Class type, Class superType) { + int count = 0; + Class currentType = type; + while (!superType.equals(currentType)) { + currentType = currentType.getSuperclass(); + count++; + if (currentType == null) { + break; + } + } + return count; + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IService.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IService.java index 8f0d8a5..8d0cc5b 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IService.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IService.java @@ -4,12 +4,12 @@ public interface IService { - public default Class getOwner() { - return getClass(); - } + public default Class getOwner() { + return getClass(); + } - public String getId(); + public String getId(); - public Status execute(ServiceManager manager); + public Status execute(ServiceManager manager); } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IServiceValue.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IServiceValue.java index d376555..92da9d3 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IServiceValue.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/IServiceValue.java @@ -6,38 +6,40 @@ public interface IServiceValue { - public ValueType getType(); + public ValueType getType(); - public default boolean isMethod() { - return getType() == ValueType.METHOD; - } + public default boolean isMethod() { + return getType() == ValueType.METHOD; + } - public default boolean isField() { - return getType() == ValueType.FIELD; - } + public default boolean isField() { + return getType() == ValueType.FIELD; + } - public default Method asMethod() { - if (isMethod()) - return (Method) getObject(); - return null; - } + public default Method asMethod() { + if (isMethod()) { + return (Method) getObject(); + } + return null; + } - public default Field asField() { - if (isField()) - return (Field) getObject(); - return null; - } + public default Field asField() { + if (isField()) { + return (Field) getObject(); + } + return null; + } - public AccessibleObject getObject(); + public AccessibleObject getObject(); - public SubscribeService getAnnotation(); + public SubscribeService getAnnotation(); - public ServicePriority getPriority(); + public ServicePriority getPriority(); - public Class getService(); + public Class getService(); - public Object getOwnerInstance(); + public Object getOwnerInstance(); - public Class getOwner(); + public Class getOwner(); } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceAnalyser.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceAnalyser.java index e69de16..4a0dd0a 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceAnalyser.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceAnalyser.java @@ -7,50 +7,57 @@ public class ServiceAnalyser { - static ArrayList findFields(boolean flag, Class clazz) { - ArrayList output = new ArrayList<>(); + static ArrayList findFields(boolean flag, Class clazz) { + ArrayList output = new ArrayList<>(); - Field[] fields = clazz.getFields(); - if (fields.length == 0) - return output; + Field[] fields = clazz.getFields(); + if (fields.length == 0) { + return output; + } - for (Field field : fields) { - if (field.getAnnotation(SubscribeService.class) == null) - continue; + for (Field field : fields) { + if (field.getAnnotation(SubscribeService.class) == null) { + continue; + } - boolean static0 = Modifier.isStatic(field.getModifiers()); - if (flag ? !static0 : static0) - continue; + boolean static0 = Modifier.isStatic(field.getModifiers()); + if (flag ? !static0 : static0) { + continue; + } - output.add(field); - } + output.add(field); + } - return output; - } + return output; + } - static ArrayList findMethods(boolean flag, Class clazz) { - ArrayList output = new ArrayList<>(); + static ArrayList findMethods(boolean flag, Class clazz) { + ArrayList output = new ArrayList<>(); - Method[] methods = clazz.getMethods(); - if (methods.length == 0) - return output; + Method[] methods = clazz.getMethods(); + if (methods.length == 0) { + return output; + } - for (Method method : methods) { + for (Method method : methods) { - if (method.getParameterCount() != 0) - continue; + if (method.getParameterCount() != 0) { + continue; + } - if (method.getAnnotation(SubscribeService.class) == null) - continue; + if (method.getAnnotation(SubscribeService.class) == null) { + continue; + } - boolean static0 = Modifier.isStatic(method.getModifiers()); - if (flag ? !static0 : static0) - continue; + boolean static0 = Modifier.isStatic(method.getModifiers()); + if (flag ? !static0 : static0) { + continue; + } - output.add(method); - } + output.add(method); + } - return output; - } + return output; + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceContainer.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceContainer.java index 4cbbbce..b642a3b 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceContainer.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceContainer.java @@ -9,65 +9,67 @@ public class ServiceContainer { - private final ArrayList subscribed = new ArrayList<>(); - private final Object owner; - - ServiceContainer(Object owner) { - this.owner = owner; - } - - /* - * - */ - - public Object getOwner() { - return owner; - } - - /* - * - */ - - boolean isEmpty() { - return subscribed.isEmpty(); - } - - boolean add(IServiceValue value) { - return subscribed.add(value); - } - - /* - * - */ - - public IServiceValue[] getValues(Class service) { - return filter(value -> value.getService().equals(service)).toArray(size -> new IServiceValue[size]); - } - - public ServiceFieldValue getValue(Field field) { - Optional option = filter(value -> { - if (!value.isField()) - return false; - return value.asField().equals(field); - }).findAny(); - return option.isPresent() ? (ServiceFieldValue) option.get() : null; - } - - public ServiceMethodValue getValue(Method method) { - Optional option = filter(value -> { - if (!value.isMethod()) - return false; - return value.asMethod().equals(method); - }).findAny(); - return option.isPresent() ? (ServiceMethodValue) option.get() : null; - } - - /* - * - */ - - private Stream filter(Predicate predicate) { - return subscribed.stream().filter(predicate); - } + private final ArrayList subscribed = new ArrayList<>(); + private final Object owner; + + ServiceContainer(Object owner) { + this.owner = owner; + } + + /* + * + */ + + public Object getOwner() { + return owner; + } + + /* + * + */ + + boolean isEmpty() { + return subscribed.isEmpty(); + } + + boolean add(IServiceValue value) { + return subscribed.add(value); + } + + /* + * + */ + + public IServiceValue[] getValues(Class service) { + return filter(value -> value.getService().equals(service)).toArray(size -> new IServiceValue[size]); + } + + public ServiceFieldValue getValue(Field field) { + Optional option = filter(value -> { + if (!value.isField()) { + return false; + } + return value.asField().equals(field); + }).findAny(); + return option.isPresent() ? (ServiceFieldValue) option.get() : null; + } + + public ServiceMethodValue getValue(Method method) { + Optional option = filter(value -> { + if (!value.isMethod()) { + return false; + } + return value.asMethod().equals(method); + }).findAny(); + return option.isPresent() ? (ServiceMethodValue) option.get() : null; + } + + /* + * + */ + + private Stream filter(Predicate predicate) { + return subscribed.stream().filter(predicate); + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceFieldValue.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceFieldValue.java index ae81270..1e9eb74 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceFieldValue.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceFieldValue.java @@ -4,70 +4,70 @@ public class ServiceFieldValue implements IServiceValue { - private final Object instance; - private final Class owner; - - private final Field field; - private final SubscribeService annotation; - - public ServiceFieldValue(Class owner, Field field) { - this(owner, field, null); - } - - public ServiceFieldValue(Class owner, Field field, Object instance) { - this.owner = owner; - this.instance = instance; - - this.field = field; - this.annotation = field.getAnnotation(SubscribeService.class); - } - - /* - * - */ - - @Override - public Class getOwner() { - return owner; - } - - @Override - public Object getOwnerInstance() { - return instance; - } - - /* - * - */ - - @Override - public ValueType getType() { - return ValueType.FIELD; - } - - @Override - public Field asField() { - return field; - } - - @Override - public Field getObject() { - return field; - } - - @Override - public SubscribeService getAnnotation() { - return annotation; - } - - @Override - public ServicePriority getPriority() { - return annotation.priority(); - } - - @Override - public Class getService() { - return annotation.service(); - } + private final Object instance; + private final Class owner; + + private final Field field; + private final SubscribeService annotation; + + public ServiceFieldValue(Class owner, Field field) { + this(owner, field, null); + } + + public ServiceFieldValue(Class owner, Field field, Object instance) { + this.owner = owner; + this.instance = instance; + + this.field = field; + this.annotation = field.getAnnotation(SubscribeService.class); + } + + /* + * + */ + + @Override + public Class getOwner() { + return owner; + } + + @Override + public Object getOwnerInstance() { + return instance; + } + + /* + * + */ + + @Override + public ValueType getType() { + return ValueType.FIELD; + } + + @Override + public Field asField() { + return field; + } + + @Override + public Field getObject() { + return field; + } + + @Override + public SubscribeService getAnnotation() { + return annotation; + } + + @Override + public ServicePriority getPriority() { + return annotation.priority(); + } + + @Override + public Class getService() { + return annotation.service(); + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceManager.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceManager.java index 670e6ac..03abc42 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceManager.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceManager.java @@ -14,201 +14,211 @@ public class ServiceManager { - private final LinkedList containers = new LinkedList<>(); - private final LinkedList services = new LinkedList<>(); - private ILogger logger; - - public ServiceManager() { - this(null); - } - - public ServiceManager(ILogger logger) { - this.logger = logger; - } - - /* - * Logger - */ - - public ILogger getLogger() { - return logger; - } - - public boolean hasLogger() { - return logger != null; - } - - public ServiceManager setLogger(ILogger logger) { - this.logger = logger; - return this; - } - - /* - * Service Handling - */ - - public boolean register(IService service) { - if (isRegistered(service)) - return false; - return services.add(service); - } - - public boolean isRegistered(IService service) { - return isRegistered(service.getId()); - } - - public boolean isRegistered(String id) { - return services.stream().anyMatch(service -> service.getId().equals(id)); - } - - public IService getService(String id) { - Optional option = findService(id); - return option.isPresent() ? option.get() : null; - } - - public List getServices() { - return services.stream().collect(Collectors.toList()); - } - - public Optional findService(String id) { - return services.stream().filter(service -> service.getId().equals(id)).findAny(); - } - - public boolean unregister(IService service) { - return unregister(service.getId()); - } - - public boolean unregister(String id) { - Optional option = findService(id); - if (!option.isPresent()) - return false; - return services.remove(option.get()); - } - - /* - * Execution - */ - - public Status run(String id) { - Optional option = findService(id); - if (option.isPresent()) - return run(option.get()); - return Status.EMPTY; - } - - public Status run(IService service) { - return service.execute(this); - } - - /* - * Subscription - */ - - // subscribe - - public void subscribe(Object object) { - boolean flag = object instanceof Class; - Class clazz = flag ? (Class) object : object.getClass(); - ArrayList fields = ServiceAnalyser.findFields(flag, clazz); - ArrayList methods = ServiceAnalyser.findMethods(flag, clazz); - - if (hasLogger()) { - if (logger.getState().extendedInfo()) { - logger.log("Searching for Subscribtions in " + clazz + " (" + (flag ? "static" : "non-static") + ')'); - logger.log("Found " + fields.size() + " Fields"); - logger.log("Found " + methods.size() + " Methods"); - } - } - - ServiceContainer container = new ServiceContainer(object); - if (!fields.isEmpty()) - for (Field field : fields) - container.add(flag ? new ServiceFieldValue(clazz, field) : new ServiceFieldValue(clazz, field, object)); - - if (!methods.isEmpty()) - for (Method method : methods) - container.add(flag ? new ServiceMethodValue(clazz, method) : new ServiceMethodValue(clazz, method, object)); - - if (container.isEmpty()) - return; - containers.add(container); - } - - // Unsubscribe - - public void unsubscribe(ServiceContainer container) { - if (containers.isEmpty()) - return; - containers.remove(container); - } - - public void unsubscribe(Object object) { - ServiceContainer[] containers = this.containers - .stream() - .filter(container -> container.getOwner().equals(object)) - .toArray(size -> new ServiceContainer[size]); - if (containers.length == 0) - return; - for (ServiceContainer container : containers) { - this.containers.remove(container); - } - } - - public void unsubscribe(Class clazz) { - ServiceContainer[] containers = this.containers - .stream() - .filter(container -> container.getOwner().getClass() == clazz) - .toArray(size -> new ServiceContainer[size]); - if (containers.length == 0) - return; - for (ServiceContainer container : containers) { - this.containers.remove(container); - } - } - - // ServiceContainer Getter - - public List getContainers() { - return containers.stream().collect(Collectors.toList()); - } - - // Subscription Getter - - public IServiceValue[] getSubscriptions(String id) { - Optional service = findService(id); - return service.isPresent() ? getSubscriptions(service.get()) : new IServiceValue[0]; - } - - public IServiceValue[] getSubscriptions(IService service) { - return getSubscriptions(service.getOwner()); - } - - public IServiceValue[] getSubscriptions(Class service) { - if (containers.isEmpty()) - return new IServiceValue[0]; - - ArrayList services = new ArrayList<>(); - for (ServiceContainer container : containers) - services.addAll(Arrays.asList(container.getValues(service))); - - return services.toArray(new IServiceValue[0]); - } - - public IServiceValue[] getSubscriptions(String id, ValueType type) { - Optional service = findService(id); - return service.isPresent() ? getSubscriptions(service.get(), type) : new IServiceValue[0]; - } - - public IServiceValue[] getSubscriptions(IService service, ValueType type) { - return getSubscriptions(service.getOwner(), type); - } - - public IServiceValue[] getSubscriptions(Class service, ValueType type) { - IServiceValue[] valueArray = getSubscriptions(service); - if (valueArray.length == 0) - return valueArray; - List values = Arrays.asList(valueArray); - return values.stream().filter(value -> value.getType() == type).toArray(size -> new IServiceValue[size]); - } + private final LinkedList containers = new LinkedList<>(); + private final LinkedList services = new LinkedList<>(); + private ILogger logger; + + public ServiceManager() { + this(null); + } + + public ServiceManager(ILogger logger) { + this.logger = logger; + } + + /* + * Logger + */ + + public ILogger getLogger() { + return logger; + } + + public boolean hasLogger() { + return logger != null; + } + + public ServiceManager setLogger(ILogger logger) { + this.logger = logger; + return this; + } + + /* + * Service Handling + */ + + public boolean register(IService service) { + if (isRegistered(service)) { + return false; + } + return services.add(service); + } + + public boolean isRegistered(IService service) { + return isRegistered(service.getId()); + } + + public boolean isRegistered(String id) { + return services.stream().anyMatch(service -> service.getId().equals(id)); + } + + public IService getService(String id) { + Optional option = findService(id); + return option.isPresent() ? option.get() : null; + } + + public List getServices() { + return services.stream().collect(Collectors.toList()); + } + + public Optional findService(String id) { + return services.stream().filter(service -> service.getId().equals(id)).findAny(); + } + + public boolean unregister(IService service) { + return unregister(service.getId()); + } + + public boolean unregister(String id) { + Optional option = findService(id); + if (!option.isPresent()) { + return false; + } + return services.remove(option.get()); + } + + /* + * Execution + */ + + public Status run(String id) { + Optional option = findService(id); + if (option.isPresent()) { + return run(option.get()); + } + return Status.EMPTY; + } + + public Status run(IService service) { + return service.execute(this); + } + + /* + * Subscription + */ + + // subscribe + + public void subscribe(Object object) { + boolean flag = object instanceof Class; + Class clazz = flag ? (Class) object : object.getClass(); + ArrayList fields = ServiceAnalyser.findFields(flag, clazz); + ArrayList methods = ServiceAnalyser.findMethods(flag, clazz); + + if (hasLogger()) { + if (logger.getState().extendedInfo()) { + logger.log("Searching for Subscribtions in " + clazz + " (" + (flag ? "static" : "non-static") + ')'); + logger.log("Found " + fields.size() + " Fields"); + logger.log("Found " + methods.size() + " Methods"); + } + } + + ServiceContainer container = new ServiceContainer(object); + if (!fields.isEmpty()) { + for (Field field : fields) { + container.add(flag ? new ServiceFieldValue(clazz, field) : new ServiceFieldValue(clazz, field, object)); + } + } + + if (!methods.isEmpty()) { + for (Method method : methods) { + container.add(flag ? new ServiceMethodValue(clazz, method) : new ServiceMethodValue(clazz, method, object)); + } + } + + if (container.isEmpty()) { + return; + } + containers.add(container); + } + + // Unsubscribe + + public void unsubscribe(ServiceContainer container) { + if (containers.isEmpty()) { + return; + } + containers.remove(container); + } + + public void unsubscribe(Object object) { + ServiceContainer[] containers = this.containers.stream().filter(container -> container.getOwner().equals(object)) + .toArray(size -> new ServiceContainer[size]); + if (containers.length == 0) { + return; + } + for (ServiceContainer container : containers) { + this.containers.remove(container); + } + } + + public void unsubscribe(Class clazz) { + ServiceContainer[] containers = this.containers.stream().filter(container -> container.getOwner().getClass() == clazz) + .toArray(size -> new ServiceContainer[size]); + if (containers.length == 0) { + return; + } + for (ServiceContainer container : containers) { + this.containers.remove(container); + } + } + + // ServiceContainer Getter + + public List getContainers() { + return containers.stream().collect(Collectors.toList()); + } + + // Subscription Getter + + public IServiceValue[] getSubscriptions(String id) { + Optional service = findService(id); + return service.isPresent() ? getSubscriptions(service.get()) : new IServiceValue[0]; + } + + public IServiceValue[] getSubscriptions(IService service) { + return getSubscriptions(service.getOwner()); + } + + public IServiceValue[] getSubscriptions(Class service) { + if (containers.isEmpty()) { + return new IServiceValue[0]; + } + + ArrayList services = new ArrayList<>(); + for (ServiceContainer container : containers) { + services.addAll(Arrays.asList(container.getValues(service))); + } + + return services.toArray(new IServiceValue[0]); + } + + public IServiceValue[] getSubscriptions(String id, ValueType type) { + Optional service = findService(id); + return service.isPresent() ? getSubscriptions(service.get(), type) : new IServiceValue[0]; + } + + public IServiceValue[] getSubscriptions(IService service, ValueType type) { + return getSubscriptions(service.getOwner(), type); + } + + public IServiceValue[] getSubscriptions(Class service, ValueType type) { + IServiceValue[] valueArray = getSubscriptions(service); + if (valueArray.length == 0) { + return valueArray; + } + List values = Arrays.asList(valueArray); + return values.stream().filter(value -> value.getType() == type).toArray(size -> new IServiceValue[size]); + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceMethodValue.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceMethodValue.java index f9b49ce..3e49b07 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceMethodValue.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServiceMethodValue.java @@ -4,70 +4,70 @@ public class ServiceMethodValue implements IServiceValue { - private final Object instance; - private final Class owner; - - private final Method method; - private final SubscribeService annotation; - - public ServiceMethodValue(Class owner, Method method) { - this(owner, method, null); - } - - public ServiceMethodValue(Class owner, Method method, Object instance) { - this.owner = owner; - this.instance = instance; - - this.method = method; - this.annotation = method.getAnnotation(SubscribeService.class); - } - - /* - * - */ - - @Override - public Class getOwner() { - return owner; - } - - @Override - public Object getOwnerInstance() { - return instance; - } - - /* - * - */ - - @Override - public ValueType getType() { - return ValueType.METHOD; - } - - @Override - public Method asMethod() { - return method; - } - - @Override - public Method getObject() { - return method; - } - - @Override - public SubscribeService getAnnotation() { - return annotation; - } - - @Override - public ServicePriority getPriority() { - return annotation.priority(); - } - - @Override - public Class getService() { - return annotation.service(); - } + private final Object instance; + private final Class owner; + + private final Method method; + private final SubscribeService annotation; + + public ServiceMethodValue(Class owner, Method method) { + this(owner, method, null); + } + + public ServiceMethodValue(Class owner, Method method, Object instance) { + this.owner = owner; + this.instance = instance; + + this.method = method; + this.annotation = method.getAnnotation(SubscribeService.class); + } + + /* + * + */ + + @Override + public Class getOwner() { + return owner; + } + + @Override + public Object getOwnerInstance() { + return instance; + } + + /* + * + */ + + @Override + public ValueType getType() { + return ValueType.METHOD; + } + + @Override + public Method asMethod() { + return method; + } + + @Override + public Method getObject() { + return method; + } + + @Override + public SubscribeService getAnnotation() { + return annotation; + } + + @Override + public ServicePriority getPriority() { + return annotation.priority(); + } + + @Override + public Class getService() { + return annotation.service(); + } } \ No newline at end of file diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServicePriority.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServicePriority.java index 7cdc435..86d3c04 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServicePriority.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ServicePriority.java @@ -6,30 +6,31 @@ public enum ServicePriority { - LOWEST(-2), - LOW(-1), - NORMAL(0), - HIGH(1), - HIGHEST(2); + LOWEST(-2), + LOW(-1), + NORMAL(0), + HIGH(1), + HIGHEST(2); - /* - * - */ + /* + * + */ - public static final List ORDERED_VALUES = Collections.unmodifiableList(Arrays.asList(HIGHEST, HIGH, NORMAL, LOW, LOWEST)); + public static final List ORDERED_VALUES = Collections + .unmodifiableList(Arrays.asList(HIGHEST, HIGH, NORMAL, LOW, LOWEST)); - /* - * - */ + /* + * + */ - private int priority; + private int priority; - private ServicePriority(int priority) { - this.priority = priority; - } + private ServicePriority(int priority) { + this.priority = priority; + } - public int priority() { - return priority; - } + public int priority() { + return priority; + } } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/SubscribeService.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/SubscribeService.java index 7aebec8..f049200 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/SubscribeService.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/SubscribeService.java @@ -5,22 +5,21 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; - import java.lang.annotation.Target; @Retention(RUNTIME) @Target({ - FIELD, - METHOD + FIELD, + METHOD }) public @interface SubscribeService { - public Class service(); + public Class service(); - public ServicePriority priority() default ServicePriority.NORMAL; + public ServicePriority priority() default ServicePriority.NORMAL; - public boolean returnsObject() default false; + public boolean returnsObject() default false; - public Class returnType() default Object.class; + public Class returnType() default Object.class; } diff --git a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ValueType.java b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ValueType.java index 1e63aea..3f727f0 100644 --- a/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ValueType.java +++ b/service/service-base/src/main/java/com/syntaxphoenix/syntaxapi/service/ValueType.java @@ -2,7 +2,7 @@ public enum ValueType { - FIELD, - METHOD; + FIELD, + METHOD; } diff --git a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DisconnectReason.java b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DisconnectReason.java index b0d52b4..4b0553c 100644 --- a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DisconnectReason.java +++ b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DisconnectReason.java @@ -2,8 +2,8 @@ public enum DisconnectReason { - TIMEOUT, - ABORTED, - DEFAULT; + TIMEOUT, + ABORTED, + DEFAULT; } diff --git a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/Download.java b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/Download.java index b83c966..acda0fa 100644 --- a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/Download.java +++ b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/Download.java @@ -5,73 +5,75 @@ public class Download { - private final String host; - private final HashMap paths = new HashMap<>(); - private final ArrayList listeners = new ArrayList<>(); - - private int timeout = 30; - - public Download(String host) { - this.host = host; - } - - /* - * - */ - - public void add(String path, String location) { - if (!paths.containsKey(path)) - paths.put(path, location); - } - - public void set(String path, String location) { - paths.put(path, location); - } - - public void remove(String path) { - paths.remove(path); - } - - /* - * - */ - - public void addListener(DownloadListener listener) { - if (listeners.contains(listener)) - return; - listeners.add(listener); - } - - public void removeListener(DownloadListener listener) { - listeners.remove(listener); - } - - public ArrayList getListeners() { - return listeners; - } - - /* - * - */ - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public int getTimeout() { - return timeout; - } - - /* - * - */ - - public String getHost() { - return host; - } - - public HashMap getPaths() { - return paths; - } + private final String host; + private final HashMap paths = new HashMap<>(); + private final ArrayList listeners = new ArrayList<>(); + + private int timeout = 30; + + public Download(String host) { + this.host = host; + } + + /* + * + */ + + public void add(String path, String location) { + if (!paths.containsKey(path)) { + paths.put(path, location); + } + } + + public void set(String path, String location) { + paths.put(path, location); + } + + public void remove(String path) { + paths.remove(path); + } + + /* + * + */ + + public void addListener(DownloadListener listener) { + if (listeners.contains(listener)) { + return; + } + listeners.add(listener); + } + + public void removeListener(DownloadListener listener) { + listeners.remove(listener); + } + + public ArrayList getListeners() { + return listeners; + } + + /* + * + */ + + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + public int getTimeout() { + return timeout; + } + + /* + * + */ + + public String getHost() { + return host; + } + + public HashMap getPaths() { + return paths; + } } diff --git a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadListener.java b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadListener.java index ee5f2f4..69e2566 100644 --- a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadListener.java +++ b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadListener.java @@ -2,19 +2,14 @@ public interface DownloadListener { - public default void onConnect(Download download) { - } + public default void onConnect(Download download) {} - public default void onDisconnect(Download download, DisconnectReason reason) { - } + public default void onDisconnect(Download download, DisconnectReason reason) {} - public default void onStart(Download download, String path, String location) { - } + public default void onStart(Download download, String path, String location) {} - public default void onFail(Download download, String path, String location) { - } + public default void onFail(Download download, String path, String location) {} - public default void onSuccess(Download download, String path, String location) { - } + public default void onSuccess(Download download, String path, String location) {} } diff --git a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadService.java b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadService.java index 1e8984b..e6a3ef0 100644 --- a/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadService.java +++ b/service/service-download/src/main/java/com/syntaxphoenix/syntaxapi/service/download/DownloadService.java @@ -25,203 +25,215 @@ public class DownloadService implements IService { - private final ExecutorService executor; + private final ExecutorService executor; - public DownloadService() { - this.executor = Executors.newSingleThreadExecutor(); - } + public DownloadService() { + this.executor = Executors.newSingleThreadExecutor(); + } - public DownloadService(ExecutorService executor) { - this.executor = executor; - } + public DownloadService(ExecutorService executor) { + this.executor = executor; + } - /* - * - */ + /* + * + */ - @Override - public String getId() { - return "download"; - } + @Override + public String getId() { + return "download"; + } + + @Override + public Status execute(ServiceManager services) { + + Status status = Status.create(); + + executor.submit(() -> { + + IServiceValue[] subscriptions = services.getSubscriptions(getOwner(), ValueType.METHOD); + + if (services.hasLogger()) { + ILogger logger = services.getLogger(); + if (logger.getState().extendedInfo()) { + logger.log("Found " + subscriptions.length + " Subscriptions"); + } + } + + for (IServiceValue subscription : subscriptions) { + + SubscribeService annotation = subscription.getAnnotation(); + + try { + + if (!annotation.returnsObject()) { + status.add(); + status.skip(); + ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); + continue; + } + + if (!annotation.returnType().isAssignableFrom(Download.class)) { + status.add(); + status.skip(); + ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); + continue; + } - @Override - public Status execute(ServiceManager services) { + Download download = (Download) ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); + List listeners = download.getListeners(); - Status status = Status.create(); - - executor.submit(() -> { + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onConnect(download)); + } - IServiceValue[] subscriptions = services.getSubscriptions(getOwner(), ValueType.METHOD); + int timeout = download.getTimeout(); - if (services.hasLogger()) { - ILogger logger = services.getLogger(); - if (logger.getState().extendedInfo()) - logger.log("Found " + subscriptions.length + " Subscriptions"); - } - - for (IServiceValue subscription : subscriptions) { - - SubscribeService annotation = subscription.getAnnotation(); + String host = download.getHost(); + HashMap paths = download.getPaths(); - try { + if (paths.isEmpty()) { + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.ABORTED)); + } + continue; + } - if (!annotation.returnsObject()) { - status.add(); - status.skip(); - ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); - continue; - } + status.add(paths.size()); - if (!annotation.returnType().isAssignableFrom(Download.class)) { - status.add(); - status.skip(); - ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); - continue; - } + URL url = new URL(host); - Download download = (Download) ReflectionTools.execute(subscription.getOwnerInstance(), subscription.asMethod()); - List listeners = download.getListeners(); + URLConnection connection = url.openConnection(); - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onConnect(download)); + if (connection instanceof HttpURLConnection) { + HttpURLConnection http = (HttpURLConnection) connection; - int timeout = download.getTimeout(); + http.setReadTimeout(15000); + http.setConnectTimeout(10000); + http.setRequestMethod("GET"); - String host = download.getHost(); - HashMap paths = download.getPaths(); + int code = http.getResponseCode(); - if (paths.isEmpty()) { - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.ABORTED)); - continue; - } + if (code != 200) { + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.TIMEOUT)); + } + while (status.failed()) { + ; + } + if (services.hasLogger()) { + ILogger logger = services.getLogger(); + if (logger.getState().extendedInfo()) { + logger.log("Failed to connect to '" + host + "'!"); + } + } + continue; + } + } - status.add(paths.size()); + Set> entries = paths.entrySet(); - URL url = new URL(host); + Throwable throwable; + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.DEFAULT)); + } + for (Entry entry : entries) { + if ((throwable = download(host, entry.getKey(), entry.getValue(), timeout)) == null) { + status.success(); + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onSuccess(download, entry.getKey(), entry.getValue())); + } + } else { + status.failed(); - URLConnection connection = url.openConnection(); + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onFail(download, entry.getKey(), entry.getValue())); + } - if (connection instanceof HttpURLConnection) { - HttpURLConnection http = (HttpURLConnection) connection; + if (services.hasLogger()) { + services.getLogger().log(new DownloadFailedException("Failed to download file from host (" + host + + ") with path (" + entry.getKey() + ") to '" + entry.getValue() + "'", throwable)); + } + } + } - http.setReadTimeout(15000); - http.setConnectTimeout(10000); - http.setRequestMethod("GET"); + if (!listeners.isEmpty()) { + listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.DEFAULT)); + } - int code = http.getResponseCode(); + } catch (Throwable throwable) { + while (status.failed()) { + ; + } + if (services.hasLogger()) { + services.getLogger().log(new DownloadFailedException(throwable)); + } + } - if (code != 200) { - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.TIMEOUT)); - while (status.failed()) - ; - if (services.hasLogger()) { - ILogger logger = services.getLogger(); - if (logger.getState().extendedInfo()) - logger.log("Failed to connect to '" + host + "'!"); - } - continue; - } - } + } - Set> entries = paths.entrySet(); + status.done(); - Throwable throwable; - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.DEFAULT)); - for (Entry entry : entries) { - if ((throwable = download(host, entry.getKey(), entry.getValue(), timeout)) == null) { - status.success(); - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onSuccess(download, entry.getKey(), entry.getValue())); - } else { - status.failed(); + }); - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onFail(download, entry.getKey(), entry.getValue())); + return status; - if (services.hasLogger()) - services - .getLogger() - .log(new DownloadFailedException( - "Failed to download file from host (" + host + ") with path (" + entry.getKey() + ") to '" + entry.getValue() + "'", - throwable)); - } - } + } - if (!listeners.isEmpty()) - listeners.forEach(listener -> listener.onDisconnect(download, DisconnectReason.DEFAULT)); + private Throwable download(String host, String path, String location, int timeout) { - } catch (Throwable throwable) { - while (status.failed()) - ; - if (services.hasLogger()) - services.getLogger().log(new DownloadFailedException(throwable)); - } + try { - } + URL url = new URL(host.endsWith("/") ? host + path : host + '/' + path); - status.done(); + URLConnection connection = url.openConnection(); - }); + connection.setConnectTimeout(12000); + connection.setReadTimeout(timeout * 1000); - return status; + if (connection instanceof HttpURLConnection) { + HttpURLConnection http = (HttpURLConnection) connection; - } + http.setRequestMethod("GET"); - private Throwable download(String host, String path, String location, int timeout) { + int code = http.getResponseCode(); - try { + if (code != 200) { + return new DownloadFailedException("Got response code " + code + "!"); + } + } - URL url = new URL(host.endsWith("/") ? host + path : host + '/' + path); + byte[] bytes = Streams.toByteArray(connection.getInputStream()); - URLConnection connection = url.openConnection(); + File file = new File(location); - connection.setConnectTimeout(12000); - connection.setReadTimeout(timeout * 1000); + if (file.exists()) { + if (!file.canWrite()) { + return new DownloadFailedException("No permission to write data to file!"); + } + } else { + if (file.getParent() != null) { + File parent = file.getParentFile(); + if (!parent.exists()) { + parent.mkdirs(); + } + } + file.createNewFile(); + } - if (connection instanceof HttpURLConnection) { - HttpURLConnection http = (HttpURLConnection) connection; + FileOutputStream stream = new FileOutputStream(file); - http.setRequestMethod("GET"); + stream.write(bytes); - int code = http.getResponseCode(); + stream.flush(); + stream.close(); - if (code != 200) { - return new DownloadFailedException("Got response code " + code + "!"); - } - } + return null; - byte[] bytes = Streams.toByteArray(connection.getInputStream()); + } catch (Throwable throwable) { + return throwable; + } - File file = new File(location); - - if (file.exists()) { - if (!file.canWrite()) - return new DownloadFailedException("No permission to write data to file!"); - } else { - if (file.getParent() != null) { - File parent = file.getParentFile(); - if (!parent.exists()) - parent.mkdirs(); - } - file.createNewFile(); - } - - FileOutputStream stream = new FileOutputStream(file); - - stream.write(bytes); - - stream.flush(); - stream.close(); - - return null; - - } catch (Throwable throwable) { - return throwable; - } - - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxExecutor.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxExecutor.java index bf07c74..49f68fb 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxExecutor.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxExecutor.java @@ -19,48 +19,48 @@ */ public class SyntaxExecutor extends Thread { - public static SynLogger LOGGER = new SynLogger(AnsiConsole.out(), LoggerState.EXTENDED_STREAM); - public static PrintWriter WRITER; + public static SynLogger LOGGER = new SynLogger(AnsiConsole.out(), LoggerState.EXTENDED_STREAM); + public static PrintWriter WRITER; - private static final BlockingQueue QUEUE = new LinkedBlockingQueue(); + private static final BlockingQueue QUEUE = new LinkedBlockingQueue(); - private static SyntaxTest test; + private static SyntaxTest test; - public static void main(String[] args) { - AnsiConsole.systemInstall(); + public static void main(String[] args) { + AnsiConsole.systemInstall(); - test = new SyntaxTest(args); + test = new SyntaxTest(args); - try { - LOGGER.setStream(WRITER = new PrintWriter(new File("debug.log"), LOGGER.getStream())); - } catch (FileNotFoundException e) { - LOGGER.log(e); - } + try { + LOGGER.setStream(WRITER = new PrintWriter(new File("debug.log"), LOGGER.getStream())); + } catch (FileNotFoundException e) { + LOGGER.log(e); + } - while (true) { - try { - QUEUE.take().run(); - } catch (Throwable error) { - Printer.spaces(); - Printer.prints(Exceptions.getError(error)); - Printer.spaces(); - getTest().getMenu().open(SyntaxTest.getReader()); - SyntaxTest.getReader().setCommand(true); - continue; - } - } + while (true) { + try { + QUEUE.take().run(); + } catch (Throwable error) { + Printer.spaces(); + Printer.prints(Exceptions.getError(error)); + Printer.spaces(); + getTest().getMenu().open(SyntaxTest.getReader()); + SyntaxTest.getReader().setCommand(true); + continue; + } + } - } + } - /** - * @return the test - */ - public static SyntaxTest getTest() { - return test; - } + /** + * @return the test + */ + public static SyntaxTest getTest() { + return test; + } - public static void queue(Runnable command) { - QUEUE.add(command); - } + public static void queue(Runnable command) { + QUEUE.add(command); + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxTest.java index 5347f2b..d7191a7 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/SyntaxTest.java @@ -4,7 +4,17 @@ import com.syntaxphoenix.syntaxapi.test.menu.MainMenu; import com.syntaxphoenix.syntaxapi.test.menu.menus.TestMenu; -import com.syntaxphoenix.syntaxapi.test.tests.*; +import com.syntaxphoenix.syntaxapi.test.tests.ColorTest; +import com.syntaxphoenix.syntaxapi.test.tests.DownloadTest; +import com.syntaxphoenix.syntaxapi.test.tests.LoggerTest; +import com.syntaxphoenix.syntaxapi.test.tests.NbtTest; +import com.syntaxphoenix.syntaxapi.test.tests.RandomChooseTest; +import com.syntaxphoenix.syntaxapi.test.tests.RandomTest; +import com.syntaxphoenix.syntaxapi.test.tests.RequestTest; +import com.syntaxphoenix.syntaxapi.test.tests.ServiceTest; +import com.syntaxphoenix.syntaxapi.test.tests.SocketTest; +import com.syntaxphoenix.syntaxapi.test.tests.ThreadTest; +import com.syntaxphoenix.syntaxapi.test.tests.VersionTest; import com.syntaxphoenix.syntaxapi.test.utils.InputReader; import com.syntaxphoenix.syntaxapi.test.utils.Printer; @@ -14,86 +24,87 @@ */ public class SyntaxTest implements Executor, Printer { - private static InputReader reader; - - public static InputReader getReader() { - return reader; - } - - /* - * - * Vars - * - */ - - private MainMenu menu; - - /* - * - * Constructor - * - */ - - public SyntaxTest(String[] args) { - (getMenu()).open((reader = new InputReader(this, input -> { - }, System.in, "ConsoleReader")).initialize()); - } - - /* - * - * Stuff - * - */ - - /** - * @return test menu - */ - private TestMenu createTests() { - TestMenu menu = new TestMenu(); - - menu.register("VersionTest", "Tests the Version Manager", new VersionTest()); - menu.register("ServiceTest", "Tests RNG", new ServiceTest()); - menu.register("ColorTest", "Tests java.awt.Color", new ColorTest()); - menu.register("LoggerTest", "Tests the new Logger", new LoggerTest()); - menu.register("NbtTest", "Tests the new NbtLib", new NbtTest()); - menu.register("RandomTest", "Tests the Random things", new RandomTest()); - menu.register("RandomChooseTest", "Tests the Random Choose thing", new RandomChooseTest()); - menu.register("DownloadTest", "Tests the DownloadService", new DownloadTest()); - menu.register("ThreadTest", "Tests the new Threading Stuff", new ThreadTest(), "amount=", "threadsMin=", "threadsMax="); - menu.register("SocketTest", "Tests the socket server", new SocketTest(), "port="); - menu.register("RequestTest", "Tests the Request util", new RequestTest()); - - return menu; - } - - /* - * - * Getter & Setter - * - */ - - /** - * @return the menu - */ - public MainMenu getMenu() { - if (menu == null) { - menu = new MainMenu(); - - menu.register("TestMenu - open the text menu", createTests()); - - } - return menu; - } - - /* - * - * Executor - * - */ - - @Override - public void execute(Runnable command) { - SyntaxExecutor.queue(command); - } + private static InputReader reader; + + public static InputReader getReader() { + return reader; + } + + /* + * + * Vars + * + */ + + private MainMenu menu; + + /* + * + * Constructor + * + */ + + public SyntaxTest(String[] args) { + (getMenu()).open((reader = new InputReader(this, input -> { + }, System.in, "ConsoleReader")).initialize()); + } + + /* + * + * Stuff + * + */ + + /** + * @return test menu + */ + private TestMenu createTests() { + TestMenu menu = new TestMenu(); + + menu.register("VersionTest", "Tests the Version Manager", new VersionTest()); + menu.register("ServiceTest", "Tests RNG", new ServiceTest()); + menu.register("ColorTest", "Tests java.awt.Color", new ColorTest()); + menu.register("LoggerTest", "Tests the new Logger", new LoggerTest()); + menu.register("NbtTest", "Tests the new NbtLib", new NbtTest()); + menu.register("RandomTest", "Tests the Random things", new RandomTest()); + menu.register("RandomChooseTest", "Tests the Random Choose thing", new RandomChooseTest()); + menu.register("DownloadTest", "Tests the DownloadService", new DownloadTest()); + menu.register("ThreadTest", "Tests the new Threading Stuff", new ThreadTest(), "amount=", "threadsMin=", + "threadsMax="); + menu.register("SocketTest", "Tests the socket server", new SocketTest(), "port="); + menu.register("RequestTest", "Tests the Request util", new RequestTest()); + + return menu; + } + + /* + * + * Getter & Setter + * + */ + + /** + * @return the menu + */ + public MainMenu getMenu() { + if (menu == null) { + menu = new MainMenu(); + + menu.register("TestMenu - open the text menu", createTests()); + + } + return menu; + } + + /* + * + * Executor + * + */ + + @Override + public void execute(Runnable command) { + SyntaxExecutor.queue(command); + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/AbstractMenu.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/AbstractMenu.java index 415b631..7eaf83e 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/AbstractMenu.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/AbstractMenu.java @@ -11,55 +11,54 @@ */ public abstract class AbstractMenu implements Printer { - InputReader reader; + InputReader reader; - public InputReader getReader() { - return reader; - } + public InputReader getReader() { + return reader; + } - public void open(InputReader reader) { - privateOpen(); - (this.reader = reader).setAction(input -> { - int select = -1; - if (Strings.isNumeric(input)) { - select = Integer.parseInt(input); - } - if (select >= getSize() || select < 0) { - if (select == -1) { - print("Returning to main menu..."); - print(""); - SyntaxExecutor.getTest().getMenu().open(getReader()); - getReader().setCommand(true); - return; - } - print("You cannot select a action that is not available!"); - if (getActions().length != 0) { - print("There are following actions that you can use:"); - print("[-1] Return to main menu"); - print(getActions(), "[%index%] ", true); - } - return; - } - onSelect(select); - }); - } + public void open(InputReader reader) { + privateOpen(); + (this.reader = reader).setAction(input -> { + int select = -1; + if (Strings.isNumeric(input)) { + select = Integer.parseInt(input); + } + if (select >= getSize() || select < 0) { + if (select == -1) { + print("Returning to main menu..."); + print(""); + SyntaxExecutor.getTest().getMenu().open(getReader()); + getReader().setCommand(true); + return; + } + print("You cannot select a action that is not available!"); + if (getActions().length != 0) { + print("There are following actions that you can use:"); + print("[-1] Return to main menu"); + print(getActions(), "[%index%] ", true); + } + return; + } + onSelect(select); + }); + } - protected String[] getActions() { - return new String[0]; - } + protected String[] getActions() { + return new String[0]; + } - void privateOpen() { - print("Please select one of these actions:"); - print("[-1] Return to main menu"); - print(getActions(), "[%index%] ", true); - onOpen(); - } + void privateOpen() { + print("Please select one of these actions:"); + print("[-1] Return to main menu"); + print(getActions(), "[%index%] ", true); + onOpen(); + } - protected void onOpen() { - } + protected void onOpen() {} - protected abstract int getSize(); + protected abstract int getSize(); - protected abstract void onSelect(int selected); + protected abstract void onSelect(int selected); } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/MainMenu.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/MainMenu.java index 893e278..da68984 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/MainMenu.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/MainMenu.java @@ -11,96 +11,96 @@ */ public class MainMenu extends AbstractMenu { - private ArrayList menus = new ArrayList<>(); - - public void register(String description, AbstractMenu menu) { - menus.add(new SubMenu(description, menu)); - } - - public SubMenu get(int selected) { - return menus.get(selected); - } - - @Override - protected int getSize() { - return menus.size(); - } - - @Override - protected void onOpen() { - print("Please select one of these actions:"); - print("[-1] Stop this test"); - print(getActions(), "[%index%] ", true); - } - - @Override - protected String[] getActions() { - String[] actions = new String[menus.size()]; - for (int index = 0; index < actions.length; index++) { - actions[index] = get(index).getDescription(); - } - return actions; - } - - @Override - protected void onSelect(int selected) { - menus.get(selected).getMenu().open(getReader()); - } - - public class SubMenu { - - private String description; - private AbstractMenu menu; - - SubMenu(String description, AbstractMenu menu) { - this.description = description; - this.menu = menu; - } - - public String getDescription() { - return description; - } - - public AbstractMenu getMenu() { - return menu; - } - - } - - /** - * @see com.syntaxphoenix.syntaxapi.test.menu.AbstractMenu#open(com.syntaxphoenix.syntaxapi.test.utils.InputReader) - */ - - @Override - public void open(InputReader reader) { - onOpen(); - (this.reader = reader).setAction(input -> { - int select = -1; - if (Strings.isNumeric(input)) { - select = Integer.parseInt(input); - } - if (select >= getSize() || select < 0) { - if (select == -1) { - print(""); - print("Goodbye!"); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.exit(0); - return; - } - print("You cannot select a action that is not available!"); - if (getActions().length != 0) { - print("There are following actions that you can use:"); - print("[-1] Stop this test"); - print(getActions(), "[%index%] ", true); - } - return; - } - onSelect(select); - }); - } + private ArrayList menus = new ArrayList<>(); + + public void register(String description, AbstractMenu menu) { + menus.add(new SubMenu(description, menu)); + } + + public SubMenu get(int selected) { + return menus.get(selected); + } + + @Override + protected int getSize() { + return menus.size(); + } + + @Override + protected void onOpen() { + print("Please select one of these actions:"); + print("[-1] Stop this test"); + print(getActions(), "[%index%] ", true); + } + + @Override + protected String[] getActions() { + String[] actions = new String[menus.size()]; + for (int index = 0; index < actions.length; index++) { + actions[index] = get(index).getDescription(); + } + return actions; + } + + @Override + protected void onSelect(int selected) { + menus.get(selected).getMenu().open(getReader()); + } + + public class SubMenu { + + private String description; + private AbstractMenu menu; + + SubMenu(String description, AbstractMenu menu) { + this.description = description; + this.menu = menu; + } + + public String getDescription() { + return description; + } + + public AbstractMenu getMenu() { + return menu; + } + + } + + /** + * @see com.syntaxphoenix.syntaxapi.test.menu.AbstractMenu#open(com.syntaxphoenix.syntaxapi.test.utils.InputReader) + */ + + @Override + public void open(InputReader reader) { + onOpen(); + (this.reader = reader).setAction(input -> { + int select = -1; + if (Strings.isNumeric(input)) { + select = Integer.parseInt(input); + } + if (select >= getSize() || select < 0) { + if (select == -1) { + print(""); + print("Goodbye!"); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.exit(0); + return; + } + print("You cannot select a action that is not available!"); + if (getActions().length != 0) { + print("There are following actions that you can use:"); + print("[-1] Stop this test"); + print(getActions(), "[%index%] ", true); + } + return; + } + onSelect(select); + }); + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/menus/TestMenu.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/menus/TestMenu.java index c1ffad9..49e7082 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/menus/TestMenu.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/menu/menus/TestMenu.java @@ -12,122 +12,122 @@ */ public class TestMenu extends AbstractMenu { - private ArrayList tests = new ArrayList<>(); - - public void register(String name, String description, Consumer action, String... arguments) { - if (contains(name)) { - return; - } - tests.add(new Test(name, description, action, arguments)); - } - - public void register(Test test) { - if (contains(test.getName())) { - return; - } - tests.add(test); - } - - public Optional tryGet(String name) { - return tests.stream().filter(test -> test.getName().equals(name)).findFirst(); - } - - public boolean contains(String name) { - return tryGet(name).isPresent(); - } - - public Test get(String name) { - return tryGet(name).get(); - } - - public Test get(int index) { - return tests.get(index); - } - - @Override - protected int getSize() { - return tests.size(); - } - - @Override - protected void onSelect(int selected) { - Test test = get(selected); - - String[] arguments = test.getArguments(); - if (arguments.length == 0) { - runTest(test, arguments); - } else { - print("To run the test you need following arguments:"); - print(arguments, "- ", true); - getReader().setAction(input -> runTest(test, input.split(" "))); - return; - } - } - - private void runTest(Test test, String[] input) { - getReader().setCommand(false); - print("Trying to run test with your specifications..."); - space(); - test.getAction().accept(input); - space(); - getReader().setCommand(true); - print("Test completed!"); - print(""); - onOpen(); - } - - @Override - protected String[] getActions() { - String[] actions = new String[tests.size()]; - for (int index = 0; index < actions.length; index++) { - Test test = get(index); - actions[index] = test.getName() + " - " + test.getDescription(); - } - return actions; - } - - public class Test { - - private String name; - private String description; - private String[] arguments; - private Consumer action; - - Test(String name, String description, Consumer action, String... arguments) { - this.name = name; - this.action = action; - this.arguments = arguments; - this.description = description; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @return the needed arguments - */ - public String[] getArguments() { - return arguments == null ? new String[0] : arguments; - } - - /** - * @return the action - */ - public Consumer getAction() { - return action; - } - - } + private ArrayList tests = new ArrayList<>(); + + public void register(String name, String description, Consumer action, String... arguments) { + if (contains(name)) { + return; + } + tests.add(new Test(name, description, action, arguments)); + } + + public void register(Test test) { + if (contains(test.getName())) { + return; + } + tests.add(test); + } + + public Optional tryGet(String name) { + return tests.stream().filter(test -> test.getName().equals(name)).findFirst(); + } + + public boolean contains(String name) { + return tryGet(name).isPresent(); + } + + public Test get(String name) { + return tryGet(name).get(); + } + + public Test get(int index) { + return tests.get(index); + } + + @Override + protected int getSize() { + return tests.size(); + } + + @Override + protected void onSelect(int selected) { + Test test = get(selected); + + String[] arguments = test.getArguments(); + if (arguments.length == 0) { + runTest(test, arguments); + } else { + print("To run the test you need following arguments:"); + print(arguments, "- ", true); + getReader().setAction(input -> runTest(test, input.split(" "))); + return; + } + } + + private void runTest(Test test, String[] input) { + getReader().setCommand(false); + print("Trying to run test with your specifications..."); + space(); + test.getAction().accept(input); + space(); + getReader().setCommand(true); + print("Test completed!"); + print(""); + onOpen(); + } + + @Override + protected String[] getActions() { + String[] actions = new String[tests.size()]; + for (int index = 0; index < actions.length; index++) { + Test test = get(index); + actions[index] = test.getName() + " - " + test.getDescription(); + } + return actions; + } + + public class Test { + + private String name; + private String description; + private String[] arguments; + private Consumer action; + + Test(String name, String description, Consumer action, String... arguments) { + this.name = name; + this.action = action; + this.arguments = arguments; + this.description = description; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @return the needed arguments + */ + public String[] getArguments() { + return arguments == null ? new String[0] : arguments; + } + + /** + * @return the action + */ + public Consumer getAction() { + return action; + } + + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ColorTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ColorTest.java index 0e09685..bad8fa7 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ColorTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ColorTest.java @@ -8,15 +8,15 @@ public class ColorTest implements Consumer, Printer { - @Override - public void accept(String[] args) { + @Override + public void accept(String[] args) { - Random random = new Random(); + Random random = new Random(); - Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); + Color color = new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); - print(color.toString()); + print(color.toString()); - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/DownloadTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/DownloadTest.java index 2e773d7..b852db8 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/DownloadTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/DownloadTest.java @@ -15,44 +15,45 @@ public class DownloadTest implements Consumer, Printer { - private final ServiceManager manager = new ServiceManager(SyntaxExecutor.LOGGER); + private final ServiceManager manager = new ServiceManager(SyntaxExecutor.LOGGER); - public DownloadTest() { + public DownloadTest() { - manager.register(new DownloadService()); - manager.subscribe(DownloadTest.class); + manager.register(new DownloadService()); + manager.subscribe(DownloadTest.class); - } + } - @Override - public void accept(String[] args) { + @Override + public void accept(String[] args) { - Status status = manager.run("download"); + Status status = manager.run("download"); - Instant start = Instant.now(); - while (!status.isDone()) { - try { - Thread.sleep(20); - } catch (InterruptedException e) { - print(e); - } - } + Instant start = Instant.now(); + while (!status.isDone()) { + try { + Thread.sleep(20); + } catch (InterruptedException e) { + print(e); + } + } - Duration duration = Duration.between(start, Instant.now()); + Duration duration = Duration.between(start, Instant.now()); - print("This took " + (TimeUnit.SECONDS.toMillis(duration.getSeconds()) + TimeUnit.NANOSECONDS.toMillis(duration.getNano())) + "ms!"); + print( + "This took " + (TimeUnit.SECONDS.toMillis(duration.getSeconds()) + TimeUnit.NANOSECONDS.toMillis(duration.getNano())) + "ms!"); - } + } - @SubscribeService(service = DownloadService.class, returnType = Download.class, returnsObject = true) - public static Download prepare() { - Download download = new Download("https://realistic.syntaxphoenix.com/downloads/RWGST/"); + @SubscribeService(service = DownloadService.class, returnType = Download.class, returnsObject = true) + public static Download prepare() { + Download download = new Download("https://realistic.syntaxphoenix.com/downloads/RWGST/"); - download.add("BIG_OAK_TREE_1.rwgfast", "testDl/BIG_OAK_TREE_1.rwgfast"); - download.add("BIG_OAK_TREE_2.rwgfast", "testDl/BIG_OAK_TREE_2.rwgfast"); - download.add("BIG_OAK_TREE_3.rwgfast", "testDl/BIG_OAK_TREE_3.rwgfast"); + download.add("BIG_OAK_TREE_1.rwgfast", "testDl/BIG_OAK_TREE_1.rwgfast"); + download.add("BIG_OAK_TREE_2.rwgfast", "testDl/BIG_OAK_TREE_2.rwgfast"); + download.add("BIG_OAK_TREE_3.rwgfast", "testDl/BIG_OAK_TREE_3.rwgfast"); - return download; - } + return download; + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/LoggerTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/LoggerTest.java index ae591a2..9775e43 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/LoggerTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/LoggerTest.java @@ -9,18 +9,18 @@ public class LoggerTest implements Consumer, Printer { - @Override - public void accept(String[] args) { + @Override + public void accept(String[] args) { - AnsiConsole.systemInstall(); - SynLogger logger = new SynLogger(); + AnsiConsole.systemInstall(); + SynLogger logger = new SynLogger(); - logger.log("This is a test #1", "debug"); - logger.log("This is a test #2", "info"); - logger.log("This is a test #3", "warning"); - logger.log("This is a test #4", "error"); - AnsiConsole.systemUninstall(); + logger.log("This is a test #1", "debug"); + logger.log("This is a test #2", "info"); + logger.log("This is a test #3", "warning"); + logger.log("This is a test #4", "error"); + AnsiConsole.systemUninstall(); - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/NbtTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/NbtTest.java index be24df6..26f5667 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/NbtTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/NbtTest.java @@ -12,35 +12,35 @@ public class NbtTest implements Consumer, Printer { - @Override - public void accept(String[] args) { - - NbtConfig config = new NbtConfig(false); - - File file = new File("C:\\Users\\laura\\Desktop\\Eclipse\\test.nbt"); - - try { - config.load(file); - } catch (IOException e) { - e.printStackTrace(); - } - print(config.toString()); - - file.delete(); - NbtTag tag = config.get("testBigInt"); - if (tag.getType() == NbtType.STRING) { - NbtString string = (NbtString) tag; - if (string.isBigInteger()) { - System.out.println("BIG INT"); - } - } - - try { - config.save(file); - } catch (IOException e) { - e.printStackTrace(); - } - - } + @Override + public void accept(String[] args) { + + NbtConfig config = new NbtConfig(false); + + File file = new File("C:\\Users\\laura\\Desktop\\Eclipse\\test.nbt"); + + try { + config.load(file); + } catch (IOException e) { + e.printStackTrace(); + } + print(config.toString()); + + file.delete(); + NbtTag tag = config.get("testBigInt"); + if (tag.getType() == NbtType.STRING) { + NbtString string = (NbtString) tag; + if (string.isBigInteger()) { + System.out.println("BIG INT"); + } + } + + try { + config.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomChooseTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomChooseTest.java index 4475017..b00b566 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomChooseTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomChooseTest.java @@ -10,26 +10,27 @@ public class RandomChooseTest implements Consumer, Printer { - public static final List OPTIONS = Arrays.asList("Test1", "Test2", "Test3"); - - @Override - public void accept(String[] args) { - - RandomNumberGenerator generator = NumberGeneratorType.MURMUR.create(); - - float timeout = 1.0f; - while (true) { - print(OPTIONS.get(generator.nextInt(OPTIONS.size()))); - if (timeout == 25.0f) - break; - try { - Thread.sleep((int) (10 * timeout)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - timeout += 0.5f; - } - - } + public static final List OPTIONS = Arrays.asList("Test1", "Test2", "Test3"); + + @Override + public void accept(String[] args) { + + RandomNumberGenerator generator = NumberGeneratorType.MURMUR.create(); + + float timeout = 1.0f; + while (true) { + print(OPTIONS.get(generator.nextInt(OPTIONS.size()))); + if (timeout == 25.0f) { + break; + } + try { + Thread.sleep((int) (10 * timeout)); + } catch (InterruptedException e) { + e.printStackTrace(); + } + timeout += 0.5f; + } + + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomTest.java index 55bb54d..dc4822a 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RandomTest.java @@ -12,25 +12,25 @@ public class RandomTest implements Consumer, Printer { - @Override - public void accept(String[] args) { - RandomNumberGenerator generator = NumberGeneratorType.MURMUR.create(); + @Override + public void accept(String[] args) { + RandomNumberGenerator generator = NumberGeneratorType.MURMUR.create(); - DecimalFormat format = new DecimalFormat( - "0.0##########################################################################################################################################################"); - format.setRoundingMode(RoundingMode.UNNECESSARY); + DecimalFormat format = new DecimalFormat( + "0.0##########################################################################################################################################################"); + format.setRoundingMode(RoundingMode.UNNECESSARY); - PrintWriter writer = SyntaxExecutor.WRITER; - writer.writeFile(true); - for (int tries = 10000000; tries > 0; tries--) { - double db = generator.nextDouble(0, 200); + PrintWriter writer = SyntaxExecutor.WRITER; + writer.writeFile(true); + for (int tries = 10000000; tries > 0; tries--) { + double db = generator.nextDouble(0, 200); - print(format.format(db)); + print(format.format(db)); - } - writer.writeFile(false); - writer.flush(); + } + writer.writeFile(false); + writer.flush(); - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RequestTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RequestTest.java index 1586f9f..e5b2e53 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RequestTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/RequestTest.java @@ -11,23 +11,23 @@ public class RequestTest implements Consumer, Printer { - @Override - public void accept(String[] args) { + @Override + public void accept(String[] args) { - Request request = new Request(RequestType.POST); + Request request = new Request(RequestType.POST); - request.parameter("user", "nice"); + request.parameter("user", "nice"); - try { - Response response = request.execute("http://spigot.syntaxphoenix.com/verify", StandardContentType.JSON); + try { + Response response = request.execute("http://spigot.syntaxphoenix.com/verify", StandardContentType.JSON); - print("code: " + response.getCode()); - print("message: " + response.getResponse()); + print("code: " + response.getCode()); + print("message: " + response.getResponse()); - } catch (IOException e) { - print(e); - } + } catch (IOException e) { + print(e); + } - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ServiceTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ServiceTest.java index 9a802b2..9407d59 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ServiceTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ServiceTest.java @@ -6,11 +6,11 @@ public class ServiceTest implements Consumer, Printer { - @Override - public void accept(String[] args) { + @Override + public void accept(String[] args) { - // Not written + // Not written - } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/SocketTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/SocketTest.java index 0a5afed..01c4f20 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/SocketTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/SocketTest.java @@ -3,54 +3,54 @@ import java.io.IOException; import java.util.function.Consumer; -import com.syntaxphoenix.syntaxapi.net.http.HttpServer; +import com.syntaxphoenix.syntaxapi.net.SocketServer; import com.syntaxphoenix.syntaxapi.net.http.RestApiServer; import com.syntaxphoenix.syntaxapi.test.utils.Printer; public class SocketTest implements Consumer, Printer { - public int failed = 0; - - @Override - public void accept(String[] args) { - int port = HttpServer.DEFAULT_PORT; - if (args.length >= 1) { - for (String arg : args) { - if (!arg.contains("=")) { - continue; - } - String[] parts = arg.split("="); - int value; - try { - value = Integer.parseInt(parts[1]); - } catch (Throwable thrw) { - value = HttpServer.DEFAULT_PORT; - } - if (parts[0].equalsIgnoreCase("port")) { - port = value; - } - } - } - - RestApiServer server = new RestApiServer(port); - - try { - server.start(); - } catch (IOException e) { - print(e); - } - - try { - Thread.sleep(30 * 1000); - } catch (InterruptedException e) { - print(e); - } - - try { - server.stop(); - } catch (IOException e) { - print(e); - } - } + public int failed = 0; + + @Override + public void accept(String[] args) { + int port = SocketServer.DEFAULT_PORT; + if (args.length >= 1) { + for (String arg : args) { + if (!arg.contains("=")) { + continue; + } + String[] parts = arg.split("="); + int value; + try { + value = Integer.parseInt(parts[1]); + } catch (Throwable thrw) { + value = SocketServer.DEFAULT_PORT; + } + if (parts[0].equalsIgnoreCase("port")) { + port = value; + } + } + } + + RestApiServer server = new RestApiServer(port); + + try { + server.start(); + } catch (IOException e) { + print(e); + } + + try { + Thread.sleep(30 * 1000); + } catch (InterruptedException e) { + print(e); + } + + try { + server.stop(); + } catch (IOException e) { + print(e); + } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ThreadTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ThreadTest.java index 5632059..75188cd 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ThreadTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/ThreadTest.java @@ -12,72 +12,72 @@ public class ThreadTest implements Consumer, Printer { - public int failed = 0; + public int failed = 0; - @Override - public void accept(String[] args) { - int amount = 10; - int threadsMin = 1; - int threadsMax = 4; - if (args.length >= 1) { - for (String arg : args) { - if (!arg.contains("=")) { - continue; - } - String[] parts = arg.split("="); - int value; - try { - value = Integer.parseInt(parts[1]); - } catch (Throwable thrw) { - value = 4; - } - if (parts[0].equalsIgnoreCase("amount")) { - amount = value; - } else if (parts[0].equalsIgnoreCase("threads-min")) { - threadsMin = value; - } else if (parts[0].equalsIgnoreCase("threads-max")) { - threadsMax = value; - } - } - } + @Override + public void accept(String[] args) { + int amount = 10; + int threadsMin = 1; + int threadsMax = 4; + if (args.length >= 1) { + for (String arg : args) { + if (!arg.contains("=")) { + continue; + } + String[] parts = arg.split("="); + int value; + try { + value = Integer.parseInt(parts[1]); + } catch (Throwable thrw) { + value = 4; + } + if (parts[0].equalsIgnoreCase("amount")) { + amount = value; + } else if (parts[0].equalsIgnoreCase("threads-min")) { + threadsMin = value; + } else if (parts[0].equalsIgnoreCase("threads-max")) { + threadsMax = value; + } + } + } - SynThreadPool service = new SynThreadPool((throwable, pool, thread, command) -> { - failed++; - }, threadsMin, threadsMax, "ThreadTestPool"); + SynThreadPool service = new SynThreadPool((throwable, pool, thread, command) -> { + failed++; + }, threadsMin, threadsMax, "ThreadTestPool"); - Random random = new Random((amount ^ threadsMax) * threadsMin); - shouldFail = 0; + Random random = new Random((amount ^ threadsMax) * threadsMin); + shouldFail = 0; - print("Running " + amount + " commands on a ThreadPool with [min: " + threadsMin + ", max: " + threadsMax + "] Threads."); - ArrayList> tasks = new ArrayList<>(); - for (int x = 0; x < amount; x++) { - tasks.add(service.submit(createTask(random.nextBoolean()))); - } - while (!tasks.isEmpty()) { - Object[] object = tasks.stream().filter(future -> future.isDone()).toArray(); - for (int x = 0; x < object.length; x++) { - tasks.remove(object[x]); - } - } + print("Running " + amount + " commands on a ThreadPool with [min: " + threadsMin + ", max: " + threadsMax + "] Threads."); + ArrayList> tasks = new ArrayList<>(); + for (int x = 0; x < amount; x++) { + tasks.add(service.submit(createTask(random.nextBoolean()))); + } + while (!tasks.isEmpty()) { + Object[] object = tasks.stream().filter(future -> future.isDone()).toArray(); + for (int x = 0; x < object.length; x++) { + tasks.remove(object[x]); + } + } - service.shutdown(); - print("Test is done [success: " + (amount - failed) + ", failed: " + failed + ", shouldFail: " + shouldFail + "]"); + service.shutdown(); + print("Test is done [success: " + (amount - failed) + ", failed: " + failed + ", shouldFail: " + shouldFail + "]"); - } + } - public int shouldFail = 0; + public int shouldFail = 0; - private Runnable createTask(boolean error) { - if (error) { - shouldFail++; - return () -> { - AbstractReflect reflect = new Reflect("fjsdfi.sdfsdfno"); - reflect.run("sdf0"); - }; - } else { - return () -> { - }; - } - } + private Runnable createTask(boolean error) { + if (error) { + shouldFail++; + return () -> { + AbstractReflect reflect = new Reflect("fjsdfi.sdfsdfno"); + reflect.run("sdf0"); + }; + } else { + return () -> { + }; + } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/VersionTest.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/VersionTest.java index c70aaef..0d8d49f 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/VersionTest.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/tests/VersionTest.java @@ -10,47 +10,48 @@ public class VersionTest implements Consumer, Printer { - @Override - public void accept(String[] args) { - - VersionManager manager = new VersionManager<>(); - - print("Creating seed..."); - long seed = System.currentTimeMillis(); - seed = 5 << seed; - seed *= 5; - seed = seed >>> 2; - print("Seed generated -> " + seed); - - for (VersionState state : VersionState.values()) { - Random random = new Random(seed + (state.ordinal() * 32254)); - print(state.name() + " | creating versions..."); - for (int versions = 100; versions > 0; versions--) { - DefaultVersion version = new DefaultVersion(random.nextInt(1000), random.nextInt(10000), random.nextInt(100000)); - while (manager.contains(version)) - version = new DefaultVersion(random.nextInt(10000), random.nextInt(100000), random.nextInt(1000000)); - manager.set(state, version, false); - } - print(state.name() + " | versions created"); - } - - print("Sorting versions..."); - manager.sortAll(); - print("Versions sorted"); - - print("Sending results..."); - for (VersionState state : VersionState.values()) { - - print(state.name() + " | High -> " + manager.getHighestVersion(state).toString()); - print(state.name() + " | Low -> " + manager.getLowestVersion(state).toString()); - - } - print("Results sent"); - - print("Clearing versions..."); - manager.clearAll(); - print("Versions cleared"); - - } + @Override + public void accept(String[] args) { + + VersionManager manager = new VersionManager<>(); + + print("Creating seed..."); + long seed = System.currentTimeMillis(); + seed = 5 << seed; + seed *= 5; + seed = seed >>> 2; + print("Seed generated -> " + seed); + + for (VersionState state : VersionState.values()) { + Random random = new Random(seed + (state.ordinal() * 32254)); + print(state.name() + " | creating versions..."); + for (int versions = 100; versions > 0; versions--) { + DefaultVersion version = new DefaultVersion(random.nextInt(1000), random.nextInt(10000), random.nextInt(100000)); + while (manager.contains(version)) { + version = new DefaultVersion(random.nextInt(10000), random.nextInt(100000), random.nextInt(1000000)); + } + manager.set(state, version, false); + } + print(state.name() + " | versions created"); + } + + print("Sorting versions..."); + manager.sortAll(); + print("Versions sorted"); + + print("Sending results..."); + for (VersionState state : VersionState.values()) { + + print(state.name() + " | High -> " + manager.getHighestVersion(state).toString()); + print(state.name() + " | Low -> " + manager.getLowestVersion(state).toString()); + + } + print("Results sent"); + + print("Clearing versions..."); + manager.clearAll(); + print("Versions cleared"); + + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/InputReader.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/InputReader.java index 3c7ae76..5566bf4 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/InputReader.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/InputReader.java @@ -11,75 +11,75 @@ */ public class InputReader extends Thread { - private Scanner scanner; - private Executor other; - private Consumer action; - - private boolean started = false; - private boolean online = true; - private boolean command = true; - - public InputReader(Executor executor, Consumer input, InputStream stream, String name) { - scanner = new Scanner(stream); - other = executor; - action = input; - setName(name); - } - - @Override - public void run() { - while (online) { - if (scanner.hasNextLine()) { - String input = scanner.nextLine(); - if (command) { - other.execute(() -> action.accept(input)); - } - } - } - } - - public void setCommand(boolean command) { - this.command = command; - } - - public boolean getCommand() { - return command; - } - - public boolean isOnline() { - return online; - } - - public void setAction(Consumer action) { - this.action = action; - } - - public Consumer getAction() { - return action; - } - - public InputReader initialize() { - start(); - return this; - } - - @Override - public void start() { - if (!started) { - super.start(); - } - } - - public void shutdown() { - interrupt(); - } - - @Override - public void interrupt() { - if (online) { - online = false; - super.interrupt(); - } - } + private Scanner scanner; + private Executor other; + private Consumer action; + + private boolean started = false; + private boolean online = true; + private boolean command = true; + + public InputReader(Executor executor, Consumer input, InputStream stream, String name) { + scanner = new Scanner(stream); + other = executor; + action = input; + setName(name); + } + + @Override + public void run() { + while (online) { + if (scanner.hasNextLine()) { + String input = scanner.nextLine(); + if (command) { + other.execute(() -> action.accept(input)); + } + } + } + } + + public void setCommand(boolean command) { + this.command = command; + } + + public boolean getCommand() { + return command; + } + + public boolean isOnline() { + return online; + } + + public void setAction(Consumer action) { + this.action = action; + } + + public Consumer getAction() { + return action; + } + + public InputReader initialize() { + start(); + return this; + } + + @Override + public void start() { + if (!started) { + super.start(); + } + } + + public void shutdown() { + interrupt(); + } + + @Override + public void interrupt() { + if (online) { + online = false; + super.interrupt(); + } + } } diff --git a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/Printer.java b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/Printer.java index bf0abbd..6146424 100644 --- a/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/Printer.java +++ b/test/src/main/java/com/syntaxphoenix/syntaxapi/test/utils/Printer.java @@ -8,76 +8,76 @@ */ public interface Printer { - /* - * - */ - - public static void spaces() { - prints("------------------------------------------------------------------"); - } - - public static void prints(Object input) { - prints(input.toString()); - } - - public static void prints(String input) { - SyntaxExecutor.LOGGER.log(input); - } - - public static void prints(Throwable throwable) { - SyntaxExecutor.LOGGER.log(throwable); - } - - /* - * - */ - - public default void print(Throwable throwable) { - SyntaxExecutor.LOGGER.log(throwable); - } - - public default void print(Object input) { - print(input.toString()); - } - - public default void print(String input) { - SyntaxExecutor.LOGGER.log(input); - } - - public default void space() { - print("------------------------------------------------------------------"); - } - - public default void print(String[] input) { - print(input, "- "); - } - - public default void print(String[] input, boolean pretty) { - print(input, pretty ? "- " : ", ", pretty); - } - - public default void print(String[] input, String add) { - print(input, add, true); - } - - public default void print(String[] input, String add, boolean pretty) { - if (input.length == 0) { - print("[]"); - return; - } - if (pretty) { - for (int index = 0; index < input.length; index++) { - print(add.replace("%index%", index + "") + input[index]); - } - return; - } else { - String output = "["; - for (String in : input) { - output += in + add; - } - print(output.substring(0, output.length() - add.length()) + "]"); - return; - } - } + /* + * + */ + + public static void spaces() { + prints("------------------------------------------------------------------"); + } + + public static void prints(Object input) { + prints(input.toString()); + } + + public static void prints(String input) { + SyntaxExecutor.LOGGER.log(input); + } + + public static void prints(Throwable throwable) { + SyntaxExecutor.LOGGER.log(throwable); + } + + /* + * + */ + + public default void print(Throwable throwable) { + SyntaxExecutor.LOGGER.log(throwable); + } + + public default void print(Object input) { + print(input.toString()); + } + + public default void print(String input) { + SyntaxExecutor.LOGGER.log(input); + } + + public default void space() { + print("------------------------------------------------------------------"); + } + + public default void print(String[] input) { + print(input, "- "); + } + + public default void print(String[] input, boolean pretty) { + print(input, pretty ? "- " : ", ", pretty); + } + + public default void print(String[] input, String add) { + print(input, add, true); + } + + public default void print(String[] input, String add, boolean pretty) { + if (input.length == 0) { + print("[]"); + return; + } + if (pretty) { + for (int index = 0; index < input.length; index++) { + print(add.replace("%index%", index + "") + input[index]); + } + return; + } else { + String output = "["; + for (String in : input) { + output += in + add; + } + print(output.substring(0, output.length() - add.length()) + "]"); + return; + } + } } diff --git a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynReportThrower.java b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynReportThrower.java index c734048..ab98c78 100644 --- a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynReportThrower.java +++ b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynReportThrower.java @@ -2,6 +2,6 @@ public interface SynReportThrower { - public boolean isPool(); + public boolean isPool(); } diff --git a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadFactory.java b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadFactory.java index fea76d0..f840d75 100644 --- a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadFactory.java +++ b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadFactory.java @@ -4,64 +4,64 @@ public class SynThreadFactory implements ThreadFactory, SynReportThrower { - private final SynThreadReporter reporter; + private final SynThreadReporter reporter; - private final String poolName; - private int count = 0; + private final String poolName; + private int count = 0; - public SynThreadFactory(String poolName) { - this.poolName = poolName; - this.reporter = null; - } + public SynThreadFactory(String poolName) { + this.poolName = poolName; + this.reporter = null; + } - public SynThreadFactory(String poolName, SynThreadReporter reporter) { - this.poolName = poolName; - this.reporter = reporter; - } + public SynThreadFactory(String poolName, SynThreadReporter reporter) { + this.poolName = poolName; + this.reporter = reporter; + } - public final String getName() { - return poolName; - } + public final String getName() { + return poolName; + } - public final SynThreadReporter getReporter() { - return reporter; - } + public final SynThreadReporter getReporter() { + return reporter; + } - public int getCreatedThreadCount() { - return count; - } + public int getCreatedThreadCount() { + return count; + } - private final String nextName() { - String name = poolName + " - " + count; - count++; - return name; - } + private final String nextName() { + String name = poolName + " - " + count; + count++; + return name; + } - @Override - public Thread newThread(Runnable command) { - Thread thread; - if (reporter != null) { - thread = new Thread(() -> { - try { - command.run(); - } catch (Throwable throwable) { - reporter.catchFail(throwable, this, Thread.currentThread(), command); - } - }); - } else { - thread = new Thread(command); - } - thread.setName(nextName()); - return thread; - } + @Override + public Thread newThread(Runnable command) { + Thread thread; + if (reporter != null) { + thread = new Thread(() -> { + try { + command.run(); + } catch (Throwable throwable) { + reporter.catchFail(throwable, this, Thread.currentThread(), command); + } + }); + } else { + thread = new Thread(command); + } + thread.setName(nextName()); + return thread; + } - /* - * - */ + /* + * + */ - @Override - public final boolean isPool() { - return false; - } + @Override + public final boolean isPool() { + return false; + } } diff --git a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadPool.java b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadPool.java index f7b4b31..00dfd49 100644 --- a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadPool.java +++ b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadPool.java @@ -6,51 +6,52 @@ public final class SynThreadPool extends ThreadPoolExecutor implements SynReportThrower { - private final SynThreadReporter reporter; - - public SynThreadPool(SynThreadReporter reporter, int min, int max, String poolName) { - super(min, max, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), (new SynThreadFactory(poolName))); - if (min <= 0) { - throw new IllegalArgumentException("Minimum thread count cannot be lower than 1"); - } else if (max < min || max <= 0) { - throw new IllegalArgumentException("Maximum thread count need to be higher than 0 and higher than or equal to the minimum thread count!"); - } - this.reporter = reporter; - } - - @Override - public final SynThreadFactory getThreadFactory() { - return (SynThreadFactory) super.getThreadFactory(); - } - - public final String getName() { - return getThreadFactory().getName(); - } - - /* - * - */ - - @Override - public final boolean isPool() { - return true; - } - - /* - * - * - * - */ - - @Override - public void execute(Runnable command) { - super.execute(() -> { - try { - command.run(); - } catch (Throwable throwable) { - reporter.catchFail(throwable, this, Thread.currentThread(), command); - } - }); - } + private final SynThreadReporter reporter; + + public SynThreadPool(SynThreadReporter reporter, int min, int max, String poolName) { + super(min, max, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(), (new SynThreadFactory(poolName))); + if (min <= 0) { + throw new IllegalArgumentException("Minimum thread count cannot be lower than 1"); + } else if (max < min || max <= 0) { + throw new IllegalArgumentException( + "Maximum thread count need to be higher than 0 and higher than or equal to the minimum thread count!"); + } + this.reporter = reporter; + } + + @Override + public final SynThreadFactory getThreadFactory() { + return (SynThreadFactory) super.getThreadFactory(); + } + + public final String getName() { + return getThreadFactory().getName(); + } + + /* + * + */ + + @Override + public final boolean isPool() { + return true; + } + + /* + * + * + * + */ + + @Override + public void execute(Runnable command) { + super.execute(() -> { + try { + command.run(); + } catch (Throwable throwable) { + reporter.catchFail(throwable, this, Thread.currentThread(), command); + } + }); + } } diff --git a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadReporter.java b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadReporter.java index 9cdfc3a..51fe2f8 100644 --- a/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadReporter.java +++ b/thread/src/main/java/com/syntaxphoenix/syntaxapi/thread/SynThreadReporter.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface SynThreadReporter { - public void catchFail(Throwable throwable, SynReportThrower threw, Thread thread, Runnable command); + public void catchFail(Throwable throwable, SynReportThrower threw, Thread thread, Runnable command); } diff --git a/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/Alias.java b/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/Alias.java index dfe2234..39d8cf7 100644 --- a/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/Alias.java +++ b/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/Alias.java @@ -7,103 +7,103 @@ public class Alias { - private final String name; - private final List aliases; - - private String displayName; - private String description; - - public Alias(String name, String... aliases) { - this.name = name.toLowerCase(); - this.aliases = Collections.unmodifiableList(Arrays.asList(aliases)); - } - - public String[] getAliases() { - return aliases.toArray(new String[0]); - } - - public String getName() { - return name; - } - - /* - * - */ - - public String getDisplayName() { - return displayName == null ? name : displayName; - } - - public Alias setDisplayName(String displayName) { - this.displayName = displayName; - return this; - } - - /* - * - */ - - public String getDescription() { - return description == null ? "" : description; - } - - public Alias setDescription(String description) { - this.description = description; - return this; - } - - /* - * - */ - - public boolean isName(String name) { - return this.name.equals(name); - } - - public boolean isAlias(String alias) { - return aliases.contains(alias); - } - - public boolean isLabel(String label) { - return isName((label = label.toLowerCase())) ? true : isAlias(label); - } - - /* - * - */ - - public boolean hasAliases() { - return !aliases.isEmpty(); - } - - public boolean hasDisplayName() { - return displayName != null && !displayName.isEmpty(); - } - - public boolean hasDescription() { - return description != null && !description.isEmpty(); - } - - /* - * - */ - - public Alias removeConflicts(List conflicts) { - ArrayList list = new ArrayList<>(aliases); - list.removeAll(conflicts); - return new Alias(name, list.toArray(new String[0])).setDisplayName(displayName).setDescription(description); - } - - /* - * - */ - - public static Alias create(String name) { - return new Alias(name); - } - - public static Alias create(String name, String... aliases) { - return new Alias(name, aliases); - } + private final String name; + private final List aliases; + + private String displayName; + private String description; + + public Alias(String name, String... aliases) { + this.name = name.toLowerCase(); + this.aliases = Collections.unmodifiableList(Arrays.asList(aliases)); + } + + public String[] getAliases() { + return aliases.toArray(new String[0]); + } + + public String getName() { + return name; + } + + /* + * + */ + + public String getDisplayName() { + return displayName == null ? name : displayName; + } + + public Alias setDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /* + * + */ + + public String getDescription() { + return description == null ? "" : description; + } + + public Alias setDescription(String description) { + this.description = description; + return this; + } + + /* + * + */ + + public boolean isName(String name) { + return this.name.equals(name); + } + + public boolean isAlias(String alias) { + return aliases.contains(alias); + } + + public boolean isLabel(String label) { + return isName((label = label.toLowerCase())) ? true : isAlias(label); + } + + /* + * + */ + + public boolean hasAliases() { + return !aliases.isEmpty(); + } + + public boolean hasDisplayName() { + return displayName != null && !displayName.isEmpty(); + } + + public boolean hasDescription() { + return description != null && !description.isEmpty(); + } + + /* + * + */ + + public Alias removeConflicts(List conflicts) { + ArrayList list = new ArrayList<>(aliases); + list.removeAll(conflicts); + return new Alias(name, list.toArray(new String[0])).setDisplayName(displayName).setDescription(description); + } + + /* + * + */ + + public static Alias create(String name) { + return new Alias(name); + } + + public static Alias create(String name, String... aliases) { + return new Alias(name, aliases); + } } diff --git a/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/AliasMap.java b/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/AliasMap.java index 47d493e..9a46d1e 100644 --- a/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/AliasMap.java +++ b/utils/alias/src/main/java/com/syntaxphoenix/syntaxapi/utils/alias/AliasMap.java @@ -7,114 +7,114 @@ public class AliasMap extends HashMap { - private static final long serialVersionUID = 8244987875156828827L; - private Set> entries; - - public AliasMap(Map map) { - super(map); - entries = entrySet(); - } - - public AliasMap() { - entries = entrySet(); - } - - @Override - public A put(Alias key, A value) { - A out = super.put(key, value); - return out; - } - - @Override - public void putAll(Map m) { - super.putAll(m); - } - - @Override - public A putIfAbsent(Alias key, A value) { - A out = super.putIfAbsent(key, value); - return out; - } - - @Override - public A remove(Object key) { - A out = super.remove(key); - return out; - } - - @Override - public boolean remove(Object key, Object value) { - boolean out = super.remove(key, value); - return out; - } - - public boolean containsKey(String key) { - return containsKey((Object) key); - } - - @Override - public boolean containsKey(Object key) { - if (entries == null || entries.isEmpty()) { - return false; - } - if (key instanceof String) { - return getEntryFromString((String) key) != null; - } else if (key instanceof Alias) { - return super.containsKey(key); - } else { - return false; - } - } - - public A get(String key) { - return get((Object) key); - } - - @Override - public A get(Object key) { - if (entries == null || entries.isEmpty()) { - return null; - } - if (key instanceof String) { - return getEntryFromString((String) key).getValue(); - } else if (key instanceof Alias) { - return super.get(key); - } else { - return null; - } - } - - private Entry getEntryFromString(String key) { - for (Entry entry : entries) { - if (entry.getKey().isLabel(key)) { - return entry; - } - } - return null; - } - - public ArrayList hasConflict(Alias alias) { - ArrayList conflict = new ArrayList<>(); - if (containsKey(alias.getName())) { - conflict.add(alias.getName()); - } - if (alias.hasAliases()) { - for (String current : alias.getAliases()) { - if (containsKey(current)) { - conflict.add(current); - } - } - } - return conflict; - } - - /* - * - */ - - @Override - public AliasMap clone() { - return new AliasMap(this); - } + private static final long serialVersionUID = 8244987875156828827L; + private Set> entries; + + public AliasMap(Map map) { + super(map); + entries = entrySet(); + } + + public AliasMap() { + entries = entrySet(); + } + + @Override + public A put(Alias key, A value) { + A out = super.put(key, value); + return out; + } + + @Override + public void putAll(Map m) { + super.putAll(m); + } + + @Override + public A putIfAbsent(Alias key, A value) { + A out = super.putIfAbsent(key, value); + return out; + } + + @Override + public A remove(Object key) { + A out = super.remove(key); + return out; + } + + @Override + public boolean remove(Object key, Object value) { + boolean out = super.remove(key, value); + return out; + } + + public boolean containsKey(String key) { + return containsKey((Object) key); + } + + @Override + public boolean containsKey(Object key) { + if (entries == null || entries.isEmpty()) { + return false; + } + if (key instanceof String) { + return getEntryFromString((String) key) != null; + } else if (key instanceof Alias) { + return super.containsKey(key); + } else { + return false; + } + } + + public A get(String key) { + return get((Object) key); + } + + @Override + public A get(Object key) { + if (entries == null || entries.isEmpty()) { + return null; + } + if (key instanceof String) { + return getEntryFromString((String) key).getValue(); + } else if (key instanceof Alias) { + return super.get(key); + } else { + return null; + } + } + + private Entry getEntryFromString(String key) { + for (Entry entry : entries) { + if (entry.getKey().isLabel(key)) { + return entry; + } + } + return null; + } + + public ArrayList hasConflict(Alias alias) { + ArrayList conflict = new ArrayList<>(); + if (containsKey(alias.getName())) { + conflict.add(alias.getName()); + } + if (alias.hasAliases()) { + for (String current : alias.getAliases()) { + if (containsKey(current)) { + conflict.add(current); + } + } + } + return conflict; + } + + /* + * + */ + + @Override + public AliasMap clone() { + return new AliasMap(this); + } } diff --git a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheList.java b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheList.java index a5bb654..325d2e7 100644 --- a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheList.java +++ b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheList.java @@ -12,134 +12,138 @@ public class CacheList { - private final List> cacheList; - private final long timeToLive; - - private final Consumer> action; - private final Thread timer; - - public CacheList(long timeToLive, final long timerInterval, int maxItems) { - this(timeToLive, timerInterval, maxItems, null); - } - - public CacheList(long timeToLive, final long timerInterval, int maxItems, Consumer> action) { - this.cacheList = Collections.synchronizedList(new ArrayList<>(maxItems)); - this.timeToLive = timeToLive * 1000; - this.action = action; - if (timeToLive > 0 && timerInterval > 0) { - timer = new Thread(() -> { - while (true) { - try { - Thread.sleep(timerInterval * 1000); - } catch (InterruptedException ex) { - } - cleanup(); - } - }); - } else - timer = null; - } - - public ArrayList getListCopy() { - ArrayList values = new ArrayList<>(size()); - synchronized (cacheList) { - Iterator> iterator = cacheList.iterator(); - while (iterator.hasNext()) { - values.add(iterator.next().getValue()); - } - } - return values; - } - - public void add(V value) { - synchronized (cacheList) { - cacheList.add(new CachedObject(value)); - } - } - - public V get(int index) { - synchronized (cacheList) { - CachedObject object = cacheList.get(index); - if (object == null) - return null; - return object.getValue(); - } - } - - public Optional predicateFilter(Predicate predicate) { - synchronized (cacheList) { - return cacheList.stream().filter(object -> predicate.test(object.getValue(false))).findFirst().map(cachedObject -> cachedObject.getValue()); - } - } - - public Optional streamFilter(Function, Optional> filter) { - synchronized (cacheList) { - Optional filtered = filter.apply(cacheList.stream().map(object -> object.getValue(false))); - return !filtered.isPresent() ? filtered - : cacheList.stream().filter(object -> object.getValue(false) == filtered.get()).findFirst().map(object -> object.getValue()); - } - } - - public boolean contains(V value) { - synchronized (cacheList) { - return cacheList.stream().anyMatch(object -> object.getValue(false) == value); - } - } - - public void forEach(Consumer consume) { - synchronized (cacheList) { - cacheList.stream().map(object -> object.getValue()).forEach(consume); - } - } - - public void remove(int index) { - synchronized (cacheList) { - cacheList.remove(index); - } - } - - public void remove(V value) { - synchronized (cacheList) { - cacheList.remove(value); - } - } - - public int size() { - synchronized (cacheList) { - return cacheList.size(); - } - } - - public boolean doesAutomaticCleanup() { - return timer != null; - } - - public void cleanup() { - long now = System.currentTimeMillis(); - ArrayList delete = null; - - synchronized (cacheList) { - Iterator> iterator = cacheList.iterator(); - delete = new ArrayList<>((cacheList.size() / 2) + 1); - - while (iterator.hasNext()) { - CachedObject object = iterator.next(); - if (object != null && (now > (timeToLive + object.getLastAccess()))) { - delete.add(object.getValue(false)); - } - } - } - - if (action != null) { - action.accept(delete); - } - - for (V value : delete) { - synchronized (cacheList) { - cacheList.remove(value); - } - Thread.yield(); - } - } + private final List> cacheList; + private final long timeToLive; + + private final Consumer> action; + private final Thread timer; + + public CacheList(long timeToLive, final long timerInterval, int maxItems) { + this(timeToLive, timerInterval, maxItems, null); + } + + public CacheList(long timeToLive, final long timerInterval, int maxItems, Consumer> action) { + this.cacheList = Collections.synchronizedList(new ArrayList<>(maxItems)); + this.timeToLive = timeToLive * 1000; + this.action = action; + if (timeToLive > 0 && timerInterval > 0) { + timer = new Thread(() -> { + while (true) { + try { + Thread.sleep(timerInterval * 1000); + } catch (InterruptedException ex) { + } + cleanup(); + } + }); + } else { + timer = null; + } + } + + public ArrayList getListCopy() { + ArrayList values = new ArrayList<>(size()); + synchronized (cacheList) { + Iterator> iterator = cacheList.iterator(); + while (iterator.hasNext()) { + values.add(iterator.next().getValue()); + } + } + return values; + } + + public void add(V value) { + synchronized (cacheList) { + cacheList.add(new CachedObject(value)); + } + } + + public V get(int index) { + synchronized (cacheList) { + CachedObject object = cacheList.get(index); + if (object == null) { + return null; + } + return object.getValue(); + } + } + + public Optional predicateFilter(Predicate predicate) { + synchronized (cacheList) { + return cacheList.stream().filter(object -> predicate.test(object.getValue(false))).findFirst() + .map(cachedObject -> cachedObject.getValue()); + } + } + + public Optional streamFilter(Function, Optional> filter) { + synchronized (cacheList) { + Optional filtered = filter.apply(cacheList.stream().map(object -> object.getValue(false))); + return !filtered.isPresent() ? filtered + : cacheList.stream().filter(object -> object.getValue(false) == filtered.get()).findFirst() + .map(object -> object.getValue()); + } + } + + public boolean contains(V value) { + synchronized (cacheList) { + return cacheList.stream().anyMatch(object -> object.getValue(false) == value); + } + } + + public void forEach(Consumer consume) { + synchronized (cacheList) { + cacheList.stream().map(object -> object.getValue()).forEach(consume); + } + } + + public void remove(int index) { + synchronized (cacheList) { + cacheList.remove(index); + } + } + + public void remove(V value) { + synchronized (cacheList) { + cacheList.remove(value); + } + } + + public int size() { + synchronized (cacheList) { + return cacheList.size(); + } + } + + public boolean doesAutomaticCleanup() { + return timer != null; + } + + public void cleanup() { + long now = System.currentTimeMillis(); + ArrayList delete = null; + + synchronized (cacheList) { + Iterator> iterator = cacheList.iterator(); + delete = new ArrayList<>((cacheList.size() / 2) + 1); + + while (iterator.hasNext()) { + CachedObject object = iterator.next(); + if (object != null && (now > (timeToLive + object.getLastAccess()))) { + delete.add(object.getValue(false)); + } + } + } + + if (action != null) { + action.accept(delete); + } + + for (V value : delete) { + synchronized (cacheList) { + cacheList.remove(value); + } + Thread.yield(); + } + } } diff --git a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheMap.java b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheMap.java index c42cd53..d15448c 100644 --- a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheMap.java +++ b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CacheMap.java @@ -10,119 +10,121 @@ public class CacheMap { - private final Map> cacheMap; - private final long timeToLive; - - private final Consumer>> action; - private final Thread timer; - - public CacheMap(long timeToLive, final long timerInterval, int maxItems) { - this(timeToLive, timerInterval, maxItems, null); - } - - public CacheMap(long timeToLive, final long timerInterval, int maxItems, Consumer>> action) { - this.cacheMap = Collections.synchronizedMap(new HashMap<>(maxItems)); - this.timeToLive = timeToLive * 1000; - this.action = action; - if (timeToLive > 0 && timerInterval > 0) { - timer = new Thread(() -> { - while (true) { - try { - Thread.sleep(timerInterval * 1000); - } catch (InterruptedException ex) { - } - cleanup(); - } - }); - } else - timer = null; - } - - public void put(K key, V value) { - synchronized (cacheMap) { - cacheMap.put(key, new CachedObject(value)); - } - } - - public V get(K key) { - synchronized (cacheMap) { - CachedObject object = cacheMap.get(key); - if (object == null) - return null; - return object.getValue(); - } - } - - public void remove(K key) { - synchronized (cacheMap) { - cacheMap.remove(key); - } - } - - public int size() { - synchronized (cacheMap) { - return cacheMap.size(); - } - } - - public boolean doesAutomaticCleanup() { - return timer != null; - } - - public void cleanup() { - long now = System.currentTimeMillis(); - ArrayList> delete = null; - - synchronized (cacheMap) { - Iterator>> iterator = cacheMap.entrySet().iterator(); - delete = new ArrayList<>((cacheMap.size() / 2) + 1); - - while (iterator.hasNext()) { - Entry> entry = iterator.next(); - CachedObject object = entry.getValue(); - if (object != null && (now > (timeToLive + object.getLastAccess()))) { - delete.add(new CacheEntry<>(entry.getKey(), object.getValue(false))); - } - } - } - - if (action != null) { - action.accept(delete); - } - - for (CacheEntry key : delete) { - synchronized (cacheMap) { - cacheMap.remove(key); - } - Thread.yield(); - } - } - - public static class CacheEntry implements Entry { - - private final L key; - private final B value; - - protected CacheEntry(L key, B value) { - this.value = value; - this.key = key; - } - - @Override - public L getKey() { - return key; - } - - @Override - public B getValue() { - return value; - } - - @Override - public B setValue(B value) { - return this.value; - } - - } + private final Map> cacheMap; + private final long timeToLive; + + private final Consumer>> action; + private final Thread timer; + + public CacheMap(long timeToLive, final long timerInterval, int maxItems) { + this(timeToLive, timerInterval, maxItems, null); + } + + public CacheMap(long timeToLive, final long timerInterval, int maxItems, Consumer>> action) { + this.cacheMap = Collections.synchronizedMap(new HashMap<>(maxItems)); + this.timeToLive = timeToLive * 1000; + this.action = action; + if (timeToLive > 0 && timerInterval > 0) { + timer = new Thread(() -> { + while (true) { + try { + Thread.sleep(timerInterval * 1000); + } catch (InterruptedException ex) { + } + cleanup(); + } + }); + } else { + timer = null; + } + } + + public void put(K key, V value) { + synchronized (cacheMap) { + cacheMap.put(key, new CachedObject(value)); + } + } + + public V get(K key) { + synchronized (cacheMap) { + CachedObject object = cacheMap.get(key); + if (object == null) { + return null; + } + return object.getValue(); + } + } + + public void remove(K key) { + synchronized (cacheMap) { + cacheMap.remove(key); + } + } + + public int size() { + synchronized (cacheMap) { + return cacheMap.size(); + } + } + + public boolean doesAutomaticCleanup() { + return timer != null; + } + + public void cleanup() { + long now = System.currentTimeMillis(); + ArrayList> delete = null; + + synchronized (cacheMap) { + Iterator>> iterator = cacheMap.entrySet().iterator(); + delete = new ArrayList<>((cacheMap.size() / 2) + 1); + + while (iterator.hasNext()) { + Entry> entry = iterator.next(); + CachedObject object = entry.getValue(); + if (object != null && (now > (timeToLive + object.getLastAccess()))) { + delete.add(new CacheEntry<>(entry.getKey(), object.getValue(false))); + } + } + } + + if (action != null) { + action.accept(delete); + } + + for (CacheEntry key : delete) { + synchronized (cacheMap) { + cacheMap.remove(key); + } + Thread.yield(); + } + } + + public static class CacheEntry implements Entry { + + private final L key; + private final B value; + + protected CacheEntry(L key, B value) { + this.value = value; + this.key = key; + } + + @Override + public L getKey() { + return key; + } + + @Override + public B getValue() { + return value; + } + + @Override + public B setValue(B value) { + return this.value; + } + + } } diff --git a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CachedObject.java b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CachedObject.java index 3aea8f8..5184911 100644 --- a/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CachedObject.java +++ b/utils/cache/src/main/java/com/syntaxphoenix/syntaxapi/utils/cache/CachedObject.java @@ -2,25 +2,26 @@ public class CachedObject { - private final V value; - private long lastAccessed = System.currentTimeMillis(); + private final V value; + private long lastAccessed = System.currentTimeMillis(); - public CachedObject(V value) { - this.value = value; - } + public CachedObject(V value) { + this.value = value; + } - public long getLastAccess() { - return lastAccessed; - } + public long getLastAccess() { + return lastAccessed; + } - public V getValue() { - return getValue(true); - } + public V getValue() { + return getValue(true); + } - final V getValue(boolean update) { - if (update) - lastAccessed = System.currentTimeMillis(); - return value; - } + final V getValue(boolean update) { + if (update) { + lastAccessed = System.currentTimeMillis(); + } + return value; + } } diff --git a/utils/general/src/main/java/com/syntaxphoenix/syntaxapi/utils/general/Status.java b/utils/general/src/main/java/com/syntaxphoenix/syntaxapi/utils/general/Status.java index 84d5fef..d41a397 100644 --- a/utils/general/src/main/java/com/syntaxphoenix/syntaxapi/utils/general/Status.java +++ b/utils/general/src/main/java/com/syntaxphoenix/syntaxapi/utils/general/Status.java @@ -2,238 +2,245 @@ public class Status { - public static final Status EMPTY = new Status(true); - - public static final Status create() { - return new Status(false); - }; - - private final Object sync = new Object(); - - private int total = 0; - private int failed = 0; - private int success = 0; - private int skipped = 0; - private int cancelled = 0; - - private int marked = 0; - - private boolean done = false; - - /** - * Constructs a Status with an specific done state - * - * @param loaded - defines if it was loaded or not - */ - private Status(boolean done) { - synchronized (sync) { - this.done = done; - } - } - - /** - * Constructs a Status - * - * @param total - starting total amount of objects to load - */ - public Status(int total) { - synchronized (sync) { - this.total = total; - } - } - - /** - * Set the loading to done - */ - public void done() { - synchronized (sync) { - done = true; - } - } - - /** - * Checks if loading is completly done - * - * @return if loading is done - */ - public boolean isDone() { - synchronized (sync) { - return done; - } - } - - /** - * Marks one object as successful - * - * @return if it was marked or not - */ - public boolean success() { - if (isDone() || !mark()) - return false; - synchronized (sync) { - success++; - } - return true; - } - - /** - * Marks one object as successful - * - * @return if it was marked or not - */ - public boolean failed() { - if (isDone() || !mark()) - return false; - synchronized (sync) { - failed++; - } - return true; - } - - /** - * Marks one object as skipped - * - * @return if it was marked or not - */ - public boolean skip() { - if (isDone() || !mark()) - return false; - synchronized (sync) { - skipped++; - } - return true; - } - - /** - * Marks one object as cancelled - * - * @return if it was marked or not - */ - public boolean cancel() { - if (isDone() || !mark()) - return false; - synchronized (sync) { - cancelled++; - } - return true; - } - - /** - * Marks an object - * - * @return if it was marked or not - */ - private boolean mark() { - if (marked == total) - return false; - synchronized (sync) { - marked++; - } - return true; - } - - /** - * Add one object to total objects to load - */ - public void add() { - add(1); - } - - /** - * Add amount to total objects to load - * - * @param amount - amount to add - */ - public void add(int amount) { - if (isDone()) - return; - synchronized (sync) { - total += amount; - } - } - - /** - * Add LoadingStatus to this status - * - * @param status - LoadingStatus to add - */ - public void add(Status status) { - if (isDone()) - return; - synchronized (sync) { - total += status.total; - failed += status.failed; - marked += status.marked; - success += status.success; - skipped += status.skipped; - cancelled += status.cancelled; - } - } - - /** - * Get the total amount of objects to load - * - * @return the total amount - */ - public int getTotal() { - synchronized (sync) { - return total; - } - } - - /** - * Get the total amount of objects that were marked - * - * @return the marked amount - */ - public int getMarked() { - synchronized (sync) { - return marked; - } - } - - /** - * Get the total amount of objects that failed to load - * - * @return the failed amount - */ - public int getFailed() { - synchronized (sync) { - return failed; - } - } - - /** - * Get the amount of objects that we successfully loaded - * - * @return the successful amount - */ - public int getSuccess() { - synchronized (sync) { - return success; - } - } - - /** - * Get the amount of objects that were not loaded - * - * @return the not loaded amount - */ - public int getSkipped() { - synchronized (sync) { - return skipped; - } - } - - /** - * Get the amount of objects that were cancelled on load - * - * @return the cancelled amount - */ - public int getCancelled() { - synchronized (sync) { - return cancelled; - } - } + public static final Status EMPTY = new Status(true); + + public static final Status create() { + return new Status(false); + }; + + private final Object sync = new Object(); + + private int total = 0; + private int failed = 0; + private int success = 0; + private int skipped = 0; + private int cancelled = 0; + + private int marked = 0; + + private boolean done = false; + + /** + * Constructs a Status with an specific done state + * + * @param loaded - defines if it was loaded or not + */ + private Status(boolean done) { + synchronized (sync) { + this.done = done; + } + } + + /** + * Constructs a Status + * + * @param total - starting total amount of objects to load + */ + public Status(int total) { + synchronized (sync) { + this.total = total; + } + } + + /** + * Set the loading to done + */ + public void done() { + synchronized (sync) { + done = true; + } + } + + /** + * Checks if loading is completly done + * + * @return if loading is done + */ + public boolean isDone() { + synchronized (sync) { + return done; + } + } + + /** + * Marks one object as successful + * + * @return if it was marked or not + */ + public boolean success() { + if (isDone() || !mark()) { + return false; + } + synchronized (sync) { + success++; + } + return true; + } + + /** + * Marks one object as successful + * + * @return if it was marked or not + */ + public boolean failed() { + if (isDone() || !mark()) { + return false; + } + synchronized (sync) { + failed++; + } + return true; + } + + /** + * Marks one object as skipped + * + * @return if it was marked or not + */ + public boolean skip() { + if (isDone() || !mark()) { + return false; + } + synchronized (sync) { + skipped++; + } + return true; + } + + /** + * Marks one object as cancelled + * + * @return if it was marked or not + */ + public boolean cancel() { + if (isDone() || !mark()) { + return false; + } + synchronized (sync) { + cancelled++; + } + return true; + } + + /** + * Marks an object + * + * @return if it was marked or not + */ + private boolean mark() { + if (marked == total) { + return false; + } + synchronized (sync) { + marked++; + } + return true; + } + + /** + * Add one object to total objects to load + */ + public void add() { + add(1); + } + + /** + * Add amount to total objects to load + * + * @param amount - amount to add + */ + public void add(int amount) { + if (isDone()) { + return; + } + synchronized (sync) { + total += amount; + } + } + + /** + * Add LoadingStatus to this status + * + * @param status - LoadingStatus to add + */ + public void add(Status status) { + if (isDone()) { + return; + } + synchronized (sync) { + total += status.total; + failed += status.failed; + marked += status.marked; + success += status.success; + skipped += status.skipped; + cancelled += status.cancelled; + } + } + + /** + * Get the total amount of objects to load + * + * @return the total amount + */ + public int getTotal() { + synchronized (sync) { + return total; + } + } + + /** + * Get the total amount of objects that were marked + * + * @return the marked amount + */ + public int getMarked() { + synchronized (sync) { + return marked; + } + } + + /** + * Get the total amount of objects that failed to load + * + * @return the failed amount + */ + public int getFailed() { + synchronized (sync) { + return failed; + } + } + + /** + * Get the amount of objects that we successfully loaded + * + * @return the successful amount + */ + public int getSuccess() { + synchronized (sync) { + return success; + } + } + + /** + * Get the amount of objects that were not loaded + * + * @return the not loaded amount + */ + public int getSkipped() { + synchronized (sync) { + return skipped; + } + } + + /** + * Get the amount of objects that were cancelled on load + * + * @return the cancelled amount + */ + public int getCancelled() { + synchronized (sync) { + return cancelled; + } + } } diff --git a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Deserializer.java b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Deserializer.java index 21aa59b..ef85b1b 100644 --- a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Deserializer.java +++ b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Deserializer.java @@ -1,6 +1,11 @@ package com.syntaxphoenix.syntaxapi.utils.io; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; /** @@ -19,71 +24,72 @@ */ public interface Deserializer { - /** - * Deserializes an object from an {@link InputStream}. - * - * @param stream the stream - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - public abstract T fromStream(InputStream stream) throws IOException; + /** + * Deserializes an object from an {@link InputStream}. + * + * @param stream the stream + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + public abstract T fromStream(InputStream stream) throws IOException; - /** - * Deserializes an object from a {@link File} using a {@link FileInputStream}. - * - * @param file the file - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - public default T fromFile(File file) throws IOException { - try (InputStream stream = new FileInputStream(file)) { - try (BufferedInputStream buffStream = new BufferedInputStream(stream)) { - return fromStream(buffStream); - } - } - } + /** + * Deserializes an object from a {@link File} using a {@link FileInputStream}. + * + * @param file the file + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + public default T fromFile(File file) throws IOException { + try (InputStream stream = new FileInputStream(file)) { + try (BufferedInputStream buffStream = new BufferedInputStream(stream)) { + return fromStream(buffStream); + } + } + } - /** - * Deserializes an object from a {@code byte[]} using a - * {@link ByteArrayInputStream}. - * - * @param bytes the byte array - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - public default T fromBytes(byte[] bytes) throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream(bytes); - return fromStream(stream); - } + /** + * Deserializes an object from a {@code byte[]} using a + * {@link ByteArrayInputStream}. + * + * @param bytes the byte array + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + public default T fromBytes(byte[] bytes) throws IOException { + ByteArrayInputStream stream = new ByteArrayInputStream(bytes); + return fromStream(stream); + } - /** - * Deserializes an object from a {@link Class} and a resource path by opening a - * stream to the resource via the {@link ClassLoader}. - * - * @param clazz the class which's class loader is to be used - * @param resPath the path to the resource - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - public default T fromResource(Class clazz, String resPath) throws IOException { - try (InputStream stream = clazz.getClassLoader().getResourceAsStream(resPath)) { - if (stream == null) - throw new IOException("resource \"" + resPath + "\" could not be found"); - return fromStream(stream); - } - } + /** + * Deserializes an object from a {@link Class} and a resource path by opening a + * stream to the resource via the {@link ClassLoader}. + * + * @param clazz the class which's class loader is to be used + * @param resPath the path to the resource + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + public default T fromResource(Class clazz, String resPath) throws IOException { + try (InputStream stream = clazz.getClassLoader().getResourceAsStream(resPath)) { + if (stream == null) { + throw new IOException("resource \"" + resPath + "\" could not be found"); + } + return fromStream(stream); + } + } - /** - * Deserializes an object from a {@link URL} by opening a stream to it. - * - * @param url the url - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - public default T fromURL(URL url) throws IOException { - try (InputStream stream = url.openStream()) { - return fromStream(stream); - } - } + /** + * Deserializes an object from a {@link URL} by opening a stream to it. + * + * @param url the url + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + public default T fromURL(URL url) throws IOException { + try (InputStream stream = url.openStream()) { + return fromStream(stream); + } + } } diff --git a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/PrintWriter.java b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/PrintWriter.java index c0a59ac..563f56c 100644 --- a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/PrintWriter.java +++ b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/PrintWriter.java @@ -7,41 +7,44 @@ public class PrintWriter extends PrintStream { - private final PrintStream stream; - private boolean file = false; - - public PrintWriter(File file, PrintStream stream) throws FileNotFoundException { - super(file); - this.stream = stream; - } - - public void writeFile(boolean state) { - file = state; - } - - public boolean writeFile() { - return file; - } - - @Override - public void write(byte[] b) throws IOException { - stream.write(b); - if (file) - super.write(b); - } - - @Override - public void write(byte[] buf, int off, int len) { - stream.write(buf, off, len); - if (file) - super.write(buf, off, len); - } - - @Override - public void write(int b) { - stream.write(b); - if (file) - super.write(b); - } + private final PrintStream stream; + private boolean file = false; + + public PrintWriter(File file, PrintStream stream) throws FileNotFoundException { + super(file); + this.stream = stream; + } + + public void writeFile(boolean state) { + file = state; + } + + public boolean writeFile() { + return file; + } + + @Override + public void write(byte[] b) throws IOException { + stream.write(b); + if (file) { + super.write(b); + } + } + + @Override + public void write(byte[] buf, int off, int len) { + stream.write(buf, off, len); + if (file) { + super.write(buf, off, len); + } + } + + @Override + public void write(int b) { + stream.write(b); + if (file) { + super.write(b); + } + } } diff --git a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Serializer.java b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Serializer.java index 4649b78..a20b6fd 100644 --- a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Serializer.java +++ b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/Serializer.java @@ -1,6 +1,11 @@ package com.syntaxphoenix.syntaxapi.utils.io; -import java.io.*; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; /** * Throwaway object for writing objects to files. @@ -18,61 +23,61 @@ */ public interface Serializer { - /** - * Writes the object into a {@link OutputStream}. - * - * @param object the object - * @param stream the output stream - * @throws IOException if an I/O error occurs - */ - public void toStream(T object, OutputStream stream) throws IOException; + /** + * Writes the object into a {@link OutputStream}. + * + * @param object the object + * @param stream the output stream + * @throws IOException if an I/O error occurs + */ + public void toStream(T object, OutputStream stream) throws IOException; - /** - * Writes the object into a {@link File} using a {@link FileOutputStream}. - * - * @param object the object - * @param file the file - * @throws IOException if an I/O error occurs - */ - public default void toFile(T object, File file) throws IOException { - try (FileOutputStream stream = new FileOutputStream(file)) { - try (BufferedOutputStream buffStream = new BufferedOutputStream(stream)) { - toStream(object, buffStream); - } - } - } + /** + * Writes the object into a {@link File} using a {@link FileOutputStream}. + * + * @param object the object + * @param file the file + * @throws IOException if an I/O error occurs + */ + public default void toFile(T object, File file) throws IOException { + try (FileOutputStream stream = new FileOutputStream(file)) { + try (BufferedOutputStream buffStream = new BufferedOutputStream(stream)) { + toStream(object, buffStream); + } + } + } - /** - * Writes the object into bytes {@code byte[]} using a - * {@link ByteArrayOutputStream} with set capacity. - * - * @param object the object - * @param capacity the byte buffer capacity used by the stream - * @return a byte array containing the serialized object - * @throws IOException if an I/O error occurs - * @see ByteArrayOutputStream#ByteArrayOutputStream(int) - */ - public default byte[] toBytes(T object, int capacity) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(capacity); - this.toStream(object, stream); - stream.close(); - return stream.toByteArray(); - } + /** + * Writes the object into bytes {@code byte[]} using a + * {@link ByteArrayOutputStream} with set capacity. + * + * @param object the object + * @param capacity the byte buffer capacity used by the stream + * @return a byte array containing the serialized object + * @throws IOException if an I/O error occurs + * @see ByteArrayOutputStream#ByteArrayOutputStream(int) + */ + public default byte[] toBytes(T object, int capacity) throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(capacity); + this.toStream(object, stream); + stream.close(); + return stream.toByteArray(); + } - /** - * Writes the object into bytes {@code byte[]} using a - * {@link ByteArrayOutputStream} with unset capacity. - * - * @param object the object - * @return a byte array containing the serialized object - * @throws IOException if an I/O error occurs - * @see ByteArrayOutputStream#ByteArrayOutputStream() - */ - public default byte[] toBytes(T object) throws IOException { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - this.toStream(object, stream); - stream.close(); - return stream.toByteArray(); - } + /** + * Writes the object into bytes {@code byte[]} using a + * {@link ByteArrayOutputStream} with unset capacity. + * + * @param object the object + * @return a byte array containing the serialized object + * @throws IOException if an I/O error occurs + * @see ByteArrayOutputStream#ByteArrayOutputStream() + */ + public default byte[] toBytes(T object) throws IOException { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + this.toStream(object, stream); + stream.close(); + return stream.toByteArray(); + } } diff --git a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextDeserializer.java b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextDeserializer.java index 0d2137e..54fdce8 100644 --- a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextDeserializer.java +++ b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextDeserializer.java @@ -1,6 +1,13 @@ package com.syntaxphoenix.syntaxapi.utils.io; -import java.io.*; +import java.io.CharArrayReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; /** * Throwaway object only meant to perform one deserialization of a reader. @@ -17,49 +24,49 @@ */ public interface TextDeserializer extends Deserializer { - /** - * Deserializes an object from a {@link Reader}. - * - * @param reader the reader - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - abstract T fromReader(Reader reader) throws IOException; + /** + * Deserializes an object from a {@link Reader}. + * + * @param reader the reader + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + abstract T fromReader(Reader reader) throws IOException; - /** - * Deserializes an object from a char array using a {@link CharArrayReader}. - * - * @param chars the char array - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - default T fromCharArray(char[] chars) throws IOException { - return fromReader(new CharArrayReader(chars)); - } + /** + * Deserializes an object from a char array using a {@link CharArrayReader}. + * + * @param chars the char array + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + default T fromCharArray(char[] chars) throws IOException { + return fromReader(new CharArrayReader(chars)); + } - /** - * Deserializes an object from a {@link String} using a {@link StringReader}. - * - * @param str the string - * @return the deserialized object - * @throws IOException if the deserialization fails - */ - default T fromString(String str) throws IOException { - return fromReader(new StringReader(str)); - } + /** + * Deserializes an object from a {@link String} using a {@link StringReader}. + * + * @param str the string + * @return the deserialized object + * @throws IOException if the deserialization fails + */ + default T fromString(String str) throws IOException { + return fromReader(new StringReader(str)); + } - @Override - default T fromStream(InputStream stream) throws IOException { - try (Reader reader = new InputStreamReader(stream)) { - return fromReader(reader); - } - } + @Override + default T fromStream(InputStream stream) throws IOException { + try (Reader reader = new InputStreamReader(stream)) { + return fromReader(reader); + } + } - @Override - default T fromFile(File file) throws IOException { - try (Reader reader = new FileReader(file)) { - return fromReader(reader); - } - } + @Override + default T fromFile(File file) throws IOException { + try (Reader reader = new FileReader(file)) { + return fromReader(reader); + } + } } diff --git a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextSerializer.java b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextSerializer.java index 284cbfd..ac25128 100644 --- a/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextSerializer.java +++ b/utils/io/src/main/java/com/syntaxphoenix/syntaxapi/utils/io/TextSerializer.java @@ -1,71 +1,78 @@ package com.syntaxphoenix.syntaxapi.utils.io; -import java.io.*; +import java.io.CharArrayWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.io.Writer; public interface TextSerializer extends Serializer { - /** - * Writes the object into a {@link Writer}. - * - * @param object the object - * @param writer the writer - * @throws IOException if an I/O error occurs - */ - void toWriter(T object, Writer writer) throws IOException; + /** + * Writes the object into a {@link Writer}. + * + * @param object the object + * @param writer the writer + * @throws IOException if an I/O error occurs + */ + void toWriter(T object, Writer writer) throws IOException; - /** - * Writes the object into a char array. - * - * @param object the object - * @return the written char array - * @throws IOException if an I/O error occurs - */ - default char[] toCharArray(T object) throws IOException { - CharArrayWriter writer = new CharArrayWriter(); - toWriter(object, writer); - return writer.toCharArray(); - } + /** + * Writes the object into a char array. + * + * @param object the object + * @return the written char array + * @throws IOException if an I/O error occurs + */ + default char[] toCharArray(T object) throws IOException { + CharArrayWriter writer = new CharArrayWriter(); + toWriter(object, writer); + return writer.toCharArray(); + } - /** - * Writes the object into a {@link String} using a {@link StringWriter}. - * - * @param object the object - * @throws IOException if an I/O error occurs - * @return object written to a string - */ - default String toString(T object) throws IOException { - Writer writer = new StringWriter(); - toWriter(object, writer); - return writer.toString(); - } + /** + * Writes the object into a {@link String} using a {@link StringWriter}. + * + * @param object the object + * @throws IOException if an I/O error occurs + * @return object written to a string + */ + default String toString(T object) throws IOException { + Writer writer = new StringWriter(); + toWriter(object, writer); + return writer.toString(); + } - /** - * Writes the object into an {@link OutputStream} using an - * {@link OutputStreamWriter}. - * - * @param object the object - * @param stream the stream - * @throws IOException if an I/O error occurs - */ - @Override - default void toStream(T object, OutputStream stream) throws IOException { - Writer writer = new OutputStreamWriter(stream); - toWriter(object, writer); - writer.flush(); - } + /** + * Writes the object into an {@link OutputStream} using an + * {@link OutputStreamWriter}. + * + * @param object the object + * @param stream the stream + * @throws IOException if an I/O error occurs + */ + @Override + default void toStream(T object, OutputStream stream) throws IOException { + Writer writer = new OutputStreamWriter(stream); + toWriter(object, writer); + writer.flush(); + } - /** - * Writes the object into a {@link File} using an {@link FileWriter}. - * - * @param object the object - * @param file the file - * @throws IOException if an I/O error occurs - */ - @Override - default void toFile(T object, File file) throws IOException { - try (Writer writer = new FileWriter(file)) { - toWriter(object, writer); - } - } + /** + * Writes the object into a {@link File} using an {@link FileWriter}. + * + * @param object the object + * @param file the file + * @throws IOException if an I/O error occurs + */ + @Override + default void toFile(T object, File file) throws IOException { + try (Writer writer = new FileWriter(file)) { + toWriter(object, writer); + } + } } diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/AbstractStringBuilder.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/AbstractStringBuilder.java index 0197c25..0712cb8 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/AbstractStringBuilder.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/AbstractStringBuilder.java @@ -6,571 +6,570 @@ @SuppressWarnings("restriction") abstract class AbstractStringBuilder implements Appendable, CharSequence { - char[] value; - int count; - @SuppressWarnings("unused") - private static final int MAX_ARRAY_SIZE = 2147483639; - - AbstractStringBuilder() { - } - - AbstractStringBuilder(int var1) { - this.value = new char[var1]; - } - - @Override - public int length() { - return this.count; - } - - public int capacity() { - return this.value.length; - } - - public void ensureCapacity(int var1) { - if (var1 > 0) { - this.ensureCapacityInternal(var1); - } - - } - - private void ensureCapacityInternal(int var1) { - if (var1 - this.value.length > 0) { - this.value = Arrays.copyOf(this.value, this.newCapacity(var1)); - } - - } - - private int newCapacity(int var1) { - int var2 = (this.value.length << 1) + 2; - if (var2 - var1 < 0) { - var2 = var1; - } - - return var2 > 0 && 2147483639 - var2 >= 0 ? var2 : this.hugeCapacity(var1); - } - - private int hugeCapacity(int var1) { - if (Integer.MAX_VALUE - var1 < 0) { - throw new OutOfMemoryError(); - } else { - return var1 > 2147483639 ? var1 : 2147483639; - } - } - - public void trimToSize() { - if (this.count < this.value.length) { - this.value = Arrays.copyOf(this.value, this.count); - } - - } - - public void setLength(int var1) { - if (var1 < 0) { - throw new StringIndexOutOfBoundsException(var1); - } else { - this.ensureCapacityInternal(var1); - if (this.count < var1) { - Arrays.fill(this.value, this.count, var1, ' '); - } - - this.count = var1; - } - } - - @Override - public char charAt(int var1) { - if (var1 >= 0 && var1 < this.count) { - return this.value[var1]; - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public int codePointAt(int var1) { - if (var1 >= 0 && var1 < this.count) { - return CharacterTools.codePointAtImpl(this.value, var1, this.count); - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public int codePointBefore(int var1) { - int var2 = var1 - 1; - if (var2 >= 0 && var2 < this.count) { - return CharacterTools.codePointBeforeImpl(this.value, var1, 0); - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public int codePointCount(int var1, int var2) { - if (var1 >= 0 && var2 <= this.count && var1 <= var2) { - return CharacterTools.codePointCountImpl(this.value, var1, var2 - var1); - } else { - throw new IndexOutOfBoundsException(); - } - } - - public int offsetByCodePoints(int var1, int var2) { - if (var1 >= 0 && var1 <= this.count) { - return CharacterTools.offsetByCodePointsImpl(this.value, 0, this.count, var1, var2); - } else { - throw new IndexOutOfBoundsException(); - } - } - - public void getChars(int var1, int var2, char[] var3, int var4) { - if (var1 < 0) { - throw new StringIndexOutOfBoundsException(var1); - } else if (var2 >= 0 && var2 <= this.count) { - if (var1 > var2) { - throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); - } else { - System.arraycopy(this.value, var1, var3, var4, var2 - var1); - } - } else { - throw new StringIndexOutOfBoundsException(var2); - } - } - - public void setCharAt(int var1, char var2) { - if (var1 >= 0 && var1 < this.count) { - this.value[var1] = var2; - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public AbstractStringBuilder append(Object var1) { - return this.append(String.valueOf(var1)); - } - - public AbstractStringBuilder append(String var1) { - if (var1 == null) { - return this.appendNull(); - } else { - int var2 = var1.length(); - this.ensureCapacityInternal(this.count + var2); - var1.getChars(0, var2, this.value, this.count); - this.count += var2; - return this; - } - } - - public AbstractStringBuilder append(StringBuffer var1) { - if (var1 == null) { - return this.appendNull(); - } else { - int var2 = var1.length(); - this.ensureCapacityInternal(this.count + var2); - var1.getChars(0, var2, this.value, this.count); - this.count += var2; - return this; - } - } - - AbstractStringBuilder append(AbstractStringBuilder var1) { - if (var1 == null) { - return this.appendNull(); - } else { - int var2 = var1.length(); - this.ensureCapacityInternal(this.count + var2); - var1.getChars(0, var2, this.value, this.count); - this.count += var2; - return this; - } - } - - @Override - public AbstractStringBuilder append(CharSequence var1) { - if (var1 == null) { - return this.appendNull(); - } else if (var1 instanceof String) { - return this.append((String) var1); - } else { - return var1 instanceof AbstractStringBuilder ? this.append((AbstractStringBuilder) var1) : this.append(var1, 0, var1.length()); - } - } - - private AbstractStringBuilder appendNull() { - int var1 = this.count; - this.ensureCapacityInternal(var1 + 4); - char[] var2 = this.value; - var2[var1++] = 'n'; - var2[var1++] = 'u'; - var2[var1++] = 'l'; - var2[var1++] = 'l'; - this.count = var1; - return this; - } - - @Override - public AbstractStringBuilder append(CharSequence var1, int var2, int var3) { - if (var1 == null) { - var1 = "null"; - } - - if (var2 >= 0 && var2 <= var3 && var3 <= var1.length()) { - int var4 = var3 - var2; - this.ensureCapacityInternal(this.count + var4); - int var5 = var2; - - for (int var6 = this.count; var5 < var3; ++var6) { - this.value[var6] = var1.charAt(var5); - ++var5; - } - - this.count += var4; - return this; - } else { - throw new IndexOutOfBoundsException("start " + var2 + ", end " + var3 + ", s.length() " + var1.length()); - } - } - - public AbstractStringBuilder append(char[] var1) { - int var2 = var1.length; - this.ensureCapacityInternal(this.count + var2); - System.arraycopy(var1, 0, this.value, this.count, var2); - this.count += var2; - return this; - } - - public AbstractStringBuilder append(char[] var1, int var2, int var3) { - if (var3 > 0) { - this.ensureCapacityInternal(this.count + var3); - } - - System.arraycopy(var1, var2, this.value, this.count, var3); - this.count += var3; - return this; - } - - public AbstractStringBuilder append(boolean var1) { - if (var1) { - this.ensureCapacityInternal(this.count + 4); - this.value[this.count++] = 't'; - this.value[this.count++] = 'r'; - this.value[this.count++] = 'u'; - this.value[this.count++] = 'e'; - } else { - this.ensureCapacityInternal(this.count + 5); - this.value[this.count++] = 'f'; - this.value[this.count++] = 'a'; - this.value[this.count++] = 'l'; - this.value[this.count++] = 's'; - this.value[this.count++] = 'e'; - } - - return this; - } - - @Override - public AbstractStringBuilder append(char var1) { - this.ensureCapacityInternal(this.count + 1); - this.value[this.count++] = var1; - return this; - } - - public AbstractStringBuilder append(int var1) { - if (var1 == Integer.MIN_VALUE) { - this.append("-2147483648"); - return this; - } else { - int var2 = var1 < 0 ? IntegerTools.stringSize(-var1) + 1 : IntegerTools.stringSize(var1); - int var3 = this.count + var2; - this.ensureCapacityInternal(var3); - IntegerTools.getChars(var1, var3, this.value); - this.count = var3; - return this; - } - } - - public AbstractStringBuilder append(long var1) { - if (var1 == Long.MIN_VALUE) { - this.append("-9223372036854775808"); - return this; - } else { - int var3 = var1 < 0L ? LongTools.stringSize(-var1) + 1 : LongTools.stringSize(var1); - int var4 = this.count + var3; - this.ensureCapacityInternal(var4); - LongTools.getChars(var1, var4, this.value); - this.count = var4; - return this; - } - } - - public AbstractStringBuilder append(float var1) { - FloatingDecimal.appendTo(var1, this); - return this; - } - - public AbstractStringBuilder append(double var1) { - FloatingDecimal.appendTo(var1, this); - return this; - } - - public AbstractStringBuilder delete(int var1, int var2) { - if (var1 < 0) { - throw new StringIndexOutOfBoundsException(var1); - } else { - if (var2 > this.count) { - var2 = this.count; - } - - if (var1 > var2) { - throw new StringIndexOutOfBoundsException(); - } else { - int var3 = var2 - var1; - if (var3 > 0) { - System.arraycopy(this.value, var1 + var3, this.value, var1, this.count - var2); - this.count -= var3; - } - - return this; - } - } - } - - public AbstractStringBuilder appendCodePoint(int var1) { - int var2 = this.count; - if (Character.isBmpCodePoint(var1)) { - this.ensureCapacityInternal(var2 + 1); - this.value[var2] = (char) var1; - this.count = var2 + 1; - } else { - if (!Character.isValidCodePoint(var1)) { - throw new IllegalArgumentException(); - } - - this.ensureCapacityInternal(var2 + 2); - CharacterTools.toSurrogates(var1, this.value, var2); - this.count = var2 + 2; - } - return this; - } - - public AbstractStringBuilder deleteCharAt(int var1) { - if (var1 >= 0 && var1 < this.count) { - System.arraycopy(this.value, var1 + 1, this.value, var1, this.count - var1 - 1); - --this.count; - return this; - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public AbstractStringBuilder replace(int var1, int var2, String var3) { - if (var1 < 0) { - throw new StringIndexOutOfBoundsException(var1); - } else if (var1 > this.count) { - throw new StringIndexOutOfBoundsException("start > length()"); - } else if (var1 > var2) { - throw new StringIndexOutOfBoundsException("start > end"); - } else { - if (var2 > this.count) { - var2 = this.count; - } - - int var4 = var3.length(); - int var5 = this.count + var4 - (var2 - var1); - this.ensureCapacityInternal(var5); - System.arraycopy(this.value, var2, this.value, var1 + var4, this.count - var2); - StringTools.getChars(var3, this.value, var1); - this.count = var5; - return this; - } - } - - public String substring(int var1) { - return this.substring(var1, this.count); - } - - @Override - public CharSequence subSequence(int var1, int var2) { - return this.substring(var1, var2); - } - - public String substring(int var1, int var2) { - if (var1 < 0) { - throw new StringIndexOutOfBoundsException(var1); - } else if (var2 > this.count) { - throw new StringIndexOutOfBoundsException(var2); - } else if (var1 > var2) { - throw new StringIndexOutOfBoundsException(var2 - var1); - } else { - return new String(this.value, var1, var2 - var1); - } - } - - public AbstractStringBuilder insert(int var1, char[] var2, int var3, int var4) { - if (var1 >= 0 && var1 <= this.length()) { - if (var3 >= 0 && var4 >= 0 && var3 <= var2.length - var4) { - this.ensureCapacityInternal(this.count + var4); - System.arraycopy(this.value, var1, this.value, var1 + var4, this.count - var1); - System.arraycopy(var2, var3, this.value, var1, var4); - this.count += var4; - return this; - } else { - throw new StringIndexOutOfBoundsException("offset " + var3 + ", len " + var4 + ", str.length " + var2.length); - } - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public AbstractStringBuilder insert(int var1, Object var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public AbstractStringBuilder insert(int var1, String var2) { - if (var1 >= 0 && var1 <= this.length()) { - if (var2 == null) { - var2 = "null"; - } - - int var3 = var2.length(); - this.ensureCapacityInternal(this.count + var3); - System.arraycopy(this.value, var1, this.value, var1 + var3, this.count - var1); - StringTools.getChars(var2, this.value, var1); - this.count += var3; - return this; - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public AbstractStringBuilder insert(int var1, char[] var2) { - if (var1 >= 0 && var1 <= this.length()) { - int var3 = var2.length; - this.ensureCapacityInternal(this.count + var3); - System.arraycopy(this.value, var1, this.value, var1 + var3, this.count - var1); - System.arraycopy(var2, 0, this.value, var1, var3); - this.count += var3; - return this; - } else { - throw new StringIndexOutOfBoundsException(var1); - } - } - - public AbstractStringBuilder insert(int var1, CharSequence var2) { - if (var2 == null) { - var2 = "null"; - } - - return var2 instanceof String ? this.insert(var1, (String) var2) : this.insert(var1, var2, 0, var2.length()); - } - - public AbstractStringBuilder insert(int var1, CharSequence var2, int var3, int var4) { - if (var2 == null) { - var2 = "null"; - } - - if (var1 >= 0 && var1 <= this.length()) { - if (var3 >= 0 && var4 >= 0 && var3 <= var4 && var4 <= var2.length()) { - int var5 = var4 - var3; - this.ensureCapacityInternal(this.count + var5); - System.arraycopy(this.value, var1, this.value, var1 + var5, this.count - var1); - - for (int var6 = var3; var6 < var4; ++var6) { - this.value[var1++] = var2.charAt(var6); - } - - this.count += var5; - return this; - } else { - throw new IndexOutOfBoundsException("start " + var3 + ", end " + var4 + ", s.length() " + var2.length()); - } - } else { - throw new IndexOutOfBoundsException("dstOffset " + var1); - } - } - - public AbstractStringBuilder insert(int var1, boolean var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public AbstractStringBuilder insert(int var1, char var2) { - this.ensureCapacityInternal(this.count + 1); - System.arraycopy(this.value, var1, this.value, var1 + 1, this.count - var1); - this.value[var1] = var2; - ++this.count; - return this; - } - - public AbstractStringBuilder insert(int var1, int var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public AbstractStringBuilder insert(int var1, long var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public AbstractStringBuilder insert(int var1, float var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public AbstractStringBuilder insert(int var1, double var2) { - return this.insert(var1, String.valueOf(var2)); - } - - public int indexOf(String var1) { - return this.indexOf(var1, 0); - } - - public int indexOf(String var1, int var2) { - return StringTools.indexOf(this.value, 0, this.count, var1, var2); - } - - public int lastIndexOf(String var1) { - return this.lastIndexOf(var1, this.count); - } - - public int lastIndexOf(String var1, int var2) { - return StringTools.lastIndexOf(this.value, 0, this.count, var1, var2); - } - - public AbstractStringBuilder reverse() { - boolean var1 = false; - int var2 = this.count - 1; - - for (int var3 = var2 - 1 >> 1; var3 >= 0; --var3) { - int var4 = var2 - var3; - char var5 = this.value[var3]; - char var6 = this.value[var4]; - this.value[var3] = var6; - this.value[var4] = var5; - if (Character.isSurrogate(var5) || Character.isSurrogate(var6)) { - var1 = true; - } - } - - if (var1) { - this.reverseAllValidSurrogatePairs(); - } - - return this; - } - - private void reverseAllValidSurrogatePairs() { - for (int var1 = 0; var1 < this.count - 1; ++var1) { - char var2 = this.value[var1]; - if (Character.isLowSurrogate(var2)) { - char var3 = this.value[var1 + 1]; - if (Character.isHighSurrogate(var3)) { - this.value[var1++] = var3; - this.value[var1] = var2; - } - } - } - - } - - @Override - public abstract String toString(); - - final char[] getValue() { - return this.value; - } + char[] value; + int count; + @SuppressWarnings("unused") + private static final int MAX_ARRAY_SIZE = 2147483639; + + AbstractStringBuilder() {} + + AbstractStringBuilder(int var1) { + this.value = new char[var1]; + } + + @Override + public int length() { + return this.count; + } + + public int capacity() { + return this.value.length; + } + + public void ensureCapacity(int var1) { + if (var1 > 0) { + this.ensureCapacityInternal(var1); + } + + } + + private void ensureCapacityInternal(int var1) { + if (var1 - this.value.length > 0) { + this.value = Arrays.copyOf(this.value, this.newCapacity(var1)); + } + + } + + private int newCapacity(int var1) { + int var2 = (this.value.length << 1) + 2; + if (var2 - var1 < 0) { + var2 = var1; + } + + return var2 > 0 && 2147483639 - var2 >= 0 ? var2 : this.hugeCapacity(var1); + } + + private int hugeCapacity(int var1) { + if (Integer.MAX_VALUE - var1 < 0) { + throw new OutOfMemoryError(); + } else { + return var1 > 2147483639 ? var1 : 2147483639; + } + } + + public void trimToSize() { + if (this.count < this.value.length) { + this.value = Arrays.copyOf(this.value, this.count); + } + + } + + public void setLength(int var1) { + if (var1 < 0) { + throw new StringIndexOutOfBoundsException(var1); + } else { + this.ensureCapacityInternal(var1); + if (this.count < var1) { + Arrays.fill(this.value, this.count, var1, ' '); + } + + this.count = var1; + } + } + + @Override + public char charAt(int var1) { + if (var1 >= 0 && var1 < this.count) { + return this.value[var1]; + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public int codePointAt(int var1) { + if (var1 >= 0 && var1 < this.count) { + return CharacterTools.codePointAtImpl(this.value, var1, this.count); + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public int codePointBefore(int var1) { + int var2 = var1 - 1; + if (var2 >= 0 && var2 < this.count) { + return CharacterTools.codePointBeforeImpl(this.value, var1, 0); + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public int codePointCount(int var1, int var2) { + if (var1 >= 0 && var2 <= this.count && var1 <= var2) { + return CharacterTools.codePointCountImpl(this.value, var1, var2 - var1); + } else { + throw new IndexOutOfBoundsException(); + } + } + + public int offsetByCodePoints(int var1, int var2) { + if (var1 >= 0 && var1 <= this.count) { + return CharacterTools.offsetByCodePointsImpl(this.value, 0, this.count, var1, var2); + } else { + throw new IndexOutOfBoundsException(); + } + } + + public void getChars(int var1, int var2, char[] var3, int var4) { + if (var1 < 0) { + throw new StringIndexOutOfBoundsException(var1); + } else if (var2 >= 0 && var2 <= this.count) { + if (var1 > var2) { + throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); + } else { + System.arraycopy(this.value, var1, var3, var4, var2 - var1); + } + } else { + throw new StringIndexOutOfBoundsException(var2); + } + } + + public void setCharAt(int var1, char var2) { + if (var1 >= 0 && var1 < this.count) { + this.value[var1] = var2; + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public AbstractStringBuilder append(Object var1) { + return this.append(String.valueOf(var1)); + } + + public AbstractStringBuilder append(String var1) { + if (var1 == null) { + return this.appendNull(); + } else { + int var2 = var1.length(); + this.ensureCapacityInternal(this.count + var2); + var1.getChars(0, var2, this.value, this.count); + this.count += var2; + return this; + } + } + + public AbstractStringBuilder append(StringBuffer var1) { + if (var1 == null) { + return this.appendNull(); + } else { + int var2 = var1.length(); + this.ensureCapacityInternal(this.count + var2); + var1.getChars(0, var2, this.value, this.count); + this.count += var2; + return this; + } + } + + AbstractStringBuilder append(AbstractStringBuilder var1) { + if (var1 == null) { + return this.appendNull(); + } else { + int var2 = var1.length(); + this.ensureCapacityInternal(this.count + var2); + var1.getChars(0, var2, this.value, this.count); + this.count += var2; + return this; + } + } + + @Override + public AbstractStringBuilder append(CharSequence var1) { + if (var1 == null) { + return this.appendNull(); + } else if (var1 instanceof String) { + return this.append((String) var1); + } else { + return var1 instanceof AbstractStringBuilder ? this.append((AbstractStringBuilder) var1) : this.append(var1, 0, var1.length()); + } + } + + private AbstractStringBuilder appendNull() { + int var1 = this.count; + this.ensureCapacityInternal(var1 + 4); + char[] var2 = this.value; + var2[var1++] = 'n'; + var2[var1++] = 'u'; + var2[var1++] = 'l'; + var2[var1++] = 'l'; + this.count = var1; + return this; + } + + @Override + public AbstractStringBuilder append(CharSequence var1, int var2, int var3) { + if (var1 == null) { + var1 = "null"; + } + + if (var2 >= 0 && var2 <= var3 && var3 <= var1.length()) { + int var4 = var3 - var2; + this.ensureCapacityInternal(this.count + var4); + int var5 = var2; + + for (int var6 = this.count; var5 < var3; ++var6) { + this.value[var6] = var1.charAt(var5); + ++var5; + } + + this.count += var4; + return this; + } else { + throw new IndexOutOfBoundsException("start " + var2 + ", end " + var3 + ", s.length() " + var1.length()); + } + } + + public AbstractStringBuilder append(char[] var1) { + int var2 = var1.length; + this.ensureCapacityInternal(this.count + var2); + System.arraycopy(var1, 0, this.value, this.count, var2); + this.count += var2; + return this; + } + + public AbstractStringBuilder append(char[] var1, int var2, int var3) { + if (var3 > 0) { + this.ensureCapacityInternal(this.count + var3); + } + + System.arraycopy(var1, var2, this.value, this.count, var3); + this.count += var3; + return this; + } + + public AbstractStringBuilder append(boolean var1) { + if (var1) { + this.ensureCapacityInternal(this.count + 4); + this.value[this.count++] = 't'; + this.value[this.count++] = 'r'; + this.value[this.count++] = 'u'; + this.value[this.count++] = 'e'; + } else { + this.ensureCapacityInternal(this.count + 5); + this.value[this.count++] = 'f'; + this.value[this.count++] = 'a'; + this.value[this.count++] = 'l'; + this.value[this.count++] = 's'; + this.value[this.count++] = 'e'; + } + + return this; + } + + @Override + public AbstractStringBuilder append(char var1) { + this.ensureCapacityInternal(this.count + 1); + this.value[this.count++] = var1; + return this; + } + + public AbstractStringBuilder append(int var1) { + if (var1 == Integer.MIN_VALUE) { + this.append("-2147483648"); + return this; + } else { + int var2 = var1 < 0 ? IntegerTools.stringSize(-var1) + 1 : IntegerTools.stringSize(var1); + int var3 = this.count + var2; + this.ensureCapacityInternal(var3); + IntegerTools.getChars(var1, var3, this.value); + this.count = var3; + return this; + } + } + + public AbstractStringBuilder append(long var1) { + if (var1 == Long.MIN_VALUE) { + this.append("-9223372036854775808"); + return this; + } else { + int var3 = var1 < 0L ? LongTools.stringSize(-var1) + 1 : LongTools.stringSize(var1); + int var4 = this.count + var3; + this.ensureCapacityInternal(var4); + LongTools.getChars(var1, var4, this.value); + this.count = var4; + return this; + } + } + + public AbstractStringBuilder append(float var1) { + FloatingDecimal.appendTo(var1, this); + return this; + } + + public AbstractStringBuilder append(double var1) { + FloatingDecimal.appendTo(var1, this); + return this; + } + + public AbstractStringBuilder delete(int var1, int var2) { + if (var1 < 0) { + throw new StringIndexOutOfBoundsException(var1); + } else { + if (var2 > this.count) { + var2 = this.count; + } + + if (var1 > var2) { + throw new StringIndexOutOfBoundsException(); + } else { + int var3 = var2 - var1; + if (var3 > 0) { + System.arraycopy(this.value, var1 + var3, this.value, var1, this.count - var2); + this.count -= var3; + } + + return this; + } + } + } + + public AbstractStringBuilder appendCodePoint(int var1) { + int var2 = this.count; + if (Character.isBmpCodePoint(var1)) { + this.ensureCapacityInternal(var2 + 1); + this.value[var2] = (char) var1; + this.count = var2 + 1; + } else { + if (!Character.isValidCodePoint(var1)) { + throw new IllegalArgumentException(); + } + + this.ensureCapacityInternal(var2 + 2); + CharacterTools.toSurrogates(var1, this.value, var2); + this.count = var2 + 2; + } + return this; + } + + public AbstractStringBuilder deleteCharAt(int var1) { + if (var1 >= 0 && var1 < this.count) { + System.arraycopy(this.value, var1 + 1, this.value, var1, this.count - var1 - 1); + --this.count; + return this; + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public AbstractStringBuilder replace(int var1, int var2, String var3) { + if (var1 < 0) { + throw new StringIndexOutOfBoundsException(var1); + } else if (var1 > this.count) { + throw new StringIndexOutOfBoundsException("start > length()"); + } else if (var1 > var2) { + throw new StringIndexOutOfBoundsException("start > end"); + } else { + if (var2 > this.count) { + var2 = this.count; + } + + int var4 = var3.length(); + int var5 = this.count + var4 - (var2 - var1); + this.ensureCapacityInternal(var5); + System.arraycopy(this.value, var2, this.value, var1 + var4, this.count - var2); + StringTools.getChars(var3, this.value, var1); + this.count = var5; + return this; + } + } + + public String substring(int var1) { + return this.substring(var1, this.count); + } + + @Override + public CharSequence subSequence(int var1, int var2) { + return this.substring(var1, var2); + } + + public String substring(int var1, int var2) { + if (var1 < 0) { + throw new StringIndexOutOfBoundsException(var1); + } else if (var2 > this.count) { + throw new StringIndexOutOfBoundsException(var2); + } else if (var1 > var2) { + throw new StringIndexOutOfBoundsException(var2 - var1); + } else { + return new String(this.value, var1, var2 - var1); + } + } + + public AbstractStringBuilder insert(int var1, char[] var2, int var3, int var4) { + if (var1 >= 0 && var1 <= this.length()) { + if (var3 >= 0 && var4 >= 0 && var3 <= var2.length - var4) { + this.ensureCapacityInternal(this.count + var4); + System.arraycopy(this.value, var1, this.value, var1 + var4, this.count - var1); + System.arraycopy(var2, var3, this.value, var1, var4); + this.count += var4; + return this; + } else { + throw new StringIndexOutOfBoundsException("offset " + var3 + ", len " + var4 + ", str.length " + var2.length); + } + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public AbstractStringBuilder insert(int var1, Object var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public AbstractStringBuilder insert(int var1, String var2) { + if (var1 >= 0 && var1 <= this.length()) { + if (var2 == null) { + var2 = "null"; + } + + int var3 = var2.length(); + this.ensureCapacityInternal(this.count + var3); + System.arraycopy(this.value, var1, this.value, var1 + var3, this.count - var1); + StringTools.getChars(var2, this.value, var1); + this.count += var3; + return this; + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public AbstractStringBuilder insert(int var1, char[] var2) { + if (var1 >= 0 && var1 <= this.length()) { + int var3 = var2.length; + this.ensureCapacityInternal(this.count + var3); + System.arraycopy(this.value, var1, this.value, var1 + var3, this.count - var1); + System.arraycopy(var2, 0, this.value, var1, var3); + this.count += var3; + return this; + } else { + throw new StringIndexOutOfBoundsException(var1); + } + } + + public AbstractStringBuilder insert(int var1, CharSequence var2) { + if (var2 == null) { + var2 = "null"; + } + + return var2 instanceof String ? this.insert(var1, (String) var2) : this.insert(var1, var2, 0, var2.length()); + } + + public AbstractStringBuilder insert(int var1, CharSequence var2, int var3, int var4) { + if (var2 == null) { + var2 = "null"; + } + + if (var1 >= 0 && var1 <= this.length()) { + if (var3 >= 0 && var4 >= 0 && var3 <= var4 && var4 <= var2.length()) { + int var5 = var4 - var3; + this.ensureCapacityInternal(this.count + var5); + System.arraycopy(this.value, var1, this.value, var1 + var5, this.count - var1); + + for (int var6 = var3; var6 < var4; ++var6) { + this.value[var1++] = var2.charAt(var6); + } + + this.count += var5; + return this; + } else { + throw new IndexOutOfBoundsException("start " + var3 + ", end " + var4 + ", s.length() " + var2.length()); + } + } else { + throw new IndexOutOfBoundsException("dstOffset " + var1); + } + } + + public AbstractStringBuilder insert(int var1, boolean var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public AbstractStringBuilder insert(int var1, char var2) { + this.ensureCapacityInternal(this.count + 1); + System.arraycopy(this.value, var1, this.value, var1 + 1, this.count - var1); + this.value[var1] = var2; + ++this.count; + return this; + } + + public AbstractStringBuilder insert(int var1, int var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public AbstractStringBuilder insert(int var1, long var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public AbstractStringBuilder insert(int var1, float var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public AbstractStringBuilder insert(int var1, double var2) { + return this.insert(var1, String.valueOf(var2)); + } + + public int indexOf(String var1) { + return this.indexOf(var1, 0); + } + + public int indexOf(String var1, int var2) { + return StringTools.indexOf(this.value, 0, this.count, var1, var2); + } + + public int lastIndexOf(String var1) { + return this.lastIndexOf(var1, this.count); + } + + public int lastIndexOf(String var1, int var2) { + return StringTools.lastIndexOf(this.value, 0, this.count, var1, var2); + } + + public AbstractStringBuilder reverse() { + boolean var1 = false; + int var2 = this.count - 1; + + for (int var3 = var2 - 1 >> 1; var3 >= 0; --var3) { + int var4 = var2 - var3; + char var5 = this.value[var3]; + char var6 = this.value[var4]; + this.value[var3] = var6; + this.value[var4] = var5; + if (Character.isSurrogate(var5) || Character.isSurrogate(var6)) { + var1 = true; + } + } + + if (var1) { + this.reverseAllValidSurrogatePairs(); + } + + return this; + } + + private void reverseAllValidSurrogatePairs() { + for (int var1 = 0; var1 < this.count - 1; ++var1) { + char var2 = this.value[var1]; + if (Character.isLowSurrogate(var2)) { + char var3 = this.value[var1 + 1]; + if (Character.isHighSurrogate(var3)) { + this.value[var1++] = var3; + this.value[var1] = var2; + } + } + } + + } + + @Override + public abstract String toString(); + + final char[] getValue() { + return this.value; + } } \ No newline at end of file diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/CharacterTools.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/CharacterTools.java index 9d57af3..bbdd238 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/CharacterTools.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/CharacterTools.java @@ -2,85 +2,85 @@ public class CharacterTools { - public static void toSurrogates(int var0, char[] var1, int var2) { - var1[var2 + 1] = Character.lowSurrogate(var0); - var1[var2] = Character.highSurrogate(var0); - } + public static void toSurrogates(int var0, char[] var1, int var2) { + var1[var2 + 1] = Character.lowSurrogate(var0); + var1[var2] = Character.highSurrogate(var0); + } - public static int codePointBeforeImpl(char[] var0, int var1, int var2) { - --var1; - char var3 = var0[var1]; - if (Character.isLowSurrogate(var3) && var1 > var2) { - --var1; - char var4 = var0[var1]; - if (Character.isHighSurrogate(var4)) { - return Character.toCodePoint(var4, var3); - } - } + public static int codePointBeforeImpl(char[] var0, int var1, int var2) { + --var1; + char var3 = var0[var1]; + if (Character.isLowSurrogate(var3) && var1 > var2) { + --var1; + char var4 = var0[var1]; + if (Character.isHighSurrogate(var4)) { + return Character.toCodePoint(var4, var3); + } + } - return var3; - } + return var3; + } - static int codePointAtImpl(char[] var0, int var1, int var2) { - char var3 = var0[var1]; - if (Character.isHighSurrogate(var3)) { - ++var1; - if (var1 < var2) { - char var4 = var0[var1]; - if (Character.isLowSurrogate(var4)) { - return Character.toCodePoint(var3, var4); - } - } - } + static int codePointAtImpl(char[] var0, int var1, int var2) { + char var3 = var0[var1]; + if (Character.isHighSurrogate(var3)) { + ++var1; + if (var1 < var2) { + char var4 = var0[var1]; + if (Character.isLowSurrogate(var4)) { + return Character.toCodePoint(var3, var4); + } + } + } - return var3; - } + return var3; + } - public static int codePointCountImpl(char[] var0, int var1, int var2) { - int var3 = var1 + var2; - int var4 = var2; - int var5 = var1; + public static int codePointCountImpl(char[] var0, int var1, int var2) { + int var3 = var1 + var2; + int var4 = var2; + int var5 = var1; - while (var5 < var3) { - if (Character.isHighSurrogate(var0[var5++]) && var5 < var3 && Character.isLowSurrogate(var0[var5])) { - --var4; - ++var5; - } - } + while (var5 < var3) { + if (Character.isHighSurrogate(var0[var5++]) && var5 < var3 && Character.isLowSurrogate(var0[var5])) { + --var4; + ++var5; + } + } - return var4; - } + return var4; + } - public static int offsetByCodePointsImpl(char[] var0, int var1, int var2, int var3, int var4) { - int var5 = var3; - int var6; - if (var4 >= 0) { - var6 = var1 + var2; + public static int offsetByCodePointsImpl(char[] var0, int var1, int var2, int var3, int var4) { + int var5 = var3; + int var6; + if (var4 >= 0) { + var6 = var1 + var2; - int var7; - for (var7 = 0; var5 < var6 && var7 < var4; ++var7) { - if (Character.isHighSurrogate(var0[var5++]) && var5 < var6 && Character.isLowSurrogate(var0[var5])) { - ++var5; - } - } + int var7; + for (var7 = 0; var5 < var6 && var7 < var4; ++var7) { + if (Character.isHighSurrogate(var0[var5++]) && var5 < var6 && Character.isLowSurrogate(var0[var5])) { + ++var5; + } + } - if (var7 < var4) { - throw new IndexOutOfBoundsException(); - } - } else { - for (var6 = var4; var5 > var1 && var6 < 0; ++var6) { - --var5; - if (Character.isLowSurrogate(var0[var5]) && var5 > var1 && Character.isHighSurrogate(var0[var5 - 1])) { - --var5; - } - } + if (var7 < var4) { + throw new IndexOutOfBoundsException(); + } + } else { + for (var6 = var4; var5 > var1 && var6 < 0; ++var6) { + --var5; + if (Character.isLowSurrogate(var0[var5]) && var5 > var1 && Character.isHighSurrogate(var0[var5 - 1])) { + --var5; + } + } - if (var6 < 0) { - throw new IndexOutOfBoundsException(); - } - } + if (var6 < 0) { + throw new IndexOutOfBoundsException(); + } + } - return var5; - } + return var5; + } } diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/IntegerTools.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/IntegerTools.java index 672270d..8a23e37 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/IntegerTools.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/IntegerTools.java @@ -2,30 +2,30 @@ public class IntegerTools { - static final int[] sizeTable = new int[] { - 9, - 99, - 999, - 9999, - 99999, - 999999, - 9999999, - 99999999, - 999999999, - Integer.MAX_VALUE - }; + static final int[] sizeTable = new int[] { + 9, + 99, + 999, + 9999, + 99999, + 999999, + 9999999, + 99999999, + 999999999, + Integer.MAX_VALUE + }; - public static int stringSize(int var0) { - int var1; - for (var1 = 0; var0 > sizeTable[var1]; ++var1) { - ; - } + public static int stringSize(int var0) { + int var1; + for (var1 = 0; var0 > sizeTable[var1]; ++var1) { + ; + } - return var1 + 1; - } + return var1 + 1; + } - public static void getChars(Integer var0, int var1, char[] var2) { - StringTools.getChars(var0.toString(), var2, var1); - } + public static void getChars(Integer var0, int var1, char[] var2) { + StringTools.getChars(var0.toString(), var2, var1); + } } diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/LongTools.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/LongTools.java index 182249b..35e7b92 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/LongTools.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/LongTools.java @@ -2,22 +2,22 @@ public class LongTools { - public static int stringSize(long var0) { - long var2 = 10L; + public static int stringSize(long var0) { + long var2 = 10L; - for (int var4 = 1; var4 < 19; ++var4) { - if (var0 < var2) { - return var4; - } + for (int var4 = 1; var4 < 19; ++var4) { + if (var0 < var2) { + return var4; + } - var2 = 10L * var2; - } + var2 = 10L * var2; + } - return 19; - } + return 19; + } - public static void getChars(Long var0, int var1, char[] var2) { - StringTools.getChars(var0.toString(), var2, var1); - } + public static void getChars(Long var0, int var1, char[] var2) { + StringTools.getChars(var0.toString(), var2, var1); + } } diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringBuilder.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringBuilder.java index 0219fc8..a6aa74e 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringBuilder.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringBuilder.java @@ -6,250 +6,250 @@ import java.io.Serializable; public final class StringBuilder extends AbstractStringBuilder implements Serializable, CharSequence { - static final long serialVersionUID = 3845685871479210112L; - - public StringBuilder() { - super(16); - } - - public StringBuilder(int var1) { - super(var1); - } - - public StringBuilder(String var1) { - super(var1.length() + 16); - this.append(var1); - } - - public StringBuilder(CharSequence var1) { - this(var1.length() + 16); - this.append(var1); - } - - @Override - public StringBuilder append(Object var1) { - return this.append(String.valueOf(var1)); - } - - @Override - public StringBuilder append(String var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(StringBuffer var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(CharSequence var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(CharSequence var1, int var2, int var3) { - super.append(var1, var2, var3); - return this; - } - - @Override - public StringBuilder append(char[] var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(char[] var1, int var2, int var3) { - super.append(var1, var2, var3); - return this; - } - - @Override - public StringBuilder append(boolean var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(char var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(int var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(long var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(float var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder append(double var1) { - super.append(var1); - return this; - } - - @Override - public StringBuilder appendCodePoint(int var1) { - super.appendCodePoint(var1); - return this; - } - - @Override - public StringBuilder delete(int var1, int var2) { - super.delete(var1, var2); - return this; - } - - @Override - public StringBuilder deleteCharAt(int var1) { - super.deleteCharAt(var1); - return this; - } - - @Override - public StringBuilder replace(int var1, int var2, String var3) { - super.replace(var1, var2, var3); - return this; - } - - @Override - public StringBuilder insert(int var1, char[] var2, int var3, int var4) { - super.insert(var1, var2, var3, var4); - return this; - } - - @Override - public StringBuilder insert(int var1, Object var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, String var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, char[] var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, CharSequence var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, CharSequence var2, int var3, int var4) { - super.insert(var1, var2, var3, var4); - return this; - } - - @Override - public StringBuilder insert(int var1, boolean var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, char var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, int var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, long var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, float var2) { - super.insert(var1, var2); - return this; - } - - @Override - public StringBuilder insert(int var1, double var2) { - super.insert(var1, var2); - return this; - } - - @Override - public int indexOf(String var1) { - return super.indexOf(var1); - } - - @Override - public int indexOf(String var1, int var2) { - return super.indexOf(var1, var2); - } - - @Override - public int lastIndexOf(String var1) { - return super.lastIndexOf(var1); - } - - @Override - public int lastIndexOf(String var1, int var2) { - return super.lastIndexOf(var1, var2); - } - - @Override - public StringBuilder reverse() { - super.reverse(); - return this; - } - - @Override - public String toString() { - return new String(this.value, 0, this.count); - } - - public String toStringClear() { - String out = toString(); - clear(); - return out; - } - - public void clear() { - this.count = 0; - this.value = new char[16]; - } - - private void writeObject(ObjectOutputStream var1) throws IOException { - var1.defaultWriteObject(); - var1.writeInt(this.count); - var1.writeObject(this.value); - } - - private void readObject(ObjectInputStream var1) throws IOException, ClassNotFoundException { - var1.defaultReadObject(); - this.count = var1.readInt(); - this.value = ((char[]) var1.readObject()); - } + static final long serialVersionUID = 3845685871479210112L; + + public StringBuilder() { + super(16); + } + + public StringBuilder(int var1) { + super(var1); + } + + public StringBuilder(String var1) { + super(var1.length() + 16); + this.append(var1); + } + + public StringBuilder(CharSequence var1) { + this(var1.length() + 16); + this.append(var1); + } + + @Override + public StringBuilder append(Object var1) { + return this.append(String.valueOf(var1)); + } + + @Override + public StringBuilder append(String var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(StringBuffer var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(CharSequence var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(CharSequence var1, int var2, int var3) { + super.append(var1, var2, var3); + return this; + } + + @Override + public StringBuilder append(char[] var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(char[] var1, int var2, int var3) { + super.append(var1, var2, var3); + return this; + } + + @Override + public StringBuilder append(boolean var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(char var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(int var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(long var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(float var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder append(double var1) { + super.append(var1); + return this; + } + + @Override + public StringBuilder appendCodePoint(int var1) { + super.appendCodePoint(var1); + return this; + } + + @Override + public StringBuilder delete(int var1, int var2) { + super.delete(var1, var2); + return this; + } + + @Override + public StringBuilder deleteCharAt(int var1) { + super.deleteCharAt(var1); + return this; + } + + @Override + public StringBuilder replace(int var1, int var2, String var3) { + super.replace(var1, var2, var3); + return this; + } + + @Override + public StringBuilder insert(int var1, char[] var2, int var3, int var4) { + super.insert(var1, var2, var3, var4); + return this; + } + + @Override + public StringBuilder insert(int var1, Object var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, String var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, char[] var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, CharSequence var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, CharSequence var2, int var3, int var4) { + super.insert(var1, var2, var3, var4); + return this; + } + + @Override + public StringBuilder insert(int var1, boolean var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, char var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, int var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, long var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, float var2) { + super.insert(var1, var2); + return this; + } + + @Override + public StringBuilder insert(int var1, double var2) { + super.insert(var1, var2); + return this; + } + + @Override + public int indexOf(String var1) { + return super.indexOf(var1); + } + + @Override + public int indexOf(String var1, int var2) { + return super.indexOf(var1, var2); + } + + @Override + public int lastIndexOf(String var1) { + return super.lastIndexOf(var1); + } + + @Override + public int lastIndexOf(String var1, int var2) { + return super.lastIndexOf(var1, var2); + } + + @Override + public StringBuilder reverse() { + super.reverse(); + return this; + } + + @Override + public String toString() { + return new String(this.value, 0, this.count); + } + + public String toStringClear() { + String out = toString(); + clear(); + return out; + } + + public void clear() { + this.count = 0; + this.value = new char[16]; + } + + private void writeObject(ObjectOutputStream var1) throws IOException { + var1.defaultWriteObject(); + var1.writeInt(this.count); + var1.writeObject(this.value); + } + + private void readObject(ObjectInputStream var1) throws IOException, ClassNotFoundException { + var1.defaultReadObject(); + this.count = var1.readInt(); + this.value = ((char[]) var1.readObject()); + } } \ No newline at end of file diff --git a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringTools.java b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringTools.java index 2028a50..60cc573 100644 --- a/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringTools.java +++ b/utils/java-lang/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/lang/StringTools.java @@ -2,101 +2,101 @@ public class StringTools { - public static void getChars(String var0, char[] var1, int var2) { - char[] var4 = var0.toCharArray(); - System.arraycopy(var4, 0, var1, var2, var4.length); - } - - public static int lastIndexOf(char[] var0, int var1, int var2, String var3, int var4) { - char[] var5 = var3.toCharArray(); - return lastIndexOf(var0, var1, var2, var5, 0, var5.length, var4); - } - - public static int lastIndexOf(char[] var0, int var1, int var2, char[] var3, int var4, int var5, int var6) { - int var7 = var2 - var5; - if (var6 < 0) { - return -1; - } else { - if (var6 > var7) { - var6 = var7; - } - - if (var5 == 0) { - return var6; - } else { - int var8 = var4 + var5 - 1; - char var9 = var3[var8]; - int var10 = var1 + var5 - 1; - int var11 = var10 + var6; - - while (true) { - while (var11 < var10 || var0[var11] == var9) { - if (var11 < var10) { - return -1; - } - - int var12 = var11 - 1; - int var13 = var12 - (var5 - 1); - int var14 = var8 - 1; - - do { - if (var12 <= var13) { - return var13 - var1 + 1; - } - } while (var0[var12--] == var3[var14--]); - - --var11; - } - - --var11; - } - } - } - } - - static int indexOf(char[] var0, int var1, int var2, String var3, int var4) { - char[] var5 = var3.toCharArray(); - return indexOf(var0, var1, var2, var5, 0, var5.length, var4); - } - - static int indexOf(char[] var0, int var1, int var2, char[] var3, int var4, int var5, int var6) { - if (var6 >= var2) { - return var5 == 0 ? var2 : -1; - } else { - if (var6 < 0) { - var6 = 0; - } - - if (var5 == 0) { - return var6; - } else { - char var7 = var3[var4]; - int var8 = var1 + (var2 - var5); - - for (int var9 = var1 + var6; var9 <= var8; ++var9) { - if (var0[var9] != var7) { - do { - ++var9; - } while (var9 <= var8 && var0[var9] != var7); - } - - if (var9 <= var8) { - int var10 = var9 + 1; - int var11 = var10 + var5 - 1; - - for (int var12 = var4 + 1; var10 < var11 && var0[var10] == var3[var12]; ++var12) { - ++var10; - } - - if (var10 == var11) { - return var9 - var1; - } - } - } - - return -1; - } - } - } + public static void getChars(String var0, char[] var1, int var2) { + char[] var4 = var0.toCharArray(); + System.arraycopy(var4, 0, var1, var2, var4.length); + } + + public static int lastIndexOf(char[] var0, int var1, int var2, String var3, int var4) { + char[] var5 = var3.toCharArray(); + return lastIndexOf(var0, var1, var2, var5, 0, var5.length, var4); + } + + public static int lastIndexOf(char[] var0, int var1, int var2, char[] var3, int var4, int var5, int var6) { + int var7 = var2 - var5; + if (var6 < 0) { + return -1; + } else { + if (var6 > var7) { + var6 = var7; + } + + if (var5 == 0) { + return var6; + } else { + int var8 = var4 + var5 - 1; + char var9 = var3[var8]; + int var10 = var1 + var5 - 1; + int var11 = var10 + var6; + + while (true) { + while (var11 < var10 || var0[var11] == var9) { + if (var11 < var10) { + return -1; + } + + int var12 = var11 - 1; + int var13 = var12 - (var5 - 1); + int var14 = var8 - 1; + + do { + if (var12 <= var13) { + return var13 - var1 + 1; + } + } while (var0[var12--] == var3[var14--]); + + --var11; + } + + --var11; + } + } + } + } + + static int indexOf(char[] var0, int var1, int var2, String var3, int var4) { + char[] var5 = var3.toCharArray(); + return indexOf(var0, var1, var2, var5, 0, var5.length, var4); + } + + static int indexOf(char[] var0, int var1, int var2, char[] var3, int var4, int var5, int var6) { + if (var6 >= var2) { + return var5 == 0 ? var2 : -1; + } else { + if (var6 < 0) { + var6 = 0; + } + + if (var5 == 0) { + return var6; + } else { + char var7 = var3[var4]; + int var8 = var1 + (var2 - var5); + + for (int var9 = var1 + var6; var9 <= var8; ++var9) { + if (var0[var9] != var7) { + do { + ++var9; + } while (var9 <= var8 && var0[var9] != var7); + } + + if (var9 <= var8) { + int var10 = var9 + 1; + int var11 = var10 + var5 - 1; + + for (int var12 = var4 + 1; var10 < var11 && var0[var10] == var3[var12]; ++var12) { + ++var10; + } + + if (var10 == var11) { + return var9 - var1; + } + } + } + + return -1; + } + } + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Arrays.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Arrays.java index 847aa25..93bc8ad 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Arrays.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Arrays.java @@ -7,89 +7,89 @@ public class Arrays { - public static Object[] merge(Object[] array1, Object... array2) { - Object[] output = new Object[array1.length + array2.length]; - System.arraycopy(array1, 0, output, 0, array1.length); - System.arraycopy(array2, 0, output, array1.length, array2.length); - return output; - } + public static Object[] merge(Object[] array1, Object... array2) { + Object[] output = new Object[array1.length + array2.length]; + System.arraycopy(array1, 0, output, 0, array1.length); + System.arraycopy(array2, 0, output, array1.length, array2.length); + return output; + } - @SafeVarargs - public static E[] merge(IntFunction function, E[] array1, E... array2) { - E[] output = function.apply(array1.length + array2.length); - System.arraycopy(array1, 0, output, 0, array1.length); - System.arraycopy(array2, 0, output, array1.length, array2.length); - return output; - } + @SafeVarargs + public static E[] merge(IntFunction function, E[] array1, E... array2) { + E[] output = function.apply(array1.length + array2.length); + System.arraycopy(array1, 0, output, 0, array1.length); + System.arraycopy(array2, 0, output, array1.length, array2.length); + return output; + } - public static Object[] subArray(Object[] args, int index) { - if (index < 0 || index >= args.length) { - return new Object[0]; - } - int length = args.length - index; - Object[] output = new Object[length]; - System.arraycopy(args, index, output, 0, length); - return output; - } + public static Object[] subArray(Object[] args, int index) { + if (index < 0 || index >= args.length) { + return new Object[0]; + } + int length = args.length - index; + Object[] output = new Object[length]; + System.arraycopy(args, index, output, 0, length); + return output; + } - public static E[] subArray(IntFunction function, E[] args, int index) { - if (index < 0 || index >= args.length) { - return function.apply(0); - } - int length = args.length - index; - E[] output = function.apply(length); - System.arraycopy(args, index, output, 0, length); - return output; - } + public static E[] subArray(IntFunction function, E[] args, int index) { + if (index < 0 || index >= args.length) { + return function.apply(0); + } + int length = args.length - index; + E[] output = function.apply(length); + System.arraycopy(args, index, output, 0, length); + return output; + } - public static Object[] subArray(Object[] args, int index, int length) { - if (index < 0 || index >= args.length) { - return new Object[0]; - } - Object[] output = new Object[length]; - System.arraycopy(args, index, output, 0, length); - return output; - } + public static Object[] subArray(Object[] args, int index, int length) { + if (index < 0 || index >= args.length) { + return new Object[0]; + } + Object[] output = new Object[length]; + System.arraycopy(args, index, output, 0, length); + return output; + } - public static E[] subArray(IntFunction function, E[] args, int index, int length) { - if (index < 0 || index >= args.length) { - return function.apply(0); - } - E[] output = function.apply(length); - System.arraycopy(args, index, output, 0, length); - return output; - } + public static E[] subArray(IntFunction function, E[] args, int index, int length) { + if (index < 0 || index >= args.length) { + return function.apply(0); + } + E[] output = function.apply(length); + System.arraycopy(args, index, output, 0, length); + return output; + } - public static Object[][] partition(Object[] args, int length) { - int size = (int) Math.floor(args.length / (float) length); - if(args.length % length != 0) { - size++; - } - Object[][] output = new Object[size][length]; - for(int index = 0; index < size; index++) { - System.arraycopy(args, index * length, output[index], 0, length); - } - return output; - } + public static Object[][] partition(Object[] args, int length) { + int size = (int) Math.floor(args.length / (float) length); + if (args.length % length != 0) { + size++; + } + Object[][] output = new Object[size][length]; + for (int index = 0; index < size; index++) { + System.arraycopy(args, index * length, output[index], 0, length); + } + return output; + } - public static E[][] partition(BiFunction function, E[] args, int length) { - int size = (int) Math.floor(args.length / (float) length); - if(args.length % length != 0) { - size++; - } - E[][] output = function.apply(size, length); - for(int index = 0; index < size; index++) { - System.arraycopy(args, index * length, output[index], 0, length); - } - return output; - } + public static E[][] partition(BiFunction function, E[] args, int length) { + int size = (int) Math.floor(args.length / (float) length); + if (args.length % length != 0) { + size++; + } + E[][] output = function.apply(size, length); + for (int index = 0; index < size; index++) { + System.arraycopy(args, index * length, output[index], 0, length); + } + return output; + } - public static boolean contains(A[] values, A find) { - return java.util.Arrays.stream(values).anyMatch(value -> value.equals(find)); - } + public static boolean contains(A[] values, A find) { + return java.util.Arrays.stream(values).anyMatch(value -> value.equals(find)); + } - public static boolean contains(A[] values, B find, Compare comparator) { - return java.util.Arrays.stream(values).anyMatch(value -> comparator.compare(value, find)); - } + public static boolean contains(A[] values, B find, Compare comparator) { + return java.util.Arrays.stream(values).anyMatch(value -> comparator.compare(value, find)); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Collect.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Collect.java index 6215b7c..a227c7e 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Collect.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Collect.java @@ -14,122 +14,124 @@ public final class Collect { - public static final Set CH_ID = Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); - - @SuppressWarnings("unchecked") - public static Function castingIdentity() { - return i -> (R) i; - } - - public static Function passthrough() { - return i -> i; - } - - /** - * Simple implementation class for {@code Collector}. - * - * @param the type of elements to be collected - * @param the type of the result - */ - public static class CollectorImpl implements Collector { - private final Supplier supplier; - private final BiConsumer accumulator; - private final BinaryOperator combiner; - private final Function finisher; - private final Set characteristics; - - public CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher, - Set characteristics) { - this.supplier = supplier; - this.accumulator = accumulator; - this.combiner = combiner; - this.finisher = finisher; - this.characteristics = characteristics; - } - - public CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Set characteristics) { - this(supplier, accumulator, combiner, castingIdentity(), characteristics); - } - - @Override - public BiConsumer accumulator() { - return accumulator; - } - - @Override - public Supplier supplier() { - return supplier; - } - - @Override - public BinaryOperator combiner() { - return combiner; - } - - @Override - public Function finisher() { - return finisher; - } - - @Override - public Set characteristics() { - return characteristics; - } - } - - /** - * Returns a {@code Collector} that accumulates the input elements into a new - * {@code Collection}, in encounter order. The {@code Collection} is created by - * the provided factory. - * - * @param the collection type of the input elements - * @param the type of the resulting {@code Collection} - * @param collectionFactory a {@code Supplier} which returns a new, empty - * {@code Collection} of the appropriate type - * @return a {@code Collector} which collects all the input elements into a - * {@code Collection}, in encounter order - */ - public static > Collector combineCollection(Supplier collectionFactory) { - return new CollectorImpl<>(collectionFactory, Collection::addAll, (r1, r2) -> { - r1.addAll(r2); - return r1; - }, passthrough(), CH_ID); - } - - /** - * Returns a {@code Collector} that accumulates the input list elements into a - * new {@code List}. There are no guarantees on the type, mutability, - * serializability, or thread-safety of the {@code List} returned; if more - * control over the returned {@code List} is required, use - * - * @param the collection type of the input elements - * @return a {@code Collector} which collects all the input elements into a - * {@code List}, in encounter order - */ - public static Collector, ?, List> combineList() { - return new CollectorImpl<>((Supplier>) ArrayList::new, List::addAll, (left, right) -> { - left.addAll(right); - return left; - }, passthrough(), CH_ID); - } - - /** - * Returns a {@code Collector} that accumulates the input list elements into a - * new {@code List}. There are no guarantees on the type, mutability, - * serializability, or thread-safety of the {@code List} returned; if more - * control over the returned {@code List} is required, use - * - * @param the type of the input elements - * @param the type of the output element - * @param consumer accumulator of collector - * @return a {@code Collector} which collects all the transformed elements into - * a {@code List}, in encounter order - */ - public static Collector, List> collectList(BiConsumer, T> consumer) { - return new CollectorImpl<>((Supplier>) ArrayList::new, consumer, (left, right) -> { - left.addAll(right); - return left; - }, passthrough(), CH_ID); - } + public static final Set CH_ID = Collections + .unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH)); + + @SuppressWarnings("unchecked") + public static Function castingIdentity() { + return i -> (R) i; + } + + public static Function passthrough() { + return i -> i; + } + + /** + * Simple implementation class for {@code Collector}. + * + * @param the type of elements to be collected + * @param the type of the result + */ + public static class CollectorImpl implements Collector { + private final Supplier supplier; + private final BiConsumer accumulator; + private final BinaryOperator combiner; + private final Function finisher; + private final Set characteristics; + + public CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, Function finisher, + Set characteristics) { + this.supplier = supplier; + this.accumulator = accumulator; + this.combiner = combiner; + this.finisher = finisher; + this.characteristics = characteristics; + } + + public CollectorImpl(Supplier supplier, BiConsumer accumulator, BinaryOperator combiner, + Set characteristics) { + this(supplier, accumulator, combiner, castingIdentity(), characteristics); + } + + @Override + public BiConsumer accumulator() { + return accumulator; + } + + @Override + public Supplier supplier() { + return supplier; + } + + @Override + public BinaryOperator combiner() { + return combiner; + } + + @Override + public Function finisher() { + return finisher; + } + + @Override + public Set characteristics() { + return characteristics; + } + } + + /** + * Returns a {@code Collector} that accumulates the input elements into a new + * {@code Collection}, in encounter order. The {@code Collection} is created by + * the provided factory. + * + * @param the collection type of the input elements + * @param the type of the resulting {@code Collection} + * @param collectionFactory a {@code Supplier} which returns a new, empty + * {@code Collection} of the appropriate type + * @return a {@code Collector} which collects all the input elements into a + * {@code Collection}, in encounter order + */ + public static > Collector combineCollection(Supplier collectionFactory) { + return new CollectorImpl<>(collectionFactory, Collection::addAll, (r1, r2) -> { + r1.addAll(r2); + return r1; + }, passthrough(), CH_ID); + } + + /** + * Returns a {@code Collector} that accumulates the input list elements into a + * new {@code List}. There are no guarantees on the type, mutability, + * serializability, or thread-safety of the {@code List} returned; if more + * control over the returned {@code List} is required, use + * + * @param the collection type of the input elements + * @return a {@code Collector} which collects all the input elements into a + * {@code List}, in encounter order + */ + public static Collector, ?, List> combineList() { + return new CollectorImpl<>((Supplier>) ArrayList::new, List::addAll, (left, right) -> { + left.addAll(right); + return left; + }, passthrough(), CH_ID); + } + + /** + * Returns a {@code Collector} that accumulates the input list elements into a + * new {@code List}. There are no guarantees on the type, mutability, + * serializability, or thread-safety of the {@code List} returned; if more + * control over the returned {@code List} is required, use + * + * @param the type of the input elements + * @param the type of the output element + * @param consumer accumulator of collector + * @return a {@code Collector} which collects all the transformed elements into + * a {@code List}, in encounter order + */ + public static Collector, List> collectList(BiConsumer, T> consumer) { + return new CollectorImpl<>((Supplier>) ArrayList::new, consumer, (left, right) -> { + left.addAll(right); + return left; + }, passthrough(), CH_ID); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Exceptions.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Exceptions.java index dceea16..c7cdd01 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Exceptions.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Exceptions.java @@ -8,98 +8,98 @@ public class Exceptions { - public static String[] toStringArray(Throwable cause) { - List out = new ArrayList<>(); - StringBuilder builder = new StringBuilder(); - String next = "\r\n"; - java.util.Arrays.stream(cause.getStackTrace()).forEach(stack -> { - builder.append(next); - builder.append("Error Type: " + cause.getClass().getSimpleName()); - builder.append(next); - builder.append("Error Message: " + cause.getLocalizedMessage()); - builder.append(next); - builder.append("Class: " + stack.getClassName()); - builder.append(next); - builder.append("File: " + stack.getFileName()); - builder.append(next); - builder.append("Method: " + stack.getMethodName()); - builder.append(next); - builder.append("Line: " + stack.getLineNumber()); - out.add(builder.toStringClear()); - }); - Collections.reverse(out); - return out.toArray(new String[0]); - } + public static String[] toStringArray(Throwable cause) { + List out = new ArrayList<>(); + StringBuilder builder = new StringBuilder(); + String next = "\r\n"; + java.util.Arrays.stream(cause.getStackTrace()).forEach(stack -> { + builder.append(next); + builder.append("Error Type: " + cause.getClass().getSimpleName()); + builder.append(next); + builder.append("Error Message: " + cause.getLocalizedMessage()); + builder.append(next); + builder.append("Class: " + stack.getClassName()); + builder.append(next); + builder.append("File: " + stack.getFileName()); + builder.append(next); + builder.append("Method: " + stack.getMethodName()); + builder.append(next); + builder.append("Line: " + stack.getLineNumber()); + out.add(builder.toStringClear()); + }); + Collections.reverse(out); + return out.toArray(new String[0]); + } - public static String getError(Throwable cause) { - StringBuilder builder = new StringBuilder(); - String next = "\r\n"; - StackTraceElement stack = cause.getStackTrace()[0]; - builder.append(next); - builder.append("Error Type: " + cause.getClass().getSimpleName()); - builder.append(next); - builder.append("Error Message: " + cause.getLocalizedMessage()); - builder.append(next); - builder.append("Class: " + stack.getClassName()); - builder.append(next); - builder.append("File: " + stack.getFileName()); - builder.append(next); - builder.append("Method: " + stack.getMethodName()); - builder.append(next); - builder.append("Line: " + stack.getLineNumber()); - return builder.toStringClear(); - } + public static String getError(Throwable cause) { + StringBuilder builder = new StringBuilder(); + String next = "\r\n"; + StackTraceElement stack = cause.getStackTrace()[0]; + builder.append(next); + builder.append("Error Type: " + cause.getClass().getSimpleName()); + builder.append(next); + builder.append("Error Message: " + cause.getLocalizedMessage()); + builder.append(next); + builder.append("Class: " + stack.getClassName()); + builder.append(next); + builder.append("File: " + stack.getFileName()); + builder.append(next); + builder.append("Method: " + stack.getMethodName()); + builder.append(next); + builder.append("Line: " + stack.getLineNumber()); + return builder.toStringClear(); + } - public static String[] stackTraceToStringArray(Throwable throwable) { - return stackTraceToString(throwable).split("\n"); - } + public static String[] stackTraceToStringArray(Throwable throwable) { + return stackTraceToString(throwable).split("\n"); + } - public static String stackTraceToString(Throwable throwable) { - StringBuilder builder = new StringBuilder(); - stackTraceToBuilder(throwable, builder, false); - return builder.toString(); - } + public static String stackTraceToString(Throwable throwable) { + StringBuilder builder = new StringBuilder(); + stackTraceToBuilder(throwable, builder, false); + return builder.toString(); + } - private static void stackTraceToBuilder(Throwable throwable, StringBuilder builder, boolean cause) { - StringBuilder stack = new StringBuilder(); + private static void stackTraceToBuilder(Throwable throwable, StringBuilder builder, boolean cause) { + StringBuilder stack = new StringBuilder(); - if (cause) { - stack.append('\n'); - stack.append("Caused by: "); - } - stack.append(throwable.getClass().getName()); - stack.append(": "); - stack.append(throwable.getLocalizedMessage()); - builder.append(stack.toStringClear()); + if (cause) { + stack.append('\n'); + stack.append("Caused by: "); + } + stack.append(throwable.getClass().getName()); + stack.append(": "); + stack.append(throwable.getLocalizedMessage()); + builder.append(stack.toStringClear()); - StackTraceElement[] stackTrace = throwable.getStackTrace(); + StackTraceElement[] stackTrace = throwable.getStackTrace(); - for (StackTraceElement element : stackTrace) { + for (StackTraceElement element : stackTrace) { - String fileName = element.getFileName(); - stack.append("\n"); - stack.append(' '); - stack.append("at "); + String fileName = element.getFileName(); + stack.append("\n"); + stack.append(' '); + stack.append("at "); - stack.append(element.getClassName()); - stack.append('.'); - stack.append(element.getMethodName()); - stack.append('('); - if (fileName == null) { - stack.append("Unknown Source"); - } else { - stack.append(fileName); - stack.append(':'); - stack.append(Integer.toString(element.getLineNumber())); - } - stack.append(')'); - builder.append(stack.toStringClear()); - } + stack.append(element.getClassName()); + stack.append('.'); + stack.append(element.getMethodName()); + stack.append('('); + if (fileName == null) { + stack.append("Unknown Source"); + } else { + stack.append(fileName); + stack.append(':'); + stack.append(Integer.toString(element.getLineNumber())); + } + stack.append(')'); + builder.append(stack.toStringClear()); + } - Throwable caused = throwable.getCause(); - if (caused != null) { - stackTraceToBuilder(caused, builder, true); - } - } + Throwable caused = throwable.getCause(); + if (caused != null) { + stackTraceToBuilder(caused, builder, true); + } + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Files.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Files.java index a4656c0..58bb00b 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Files.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Files.java @@ -7,100 +7,108 @@ public class Files { - /* - * File / Folder creation - */ - - public static File createFolder(File folder) { - if (!folder.exists()) { - if (!folder.mkdirs()) - return null; - return folder; - } else if (!folder.isDirectory()) { - if (folder.delete()) { - if (!folder.mkdirs()) - return null; - return folder; - } - return null; - } - return folder; - } - - public static File createFile(File file) { - if (file.getParent() != null && !file.getParent().trim().isEmpty()) - if (createFolder(file.getParentFile()) == null) - return null; - - if (!file.exists()) { - if (!createFile0(file)) - return null; - return file; - } else if (!file.isFile()) { - if (file.delete()) { - if (!createFile0(file)) - return null; - return file; - } - return null; - } - return file; - } - - private static boolean createFile0(File file) { - try { - return file.createNewFile(); - } catch (IOException e) { - return false; - } - } - - /* - * File Listing - */ - - public static List listFiles(File directory) { - return Arrays.stream(directory.listFiles()).collect(Collect.collectList((output, input) -> { - if (input.isDirectory()) - output.addAll(listFiles(input)); - else - output.add(input); - })); - } - - public static List listFiles(File directory, String fileEnd) { - return Arrays - .stream(directory.listFiles()) - .filter(file -> file.isDirectory() || file.getName().endsWith(fileEnd)) - .collect(Collect.collectList((output, input) -> { - if (input.isDirectory()) - output.addAll(listFiles(input)); - else - output.add(input); - })); - } - - /* - * Zip Files - */ - - public static void zipFileToFolderTime(File file, File folder) { - if (!file.exists() || createFolder(folder) == null) - return; - - String name = Times.getDate("_") + "-%count%.zip"; - int tries = 0; - - File zipFile = new File(folder, name.replace("%count%", tries + "")); - while (zipFile.exists()) - zipFile = new File(folder, name.replace("%count%", (tries++) + "")); - - try { - Zipper.zip(zipFile, file); - } catch (IOException e) { - e.printStackTrace(); - } - - } + /* + * File / Folder creation + */ + + public static File createFolder(File folder) { + if (!folder.exists()) { + if (!folder.mkdirs()) { + return null; + } + return folder; + } else if (!folder.isDirectory()) { + if (folder.delete()) { + if (!folder.mkdirs()) { + return null; + } + return folder; + } + return null; + } + return folder; + } + + public static File createFile(File file) { + if (file.getParent() != null && !file.getParent().trim().isEmpty()) { + if (createFolder(file.getParentFile()) == null) { + return null; + } + } + + if (!file.exists()) { + if (!createFile0(file)) { + return null; + } + return file; + } else if (!file.isFile()) { + if (file.delete()) { + if (!createFile0(file)) { + return null; + } + return file; + } + return null; + } + return file; + } + + private static boolean createFile0(File file) { + try { + return file.createNewFile(); + } catch (IOException e) { + return false; + } + } + + /* + * File Listing + */ + + public static List listFiles(File directory) { + return Arrays.stream(directory.listFiles()).collect(Collect.collectList((output, input) -> { + if (input.isDirectory()) { + output.addAll(listFiles(input)); + } else { + output.add(input); + } + })); + } + + public static List listFiles(File directory, String fileEnd) { + return Arrays.stream(directory.listFiles()).filter(file -> file.isDirectory() || file.getName().endsWith(fileEnd)) + .collect(Collect.collectList((output, input) -> { + if (input.isDirectory()) { + output.addAll(listFiles(input)); + } else { + output.add(input); + } + })); + } + + /* + * Zip Files + */ + + public static void zipFileToFolderTime(File file, File folder) { + if (!file.exists() || createFolder(folder) == null) { + return; + } + + String name = Times.getDate("_") + "-%count%.zip"; + int tries = 0; + + File zipFile = new File(folder, name.replace("%count%", tries + "")); + while (zipFile.exists()) { + zipFile = new File(folder, name.replace("%count%", (tries++) + "")); + } + + try { + Zipper.zip(zipFile, file); + } catch (IOException e) { + e.printStackTrace(); + } + + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Lists.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Lists.java index c4e3566..f11baea 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Lists.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Lists.java @@ -1,78 +1,80 @@ package com.syntaxphoenix.syntaxapi.utils.java; -import java.util.List; import java.util.ArrayList; import java.util.Collection; +import java.util.List; import java.util.function.Consumer; public class Lists { - public static String getEqualsIgnoreCase(String equals, List list) { - if (list.isEmpty()) - return equals; - for (String input : list) { - if (input.equalsIgnoreCase(equals)) { - return input; - } - } - return equals; - } + public static String getEqualsIgnoreCase(String equals, List list) { + if (list.isEmpty()) { + return equals; + } + for (String input : list) { + if (input.equalsIgnoreCase(equals)) { + return input; + } + } + return equals; + } - public static boolean containsEqualsIgnoreCase(String equals, List list) { - if (list.isEmpty()) - return false; - for (String input : list) { - if (input.equalsIgnoreCase(equals)) { - return true; - } - } - return false; - } + public static boolean containsEqualsIgnoreCase(String equals, List list) { + if (list.isEmpty()) { + return false; + } + for (String input : list) { + if (input.equalsIgnoreCase(equals)) { + return true; + } + } + return false; + } - public static String[] toStringArray(Collection collection) { - List output = new ArrayList<>(); - collection.forEach(new Consumer() { - @Override - public void accept(String[] array) { - for (int index = 0; index < array.length; index++) { - output.add(array[index]); - } - } - }); - return output.toArray(new String[0]); - } + public static String[] toStringArray(Collection collection) { + List output = new ArrayList<>(); + collection.forEach(new Consumer() { + @Override + public void accept(String[] array) { + for (int index = 0; index < array.length; index++) { + output.add(array[index]); + } + } + }); + return output.toArray(new String[0]); + } - public static List> partition(List list, int amount) { - List> parition = new ArrayList<>(); - List current = new ArrayList<>(); - for (int index = 0; index < list.size(); index++) { - if (current.size() == amount) { - parition.add(current); - current = new ArrayList<>(); - } - current.add(list.get(index)); - } - if (!current.isEmpty()) { - parition.add(current); - } - return parition; - } + public static List> partition(List list, int amount) { + List> parition = new ArrayList<>(); + List current = new ArrayList<>(); + for (int index = 0; index < list.size(); index++) { + if (current.size() == amount) { + parition.add(current); + current = new ArrayList<>(); + } + current.add(list.get(index)); + } + if (!current.isEmpty()) { + parition.add(current); + } + return parition; + } - @SafeVarargs - public static ArrayList merge(List... lists) { - ArrayList output = new ArrayList<>(); - for (List list : lists) { - output.addAll(list); - } - return output; - } + @SafeVarargs + public static ArrayList merge(List... lists) { + ArrayList output = new ArrayList<>(); + for (List list : lists) { + output.addAll(list); + } + return output; + } - public static List createWithType(Class sample) { - return new ArrayList<>(); - } + public static List createWithType(Class sample) { + return new ArrayList<>(); + } - public static List createWithType(E sample) { - return new ArrayList<>(); - } + public static List createWithType(E sample) { + return new ArrayList<>(); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Numbers.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Numbers.java index de8c095..aed57c4 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Numbers.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Numbers.java @@ -4,10 +4,10 @@ public class Numbers { - public static final Pattern ODD_NUMBER = Pattern.compile(".*([13579])$"); + public static final Pattern ODD_NUMBER = Pattern.compile(".*([13579])$"); - public static boolean isOddNumber(Number input) { - return ODD_NUMBER.matcher(input.toString()).matches(); - } + public static boolean isOddNumber(Number input) { + return ODD_NUMBER.matcher(input.toString()).matches(); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Primitives.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Primitives.java index 5146fa0..5214a77 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Primitives.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Primitives.java @@ -8,69 +8,70 @@ public final class Primitives { - private static final Map, Class> PRIMITIVE_TO_COMPLEX, COMPLEX_TO_PRIMITIVE; - - static { - Map, Class> collect = new LinkedHashMap<>(10); - - collect.put(byte.class, Byte.class); - collect.put(boolean.class, Boolean.class); - collect.put(short.class, Short.class); - collect.put(int.class, Integer.class); - collect.put(long.class, Long.class); - collect.put(float.class, Float.class); - collect.put(double.class, Double.class); - collect.put(String.class, String.class); - collect.put(void.class, Void.class); - collect.put(char.class, Character.class); - - PRIMITIVE_TO_COMPLEX = Collections.unmodifiableMap(collect); - - collect = new LinkedHashMap<>(10); - for (Entry, Class> entry : PRIMITIVE_TO_COMPLEX.entrySet()) - collect.put(entry.getValue(), entry.getKey()); - - COMPLEX_TO_PRIMITIVE = Collections.unmodifiableMap(collect); - } - - public static boolean isInstance(Object object) { - return isComplex(object) || isPrimitive(object); - } - - public static boolean isInstance(Class type) { - return isComplex(type) || isPrimitive(type); - } - - public static boolean isComplex(Object object) { - return object == null ? false : (object instanceof Class ? isComplex((Class) object) : isComplex(object.getClass())); - } - - public static boolean isComplex(Class type) { - return COMPLEX_TO_PRIMITIVE.containsKey(type); - } - - public static boolean isPrimitive(Object object) { - return object == null ? false : (object instanceof Class ? isPrimitive((Class) object) : isPrimitive(object.getClass())); - } - - public static boolean isPrimitive(Class type) { - return PRIMITIVE_TO_COMPLEX.containsKey(type); - } - - @SuppressWarnings("unchecked") - public static Class fromPrimitive(Class primitive) { - Objects.requireNonNull(primitive); - - Class complex = PRIMITIVE_TO_COMPLEX.get(primitive); - return complex == null ? primitive : (Class) complex; - } - - @SuppressWarnings("unchecked") - public static Class toPrimitive(Class complex) { - Objects.requireNonNull(complex); - - Class primitive = COMPLEX_TO_PRIMITIVE.get(complex); - return primitive == null ? complex : (Class) primitive; - } + private static final Map, Class> PRIMITIVE_TO_COMPLEX, COMPLEX_TO_PRIMITIVE; + + static { + Map, Class> collect = new LinkedHashMap<>(10); + + collect.put(byte.class, Byte.class); + collect.put(boolean.class, Boolean.class); + collect.put(short.class, Short.class); + collect.put(int.class, Integer.class); + collect.put(long.class, Long.class); + collect.put(float.class, Float.class); + collect.put(double.class, Double.class); + collect.put(String.class, String.class); + collect.put(void.class, Void.class); + collect.put(char.class, Character.class); + + PRIMITIVE_TO_COMPLEX = Collections.unmodifiableMap(collect); + + collect = new LinkedHashMap<>(10); + for (Entry, Class> entry : PRIMITIVE_TO_COMPLEX.entrySet()) { + collect.put(entry.getValue(), entry.getKey()); + } + + COMPLEX_TO_PRIMITIVE = Collections.unmodifiableMap(collect); + } + + public static boolean isInstance(Object object) { + return isComplex(object) || isPrimitive(object); + } + + public static boolean isInstance(Class type) { + return isComplex(type) || isPrimitive(type); + } + + public static boolean isComplex(Object object) { + return object == null ? false : (object instanceof Class ? isComplex((Class) object) : isComplex(object.getClass())); + } + + public static boolean isComplex(Class type) { + return COMPLEX_TO_PRIMITIVE.containsKey(type); + } + + public static boolean isPrimitive(Object object) { + return object == null ? false : (object instanceof Class ? isPrimitive((Class) object) : isPrimitive(object.getClass())); + } + + public static boolean isPrimitive(Class type) { + return PRIMITIVE_TO_COMPLEX.containsKey(type); + } + + @SuppressWarnings("unchecked") + public static Class fromPrimitive(Class primitive) { + Objects.requireNonNull(primitive); + + Class complex = PRIMITIVE_TO_COMPLEX.get(primitive); + return complex == null ? primitive : (Class) complex; + } + + @SuppressWarnings("unchecked") + public static Class toPrimitive(Class complex) { + Objects.requireNonNull(complex); + + Class primitive = COMPLEX_TO_PRIMITIVE.get(complex); + return primitive == null ? complex : (Class) primitive; + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Streams.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Streams.java index f46330b..21ec3cf 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Streams.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Streams.java @@ -10,22 +10,22 @@ public class Streams { - public static String toString(InputStream input) throws IOException { - try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { - return buffer.lines().collect(Collectors.joining(System.lineSeparator())); - } - } + public static String toString(InputStream input) throws IOException { + try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) { + return buffer.lines().collect(Collectors.joining(System.lineSeparator())); + } + } - public static byte[] toByteArray(InputStream input) throws IOException { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - byte[] data = new byte[1024]; - int length; - while ((length = input.read(data, 0, data.length)) != -1) { - buffer.write(data, 0, length); - } - buffer.flush(); - buffer.close(); - return buffer.toByteArray(); - } + public static byte[] toByteArray(InputStream input) throws IOException { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + byte[] data = new byte[1024]; + int length; + while ((length = input.read(data, 0, data.length)) != -1) { + buffer.write(data, 0, length); + } + buffer.flush(); + buffer.close(); + return buffer.toByteArray(); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Strings.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Strings.java index 9aed34a..93192d2 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Strings.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Strings.java @@ -5,84 +5,85 @@ import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; + import com.syntaxphoenix.syntaxapi.utils.java.lang.StringBuilder; public class Strings { - public static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d*"); - public static final Pattern DECIMAL_PATTERN = Pattern.compile("-?\\d*\\.\\d*"); - - public static boolean isNumeric(String msg) { - return NUMBER_PATTERN.matcher(msg).matches(); - } - - public static boolean isDecimal(String msg) { - return DECIMAL_PATTERN.matcher(msg).matches(); - } - - public static String toString(Collection collection) { - return toString(collection.toArray(new String[collection.size()])); - } - - public static String toString(Collection collection, String adder) { - return toString(collection.toArray(new String[collection.size()]), adder); - } - - public static String toString(String[] array) { - return toString(array, " "); - } - - public static String toString(String[] array, String adder) { - StringBuilder builder = new StringBuilder(); - for (int index = 0; index < array.length; index++) { - builder.append(array[index]); - if ((index + 1) != array.length) { - builder.append(adder); - } - } - return builder.toStringClear(); - } - - public static String toString(List list) { - return toString(list, " "); - } - - public static String toString(List list, String adder) { - StringBuilder builder = new StringBuilder(); - int size = list.size(); - for (int index = 0; index < size; index++) { - builder.append(list.get(index)); - if ((index + 1) != size) { - builder.append(adder); - } - } - return builder.toStringClear(); - } - - public static UUID toUUID(String id) { - return UUID - .fromString(String.valueOf(id.substring(0, 8)) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" - + id.substring(20, 32)); - } - - public static int count(String message, Character character) { - int count = 0; - Matcher matcher = Pattern.compile(character.toString()).matcher(message); - while (matcher.find()) - count++; - return count; - } - - public static boolean isBoolean(String input) { - if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false")) { - return true; - } - return false; - } - - public static String firstLetterToUpperCase(String string) { - String letter = (string = string.toLowerCase()).substring(0, 1); - return string.replaceFirst(letter, letter.toUpperCase()); - } + public static final Pattern NUMBER_PATTERN = Pattern.compile("-?\\d*"); + public static final Pattern DECIMAL_PATTERN = Pattern.compile("-?\\d*\\.\\d*"); + + public static boolean isNumeric(String msg) { + return NUMBER_PATTERN.matcher(msg).matches(); + } + + public static boolean isDecimal(String msg) { + return DECIMAL_PATTERN.matcher(msg).matches(); + } + + public static String toString(Collection collection) { + return toString(collection.toArray(new String[collection.size()])); + } + + public static String toString(Collection collection, String adder) { + return toString(collection.toArray(new String[collection.size()]), adder); + } + + public static String toString(String[] array) { + return toString(array, " "); + } + + public static String toString(String[] array, String adder) { + StringBuilder builder = new StringBuilder(); + for (int index = 0; index < array.length; index++) { + builder.append(array[index]); + if ((index + 1) != array.length) { + builder.append(adder); + } + } + return builder.toStringClear(); + } + + public static String toString(List list) { + return toString(list, " "); + } + + public static String toString(List list, String adder) { + StringBuilder builder = new StringBuilder(); + int size = list.size(); + for (int index = 0; index < size; index++) { + builder.append(list.get(index)); + if ((index + 1) != size) { + builder.append(adder); + } + } + return builder.toStringClear(); + } + + public static UUID toUUID(String id) { + return UUID.fromString(String.valueOf(id.substring(0, 8)) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + + id.substring(16, 20) + "-" + id.substring(20, 32)); + } + + public static int count(String message, Character character) { + int count = 0; + Matcher matcher = Pattern.compile(character.toString()).matcher(message); + while (matcher.find()) { + count++; + } + return count; + } + + public static boolean isBoolean(String input) { + if (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("false")) { + return true; + } + return false; + } + + public static String firstLetterToUpperCase(String string) { + String letter = (string = string.toLowerCase()).substring(0, 1); + return string.replaceFirst(letter, letter.toUpperCase()); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Times.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Times.java index 76f7150..ee320be 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Times.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Times.java @@ -5,20 +5,20 @@ public class Times { - public static String getTime(String x) { - return new SimpleDateFormat("HH" + x + "mm" + x + "ss").format((Calendar.getInstance()).getTime()); + public static String getTime(String x) { + return new SimpleDateFormat("HH" + x + "mm" + x + "ss").format((Calendar.getInstance()).getTime()); - } + } - public static String getDate(String x) { - return new SimpleDateFormat("dd" + x + "MM" + x + "yyyy").format((Calendar.getInstance()).getTime()); + public static String getDate(String x) { + return new SimpleDateFormat("dd" + x + "MM" + x + "yyyy").format((Calendar.getInstance()).getTime()); - } + } - public static String getDateAfter(String x, int days) { - Calendar calendar = (Calendar) Calendar.getInstance().clone(); - calendar.add(Calendar.DATE, days); - return new SimpleDateFormat("dd" + x + "MM" + x + "yyyy").format(calendar.getTime()); - } + public static String getDateAfter(String x, int days) { + Calendar calendar = (Calendar) Calendar.getInstance().clone(); + calendar.add(Calendar.DATE, days); + return new SimpleDateFormat("dd" + x + "MM" + x + "yyyy").format(calendar.getTime()); + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/UniCode.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/UniCode.java index 6c16af8..bf12c23 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/UniCode.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/UniCode.java @@ -2,18 +2,18 @@ public final class UniCode { - public static final char ARROWS_RIGHT = '\u00BB'; - public static final char ARROWS_LEFT = '\u00AB'; + public static final char ARROWS_RIGHT = '\u00BB'; + public static final char ARROWS_LEFT = '\u00AB'; - public static final char UPPER_UE = '\u00CC'; - public static final char LOWER_UE = '\u00FC'; + public static final char UPPER_UE = '\u00CC'; + public static final char LOWER_UE = '\u00FC'; - public static final char UPPER_OE = '\u00D6'; - public static final char LOWER_OE = '\u00F6'; + public static final char UPPER_OE = '\u00D6'; + public static final char LOWER_OE = '\u00F6'; - public static final char UPPER_AE = '\u00C4'; - public static final char LOWER_AE = '\u00E4'; + public static final char UPPER_AE = '\u00C4'; + public static final char LOWER_AE = '\u00E4'; - public static final char SS = '\u00df'; + public static final char SS = '\u00df'; } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Zipper.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Zipper.java index 56b6565..5d82deb 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Zipper.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/Zipper.java @@ -10,76 +10,81 @@ public final class Zipper { - public static File[] unzip(File zip, File directory, boolean deleteZipOnEnd) throws IOException { - if (!zip.exists() || !zip.isFile()) { - return null; - } - if (!directory.exists()) { - if (Files.createFolder(directory) == null) - return null; - } else if (!directory.isDirectory()) { - return null; - } - byte[] buffer = new byte[2048]; - ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zip)); - ZipEntry entry = inputStream.getNextEntry(); - while (entry != null) { - File file = new File(directory, entry.getName()); - FileOutputStream fileOutput = new FileOutputStream(file); - int length; - while ((length = inputStream.read(buffer)) > 0) { - fileOutput.write(buffer, 0, length); - } - fileOutput.close(); - entry = inputStream.getNextEntry(); - } - inputStream.closeEntry(); - inputStream.close(); - if (deleteZipOnEnd) - zip.delete(); - return directory.listFiles(); - } + public static File[] unzip(File zip, File directory, boolean deleteZipOnEnd) throws IOException { + if (!zip.exists() || !zip.isFile()) { + return null; + } + if (!directory.exists()) { + if (Files.createFolder(directory) == null) { + return null; + } + } else if (!directory.isDirectory()) { + return null; + } + byte[] buffer = new byte[2048]; + ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zip)); + ZipEntry entry = inputStream.getNextEntry(); + while (entry != null) { + File file = new File(directory, entry.getName()); + FileOutputStream fileOutput = new FileOutputStream(file); + int length; + while ((length = inputStream.read(buffer)) > 0) { + fileOutput.write(buffer, 0, length); + } + fileOutput.close(); + entry = inputStream.getNextEntry(); + } + inputStream.closeEntry(); + inputStream.close(); + if (deleteZipOnEnd) { + zip.delete(); + } + return directory.listFiles(); + } - public static void zip(String zipName, File directory, File... toZip) throws IOException { - if (!directory.exists()) { - if (Files.createFolder(directory) == null) - return; - } else if (!directory.isDirectory()) { - return; - } - zip(new File(directory, zipName)); - } + public static void zip(String zipName, File directory, File... toZip) throws IOException { + if (!directory.exists()) { + if (Files.createFolder(directory) == null) { + return; + } + } else if (!directory.isDirectory()) { + return; + } + zip(new File(directory, zipName)); + } - public static void zip(File zipFile, File... toZip) throws IOException { - if (toZip == null || toZip.length == 0) - return; - if (Files.createFile(zipFile) == null) - return; + public static void zip(File zipFile, File... toZip) throws IOException { + if (toZip == null || toZip.length == 0) { + return; + } + if (Files.createFile(zipFile) == null) { + return; + } - FileOutputStream fileOutput = new FileOutputStream(zipFile); - ZipOutputStream zipOutput = new ZipOutputStream(fileOutput); - int failed = 0; - for (int index = 0; index < toZip.length; index++) { - File file = toZip[index]; - if (file == null) { - failed += 1; - continue; - } - FileInputStream fileInput = new FileInputStream(file); - ZipEntry entry = new ZipEntry(file.getName()); - zipOutput.putNextEntry(entry); - byte[] bytes = new byte[2048]; - int length; - while ((length = fileInput.read(bytes)) >= 0) { - zipOutput.write(bytes, 0, length); - } - fileInput.close(); - } - zipOutput.close(); - fileOutput.close(); - if (failed == toZip.length) { - zipFile.delete(); - } - } + FileOutputStream fileOutput = new FileOutputStream(zipFile); + ZipOutputStream zipOutput = new ZipOutputStream(fileOutput); + int failed = 0; + for (int index = 0; index < toZip.length; index++) { + File file = toZip[index]; + if (file == null) { + failed += 1; + continue; + } + FileInputStream fileInput = new FileInputStream(file); + ZipEntry entry = new ZipEntry(file.getName()); + zipOutput.putNextEntry(entry); + byte[] bytes = new byte[2048]; + int length; + while ((length = fileInput.read(bytes)) >= 0) { + zipOutput.write(bytes, 0, length); + } + fileInput.close(); + } + zipOutput.close(); + fileOutput.close(); + if (failed == toZip.length) { + zipFile.delete(); + } + } } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Compare.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Compare.java index d53eb45..ec4352f 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Compare.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Compare.java @@ -3,6 +3,6 @@ @FunctionalInterface public interface Compare { - public boolean compare(A var1, B var2); + public boolean compare(A var1, B var2); } diff --git a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Container.java b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Container.java index cbf3ab1..e49e3da 100644 --- a/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Container.java +++ b/utils/java/src/main/java/com/syntaxphoenix/syntaxapi/utils/java/tools/Container.java @@ -2,410 +2,414 @@ import java.util.NoSuchElementException; import java.util.Objects; +import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Stream; -import java.util.Optional; public final class Container { - /** - * Common instance for {@code empty()}. - */ - private static final Container EMPTY = new Container<>(); - - /** - * If false, is modifiable; if true, is not modifiable - */ - private boolean modifiable; - - /** - * If non-null, the value; if null, indicates no value is present - */ - private T value; - - /** - * Returns an empty {@code Container} instance. No value is present for this - * {@code Container}. - * - * - * @param The type of the non-existent value - * @return an empty {@code Container} - */ - @SuppressWarnings("unchecked") - public static Container empty() { - return (Container) EMPTY; - } - - /** - * Constructs an unmodifiable instance. - */ - private Container() { - this.value = null; - this.modifiable = false; - } - - /** - * Constructs an instance with the described value. - * - * @param value the value to describe; it's the caller's responsibility to - * ensure the value is non-{@code null} unless creating the - * singleton instance returned by {@code empty()}. - */ - private Container(T value, boolean modifiable) { - this.value = value; - this.modifiable = modifiable; - } - - /** - * Returns an {@code Container} - * - * @param the type of the value - * @return an {@code Container} - */ - public static Container of() { - return new Container<>(null, true); - } - - /** - * Returns an {@code Container} describing the given value. - * - * @param value the value to describe - * @param the type of the value - * @return an {@code Container} with the value - */ - public static Container of(T value) { - return new Container<>(value, true); - } - - /** - * Returns an {@code Container} describing the given value. - * - * @param value the value to describe - * @param the type of the value - * @return an unmodifiable {@code Container} with the value or empty - */ - public static Container ofUnmodifiable(T value) { - return value == null ? empty() : new Container<>(value, false); - } - - /** - * Returns an {@code Container} describing the given value of the optional. - * - * @param value {code Optional} that contains a value or null - * @param the type of the value - * @return an {@code Container} with the value of the optional - */ - public static Container ofOptional(Optional value) { - return value.isPresent() ? new Container<>(null, true) : new Container<>(value.get(), true); - } - - /** - * Returns an {@code Container} describing the given value of the optional. - * - * @param value {code Optional} that contains a value or null - * @param the type of the value - * @return an {@code Container} with the value of the optional - */ - public static Container ofOptionalUnmodifiable(Optional value) { - return value.isPresent() ? empty() : new Container<>(value.get(), false); - } - - /** - * returns the value as an optional - * - * @return the optional - */ - public Optional asOptional() { - return Optional.ofNullable(value); - } - - /** - * replaces the value with the given value - * - * @param value the value to describe - * @return the old value described by this {@code Container} - */ - public Container replace(T value) { - if (isModifiable()) - this.value = value; - return this; - } - - /** - * returns the value - * - * @return the value described by this {@code Container} - */ - public T get() { - return value; - } - - /** - * locks the container - * - * @return this - */ - public Container lock() { - modifiable = false; - return this; - } - - /** - * returns the modifiable - * - * @return {@code true} if a value is present, otherwise {@code false} - */ - public boolean isModifiable() { - return modifiable; - } - - /** - * If a value is present, returns {@code true}, otherwise {@code false}. - * - * @return {@code true} if a value is present, otherwise {@code false} - */ - public boolean isPresent() { - return value != null; - } - - /** - * If a value is not present, returns {@code true}, otherwise {@code false}. - * - * @return {@code true} if a value is not present, otherwise {@code false} - */ - public boolean isEmpty() { - return value == null; - } - - /** - * If a value is present, performs the given action with the value, otherwise - * does nothing. - * - * @param action the action to be performed, if a value is present - * @throws NullPointerException if value is present and the given action is - * {@code null} - */ - public void ifPresent(Consumer action) { - if (isEmpty()) - return; - action.accept(value); - } - - /** - * If a value is present, performs the given action with the value, otherwise - * performs the given empty-based action. - * - * @param action the action to be performed, if a value is present - * @param emptyAction the empty-based action to be performed, if no value is - * present - * @throws NullPointerException if a value is present and the given action is - * {@code null}, or no value is present and the - * given empty-based action is {@code null}. - */ - public void ifPresentOrElse(Consumer action, Runnable emptyAction) { - if (isEmpty()) { - emptyAction.run(); - return; - } - action.accept(value); - } - - /** - * If a value is present, and the value matches the given predicate, returns an - * {@code Container} describing the value, otherwise returns an empty - * {@code Container}. - * - * @param predicate the predicate to apply to a value, if present - * @return an {@code Container} describing the value of this {@code Container}, - * if a value is present and the value matches the given predicate, - * otherwise an empty {@code Container} - * @throws NullPointerException if the predicate is {@code null} - */ - public Container filter(Predicate predicate) { - Objects.requireNonNull(predicate); - return isPresent() ? (predicate.test(value) ? this : empty()) : this; - } - - /** - * If a value is present, returns an {@code Container} describing the result of - * applying the given mapping function to the value, otherwise returns an empty - * {@code Container}. - * - *

- * If the mapping function returns a {@code null} result then this method - * returns an empty {@code Container}. - * - * @param mapper the mapping function to apply to a value, if present - * @param The type of the value returned from the mapping function - * @return an {@code Container} describing the result of applying a mapping - * function to the value of this {@code Container}, if a value is - * present, otherwise an empty {@code Container} - * @throws NullPointerException if the mapping function is {@code null} - */ - public Container map(Function mapper) { - Objects.requireNonNull(mapper); - return isPresent() ? Container.of(mapper.apply(value)) : empty(); - } - - /** - * If a value is present, returns the result of applying the given - * {@code Container}-bearing mapping function to the value, otherwise returns an - * empty {@code Container}. - * - *

- * This method is similar to {@link #map(Function)}, but the mapping function is - * one whose result is already an {@code Container}, and if invoked, - * {@code flatMap} does not wrap it within an additional {@code Container}. - * - * @param The type of value of the {@code Container} returned by the - * mapping function - * @param mapper the mapping function to apply to a value, if present - * @return the result of applying an {@code Container}-bearing mapping function - * to the value of this {@code Container}, if a value is present, - * otherwise an empty {@code Container} - * @throws NullPointerException if the mapping function is {@code null} or - * returns a {@code null} result - */ - @SuppressWarnings("unchecked") - public Container flatMap(Function> mapper) { - Objects.requireNonNull(mapper); - return isPresent() ? Objects.requireNonNull((Container) mapper.apply(value)) : empty(); - } - - /** - * If a value is present, returns an {@code Container} describing the value, - * otherwise returns an {@code Container} produced by the supplying function. - * - * @param supplier the supplying function that produces an {@code Container} to - * be returned - * @return returns an {@code Container} describing the value of this - * {@code Container}, if a value is present, otherwise an - * {@code Container} produced by the supplying function. - * @throws NullPointerException if the supplying function is {@code null} or - * produces a {@code null} result - */ - @SuppressWarnings("unchecked") - public Container or(Supplier> supplier) { - Objects.requireNonNull(supplier); - return isPresent() ? this : Objects.requireNonNull((Container) supplier.get()); - } - - /** - * If a value is present, returns a sequential {@link Stream} containing only - * that value, otherwise returns an empty {@code Stream}. - * - * @return the optional value as a {@code Stream} - */ - public Stream stream() { - return isPresent() ? Stream.of(value) : Stream.empty(); - } - - /** - * If a value is present, returns the value, otherwise returns {@code other}. - * - * @param other the value to be returned, if no value is present. May be - * {@code null}. - * @return the value, if present, otherwise {@code other} - */ - public T orElse(T other) { - return value != null ? value : other; - } - - /** - * If a value is present, returns the value, otherwise returns the result - * produced by the supplying function. - * - * @param supplier the supplying function that produces a value to be returned - * @return the value, if present, otherwise the result produced by the supplying - * function - * @throws NullPointerException if no value is present and the supplying - * function is {@code null} - */ - public T orElseGet(Supplier supplier) { - return isPresent() ? value : supplier.get(); - } - - /** - * If a value is present, returns the value, otherwise throws - * {@code NoSuchElementException}. - * - * @return the non-{@code null} value described by this {@code Container} - * @throws NoSuchElementException if no value is present - */ - public T orElseThrow() { - if (isPresent()) - return value; - throw new NoSuchElementException("No value present"); - } - - /** - * If a value is present, returns the value, otherwise throws an exception - * produced by the exception supplying function. - * - * @param Type of the exception to be thrown - * @param exceptionSupplier the supplying function that produces an exception to - * be thrown - * @return the value, if present - * @throws X if no value is present - * @throws NullPointerException if no value is present and the exception - * supplying function is {@code null} - */ - public T orElseThrow(Supplier exceptionSupplier) throws X { - if (isPresent()) - return value; - throw exceptionSupplier.get(); - } - - /** - * Indicates whether some other object is "equal to" this {@code Container}. The - * other object is considered equal if: - *

- * - * @param obj an object to be tested for equality - * @return {@code true} if the other object is "equal to" this object otherwise - * {@code false} - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if (!(obj instanceof Container)) { - return false; - } - - Container other = (Container) obj; - return Objects.equals(value, other.value); - } - - /** - * Returns the hash code of the value, if present, otherwise {@code 0} (zero) if - * no value is present. - * - * @return hash code value of the present value or {@code 0} if no value is - * present - */ - @Override - public int hashCode() { - return Objects.hashCode(value); - } - - /** - * Returns a non-empty string representation of this {@code Container} suitable - * for debugging. The exact presentation format is unspecified and may vary - * between implementations and versions. - * - * @return the string representation of this instance - */ - @Override - public String toString() { - return isPresent() ? String.format("Container[%s]", value) : "Container.empty"; - } + /** + * Common instance for {@code empty()}. + */ + private static final Container EMPTY = new Container<>(); + + /** + * If false, is modifiable; if true, is not modifiable + */ + private boolean modifiable; + + /** + * If non-null, the value; if null, indicates no value is present + */ + private T value; + + /** + * Returns an empty {@code Container} instance. No value is present for this + * {@code Container}. + * + * + * @param The type of the non-existent value + * @return an empty {@code Container} + */ + @SuppressWarnings("unchecked") + public static Container empty() { + return (Container) EMPTY; + } + + /** + * Constructs an unmodifiable instance. + */ + private Container() { + this.value = null; + this.modifiable = false; + } + + /** + * Constructs an instance with the described value. + * + * @param value the value to describe; it's the caller's responsibility to + * ensure the value is non-{@code null} unless creating the + * singleton instance returned by {@code empty()}. + */ + private Container(T value, boolean modifiable) { + this.value = value; + this.modifiable = modifiable; + } + + /** + * Returns an {@code Container} + * + * @param the type of the value + * @return an {@code Container} + */ + public static Container of() { + return new Container<>(null, true); + } + + /** + * Returns an {@code Container} describing the given value. + * + * @param value the value to describe + * @param the type of the value + * @return an {@code Container} with the value + */ + public static Container of(T value) { + return new Container<>(value, true); + } + + /** + * Returns an {@code Container} describing the given value. + * + * @param value the value to describe + * @param the type of the value + * @return an unmodifiable {@code Container} with the value or empty + */ + public static Container ofUnmodifiable(T value) { + return value == null ? empty() : new Container<>(value, false); + } + + /** + * Returns an {@code Container} describing the given value of the optional. + * + * @param value {code Optional} that contains a value or null + * @param the type of the value + * @return an {@code Container} with the value of the optional + */ + public static Container ofOptional(Optional value) { + return value.isPresent() ? new Container<>(null, true) : new Container<>(value.get(), true); + } + + /** + * Returns an {@code Container} describing the given value of the optional. + * + * @param value {code Optional} that contains a value or null + * @param the type of the value + * @return an {@code Container} with the value of the optional + */ + public static Container ofOptionalUnmodifiable(Optional value) { + return value.isPresent() ? empty() : new Container<>(value.get(), false); + } + + /** + * returns the value as an optional + * + * @return the optional + */ + public Optional asOptional() { + return Optional.ofNullable(value); + } + + /** + * replaces the value with the given value + * + * @param value the value to describe + * @return the old value described by this {@code Container} + */ + public Container replace(T value) { + if (isModifiable()) { + this.value = value; + } + return this; + } + + /** + * returns the value + * + * @return the value described by this {@code Container} + */ + public T get() { + return value; + } + + /** + * locks the container + * + * @return this + */ + public Container lock() { + modifiable = false; + return this; + } + + /** + * returns the modifiable + * + * @return {@code true} if a value is present, otherwise {@code false} + */ + public boolean isModifiable() { + return modifiable; + } + + /** + * If a value is present, returns {@code true}, otherwise {@code false}. + * + * @return {@code true} if a value is present, otherwise {@code false} + */ + public boolean isPresent() { + return value != null; + } + + /** + * If a value is not present, returns {@code true}, otherwise {@code false}. + * + * @return {@code true} if a value is not present, otherwise {@code false} + */ + public boolean isEmpty() { + return value == null; + } + + /** + * If a value is present, performs the given action with the value, otherwise + * does nothing. + * + * @param action the action to be performed, if a value is present + * @throws NullPointerException if value is present and the given action is + * {@code null} + */ + public void ifPresent(Consumer action) { + if (isEmpty()) { + return; + } + action.accept(value); + } + + /** + * If a value is present, performs the given action with the value, otherwise + * performs the given empty-based action. + * + * @param action the action to be performed, if a value is present + * @param emptyAction the empty-based action to be performed, if no value is + * present + * @throws NullPointerException if a value is present and the given action is + * {@code null}, or no value is present and the + * given empty-based action is {@code null}. + */ + public void ifPresentOrElse(Consumer action, Runnable emptyAction) { + if (isEmpty()) { + emptyAction.run(); + return; + } + action.accept(value); + } + + /** + * If a value is present, and the value matches the given predicate, returns an + * {@code Container} describing the value, otherwise returns an empty + * {@code Container}. + * + * @param predicate the predicate to apply to a value, if present + * @return an {@code Container} describing the value of this {@code Container}, + * if a value is present and the value matches the given predicate, + * otherwise an empty {@code Container} + * @throws NullPointerException if the predicate is {@code null} + */ + public Container filter(Predicate predicate) { + Objects.requireNonNull(predicate); + return isPresent() ? (predicate.test(value) ? this : empty()) : this; + } + + /** + * If a value is present, returns an {@code Container} describing the result of + * applying the given mapping function to the value, otherwise returns an empty + * {@code Container}. + * + *

+ * If the mapping function returns a {@code null} result then this method + * returns an empty {@code Container}. + * + * @param mapper the mapping function to apply to a value, if present + * @param The type of the value returned from the mapping function + * @return an {@code Container} describing the result of applying a mapping + * function to the value of this {@code Container}, if a value is + * present, otherwise an empty {@code Container} + * @throws NullPointerException if the mapping function is {@code null} + */ + public Container map(Function mapper) { + Objects.requireNonNull(mapper); + return isPresent() ? Container.of(mapper.apply(value)) : empty(); + } + + /** + * If a value is present, returns the result of applying the given + * {@code Container}-bearing mapping function to the value, otherwise returns an + * empty {@code Container}. + * + *

+ * This method is similar to {@link #map(Function)}, but the mapping function is + * one whose result is already an {@code Container}, and if invoked, + * {@code flatMap} does not wrap it within an additional {@code Container}. + * + * @param The type of value of the {@code Container} returned by the + * mapping function + * @param mapper the mapping function to apply to a value, if present + * @return the result of applying an {@code Container}-bearing mapping function + * to the value of this {@code Container}, if a value is present, + * otherwise an empty {@code Container} + * @throws NullPointerException if the mapping function is {@code null} or + * returns a {@code null} result + */ + @SuppressWarnings("unchecked") + public Container flatMap(Function> mapper) { + Objects.requireNonNull(mapper); + return isPresent() ? Objects.requireNonNull((Container) mapper.apply(value)) : empty(); + } + + /** + * If a value is present, returns an {@code Container} describing the value, + * otherwise returns an {@code Container} produced by the supplying function. + * + * @param supplier the supplying function that produces an {@code Container} to + * be returned + * @return returns an {@code Container} describing the value of this + * {@code Container}, if a value is present, otherwise an + * {@code Container} produced by the supplying function. + * @throws NullPointerException if the supplying function is {@code null} or + * produces a {@code null} result + */ + @SuppressWarnings("unchecked") + public Container or(Supplier> supplier) { + Objects.requireNonNull(supplier); + return isPresent() ? this : Objects.requireNonNull((Container) supplier.get()); + } + + /** + * If a value is present, returns a sequential {@link Stream} containing only + * that value, otherwise returns an empty {@code Stream}. + * + * @return the optional value as a {@code Stream} + */ + public Stream stream() { + return isPresent() ? Stream.of(value) : Stream.empty(); + } + + /** + * If a value is present, returns the value, otherwise returns {@code other}. + * + * @param other the value to be returned, if no value is present. May be + * {@code null}. + * @return the value, if present, otherwise {@code other} + */ + public T orElse(T other) { + return value != null ? value : other; + } + + /** + * If a value is present, returns the value, otherwise returns the result + * produced by the supplying function. + * + * @param supplier the supplying function that produces a value to be returned + * @return the value, if present, otherwise the result produced by the supplying + * function + * @throws NullPointerException if no value is present and the supplying + * function is {@code null} + */ + public T orElseGet(Supplier supplier) { + return isPresent() ? value : supplier.get(); + } + + /** + * If a value is present, returns the value, otherwise throws + * {@code NoSuchElementException}. + * + * @return the non-{@code null} value described by this {@code Container} + * @throws NoSuchElementException if no value is present + */ + public T orElseThrow() { + if (isPresent()) { + return value; + } + throw new NoSuchElementException("No value present"); + } + + /** + * If a value is present, returns the value, otherwise throws an exception + * produced by the exception supplying function. + * + * @param Type of the exception to be thrown + * @param exceptionSupplier the supplying function that produces an exception to + * be thrown + * @return the value, if present + * @throws X if no value is present + * @throws NullPointerException if no value is present and the exception + * supplying function is {@code null} + */ + public T orElseThrow(Supplier exceptionSupplier) throws X { + if (isPresent()) { + return value; + } + throw exceptionSupplier.get(); + } + + /** + * Indicates whether some other object is "equal to" this {@code Container}. The + * other object is considered equal if: + *

    + *
  • it is also an {@code Container} and; + *
  • both instances have no value present or; + *
  • the present values are "equal to" each other via {@code equals()}. + *
+ * + * @param obj an object to be tested for equality + * @return {@code true} if the other object is "equal to" this object otherwise + * {@code false} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof Container)) { + return false; + } + + Container other = (Container) obj; + return Objects.equals(value, other.value); + } + + /** + * Returns the hash code of the value, if present, otherwise {@code 0} (zero) if + * no value is present. + * + * @return hash code value of the present value or {@code 0} if no value is + * present + */ + @Override + public int hashCode() { + return Objects.hashCode(value); + } + + /** + * Returns a non-empty string representation of this {@code Container} suitable + * for debugging. The exact presentation format is unspecified and may vary + * between implementations and versions. + * + * @return the string representation of this instance + */ + @Override + public String toString() { + return isPresent() ? String.format("Container[%s]", value) : "Container.empty"; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonArray.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonArray.java index 45bf8c9..16cae84 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonArray.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonArray.java @@ -8,92 +8,95 @@ public class JsonArray extends JsonValue>> implements Iterable> { - private final ArrayList> values = new ArrayList<>(); - - @Override - public final ValueType getType() { - return ValueType.ARRAY; - } - - @Override - public List> getValue() { - return values; - } - - public JsonArray add(JsonValue value) { - if (value == null) - return this; - synchronized (values) { - values.add(value); - } - return this; - } - - public JsonArray add(Object value) { - return add(JsonValue.fromPrimitive(value)); - } - - public Optional> remove(int index) { - if (index >= size() || index < 0) - return Optional.empty(); - synchronized (values) { - return Optional.ofNullable(values.remove(index)); - } - } - - public boolean remove(JsonValue value) { - synchronized (values) { - return values.remove(value); - } - } - - public JsonValue get(int index) { - return optional(index).orElse(null); - } - - public Optional> optional(int index) { - if (index >= size() || index < 0) - return Optional.empty(); - synchronized (values) { - return Optional.ofNullable(values.get(index)); - } - } - - public boolean has(JsonValue value) { - synchronized (values) { - return values.contains(value); - } - } - - public boolean has(int index) { - return optional(index).isPresent(); - } - - public boolean has(int index, ValueType type) { - return optional(index).filter(value -> value.hasType(type)).isPresent(); - } - - public int indexOf(JsonValue value) { - synchronized (values) { - return values.indexOf(value); - } - } - - public int size() { - synchronized (values) { - return values.size(); - } - } - - @Override - public SynchronizedIterator> iterator() { - return new SynchronizedIterator<>(values); - } - - public JsonValue[] toArray() { - synchronized (values) { - return values.toArray(new JsonValue[0]); - } - } + private final ArrayList> values = new ArrayList<>(); + + @Override + public final ValueType getType() { + return ValueType.ARRAY; + } + + @Override + public List> getValue() { + return values; + } + + public JsonArray add(JsonValue value) { + if (value == null) { + return this; + } + synchronized (values) { + values.add(value); + } + return this; + } + + public JsonArray add(Object value) { + return add(JsonValue.fromPrimitive(value)); + } + + public Optional> remove(int index) { + if (index >= size() || index < 0) { + return Optional.empty(); + } + synchronized (values) { + return Optional.ofNullable(values.remove(index)); + } + } + + public boolean remove(JsonValue value) { + synchronized (values) { + return values.remove(value); + } + } + + public JsonValue get(int index) { + return optional(index).orElse(null); + } + + public Optional> optional(int index) { + if (index >= size() || index < 0) { + return Optional.empty(); + } + synchronized (values) { + return Optional.ofNullable(values.get(index)); + } + } + + public boolean has(JsonValue value) { + synchronized (values) { + return values.contains(value); + } + } + + public boolean has(int index) { + return optional(index).isPresent(); + } + + public boolean has(int index, ValueType type) { + return optional(index).filter(value -> value.hasType(type)).isPresent(); + } + + public int indexOf(JsonValue value) { + synchronized (values) { + return values.indexOf(value); + } + } + + public int size() { + synchronized (values) { + return values.size(); + } + } + + @Override + public SynchronizedIterator> iterator() { + return new SynchronizedIterator<>(values); + } + + public JsonValue[] toArray() { + synchronized (values) { + return values.toArray(new JsonValue[0]); + } + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonEntry.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonEntry.java index 9378cc8..5c84ac9 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonEntry.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonEntry.java @@ -7,29 +7,29 @@ public class JsonEntry> { - private final String key; - private final E value; - - @SuppressWarnings("unchecked") - public JsonEntry(String key, E value) { - this.key = Objects.requireNonNull(key); - this.value = value == null ? (E) JsonNull.get() : value; - } - - public String getKey() { - return key; - } - - public ValueType getType() { - return value == null ? ValueType.NULL : value.getType(); - } - - public E getValue() { - return value; - } - - public Optional getOptional() { - return Optional.ofNullable(value); - } + private final String key; + private final E value; + + @SuppressWarnings("unchecked") + public JsonEntry(String key, E value) { + this.key = Objects.requireNonNull(key); + this.value = value == null ? (E) JsonNull.get() : value; + } + + public String getKey() { + return key; + } + + public ValueType getType() { + return value == null ? ValueType.NULL : value.getType(); + } + + public E getValue() { + return value; + } + + public Optional getOptional() { + return Optional.ofNullable(value); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonObject.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonObject.java index eb94542..07a23ac 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonObject.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonObject.java @@ -9,111 +9,112 @@ public class JsonObject extends JsonValue>> implements Iterable> { - private final ArrayList> values = new ArrayList<>(); - - @Override - public final ValueType getType() { - return ValueType.OBJECT; - } - - @Override - public Map> getValue() { - HashMap> values = new HashMap<>(); - synchronized (this.values) { - for (JsonEntry entry : this.values) { - values.put(entry.getKey(), entry.getValue()); - } - } - return values; - } - - public JsonObject set(String key, JsonValue value) { - if (value == null) - return this; - remove(key); - synchronized (values) { - values.add(new JsonEntry<>(key, value)); - } - return this; - } - - public JsonObject set(String key, Object value) { - return set(key, JsonValue.fromPrimitive(value)); - } - - public Optional> remove(String key) { - Optional> option = search(key); - if (option.isPresent()) { - synchronized (values) { - values.remove(option.get()); - } - } - return option.map(JsonEntry::getValue); - } - - public JsonValue get(String key) { - return optional(key).orElse(null); - } - - public Optional> optional(String key) { - return search(key).map(JsonEntry::getValue); - } - - public String key(JsonValue value) { - return search(value).map(JsonEntry::getKey).orElse(null); - } - - public boolean has(String key) { - return search(key).isPresent(); - } - - public boolean has(String key, ValueType type) { - return optional(key).filter(value -> value.hasType(type)).isPresent(); - } - - public int size() { - synchronized (values) { - return values.size(); - } - } - - public String[] keys() { - synchronized (values) { - return values.stream().map(JsonEntry::getKey).toArray(String[]::new); - } - } - - public JsonValue[] values() { - synchronized (values) { - return values.stream().map(JsonEntry::getKey).toArray(JsonValue[]::new); - } - } - - public JsonEntry[] entries() { - synchronized (values) { - return values.toArray(new JsonEntry[0]); - } - } - - @Override - public SynchronizedIterator> iterator() { - return new SynchronizedIterator<>(values); - } - - /* - * Helper - */ - - private Optional> search(String key) { - synchronized (values) { - return values.stream().filter(entry -> entry.getKey().equals(key)).findFirst(); - } - } - - private Optional> search(JsonValue value) { - synchronized (values) { - return values.stream().filter(entry -> entry.getValue().equals(value)).findFirst(); - } - } + private final ArrayList> values = new ArrayList<>(); + + @Override + public final ValueType getType() { + return ValueType.OBJECT; + } + + @Override + public Map> getValue() { + HashMap> values = new HashMap<>(); + synchronized (this.values) { + for (JsonEntry entry : this.values) { + values.put(entry.getKey(), entry.getValue()); + } + } + return values; + } + + public JsonObject set(String key, JsonValue value) { + if (value == null) { + return this; + } + remove(key); + synchronized (values) { + values.add(new JsonEntry<>(key, value)); + } + return this; + } + + public JsonObject set(String key, Object value) { + return set(key, JsonValue.fromPrimitive(value)); + } + + public Optional> remove(String key) { + Optional> option = search(key); + if (option.isPresent()) { + synchronized (values) { + values.remove(option.get()); + } + } + return option.map(JsonEntry::getValue); + } + + public JsonValue get(String key) { + return optional(key).orElse(null); + } + + public Optional> optional(String key) { + return search(key).map(JsonEntry::getValue); + } + + public String key(JsonValue value) { + return search(value).map(JsonEntry::getKey).orElse(null); + } + + public boolean has(String key) { + return search(key).isPresent(); + } + + public boolean has(String key, ValueType type) { + return optional(key).filter(value -> value.hasType(type)).isPresent(); + } + + public int size() { + synchronized (values) { + return values.size(); + } + } + + public String[] keys() { + synchronized (values) { + return values.stream().map(JsonEntry::getKey).toArray(String[]::new); + } + } + + public JsonValue[] values() { + synchronized (values) { + return values.stream().map(JsonEntry::getKey).toArray(JsonValue[]::new); + } + } + + public JsonEntry[] entries() { + synchronized (values) { + return values.toArray(new JsonEntry[0]); + } + } + + @Override + public SynchronizedIterator> iterator() { + return new SynchronizedIterator<>(values); + } + + /* + * Helper + */ + + private Optional> search(String key) { + synchronized (values) { + return values.stream().filter(entry -> entry.getKey().equals(key)).findFirst(); + } + } + + private Optional> search(JsonValue value) { + synchronized (values) { + return values.stream().filter(entry -> entry.getValue().equals(value)).findFirst(); + } + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonValue.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonValue.java index 570b2a1..5929cc6 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonValue.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/JsonValue.java @@ -3,47 +3,66 @@ import java.math.BigDecimal; import java.math.BigInteger; -import com.syntaxphoenix.syntaxapi.json.value.*; +import com.syntaxphoenix.syntaxapi.json.value.JsonBigDecimal; +import com.syntaxphoenix.syntaxapi.json.value.JsonBigInteger; +import com.syntaxphoenix.syntaxapi.json.value.JsonByte; +import com.syntaxphoenix.syntaxapi.json.value.JsonDouble; +import com.syntaxphoenix.syntaxapi.json.value.JsonFloat; +import com.syntaxphoenix.syntaxapi.json.value.JsonInteger; +import com.syntaxphoenix.syntaxapi.json.value.JsonLong; +import com.syntaxphoenix.syntaxapi.json.value.JsonNull; +import com.syntaxphoenix.syntaxapi.json.value.JsonShort; +import com.syntaxphoenix.syntaxapi.json.value.JsonString; import com.syntaxphoenix.syntaxapi.utils.java.Primitives; public abstract class JsonValue { - @SuppressWarnings("unchecked") - public static JsonValue fromPrimitive(E primitive) { - if (primitive == null) - return JsonNull.get(); - Class complex = Primitives.fromPrimitive(primitive.getClass()); - if (complex == String.class) - return (JsonValue) new JsonString((String) primitive); - if (complex == Byte.class) - return (JsonValue) new JsonByte((Byte) primitive); - if (complex == Short.class) - return (JsonValue) new JsonShort((Short) primitive); - if (complex == Integer.class) - return (JsonValue) new JsonInteger((Integer) primitive); - if (complex == Long.class) - return (JsonValue) new JsonLong((Long) primitive); - if (complex == Float.class) - return (JsonValue) new JsonFloat((Float) primitive); - if (complex == Double.class) - return (JsonValue) new JsonDouble((Double) primitive); - if (complex == BigInteger.class) - return (JsonValue) new JsonBigInteger((BigInteger) primitive); - if (complex == BigDecimal.class) - return (JsonValue) new JsonBigDecimal((BigDecimal) primitive); - return null; - } - - public abstract ValueType getType(); - - public abstract E getValue(); - - public boolean hasType(ValueType type) { - return type.hasType(this); - } - - public boolean isPrimitive() { - return getType().isPrimitive(); - } + @SuppressWarnings("unchecked") + public static JsonValue fromPrimitive(E primitive) { + if (primitive == null) { + return JsonNull.get(); + } + Class complex = Primitives.fromPrimitive(primitive.getClass()); + if (complex == String.class) { + return (JsonValue) new JsonString((String) primitive); + } + if (complex == Byte.class) { + return (JsonValue) new JsonByte((Byte) primitive); + } + if (complex == Short.class) { + return (JsonValue) new JsonShort((Short) primitive); + } + if (complex == Integer.class) { + return (JsonValue) new JsonInteger((Integer) primitive); + } + if (complex == Long.class) { + return (JsonValue) new JsonLong((Long) primitive); + } + if (complex == Float.class) { + return (JsonValue) new JsonFloat((Float) primitive); + } + if (complex == Double.class) { + return (JsonValue) new JsonDouble((Double) primitive); + } + if (complex == BigInteger.class) { + return (JsonValue) new JsonBigInteger((BigInteger) primitive); + } + if (complex == BigDecimal.class) { + return (JsonValue) new JsonBigDecimal((BigDecimal) primitive); + } + return null; + } + + public abstract ValueType getType(); + + public abstract E getValue(); + + public boolean hasType(ValueType type) { + return type.hasType(this); + } + + public boolean isPrimitive() { + return getType().isPrimitive(); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/ValueType.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/ValueType.java index b6106a5..58c4a2a 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/ValueType.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/ValueType.java @@ -2,54 +2,54 @@ public enum ValueType { - // JSON - JSON, - ARRAY(JSON), - OBJECT(JSON), - - // Primitives - NULL, - STRING, - NUMBER, - BOOLEAN, - BYTE(NUMBER), - SHORT(NUMBER), - INTEGER(NUMBER), - LONG(NUMBER), - BIG_INTEGER(NUMBER), - FLOAT(NUMBER), - DOUBLE(NUMBER), - BIG_DECIMAL(NUMBER); - - private final ValueType parent; - - private ValueType() { - this(null); - } - - private ValueType(ValueType parent) { - this.parent = parent; - } - - public ValueType getParent() { - return parent; - } - - public boolean hasParent() { - return parent != null; - } - - public boolean isPrimitive() { - return parent != null ? parent != JSON : this != JSON; - } - - public boolean isJson() { - return !isPrimitive(); - } - - public boolean hasType(JsonValue value) { - ValueType type = value.getType(); - return parent != null ? (parent == type ? true : this == type) : this == type; - } + // JSON + JSON, + ARRAY(JSON), + OBJECT(JSON), + + // Primitives + NULL, + STRING, + NUMBER, + BOOLEAN, + BYTE(NUMBER), + SHORT(NUMBER), + INTEGER(NUMBER), + LONG(NUMBER), + BIG_INTEGER(NUMBER), + FLOAT(NUMBER), + DOUBLE(NUMBER), + BIG_DECIMAL(NUMBER); + + private final ValueType parent; + + private ValueType() { + this(null); + } + + private ValueType(ValueType parent) { + this.parent = parent; + } + + public ValueType getParent() { + return parent; + } + + public boolean hasParent() { + return parent != null; + } + + public boolean isPrimitive() { + return parent != null ? parent != JSON : this != JSON; + } + + public boolean isJson() { + return !isPrimitive(); + } + + public boolean hasType(JsonValue value) { + ValueType type = value.getType(); + return parent != null ? (parent == type ? true : this == type) : this == type; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/EndOfFileException.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/EndOfFileException.java index af2ae62..12bb748 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/EndOfFileException.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/EndOfFileException.java @@ -2,10 +2,10 @@ public class EndOfFileException extends RuntimeException { - private static final long serialVersionUID = -2018244357667590533L; + private static final long serialVersionUID = -2018244357667590533L; - public EndOfFileException() { - super(); - } + public EndOfFileException() { + super(); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonParser.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonParser.java index f846dbb..b094ca4 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonParser.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonParser.java @@ -6,70 +6,80 @@ import com.syntaxphoenix.syntaxapi.json.JsonArray; import com.syntaxphoenix.syntaxapi.json.JsonObject; import com.syntaxphoenix.syntaxapi.json.JsonValue; -import com.syntaxphoenix.syntaxapi.json.value.*; +import com.syntaxphoenix.syntaxapi.json.value.JsonBigDecimal; +import com.syntaxphoenix.syntaxapi.json.value.JsonBigInteger; +import com.syntaxphoenix.syntaxapi.json.value.JsonBoolean; +import com.syntaxphoenix.syntaxapi.json.value.JsonByte; +import com.syntaxphoenix.syntaxapi.json.value.JsonDouble; +import com.syntaxphoenix.syntaxapi.json.value.JsonFloat; +import com.syntaxphoenix.syntaxapi.json.value.JsonInteger; +import com.syntaxphoenix.syntaxapi.json.value.JsonLong; +import com.syntaxphoenix.syntaxapi.json.value.JsonNull; +import com.syntaxphoenix.syntaxapi.json.value.JsonShort; +import com.syntaxphoenix.syntaxapi.json.value.JsonString; import com.syntaxphoenix.syntaxapi.utils.io.TextDeserializer; public class JsonParser implements TextDeserializer> { - @Override - public JsonValue fromReader(Reader reader) throws IOException, JsonSyntaxException { - return read(new JsonReader(reader)); - } - - /* - * WIP c.c - */ - - protected JsonValue read(JsonReader reader) throws IOException, JsonSyntaxException { - JsonToken token = reader.next(); - switch (token) { - case NULL: - reader.readNull(); - return JsonNull.get(); - case BOOLEAN: - return new JsonBoolean(reader.readBoolean()); - case STRING: - return new JsonString(reader.readString()); - case START_ARRAY: - JsonArray array = new JsonArray(); - reader.beginArray(); - while (reader.hasNext()) { - array.add(read(reader)); - } - reader.endArray(); - return array; - case START_OBJECT: - JsonObject object = new JsonObject(); - reader.beginObject(); - while (reader.hasNext()) { - object.set(reader.readName(), read(reader)); - } - reader.endObject(); - return object; - case BYTE: - return new JsonByte(reader.readByte()); - case SHORT: - return new JsonShort(reader.readShort()); - case INTEGER: - return new JsonInteger(reader.readInteger()); - case LONG: - return new JsonLong(reader.readLong()); - case BIG_INTEGER: - return new JsonBigInteger(reader.readBigInteger()); - case FLOAT: - return new JsonFloat(reader.readFloat()); - case DOUBLE: - return new JsonDouble(reader.readDouble()); - case BIG_DECIMAL: - return new JsonBigDecimal(reader.readBigDecimal()); - case EOF: - case KEY: - case NUMBER: - case END_ARRAY: - case END_OBJECT: - default: - throw new IllegalArgumentException(); - } - } + @Override + public JsonValue fromReader(Reader reader) throws IOException, JsonSyntaxException { + return read(new JsonReader(reader)); + } + + /* + * WIP c.c + */ + + protected JsonValue read(JsonReader reader) throws IOException, JsonSyntaxException { + JsonToken token = reader.next(); + switch (token) { + case NULL: + reader.readNull(); + return JsonNull.get(); + case BOOLEAN: + return new JsonBoolean(reader.readBoolean()); + case STRING: + return new JsonString(reader.readString()); + case START_ARRAY: + JsonArray array = new JsonArray(); + reader.beginArray(); + while (reader.hasNext()) { + array.add(read(reader)); + } + reader.endArray(); + return array; + case START_OBJECT: + JsonObject object = new JsonObject(); + reader.beginObject(); + while (reader.hasNext()) { + object.set(reader.readName(), read(reader)); + } + reader.endObject(); + return object; + case BYTE: + return new JsonByte(reader.readByte()); + case SHORT: + return new JsonShort(reader.readShort()); + case INTEGER: + return new JsonInteger(reader.readInteger()); + case LONG: + return new JsonLong(reader.readLong()); + case BIG_INTEGER: + return new JsonBigInteger(reader.readBigInteger()); + case FLOAT: + return new JsonFloat(reader.readFloat()); + case DOUBLE: + return new JsonDouble(reader.readDouble()); + case BIG_DECIMAL: + return new JsonBigDecimal(reader.readBigDecimal()); + case EOF: + case KEY: + case NUMBER: + case END_ARRAY: + case END_OBJECT: + default: + throw new IllegalArgumentException(); + } + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonReader.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonReader.java index 863bbd6..aa7399e 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonReader.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonReader.java @@ -9,973 +9,974 @@ public class JsonReader { - public static final int INDICATOR_EOL = 0; - public static final int INDICATOR_EOC = 1; - - public static final int LENGTH_BYTE = 3; - public static final int LENGTH_SHORT = 5; - public static final int LENGTH_INTEGER = 10; - public static final int LENGTH_LONG = 19; - public static final int LENGTH_FLOAT = 21; - public static final int LENGTH_DOUBLE = 79; - - public static final BigInteger SIZE_BYTE = BigInteger.valueOf(Byte.MAX_VALUE); - public static final BigInteger SIZE_SHORT = BigInteger.valueOf(Short.MAX_VALUE); - public static final BigInteger SIZE_INTEGER = BigInteger.valueOf(Integer.MAX_VALUE); - public static final BigInteger SIZE_LONG = BigInteger.valueOf(Long.MAX_VALUE); - - public static final BigDecimal SIZE_FLOAT = new BigDecimal(Float.MAX_VALUE); - public static final BigDecimal SIZE_DOUBLE = new BigDecimal(Double.MAX_VALUE); - - public static final int NUMBER_NONE = -1; - public static final int NUMBER_DIGIT = 0; - public static final int NUMBER_SIGN = 1; - public static final int NUMBER_DECIMAL = 2; - - public static final int NUMBER_EXP_IND = 10; - public static final int NUMBER_EXP_SIGN = 11; - public static final int NUMBER_EXP_DIGIT = 12; - public static final int NUMBER_EXP_FRAC = 13; - - public final Reader reader; - public final char[] buffer = new char[1024]; - - public final Stack stack = new Stack<>(); - public JsonScope scope; - public JsonState state; - - public JsonState next; - - public int limit; - public int cursor; - - public int lineAmount; - public int linePosition; - - public String stringBuffer; - - public JsonReader(Reader reader) throws IOException { - this.reader = reader; - reader.reset(); - stack.push(JsonScope.EMPTY_READER); - } - - /* - * Accissible things - */ - - public JsonToken next() throws IOException, JsonSyntaxException { - JsonToken token = nextState(false).asToken(); - return token; - } - - public boolean hasNext() throws IOException, JsonSyntaxException { - JsonState state = peekState(); - return state != JsonState.END_OBJECT && state != JsonState.END_ARRAY && state != JsonState.EOF; - } - - public String readName() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState current = currentState(); - switch (current) { - case KEY_SINGLE: - resetState(); - return readSingleString(); - case KEY_DOUBLE: - resetState(); - return readDoubleString(); - default: - throw illegalState(JsonToken.KEY, current); - } - } - - public String readString() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState state = currentState(); - switch (state.asToken().actualToken()) { - case STRING: - resetState(); - return state == JsonState.VALUE_SINGLE ? readSingleString() : readDoubleString(); - case NUMBER: - resetState(); - return stringBuffer; - default: - throw illegalState(JsonToken.STRING, state); - } - } - - public boolean readBoolean() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState state = currentState(); - switch (state) { - case TRUE: - resetState(); - return true; - case FALSE: - resetState(); - return false; - default: - throw illegalState(JsonToken.BOOLEAN, state); - } - } - - public byte readByte() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.BYTE) { - throw illegalState(JsonToken.BYTE, state); - } - resetState(); - return Byte.parseByte(stringBuffer); - } - - public short readShort() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.SHORT) { - throw illegalState(JsonToken.SHORT, state); - } - resetState(); - return Short.parseShort(stringBuffer); - } - - public int readInteger() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.INTEGER) { - throw illegalState(JsonToken.INTEGER, state); - } - resetState(); - return Integer.parseInt(stringBuffer); - } - - public long readLong() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.LONG) { - throw illegalState(JsonToken.LONG, state); - } - resetState(); - return Long.parseLong(stringBuffer); - } - - public BigInteger readBigInteger() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.BIG_INTEGER) { - throw illegalState(JsonToken.BIG_INTEGER, state); - } - resetState(); - return new BigInteger(stringBuffer); - } - - public float readFloat() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.FLOAT) { - throw illegalState(JsonToken.FLOAT, state); - } - resetState(); - return Float.parseFloat(stringBuffer); - } - - public double readDouble() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.DOUBLE) { - throw illegalState(JsonToken.DOUBLE, state); - } - resetState(); - return Double.parseDouble(stringBuffer); - } - - public BigDecimal readBigDecimal() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - if (state != JsonState.BIG_DECIMAL) { - throw illegalState(JsonToken.BIG_DECIMAL, state); - } - resetState(); - return new BigDecimal(stringBuffer); - } - - public Number readNumber() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { - JsonState state = currentState(); - switch (state) { - case BYTE: - return readByte(); - case SHORT: - return readShort(); - case INTEGER: - return readInteger(); - case LONG: - return readLong(); - case BIG_INTEGER: - return readBigInteger(); - case FLOAT: - return readFloat(); - case DOUBLE: - return readDouble(); - case BIG_DECIMAL: - return readBigDecimal(); - default: - throw illegalState(JsonToken.NUMBER, state, true); - } - } - - public void readNull() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState state = currentState(); - if (state != JsonState.NULL) { - throw illegalState(JsonToken.NULL, state); - } - resetState(); - } - - public void beginArray() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState current = currentState(); - if (current != JsonState.START_ARRAY) { - throw illegalState(JsonToken.START_ARRAY, current); - } - stack.push(JsonScope.EMPTY_ARRAY); - resetState(); - } - - public void endArray() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState current = currentState(); - if (current != JsonState.END_ARRAY) { - throw illegalState(JsonToken.END_ARRAY, current); - } - resetState(); - } - - public void beginObject() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState current = currentState(); - if (current != JsonState.START_OBJECT) { - throw illegalState(JsonToken.START_OBJECT, current); - } - stack.push(JsonScope.EMPTY_OBJECT); - resetState(); - } - - public void endObject() throws IOException, JsonSyntaxException, IllegalStateException { - JsonState current = currentState(); - if (current != JsonState.END_OBJECT) { - throw illegalState(JsonToken.END_OBJECT, current); - } - resetState(); - } - - /* - * Inner workings - */ - - protected String readSingleString() throws IOException, JsonSyntaxException { - char[] buffer = this.buffer; - StringBuilder builder = null; - while (true) { - int position = cursor; - int limit = this.limit; - - int start = position; - while (position < limit) { - char current = buffer[position++]; - switch (current) { - case '\'': - cursor = position; - int length0 = position - start - 1; - if (builder == null) { - return new String(buffer, start, length0); - } else { - return builder.append(buffer, start, length0).toString(); - } - case '\\': - cursor = position; - int length1 = position - start - 1; - if (builder == null) { - builder = new StringBuilder(Math.max((length1 + 1) * 2, 16)); - } - builder.append(buffer, start, length1); - builder.append(readEscapeCharacter()); - position = cursor; - limit = this.limit; - start = position; - continue; - case '\n': - lineAmount++; - linePosition = position; - continue; - } - } - - if (builder == null) { - builder = new StringBuilder(Math.max((position - start) * 2, 16)); - } - builder.append(buffer, start, position - start); - cursor = position; - if (!readToBuffer(1)) { - throw wrongSyntax("Never ending string"); - } - } - } - - protected String readDoubleString() throws IOException, JsonSyntaxException { - char[] buffer = this.buffer; - StringBuilder builder = null; - while (true) { - int position = cursor; - int limit = this.limit; - - int start = position; - while (position < limit) { - char current = buffer[position++]; - switch (current) { - case '"': - cursor = position; - int length0 = position - start - 1; - if (builder == null) { - return new String(buffer, start, length0); - } else { - return builder.append(buffer, start, length0).toString(); - } - case '\\': - cursor = position; - int length1 = position - start - 1; - if (builder == null) { - builder = new StringBuilder(Math.max((length1 + 1) * 2, 16)); - } - builder.append(buffer, start, length1); - builder.append(readEscapeCharacter()); - position = cursor; - limit = this.limit; - start = position; - continue; - case '\n': - lineAmount++; - linePosition = position; - continue; - } - } - - if (builder == null) { - builder = new StringBuilder(Math.max((position - start) * 2, 16)); - } - builder.append(buffer, start, position - start); - cursor = position; - if (!readToBuffer(1)) { - throw wrongSyntax("Never ending string"); - } - } - } - - protected char readEscapeCharacter() throws IOException, JsonSyntaxException, NumberFormatException { - if (cursor == limit && !readToBuffer(1)) { - throw wrongSyntax("Never ending escape sequence"); - } - - char current = buffer[cursor++]; - switch (current) { - case 'u': - if (cursor + 4 > limit && !readToBuffer(4)) { - throw wrongSyntax("Never ending escape sequence"); - } - - char output = 0; - for (int index = cursor, max = index + 4; index < max; index++) { - char check = buffer[index]; - output <<= 4; - if (check >= '0' && check <= '9') { - output += (check - '0'); - continue; - } - if (check >= 'a' && check <= 'f') { - output += (check - 'a' + 10); - continue; - } - if (check >= 'a' && check <= 'F') { - output += (check - 'A' + 10); - continue; - } - throw new NumberFormatException("\\u" + new String(buffer, cursor, 4)); - } - cursor += 4; - return output; - case 't': - return '\t'; - case 'b': - return '\b'; - case 'n': - return '\n'; - case 'r': - return '\r'; - case 'f': - return '\f'; - case '\n': - lineAmount++; - linePosition = cursor; - case '\'': - case '"': - case '\\': - case '/': - return current; - default: - throw wrongSyntax("Invalid exscaped sequence"); - } - } - - protected void resetState() { - state = null; - } - - protected JsonState currentState() throws IOException, JsonSyntaxException { - JsonState current = this.state; - if (current == null) { - current = nextState(false); - } - return current; - } - - protected JsonState peekState() throws IOException, JsonSyntaxException { - return next == null ? next = nextState(true) : next; - } - - protected JsonState nextState(boolean peek) throws IOException, JsonSyntaxException { - next = null; - JsonScope current = scope; - if (scope == null) { - current = scope = peek ? peek() : pop(); - } - try { - switch (current) { - case EMPTY_ARRAY: - stack.push(JsonScope.FILLED_ARRAY); - break; - case FILLED_ARRAY: - char character3 = nextCharacter(); - switch (character3) { - case ']': - return state = JsonState.END_ARRAY; - case ',': - break; - default: - throw wrongSyntax("Never ending array"); - } - break; - case EMPTY_OBJECT: - case FILLED_OBJECT: - stack.push(JsonScope.PENDING_NAME); - if (current == JsonScope.FILLED_OBJECT) { - char character1 = nextCharacter(); - switch (character1) { - case '}': - return state = JsonState.END_OBJECT; - case ',': - break; - default: - throw wrongSyntax("Never ending object"); - } - } - char character2 = nextCharacter(); - switch (character2) { - case '\'': - return state = JsonState.KEY_SINGLE; - case '"': - return state = JsonState.KEY_DOUBLE; - case '}': - if (current == JsonScope.FILLED_OBJECT) { - wrongSyntax("Unnamed element"); - } - return state = JsonState.END_OBJECT; - default: - throw wrongSyntax("Unnamed element"); - } - case EMPTY_READER: - stack.push(JsonScope.FILLED_READER); - break; - case FILLED_READER: - nextCharacter(); - cursor--; - break; - case PENDING_NAME: - stack.push(JsonScope.FILLED_OBJECT); - char character0 = nextCharacter(); - if (character0 != ':') { - throw wrongSyntax("Expected ':'"); - } - break; - case CLOSED: - return state = JsonState.EOF; - } - - char character = nextCharacter(); - switch (character) { - case ']': - if (current == JsonScope.EMPTY_ARRAY) { - return state = JsonState.END_ARRAY; - } - case ',': - throw wrongSyntax("Unexpected value"); - case '\'': - return state = JsonState.VALUE_SINGLE; - case '"': - return state = JsonState.VALUE_DOUBLE; - case '[': - return state = JsonState.START_ARRAY; - case '{': - return state = JsonState.START_OBJECT; - default: - cursor--; - } - - if (isKeyword() || isNumber()) { - return state; - } - - throw wrongSyntax("No value present"); - } catch (EndOfFileException eof) { - return state = JsonState.EOF; - } - } - - protected boolean isKeyword() throws IOException, JsonSyntaxException { - char current = buffer[cursor]; - JsonState expect; - String word; - String wordUpped; - switch (current) { - case 't': - case 'T': - word = "true"; - wordUpped = "TRUE"; - expect = JsonState.TRUE; - break; - case 'f': - case 'F': - word = "false"; - wordUpped = "FALSE"; - expect = JsonState.FALSE; - break; - case 'n': - case 'N': - word = "null"; - wordUpped = "NULL"; - expect = JsonState.NULL; - break; - default: - return false; - } - - int length = word.length(); - for (int index = 1; index < length; index++) { - if (cursor + index >= limit && !readToBuffer(index + 1)) { - return false; - } - char character = buffer[cursor + index]; - if (character != word.charAt(index) && character != wordUpped.charAt(index)) { - return false; - } - } - - if ((cursor + length < limit || readToBuffer(length + 1)) && isLiteral(buffer[cursor + length])) { - return false; - } - - cursor += length; - state = expect; - return true; - } - - protected boolean isNumber() throws IOException { - char[] buffer = this.buffer; - int position = cursor; - int limit = this.limit; - - boolean first = true; - boolean decimal = false; - boolean negative = false; - boolean exponential = false; - - int exponentialLength = 0; - - StringBuilder value = new StringBuilder(); - StringBuilder exponentialValue = new StringBuilder(); - - int parser = NUMBER_NONE; - - int index = 0; - - characterLoop: - for (; true; index++) { - if (position + index == limit) { - if (!readToBuffer(index + 1)) { - break; - } - position = cursor; - limit = this.limit; - } - - char current = buffer[position + index]; - switch (current) { - case '-': - switch (parser) { - case NUMBER_NONE: - negative = true; - parser = NUMBER_SIGN; - value.append(current); - continue; - case NUMBER_EXP_IND: - parser = NUMBER_EXP_SIGN; - exponentialLength = 2; - value.append(current); - continue; - default: - return false; - } - case '+': - switch (parser) { - case NUMBER_NONE: - parser = NUMBER_SIGN; - value.append(current); - continue; - case NUMBER_EXP_IND: - parser = NUMBER_EXP_SIGN; - exponentialLength = 2; - value.append(current); - continue; - default: - return false; - } - case 'e': - case 'E': - if (parser != NUMBER_DIGIT || exponential) { - return false; - } - exponential = true; - parser = NUMBER_EXP_IND; - exponentialLength = 1; - value.append(current); - continue; - case '.': - if (parser != NUMBER_DIGIT || decimal) { - return false; - } - decimal = true; - parser = NUMBER_DECIMAL; - value.append(current); - continue; - default: - if (!isDigit(current)) { - if (!isLiteral(current)) { - break characterLoop; - } - return false; - } - switch (parser) { - case NUMBER_NONE: - if (first && current == '0') { - continue; - } - first = false; - parser = NUMBER_DIGIT; - value.append(current); - continue; - case NUMBER_SIGN: - case NUMBER_DIGIT: - value.append(current); - continue; - case NUMBER_DECIMAL: - value.append(current); - parser = NUMBER_DIGIT; - continue; - case NUMBER_EXP_IND: - case NUMBER_EXP_SIGN: - value.append(current); - exponentialValue.append(current); - parser = NUMBER_EXP_DIGIT; - continue; - default: - return false; - } - } - } - try { - stringBuffer = value.toString(); - int length = (((decimal ? stringBuffer.split(".", 2)[0].length() : stringBuffer.length()) - exponentialLength) - * (exponential ? 10 ^ Integer.parseInt(exponentialValue.toString()) : 1)) - (negative ? 0 : 1); - - if (decimal) { - switch (length) { - case LENGTH_FLOAT: - state = isLower(stringBuffer, SIZE_FLOAT, negative) ? JsonState.FLOAT : JsonState.DOUBLE; - break; - case LENGTH_DOUBLE: - state = isLower(stringBuffer, SIZE_DOUBLE, negative) ? JsonState.DOUBLE : JsonState.BIG_DECIMAL; - break; - default: - if (length < LENGTH_FLOAT) { - state = JsonState.FLOAT; - break; - } - if (length < LENGTH_DOUBLE) { - state = JsonState.DOUBLE; - break; - } - state = JsonState.BIG_DECIMAL; - } - } else { - switch (length) { - case LENGTH_BYTE: - state = isLower(stringBuffer, SIZE_BYTE, negative) ? JsonState.BYTE : JsonState.SHORT; - break; - case LENGTH_SHORT: - state = isLower(stringBuffer, SIZE_SHORT, negative) ? JsonState.SHORT : JsonState.INTEGER; - break; - case LENGTH_INTEGER: - state = isLower(stringBuffer, SIZE_INTEGER, negative) ? JsonState.INTEGER : JsonState.LONG; - break; - case LENGTH_LONG: - state = isLower(stringBuffer, SIZE_LONG, negative) ? JsonState.LONG : JsonState.BIG_INTEGER; - break; - default: - if (length < LENGTH_BYTE) { - state = JsonState.BYTE; - break; - } - if (length < LENGTH_SHORT) { - state = JsonState.SHORT; - break; - } - if (length < LENGTH_INTEGER) { - state = JsonState.INTEGER; - break; - } - if (length < LENGTH_LONG) { - state = JsonState.LONG; - break; - } - state = JsonState.BIG_INTEGER; - } - } - cursor += length + 1; - return true; - } catch (NumberFormatException exception) { - exception.printStackTrace(); - return false; - } - } - - protected boolean isLower(String value, BigDecimal comparision, boolean negative) { - if (negative) { - return new BigDecimal(value).compareTo(comparision.multiply(BigDecimal.ONE.negate())) == 1; - } - return new BigDecimal(value).compareTo(comparision) == -1; - } - - protected boolean isLower(String value, BigInteger comparision, boolean negative) { - if (negative) { - return new BigInteger(value).compareTo(comparision.multiply(BigInteger.ONE.negate())) == 1; - } - return new BigInteger(value).compareTo(comparision) == -1; - } - - protected char nextCharacter() throws IOException, EndOfFileException, JsonSyntaxException { - char[] buffer = this.buffer; - int position = cursor; - int limit = this.limit; - while (true) { - if (position == limit) { - cursor = position; - if (!readToBuffer(1)) { - break; - } - position = cursor; - limit = this.limit; - } - char current = buffer[position++]; - switch (current) { - case '\n': - lineAmount++; - linePosition = position; - continue; - case ' ': - case '\r': - case '\t': - continue; - case '/': - cursor = position; - if (position == limit) { - cursor--; - boolean loaded = readToBuffer(2); - cursor++; - if (!loaded) { - return current; - } - } - char test = buffer[cursor]; - switch (test) { - case '*': - cursor++; - if (!skipTo(INDICATOR_EOC)) { - throw wrongSyntax("Never ending comment"); - } - position = cursor + 2; - limit = this.limit; - continue; - case '/': - cursor++; - skipTo(INDICATOR_EOL); - position = cursor; - limit = this.limit; - continue; - default: - return current; - } - case '#': - cursor = position; - skipTo(INDICATOR_EOL); - position = cursor; - limit = this.limit; - continue; - default: - cursor = position; - return current; - } - } - throw new EndOfFileException(); - } - - protected boolean skipTo(int indicator) throws IOException { - switch (indicator) { - case INDICATOR_EOL: - while (cursor < limit || readToBuffer(1)) { - char current = buffer[cursor++]; - switch (current) { - case '\n': - lineAmount++; - linePosition = cursor; - case '\r': - break; - default: - continue; - } - break; - } - return true; - case INDICATOR_EOC: - loop: - for (; cursor + 2 <= limit || readToBuffer(2); cursor++) { - if (buffer[cursor] == '\n') { - lineAmount++; - linePosition = cursor + 1; - continue; - } - if (buffer[cursor] != '*' || buffer[cursor + 1] != '/') { - continue loop; - } - return true; - } - return false; - default: - return true; - } - } - - protected boolean readToBuffer(int minimum) throws IOException { - char[] buffer = this.buffer; - linePosition -= cursor; - if (limit != cursor) { - limit -= cursor; - System.arraycopy(buffer, cursor, buffer, 0, limit); - } else { - limit = 0; - } - cursor = 0; - int total; - while ((total = reader.read(buffer, limit, buffer.length - limit)) != -1) { - limit += total; - if (lineAmount == 0 && linePosition == 0 && limit > 0 && buffer[0] == '\ufeff') { - cursor++; - linePosition++; - minimum++; - } - if (limit >= minimum) { - return true; - } - } - return false; - } - - protected boolean isHexDigit(char character) { - switch (character) { - case 'a': - case 'A': - case 'b': - case 'B': - case 'c': - case 'C': - case 'd': - case 'D': - case 'e': - case 'E': - case 'f': - case 'F': - return true; - default: - return false; - } - } - - protected boolean isDigit(char character) { - return character >= '0' && character <= '9'; - } - - protected boolean isLiteral(char character) throws JsonSyntaxException { - switch (character) { - case '/': - case '#': - case '{': - case '}': - case '[': - case ']': - case ':': - case ',': - case ' ': - case '\t': - case '\f': - case '\r': - case '\n': - return false; - case '\\': - case ';': - case '=': - throw wrongSyntax("Unexpected character"); - default: - return true; - } - } - - protected JsonScope pop() { - try { - return stack.pop(); - } catch (EmptyStackException exception) { - return JsonScope.CLOSED; - } - } - - protected JsonScope peek() { - try { - return stack.peek(); - } catch (EmptyStackException exception) { - return JsonScope.CLOSED; - } - } - - protected JsonSyntaxException wrongSyntax(String message) { - return new JsonSyntaxException(applyLocation(message)); - } - - protected IllegalStateException illegalState(JsonToken expected, JsonState state) { - return illegalState(expected, state, false); - } - - protected IllegalStateException illegalState(JsonToken expected, JsonState state, boolean actual) { - return new IllegalStateException(applyLocation("Expected " + expected.name() + " but was " + (actual ? state.asToken() : state.asToken()).name())); - } - - protected String applyLocation(String message) { - return message + getLocation(); - } - - protected String getLocation() { - return " at line " + (lineAmount + 1) + " position " + (cursor - linePosition + 1); - } + public static final int INDICATOR_EOL = 0; + public static final int INDICATOR_EOC = 1; + + public static final int LENGTH_BYTE = 3; + public static final int LENGTH_SHORT = 5; + public static final int LENGTH_INTEGER = 10; + public static final int LENGTH_LONG = 19; + public static final int LENGTH_FLOAT = 21; + public static final int LENGTH_DOUBLE = 79; + + public static final BigInteger SIZE_BYTE = BigInteger.valueOf(Byte.MAX_VALUE); + public static final BigInteger SIZE_SHORT = BigInteger.valueOf(Short.MAX_VALUE); + public static final BigInteger SIZE_INTEGER = BigInteger.valueOf(Integer.MAX_VALUE); + public static final BigInteger SIZE_LONG = BigInteger.valueOf(Long.MAX_VALUE); + + public static final BigDecimal SIZE_FLOAT = new BigDecimal(Float.MAX_VALUE); + public static final BigDecimal SIZE_DOUBLE = new BigDecimal(Double.MAX_VALUE); + + public static final int NUMBER_NONE = -1; + public static final int NUMBER_DIGIT = 0; + public static final int NUMBER_SIGN = 1; + public static final int NUMBER_DECIMAL = 2; + + public static final int NUMBER_EXP_IND = 10; + public static final int NUMBER_EXP_SIGN = 11; + public static final int NUMBER_EXP_DIGIT = 12; + public static final int NUMBER_EXP_FRAC = 13; + + public final Reader reader; + public final char[] buffer = new char[1024]; + + public final Stack stack = new Stack<>(); + public JsonScope scope; + public JsonState state; + + public JsonState next; + + public int limit; + public int cursor; + + public int lineAmount; + public int linePosition; + + public String stringBuffer; + + public JsonReader(Reader reader) throws IOException { + this.reader = reader; + reader.reset(); + stack.push(JsonScope.EMPTY_READER); + } + + /* + * Accissible things + */ + + public JsonToken next() throws IOException, JsonSyntaxException { + JsonToken token = nextState(false).asToken(); + return token; + } + + public boolean hasNext() throws IOException, JsonSyntaxException { + JsonState state = peekState(); + return state != JsonState.END_OBJECT && state != JsonState.END_ARRAY && state != JsonState.EOF; + } + + public String readName() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState current = currentState(); + switch (current) { + case KEY_SINGLE: + resetState(); + return readSingleString(); + case KEY_DOUBLE: + resetState(); + return readDoubleString(); + default: + throw illegalState(JsonToken.KEY, current); + } + } + + public String readString() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState state = currentState(); + switch (state.asToken().actualToken()) { + case STRING: + resetState(); + return state == JsonState.VALUE_SINGLE ? readSingleString() : readDoubleString(); + case NUMBER: + resetState(); + return stringBuffer; + default: + throw illegalState(JsonToken.STRING, state); + } + } + + public boolean readBoolean() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState state = currentState(); + switch (state) { + case TRUE: + resetState(); + return true; + case FALSE: + resetState(); + return false; + default: + throw illegalState(JsonToken.BOOLEAN, state); + } + } + + public byte readByte() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.BYTE) { + throw illegalState(JsonToken.BYTE, state); + } + resetState(); + return Byte.parseByte(stringBuffer); + } + + public short readShort() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.SHORT) { + throw illegalState(JsonToken.SHORT, state); + } + resetState(); + return Short.parseShort(stringBuffer); + } + + public int readInteger() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.INTEGER) { + throw illegalState(JsonToken.INTEGER, state); + } + resetState(); + return Integer.parseInt(stringBuffer); + } + + public long readLong() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.LONG) { + throw illegalState(JsonToken.LONG, state); + } + resetState(); + return Long.parseLong(stringBuffer); + } + + public BigInteger readBigInteger() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.BIG_INTEGER) { + throw illegalState(JsonToken.BIG_INTEGER, state); + } + resetState(); + return new BigInteger(stringBuffer); + } + + public float readFloat() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.FLOAT) { + throw illegalState(JsonToken.FLOAT, state); + } + resetState(); + return Float.parseFloat(stringBuffer); + } + + public double readDouble() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.DOUBLE) { + throw illegalState(JsonToken.DOUBLE, state); + } + resetState(); + return Double.parseDouble(stringBuffer); + } + + public BigDecimal readBigDecimal() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + if (state != JsonState.BIG_DECIMAL) { + throw illegalState(JsonToken.BIG_DECIMAL, state); + } + resetState(); + return new BigDecimal(stringBuffer); + } + + public Number readNumber() throws IOException, JsonSyntaxException, IllegalStateException, NumberFormatException { + JsonState state = currentState(); + switch (state) { + case BYTE: + return readByte(); + case SHORT: + return readShort(); + case INTEGER: + return readInteger(); + case LONG: + return readLong(); + case BIG_INTEGER: + return readBigInteger(); + case FLOAT: + return readFloat(); + case DOUBLE: + return readDouble(); + case BIG_DECIMAL: + return readBigDecimal(); + default: + throw illegalState(JsonToken.NUMBER, state, true); + } + } + + public void readNull() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState state = currentState(); + if (state != JsonState.NULL) { + throw illegalState(JsonToken.NULL, state); + } + resetState(); + } + + public void beginArray() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState current = currentState(); + if (current != JsonState.START_ARRAY) { + throw illegalState(JsonToken.START_ARRAY, current); + } + stack.push(JsonScope.EMPTY_ARRAY); + resetState(); + } + + public void endArray() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState current = currentState(); + if (current != JsonState.END_ARRAY) { + throw illegalState(JsonToken.END_ARRAY, current); + } + resetState(); + } + + public void beginObject() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState current = currentState(); + if (current != JsonState.START_OBJECT) { + throw illegalState(JsonToken.START_OBJECT, current); + } + stack.push(JsonScope.EMPTY_OBJECT); + resetState(); + } + + public void endObject() throws IOException, JsonSyntaxException, IllegalStateException { + JsonState current = currentState(); + if (current != JsonState.END_OBJECT) { + throw illegalState(JsonToken.END_OBJECT, current); + } + resetState(); + } + + /* + * Inner workings + */ + + protected String readSingleString() throws IOException, JsonSyntaxException { + char[] buffer = this.buffer; + StringBuilder builder = null; + while (true) { + int position = cursor; + int limit = this.limit; + + int start = position; + while (position < limit) { + char current = buffer[position++]; + switch (current) { + case '\'': + cursor = position; + int length0 = position - start - 1; + if (builder == null) { + return new String(buffer, start, length0); + } else { + return builder.append(buffer, start, length0).toString(); + } + case '\\': + cursor = position; + int length1 = position - start - 1; + if (builder == null) { + builder = new StringBuilder(Math.max((length1 + 1) * 2, 16)); + } + builder.append(buffer, start, length1); + builder.append(readEscapeCharacter()); + position = cursor; + limit = this.limit; + start = position; + continue; + case '\n': + lineAmount++; + linePosition = position; + continue; + } + } + + if (builder == null) { + builder = new StringBuilder(Math.max((position - start) * 2, 16)); + } + builder.append(buffer, start, position - start); + cursor = position; + if (!readToBuffer(1)) { + throw wrongSyntax("Never ending string"); + } + } + } + + protected String readDoubleString() throws IOException, JsonSyntaxException { + char[] buffer = this.buffer; + StringBuilder builder = null; + while (true) { + int position = cursor; + int limit = this.limit; + + int start = position; + while (position < limit) { + char current = buffer[position++]; + switch (current) { + case '"': + cursor = position; + int length0 = position - start - 1; + if (builder == null) { + return new String(buffer, start, length0); + } else { + return builder.append(buffer, start, length0).toString(); + } + case '\\': + cursor = position; + int length1 = position - start - 1; + if (builder == null) { + builder = new StringBuilder(Math.max((length1 + 1) * 2, 16)); + } + builder.append(buffer, start, length1); + builder.append(readEscapeCharacter()); + position = cursor; + limit = this.limit; + start = position; + continue; + case '\n': + lineAmount++; + linePosition = position; + continue; + } + } + + if (builder == null) { + builder = new StringBuilder(Math.max((position - start) * 2, 16)); + } + builder.append(buffer, start, position - start); + cursor = position; + if (!readToBuffer(1)) { + throw wrongSyntax("Never ending string"); + } + } + } + + protected char readEscapeCharacter() throws IOException, JsonSyntaxException, NumberFormatException { + if (cursor == limit && !readToBuffer(1)) { + throw wrongSyntax("Never ending escape sequence"); + } + + char current = buffer[cursor++]; + switch (current) { + case 'u': + if (cursor + 4 > limit && !readToBuffer(4)) { + throw wrongSyntax("Never ending escape sequence"); + } + + char output = 0; + for (int index = cursor, max = index + 4; index < max; index++) { + char check = buffer[index]; + output <<= 4; + if (check >= '0' && check <= '9') { + output += (check - '0'); + continue; + } + if (check >= 'a' && check <= 'f') { + output += (check - 'a' + 10); + continue; + } + if (check >= 'a' && check <= 'F') { + output += (check - 'A' + 10); + continue; + } + throw new NumberFormatException("\\u" + new String(buffer, cursor, 4)); + } + cursor += 4; + return output; + case 't': + return '\t'; + case 'b': + return '\b'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 'f': + return '\f'; + case '\n': + lineAmount++; + linePosition = cursor; + case '\'': + case '"': + case '\\': + case '/': + return current; + default: + throw wrongSyntax("Invalid exscaped sequence"); + } + } + + protected void resetState() { + state = null; + } + + protected JsonState currentState() throws IOException, JsonSyntaxException { + JsonState current = this.state; + if (current == null) { + current = nextState(false); + } + return current; + } + + protected JsonState peekState() throws IOException, JsonSyntaxException { + return next == null ? next = nextState(true) : next; + } + + protected JsonState nextState(boolean peek) throws IOException, JsonSyntaxException { + next = null; + JsonScope current = scope; + if (scope == null) { + current = scope = peek ? peek() : pop(); + } + try { + switch (current) { + case EMPTY_ARRAY: + stack.push(JsonScope.FILLED_ARRAY); + break; + case FILLED_ARRAY: + char character3 = nextCharacter(); + switch (character3) { + case ']': + return state = JsonState.END_ARRAY; + case ',': + break; + default: + throw wrongSyntax("Never ending array"); + } + break; + case EMPTY_OBJECT: + case FILLED_OBJECT: + stack.push(JsonScope.PENDING_NAME); + if (current == JsonScope.FILLED_OBJECT) { + char character1 = nextCharacter(); + switch (character1) { + case '}': + return state = JsonState.END_OBJECT; + case ',': + break; + default: + throw wrongSyntax("Never ending object"); + } + } + char character2 = nextCharacter(); + switch (character2) { + case '\'': + return state = JsonState.KEY_SINGLE; + case '"': + return state = JsonState.KEY_DOUBLE; + case '}': + if (current == JsonScope.FILLED_OBJECT) { + wrongSyntax("Unnamed element"); + } + return state = JsonState.END_OBJECT; + default: + throw wrongSyntax("Unnamed element"); + } + case EMPTY_READER: + stack.push(JsonScope.FILLED_READER); + break; + case FILLED_READER: + nextCharacter(); + cursor--; + break; + case PENDING_NAME: + stack.push(JsonScope.FILLED_OBJECT); + char character0 = nextCharacter(); + if (character0 != ':') { + throw wrongSyntax("Expected ':'"); + } + break; + case CLOSED: + return state = JsonState.EOF; + } + + char character = nextCharacter(); + switch (character) { + case ']': + if (current == JsonScope.EMPTY_ARRAY) { + return state = JsonState.END_ARRAY; + } + case ',': + throw wrongSyntax("Unexpected value"); + case '\'': + return state = JsonState.VALUE_SINGLE; + case '"': + return state = JsonState.VALUE_DOUBLE; + case '[': + return state = JsonState.START_ARRAY; + case '{': + return state = JsonState.START_OBJECT; + default: + cursor--; + } + + if (isKeyword() || isNumber()) { + return state; + } + + throw wrongSyntax("No value present"); + } catch (EndOfFileException eof) { + return state = JsonState.EOF; + } + } + + protected boolean isKeyword() throws IOException, JsonSyntaxException { + char current = buffer[cursor]; + JsonState expect; + String word; + String wordUpped; + switch (current) { + case 't': + case 'T': + word = "true"; + wordUpped = "TRUE"; + expect = JsonState.TRUE; + break; + case 'f': + case 'F': + word = "false"; + wordUpped = "FALSE"; + expect = JsonState.FALSE; + break; + case 'n': + case 'N': + word = "null"; + wordUpped = "NULL"; + expect = JsonState.NULL; + break; + default: + return false; + } + + int length = word.length(); + for (int index = 1; index < length; index++) { + if (cursor + index >= limit && !readToBuffer(index + 1)) { + return false; + } + char character = buffer[cursor + index]; + if (character != word.charAt(index) && character != wordUpped.charAt(index)) { + return false; + } + } + + if ((cursor + length < limit || readToBuffer(length + 1)) && isLiteral(buffer[cursor + length])) { + return false; + } + + cursor += length; + state = expect; + return true; + } + + protected boolean isNumber() throws IOException { + char[] buffer = this.buffer; + int position = cursor; + int limit = this.limit; + + boolean first = true; + boolean decimal = false; + boolean negative = false; + boolean exponential = false; + + int exponentialLength = 0; + + StringBuilder value = new StringBuilder(); + StringBuilder exponentialValue = new StringBuilder(); + + int parser = NUMBER_NONE; + + int index = 0; + + characterLoop: + for (; true; index++) { + if (position + index == limit) { + if (!readToBuffer(index + 1)) { + break; + } + position = cursor; + limit = this.limit; + } + + char current = buffer[position + index]; + switch (current) { + case '-': + switch (parser) { + case NUMBER_NONE: + negative = true; + parser = NUMBER_SIGN; + value.append(current); + continue; + case NUMBER_EXP_IND: + parser = NUMBER_EXP_SIGN; + exponentialLength = 2; + value.append(current); + continue; + default: + return false; + } + case '+': + switch (parser) { + case NUMBER_NONE: + parser = NUMBER_SIGN; + value.append(current); + continue; + case NUMBER_EXP_IND: + parser = NUMBER_EXP_SIGN; + exponentialLength = 2; + value.append(current); + continue; + default: + return false; + } + case 'e': + case 'E': + if (parser != NUMBER_DIGIT || exponential) { + return false; + } + exponential = true; + parser = NUMBER_EXP_IND; + exponentialLength = 1; + value.append(current); + continue; + case '.': + if (parser != NUMBER_DIGIT || decimal) { + return false; + } + decimal = true; + parser = NUMBER_DECIMAL; + value.append(current); + continue; + default: + if (!isDigit(current)) { + if (!isLiteral(current)) { + break characterLoop; + } + return false; + } + switch (parser) { + case NUMBER_NONE: + if (first && current == '0') { + continue; + } + first = false; + parser = NUMBER_DIGIT; + value.append(current); + continue; + case NUMBER_SIGN: + case NUMBER_DIGIT: + value.append(current); + continue; + case NUMBER_DECIMAL: + value.append(current); + parser = NUMBER_DIGIT; + continue; + case NUMBER_EXP_IND: + case NUMBER_EXP_SIGN: + value.append(current); + exponentialValue.append(current); + parser = NUMBER_EXP_DIGIT; + continue; + default: + return false; + } + } + } + try { + stringBuffer = value.toString(); + int length = (((decimal ? stringBuffer.split(".", 2)[0].length() : stringBuffer.length()) - exponentialLength) + * (exponential ? 10 ^ Integer.parseInt(exponentialValue.toString()) : 1)) - (negative ? 0 : 1); + + if (decimal) { + switch (length) { + case LENGTH_FLOAT: + state = isLower(stringBuffer, SIZE_FLOAT, negative) ? JsonState.FLOAT : JsonState.DOUBLE; + break; + case LENGTH_DOUBLE: + state = isLower(stringBuffer, SIZE_DOUBLE, negative) ? JsonState.DOUBLE : JsonState.BIG_DECIMAL; + break; + default: + if (length < LENGTH_FLOAT) { + state = JsonState.FLOAT; + break; + } + if (length < LENGTH_DOUBLE) { + state = JsonState.DOUBLE; + break; + } + state = JsonState.BIG_DECIMAL; + } + } else { + switch (length) { + case LENGTH_BYTE: + state = isLower(stringBuffer, SIZE_BYTE, negative) ? JsonState.BYTE : JsonState.SHORT; + break; + case LENGTH_SHORT: + state = isLower(stringBuffer, SIZE_SHORT, negative) ? JsonState.SHORT : JsonState.INTEGER; + break; + case LENGTH_INTEGER: + state = isLower(stringBuffer, SIZE_INTEGER, negative) ? JsonState.INTEGER : JsonState.LONG; + break; + case LENGTH_LONG: + state = isLower(stringBuffer, SIZE_LONG, negative) ? JsonState.LONG : JsonState.BIG_INTEGER; + break; + default: + if (length < LENGTH_BYTE) { + state = JsonState.BYTE; + break; + } + if (length < LENGTH_SHORT) { + state = JsonState.SHORT; + break; + } + if (length < LENGTH_INTEGER) { + state = JsonState.INTEGER; + break; + } + if (length < LENGTH_LONG) { + state = JsonState.LONG; + break; + } + state = JsonState.BIG_INTEGER; + } + } + cursor += length + 1; + return true; + } catch (NumberFormatException exception) { + exception.printStackTrace(); + return false; + } + } + + protected boolean isLower(String value, BigDecimal comparision, boolean negative) { + if (negative) { + return new BigDecimal(value).compareTo(comparision.multiply(BigDecimal.ONE.negate())) == 1; + } + return new BigDecimal(value).compareTo(comparision) == -1; + } + + protected boolean isLower(String value, BigInteger comparision, boolean negative) { + if (negative) { + return new BigInteger(value).compareTo(comparision.multiply(BigInteger.ONE.negate())) == 1; + } + return new BigInteger(value).compareTo(comparision) == -1; + } + + protected char nextCharacter() throws IOException, EndOfFileException, JsonSyntaxException { + char[] buffer = this.buffer; + int position = cursor; + int limit = this.limit; + while (true) { + if (position == limit) { + cursor = position; + if (!readToBuffer(1)) { + break; + } + position = cursor; + limit = this.limit; + } + char current = buffer[position++]; + switch (current) { + case '\n': + lineAmount++; + linePosition = position; + continue; + case ' ': + case '\r': + case '\t': + continue; + case '/': + cursor = position; + if (position == limit) { + cursor--; + boolean loaded = readToBuffer(2); + cursor++; + if (!loaded) { + return current; + } + } + char test = buffer[cursor]; + switch (test) { + case '*': + cursor++; + if (!skipTo(INDICATOR_EOC)) { + throw wrongSyntax("Never ending comment"); + } + position = cursor + 2; + limit = this.limit; + continue; + case '/': + cursor++; + skipTo(INDICATOR_EOL); + position = cursor; + limit = this.limit; + continue; + default: + return current; + } + case '#': + cursor = position; + skipTo(INDICATOR_EOL); + position = cursor; + limit = this.limit; + continue; + default: + cursor = position; + return current; + } + } + throw new EndOfFileException(); + } + + protected boolean skipTo(int indicator) throws IOException { + switch (indicator) { + case INDICATOR_EOL: + while (cursor < limit || readToBuffer(1)) { + char current = buffer[cursor++]; + switch (current) { + case '\n': + lineAmount++; + linePosition = cursor; + case '\r': + break; + default: + continue; + } + break; + } + return true; + case INDICATOR_EOC: + loop: + for (; cursor + 2 <= limit || readToBuffer(2); cursor++) { + if (buffer[cursor] == '\n') { + lineAmount++; + linePosition = cursor + 1; + continue; + } + if (buffer[cursor] != '*' || buffer[cursor + 1] != '/') { + continue loop; + } + return true; + } + return false; + default: + return true; + } + } + + protected boolean readToBuffer(int minimum) throws IOException { + char[] buffer = this.buffer; + linePosition -= cursor; + if (limit != cursor) { + limit -= cursor; + System.arraycopy(buffer, cursor, buffer, 0, limit); + } else { + limit = 0; + } + cursor = 0; + int total; + while ((total = reader.read(buffer, limit, buffer.length - limit)) != -1) { + limit += total; + if (lineAmount == 0 && linePosition == 0 && limit > 0 && buffer[0] == '\ufeff') { + cursor++; + linePosition++; + minimum++; + } + if (limit >= minimum) { + return true; + } + } + return false; + } + + protected boolean isHexDigit(char character) { + switch (character) { + case 'a': + case 'A': + case 'b': + case 'B': + case 'c': + case 'C': + case 'd': + case 'D': + case 'e': + case 'E': + case 'f': + case 'F': + return true; + default: + return false; + } + } + + protected boolean isDigit(char character) { + return character >= '0' && character <= '9'; + } + + protected boolean isLiteral(char character) throws JsonSyntaxException { + switch (character) { + case '/': + case '#': + case '{': + case '}': + case '[': + case ']': + case ':': + case ',': + case ' ': + case '\t': + case '\f': + case '\r': + case '\n': + return false; + case '\\': + case ';': + case '=': + throw wrongSyntax("Unexpected character"); + default: + return true; + } + } + + protected JsonScope pop() { + try { + return stack.pop(); + } catch (EmptyStackException exception) { + return JsonScope.CLOSED; + } + } + + protected JsonScope peek() { + try { + return stack.peek(); + } catch (EmptyStackException exception) { + return JsonScope.CLOSED; + } + } + + protected JsonSyntaxException wrongSyntax(String message) { + return new JsonSyntaxException(applyLocation(message)); + } + + protected IllegalStateException illegalState(JsonToken expected, JsonState state) { + return illegalState(expected, state, false); + } + + protected IllegalStateException illegalState(JsonToken expected, JsonState state, boolean actual) { + return new IllegalStateException( + applyLocation("Expected " + expected.name() + " but was " + (actual ? state.asToken() : state.asToken()).name())); + } + + protected String applyLocation(String message) { + return message + getLocation(); + } + + protected String getLocation() { + return " at line " + (lineAmount + 1) + " position " + (cursor - linePosition + 1); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonScope.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonScope.java index 6ea9867..2dd351f 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonScope.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonScope.java @@ -2,13 +2,13 @@ public enum JsonScope { - EMPTY_ARRAY, - EMPTY_OBJECT, - EMPTY_READER, - FILLED_ARRAY, - FILLED_OBJECT, - FILLED_READER, - PENDING_NAME, - CLOSED; + EMPTY_ARRAY, + EMPTY_OBJECT, + EMPTY_READER, + FILLED_ARRAY, + FILLED_OBJECT, + FILLED_READER, + PENDING_NAME, + CLOSED; } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonState.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonState.java index 3135f97..8495780 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonState.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonState.java @@ -2,37 +2,37 @@ public enum JsonState { - EOF(JsonToken.EOF), - NULL(JsonToken.NULL), - TRUE(JsonToken.BOOLEAN), - FALSE(JsonToken.BOOLEAN), - KEY_SINGLE(JsonToken.KEY), - KEY_DOUBLE(JsonToken.KEY), - VALUE_SINGLE(JsonToken.STRING), - VALUE_DOUBLE(JsonToken.STRING), - END_ARRAY(JsonToken.END_ARRAY), - END_OBJECT(JsonToken.END_OBJECT), - START_ARRAY(JsonToken.START_ARRAY), - START_OBJECT(JsonToken.START_OBJECT), + EOF(JsonToken.EOF), + NULL(JsonToken.NULL), + TRUE(JsonToken.BOOLEAN), + FALSE(JsonToken.BOOLEAN), + KEY_SINGLE(JsonToken.KEY), + KEY_DOUBLE(JsonToken.KEY), + VALUE_SINGLE(JsonToken.STRING), + VALUE_DOUBLE(JsonToken.STRING), + END_ARRAY(JsonToken.END_ARRAY), + END_OBJECT(JsonToken.END_OBJECT), + START_ARRAY(JsonToken.START_ARRAY), + START_OBJECT(JsonToken.START_OBJECT), - // Numbers - BYTE(JsonToken.BYTE), - SHORT(JsonToken.SHORT), - INTEGER(JsonToken.INTEGER), - LONG(JsonToken.LONG), - BIG_INTEGER(JsonToken.BIG_INTEGER), - FLOAT(JsonToken.FLOAT), - DOUBLE(JsonToken.DOUBLE), - BIG_DECIMAL(JsonToken.BIG_DECIMAL); + // Numbers + BYTE(JsonToken.BYTE), + SHORT(JsonToken.SHORT), + INTEGER(JsonToken.INTEGER), + LONG(JsonToken.LONG), + BIG_INTEGER(JsonToken.BIG_INTEGER), + FLOAT(JsonToken.FLOAT), + DOUBLE(JsonToken.DOUBLE), + BIG_DECIMAL(JsonToken.BIG_DECIMAL); - private final JsonToken token; + private final JsonToken token; - private JsonState(JsonToken token) { - this.token = token; - } + private JsonState(JsonToken token) { + this.token = token; + } - public JsonToken asToken() { - return token; - } + public JsonToken asToken() { + return token; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonSyntaxException.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonSyntaxException.java index 8ebb4c5..f6d68ee 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonSyntaxException.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonSyntaxException.java @@ -2,18 +2,18 @@ public class JsonSyntaxException extends RuntimeException { - private static final long serialVersionUID = -461425017365081360L; + private static final long serialVersionUID = -461425017365081360L; - public JsonSyntaxException() { - super(); - } + public JsonSyntaxException() { + super(); + } - public JsonSyntaxException(String message) { - super(message); - } + public JsonSyntaxException(String message) { + super(message); + } - public JsonSyntaxException(String message, Throwable cause) { - super(message, cause); - } + public JsonSyntaxException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonToken.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonToken.java index 9a8fe86..0e213e0 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonToken.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonToken.java @@ -2,47 +2,47 @@ public enum JsonToken { - EOF, - KEY, - NULL, - STRING, - NUMBER, - BOOLEAN, - END_ARRAY, - END_OBJECT, - START_ARRAY, - START_OBJECT, - - // Numbers - BYTE(NUMBER), - SHORT(NUMBER), - INTEGER(NUMBER), - LONG(NUMBER), - BIG_INTEGER(NUMBER), - FLOAT(NUMBER), - DOUBLE(NUMBER), - BIG_DECIMAL(NUMBER); - - private final JsonToken parent; - - private JsonToken() { - this.parent = null; - } - - private JsonToken(JsonToken parent) { - this.parent = parent; - } - - public JsonToken getParent() { - return parent; - } - - public boolean hasParent() { - return parent != null; - } - - public JsonToken actualToken() { - return parent != null ? parent : this; - } + EOF, + KEY, + NULL, + STRING, + NUMBER, + BOOLEAN, + END_ARRAY, + END_OBJECT, + START_ARRAY, + START_OBJECT, + + // Numbers + BYTE(NUMBER), + SHORT(NUMBER), + INTEGER(NUMBER), + LONG(NUMBER), + BIG_INTEGER(NUMBER), + FLOAT(NUMBER), + DOUBLE(NUMBER), + BIG_DECIMAL(NUMBER); + + private final JsonToken parent; + + private JsonToken() { + this.parent = null; + } + + private JsonToken(JsonToken parent) { + this.parent = parent; + } + + public JsonToken getParent() { + return parent; + } + + public boolean hasParent() { + return parent != null; + } + + public JsonToken actualToken() { + return parent != null ? parent : this; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonWriter.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonWriter.java index be7bcbb..ee8e272 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonWriter.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/io/JsonWriter.java @@ -3,191 +3,199 @@ import java.io.IOException; import java.io.Writer; -import com.syntaxphoenix.syntaxapi.json.*; -import com.syntaxphoenix.syntaxapi.json.value.*; +import com.syntaxphoenix.syntaxapi.json.JsonArray; +import com.syntaxphoenix.syntaxapi.json.JsonEntry; +import com.syntaxphoenix.syntaxapi.json.JsonObject; +import com.syntaxphoenix.syntaxapi.json.JsonValue; +import com.syntaxphoenix.syntaxapi.json.value.JsonBoolean; +import com.syntaxphoenix.syntaxapi.json.value.JsonNull; +import com.syntaxphoenix.syntaxapi.json.value.JsonNumber; +import com.syntaxphoenix.syntaxapi.json.value.JsonString; import com.syntaxphoenix.syntaxapi.utils.io.TextSerializer; public class JsonWriter implements TextSerializer> { - public static final int TAB_SPACES = 4; - - private boolean pretty = false; - private boolean spaces = false; - private int indent = 1; - - public boolean isPretty() { - return pretty; - } - - public JsonWriter setPretty(boolean pretty) { - this.pretty = pretty; - return this; - } - - public boolean usesSpaces() { - return spaces; - } - - public JsonWriter setSpaces(boolean spaces) { - this.spaces = spaces; - return this; - } - - public int getIndent() { - return indent; - } - - public JsonWriter setIndent(int indent) { - this.indent = indent; - return this; - } - - public JsonWriter setTabIndent(int indent) { - this.indent = indent * TAB_SPACES; - return this; - } - - @Override - public void toWriter(JsonValue object, Writer writer) throws IOException { - switch (object.getType()) { - case ARRAY: - writeArray((JsonArray) object, writer, 0); - break; - case OBJECT: - writeObject((JsonObject) object, writer, 0); - break; - default: - break; - } - } - - public void writeEntry(JsonEntry entry, Writer writer, int depth) throws IOException { - if (pretty) { - indent(writer, depth); - } - writeUnescapedString(entry.getKey(), writer); - writer.append(':'); - if (pretty) - writer.append(' '); - writeValue(entry.getValue(), writer, depth); - } - - public void writeValue(JsonValue value, Writer writer, int depth) throws IOException { - switch (value.getType()) { - case NULL: - writeNull((JsonNull) value, writer); - break; - case ARRAY: - writeArray((JsonArray) value, writer, depth); - break; - case OBJECT: - writeObject((JsonObject) value, writer, depth); - break; - case STRING: - writeString((JsonString) value, writer); - break; - case BOOLEAN: - writeBoolean((JsonBoolean) value, writer); - break; - case BYTE: - case SHORT: - case INTEGER: - case LONG: - case FLOAT: - case DOUBLE: - case BIG_INTEGER: - case BIG_DECIMAL: - writeNumber((JsonNumber) value, writer); - break; - case NUMBER: - break; - default: - break; - } - } - - public void writeObject(JsonObject object, Writer writer, int depth) throws IOException { - writer.append('{'); - int size = object.size(); - if (size != 0) { - if (pretty) { - writer.append('\n'); - } - int current = 0; - int deep = depth + 1; - for (JsonEntry entry : object) { - writeEntry(entry, writer, deep); - if (++current != size) { - writer.append(','); - } - if (pretty) { - writer.append('\n'); - } - } - } - writer.append('}'); - } - - public void writeArray(JsonArray array, Writer writer, int depth) throws IOException { - writer.append('['); - int size = array.size(); - if (size != 0) { - if (pretty) { - writer.append('\n'); - } - int current = 0; - int deep = depth + 1; - for (JsonValue value : array) { - if (pretty) { - indent(writer, deep); - } - writeValue(value, writer, deep); - if (++current != size) { - writer.append(','); - } - if (pretty) { - writer.append('\n'); - } - } - if (pretty) { - indent(writer, depth); - } - } - writer.append(']'); - } - - public void writeString(JsonString string, Writer writer) throws IOException { - writeUnescapedString(string.getValue(), writer); - } - - public void writeNumber(JsonNumber number, Writer writer) throws IOException { - writer.append(number.getValue().toString()); - } - - public void writeNull(JsonNull jsonNull, Writer writer) throws IOException { - writer.append("null"); - } - - public void writeBoolean(JsonBoolean jsonBoolean, Writer writer) throws IOException { - writer.append(jsonBoolean.getValue().toString()); - } - - /* - * Helpers - */ - - private void indent(Writer writer, int depth) throws IOException { - int amount = indent * depth; - char append = spaces ? ' ' : '\t'; - for (int count = 0; count < amount; count++) - writer.append(append); - } - - private void writeUnescapedString(String string, Writer writer) throws IOException { - // TODO: escape string - writer.append('"'); - writer.append(string); - writer.append('"'); - } + public static final int TAB_SPACES = 4; + + private boolean pretty = false; + private boolean spaces = false; + private int indent = 1; + + public boolean isPretty() { + return pretty; + } + + public JsonWriter setPretty(boolean pretty) { + this.pretty = pretty; + return this; + } + + public boolean usesSpaces() { + return spaces; + } + + public JsonWriter setSpaces(boolean spaces) { + this.spaces = spaces; + return this; + } + + public int getIndent() { + return indent; + } + + public JsonWriter setIndent(int indent) { + this.indent = indent; + return this; + } + + public JsonWriter setTabIndent(int indent) { + this.indent = indent * TAB_SPACES; + return this; + } + + @Override + public void toWriter(JsonValue object, Writer writer) throws IOException { + switch (object.getType()) { + case ARRAY: + writeArray((JsonArray) object, writer, 0); + break; + case OBJECT: + writeObject((JsonObject) object, writer, 0); + break; + default: + break; + } + } + + public void writeEntry(JsonEntry entry, Writer writer, int depth) throws IOException { + if (pretty) { + indent(writer, depth); + } + writeUnescapedString(entry.getKey(), writer); + writer.append(':'); + if (pretty) { + writer.append(' '); + } + writeValue(entry.getValue(), writer, depth); + } + + public void writeValue(JsonValue value, Writer writer, int depth) throws IOException { + switch (value.getType()) { + case NULL: + writeNull((JsonNull) value, writer); + break; + case ARRAY: + writeArray((JsonArray) value, writer, depth); + break; + case OBJECT: + writeObject((JsonObject) value, writer, depth); + break; + case STRING: + writeString((JsonString) value, writer); + break; + case BOOLEAN: + writeBoolean((JsonBoolean) value, writer); + break; + case BYTE: + case SHORT: + case INTEGER: + case LONG: + case FLOAT: + case DOUBLE: + case BIG_INTEGER: + case BIG_DECIMAL: + writeNumber((JsonNumber) value, writer); + break; + case NUMBER: + break; + default: + break; + } + } + + public void writeObject(JsonObject object, Writer writer, int depth) throws IOException { + writer.append('{'); + int size = object.size(); + if (size != 0) { + if (pretty) { + writer.append('\n'); + } + int current = 0; + int deep = depth + 1; + for (JsonEntry entry : object) { + writeEntry(entry, writer, deep); + if (++current != size) { + writer.append(','); + } + if (pretty) { + writer.append('\n'); + } + } + } + writer.append('}'); + } + + public void writeArray(JsonArray array, Writer writer, int depth) throws IOException { + writer.append('['); + int size = array.size(); + if (size != 0) { + if (pretty) { + writer.append('\n'); + } + int current = 0; + int deep = depth + 1; + for (JsonValue value : array) { + if (pretty) { + indent(writer, deep); + } + writeValue(value, writer, deep); + if (++current != size) { + writer.append(','); + } + if (pretty) { + writer.append('\n'); + } + } + if (pretty) { + indent(writer, depth); + } + } + writer.append(']'); + } + + public void writeString(JsonString string, Writer writer) throws IOException { + writeUnescapedString(string.getValue(), writer); + } + + public void writeNumber(JsonNumber number, Writer writer) throws IOException { + writer.append(number.getValue().toString()); + } + + public void writeNull(JsonNull jsonNull, Writer writer) throws IOException { + writer.append("null"); + } + + public void writeBoolean(JsonBoolean jsonBoolean, Writer writer) throws IOException { + writer.append(jsonBoolean.getValue().toString()); + } + + /* + * Helpers + */ + + private void indent(Writer writer, int depth) throws IOException { + int amount = indent * depth; + char append = spaces ? ' ' : '\t'; + for (int count = 0; count < amount; count++) { + writer.append(append); + } + } + + private void writeUnescapedString(String string, Writer writer) throws IOException { + // TODO: escape string + writer.append('"'); + writer.append(string); + writer.append('"'); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/SynchronizedIterator.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/SynchronizedIterator.java index ee63fd4..dcda562 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/SynchronizedIterator.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/SynchronizedIterator.java @@ -5,30 +5,30 @@ public final class SynchronizedIterator implements Iterator { - private final Collection owner; - private final Iterator iterator; - - public SynchronizedIterator(Collection owner) { - this.owner = owner; - this.iterator = owner.iterator(); - } - - public Collection getOwner() { - return owner; - } - - @Override - public boolean hasNext() { - synchronized (owner) { - return iterator.hasNext(); - } - } - - @Override - public E next() { - synchronized (owner) { - return iterator.next(); - } - } + private final Collection owner; + private final Iterator iterator; + + public SynchronizedIterator(Collection owner) { + this.owner = owner; + this.iterator = owner.iterator(); + } + + public Collection getOwner() { + return owner; + } + + @Override + public boolean hasNext() { + synchronized (owner) { + return iterator.hasNext(); + } + } + + @Override + public E next() { + synchronized (owner) { + return iterator.next(); + } + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/TrackElement.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/TrackElement.java index 4e0777a..713760a 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/TrackElement.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/TrackElement.java @@ -9,43 +9,41 @@ public final class TrackElement { - private final StackTraceElement element; - private final Container> clazz = Container.of(); - private final Container method = Container.of(); - - TrackElement(StackTraceElement element) { - this.element = element; - } - - public boolean isValid() { - return element != null; - } - - public Optional> getCallerClass() { - return Optional.ofNullable(clazz.orElseGet(() -> clazz.replace(ClassCache.getOptionalClass(element.getClassName()).orElse(null)).get())); - } - - public Optional getCallerMethod() { - return Optional - .ofNullable(method - .orElseGet(() -> method - .replace(getCallerClass() - .map(clazz -> java.util.Arrays.stream(Arrays.merge(Method[]::new, clazz.getMethods(), clazz.getDeclaredMethods()))) - .flatMap(stream -> stream.filter(method -> method.getName().equals(element.getMethodName())).findFirst()) - .orElse(null)) - .get())); - } - - public String getFileName() { - return element.getFileName(); - } - - public int getLine() { - return element.getLineNumber(); - } - - public Optional asOptional() { - return element == null ? Optional.empty() : Optional.ofNullable(this); - } + private final StackTraceElement element; + private final Container> clazz = Container.of(); + private final Container method = Container.of(); + + TrackElement(StackTraceElement element) { + this.element = element; + } + + public boolean isValid() { + return element != null; + } + + public Optional> getCallerClass() { + return Optional + .ofNullable(clazz.orElseGet(() -> clazz.replace(ClassCache.getOptionalClass(element.getClassName()).orElse(null)).get())); + } + + public Optional getCallerMethod() { + return Optional.ofNullable(method.orElseGet(() -> method + .replace(getCallerClass() + .map(clazz -> java.util.Arrays.stream(Arrays.merge(Method[]::new, clazz.getMethods(), clazz.getDeclaredMethods()))) + .flatMap(stream -> stream.filter(method -> method.getName().equals(element.getMethodName())).findFirst()).orElse(null)) + .get())); + } + + public String getFileName() { + return element.getFileName(); + } + + public int getLine() { + return element.getLineNumber(); + } + + public Optional asOptional() { + return element == null ? Optional.empty() : Optional.ofNullable(this); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/Tracker.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/Tracker.java index 4dd60ac..c4d3ad9 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/Tracker.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/utils/Tracker.java @@ -5,30 +5,30 @@ public abstract class Tracker { - public static TrackElement getTrackElementFromStack(int offset) { - return new TrackElement(Thread.currentThread().getStackTrace()[2 + offset]); - } - - public static TrackElement getTrackElement() { - return getTrackElementFromStack(1); - } - - public static Optional getMethodFromStack(int offset) { - TrackElement element = getTrackElementFromStack(offset + 1); - return element.isValid() ? Optional.empty() : element.getCallerMethod(); - } - - public static Optional getCallerMethod() { - return getMethodFromStack(1); - } - - public static Optional> getClassFromStack(int offset) { - TrackElement element = getTrackElementFromStack(offset + 1); - return element.isValid() ? Optional.empty() : element.getCallerClass(); - } - - public static Optional> getCallerClass() { - return getClassFromStack(1); - } + public static TrackElement getTrackElementFromStack(int offset) { + return new TrackElement(Thread.currentThread().getStackTrace()[2 + offset]); + } + + public static TrackElement getTrackElement() { + return getTrackElementFromStack(1); + } + + public static Optional getMethodFromStack(int offset) { + TrackElement element = getTrackElementFromStack(offset + 1); + return element.isValid() ? Optional.empty() : element.getCallerMethod(); + } + + public static Optional getCallerMethod() { + return getMethodFromStack(1); + } + + public static Optional> getClassFromStack(int offset) { + TrackElement element = getTrackElementFromStack(offset + 1); + return element.isValid() ? Optional.empty() : element.getCallerClass(); + } + + public static Optional> getCallerClass() { + return getClassFromStack(1); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigDecimal.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigDecimal.java index 570f25c..390b930 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigDecimal.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigDecimal.java @@ -6,13 +6,13 @@ public class JsonBigDecimal extends JsonNumber { - public JsonBigDecimal(BigDecimal value) { - super(value); - } + public JsonBigDecimal(BigDecimal value) { + super(value); + } - @Override - public ValueType getType() { - return ValueType.BIG_DECIMAL; - } + @Override + public ValueType getType() { + return ValueType.BIG_DECIMAL; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigInteger.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigInteger.java index c5e055c..fca8046 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigInteger.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBigInteger.java @@ -6,13 +6,13 @@ public class JsonBigInteger extends JsonNumber { - public JsonBigInteger(BigInteger value) { - super(value); - } + public JsonBigInteger(BigInteger value) { + super(value); + } - @Override - public ValueType getType() { - return ValueType.BIG_INTEGER; - } + @Override + public ValueType getType() { + return ValueType.BIG_INTEGER; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBoolean.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBoolean.java index e89c0e5..9d71e40 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBoolean.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonBoolean.java @@ -4,13 +4,13 @@ public class JsonBoolean extends JsonSimple { - public JsonBoolean(Boolean value) { - super(value); - } + public JsonBoolean(Boolean value) { + super(value); + } - @Override - public ValueType getType() { - return ValueType.BOOLEAN; - } + @Override + public ValueType getType() { + return ValueType.BOOLEAN; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonByte.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonByte.java index e22604d..2483b25 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonByte.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonByte.java @@ -4,13 +4,13 @@ public class JsonByte extends JsonNumber { - public JsonByte(Byte value) { - super(value); - } + public JsonByte(Byte value) { + super(value); + } - @Override - public ValueType getType() { - return ValueType.BYTE; - } + @Override + public ValueType getType() { + return ValueType.BYTE; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonDouble.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonDouble.java index a2e1b87..cb4f532 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonDouble.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonDouble.java @@ -4,13 +4,13 @@ public class JsonDouble extends JsonNumber { - public JsonDouble(Double value) { - super(value); - } + public JsonDouble(Double value) { + super(value); + } - @Override - public final ValueType getType() { - return ValueType.DOUBLE; - } + @Override + public final ValueType getType() { + return ValueType.DOUBLE; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonFloat.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonFloat.java index 6579f21..c54ee4d 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonFloat.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonFloat.java @@ -4,13 +4,13 @@ public class JsonFloat extends JsonNumber { - public JsonFloat(Float value) { - super(value); - } + public JsonFloat(Float value) { + super(value); + } - @Override - public ValueType getType() { - return ValueType.FLOAT; - } + @Override + public ValueType getType() { + return ValueType.FLOAT; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonInteger.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonInteger.java index 7366f1f..e615318 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonInteger.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonInteger.java @@ -4,13 +4,13 @@ public class JsonInteger extends JsonNumber { - public JsonInteger(Integer value) { - super(value); - } + public JsonInteger(Integer value) { + super(value); + } - @Override - public final ValueType getType() { - return ValueType.INTEGER; - } + @Override + public final ValueType getType() { + return ValueType.INTEGER; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonLong.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonLong.java index b091da7..f8ce49c 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonLong.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonLong.java @@ -4,13 +4,13 @@ public class JsonLong extends JsonNumber { - public JsonLong(Long value) { - super(value); - } + public JsonLong(Long value) { + super(value); + } - @Override - public final ValueType getType() { - return ValueType.LONG; - } + @Override + public final ValueType getType() { + return ValueType.LONG; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNull.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNull.java index 7ed6318..e88583f 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNull.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNull.java @@ -5,24 +5,23 @@ public class JsonNull extends JsonValue { - private static JsonNull INSTANCE = new JsonNull<>(); + private static JsonNull INSTANCE = new JsonNull<>(); - @SuppressWarnings("unchecked") - public static JsonNull get() { - return (JsonNull) INSTANCE; - } + @SuppressWarnings("unchecked") + public static JsonNull get() { + return (JsonNull) INSTANCE; + } - private JsonNull() { - } + private JsonNull() {} - @Override - public ValueType getType() { - return ValueType.NULL; - } + @Override + public ValueType getType() { + return ValueType.NULL; + } - @Override - public E getValue() { - return null; - } + @Override + public E getValue() { + return null; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNumber.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNumber.java index b6b5c22..73261cd 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNumber.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonNumber.java @@ -2,8 +2,8 @@ public abstract class JsonNumber extends JsonSimple { - public JsonNumber(E value) { - super(value); - } + public JsonNumber(E value) { + super(value); + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonShort.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonShort.java index 3180a8a..5790ca7 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonShort.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonShort.java @@ -4,13 +4,13 @@ public class JsonShort extends JsonNumber { - public JsonShort(Short value) { - super(value); - } + public JsonShort(Short value) { + super(value); + } - @Override - public final ValueType getType() { - return ValueType.SHORT; - } + @Override + public final ValueType getType() { + return ValueType.SHORT; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonSimple.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonSimple.java index 7145ff0..ced3c36 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonSimple.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonSimple.java @@ -4,15 +4,15 @@ public abstract class JsonSimple extends JsonValue { - protected final E value; + protected final E value; - public JsonSimple(E value) { - this.value = value; - } + public JsonSimple(E value) { + this.value = value; + } - @Override - public E getValue() { - return value; - } + @Override + public E getValue() { + return value; + } } diff --git a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonString.java b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonString.java index 98ae23e..f98161a 100644 --- a/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonString.java +++ b/utils/json/json-lib/src/main/java/com/syntaxphoenix/syntaxapi/json/value/JsonString.java @@ -4,13 +4,13 @@ public class JsonString extends JsonSimple { - public JsonString(String value) { - super(value); - } + public JsonString(String value) { + super(value); + } - @Override - public final ValueType getType() { - return ValueType.STRING; - } + @Override + public final ValueType getType() { + return ValueType.STRING; + } } diff --git a/utils/json/json-lib/src/test/java/com/syntaxphoenix/syntaxapi/test/json/JsonTest.java b/utils/json/json-lib/src/test/java/com/syntaxphoenix/syntaxapi/test/json/JsonTest.java index 1c4870e..aef004b 100644 --- a/utils/json/json-lib/src/test/java/com/syntaxphoenix/syntaxapi/test/json/JsonTest.java +++ b/utils/json/json-lib/src/test/java/com/syntaxphoenix/syntaxapi/test/json/JsonTest.java @@ -12,39 +12,38 @@ public class JsonTest { - @Test - public void tryJsonWriter() throws IOException { + @Test + public void tryJsonWriter() throws IOException { - JsonWriter writer = new JsonWriter().setPretty(true).setIndent(2).setSpaces(true); + JsonWriter writer = new JsonWriter().setPretty(true).setIndent(2).setSpaces(true); - JsonObject object = new JsonObject(); - object.set("test", "Ein wert"); - object.set("test2", 397598L); - JsonArray array = new JsonArray(); - array.add("Werte1"); - array.add("Werte2"); - array.add(new JsonArray()); - array.add(new JsonObject()); - object.set("test3", array); + JsonObject object = new JsonObject(); + object.set("test", "Ein wert"); + object.set("test2", 397598L); + JsonArray array = new JsonArray(); + array.add("Werte1"); + array.add("Werte2"); + array.add(new JsonArray()); + array.add(new JsonObject()); + object.set("test3", array); - writer.toStream(object, System.out); - System.out.println(); + writer.toStream(object, System.out); + System.out.println(); - } + } - @Test - public void tryJsonReader() throws Exception { + @Test + public void tryJsonReader() throws Exception { - JsonParser parser = new JsonParser(); + JsonParser parser = new JsonParser(); - JsonValue value = parser - .fromString("{\r\n" + " \"test\": \"Ein wert\",\r\n" + " \"test2\": 397598,\r\n" + " \"test3\": [\r\n" + " \"Werte1\",\r\n" - + " \"Werte2\",\r\n" + " [],\r\n" + " {}\r\n" + " ]\r\n" + "}"); + JsonValue value = parser.fromString("{\r\n" + " \"test\": \"Ein wert\",\r\n" + " \"test2\": 397598,\r\n" + " \"test3\": [\r\n" + + " \"Werte1\",\r\n" + " \"Werte2\",\r\n" + " [],\r\n" + " {}\r\n" + " ]\r\n" + "}"); - JsonWriter writer = new JsonWriter().setPretty(true).setIndent(2).setSpaces(true); + JsonWriter writer = new JsonWriter().setPretty(true).setIndent(2).setSpaces(true); - writer.toStream(value, System.out); + writer.toStream(value, System.out); - } + } } diff --git a/utils/json/json-nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtJsonParser.java b/utils/json/json-nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtJsonParser.java index 8c7cd77..d393604 100644 --- a/utils/json/json-nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtJsonParser.java +++ b/utils/json/json-nbt/src/main/java/com/syntaxphoenix/syntaxapi/nbt/tools/NbtJsonParser.java @@ -8,214 +8,222 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; -import com.syntaxphoenix.syntaxapi.nbt.*; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigDecimal; +import com.syntaxphoenix.syntaxapi.nbt.NbtBigInt; +import com.syntaxphoenix.syntaxapi.nbt.NbtByte; +import com.syntaxphoenix.syntaxapi.nbt.NbtCompound; +import com.syntaxphoenix.syntaxapi.nbt.NbtList; +import com.syntaxphoenix.syntaxapi.nbt.NbtNumber; +import com.syntaxphoenix.syntaxapi.nbt.NbtString; +import com.syntaxphoenix.syntaxapi.nbt.NbtTag; +import com.syntaxphoenix.syntaxapi.nbt.NbtType; import com.syntaxphoenix.syntaxapi.utils.java.Strings; public class NbtJsonParser { - public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); - - public static Object fromJson(JsonElement element, Class classOfT) { - return GSON.fromJson(element, classOfT); - } - - /** - * Convert nbt to json and then serialize it with - * {@code fromJson(JsonElement, Class)} - * - * @param tag - Nbt to convert - * @param type - Type of in nbt serialized object - * - * @return the object - */ - public static Object fromNbt(NbtTag tag, Class type) { - return fromJson(toJson(tag), type); - } - - /** - * Serialize an object to json - * - * @param object - Object to serialize - * - * @return json that was created - */ - public static JsonElement toJson(Object object) { - if (object instanceof JsonElement) { - return (JsonElement) object; - } else if (object instanceof NbtTag) { - return toJson((NbtTag) object); - } - return GSON.toJsonTree(object); - } - - /** - * Serialize an object to nbt - * - * @param object - Object to serialize - * - * @return nbt that was created - */ - public static NbtTag toNbt(Object object) { - if (object instanceof JsonElement) { - return toNbt((JsonElement) object); - } else if (object instanceof NbtTag) { - return (NbtTag) object; - } - return toNbt(toJson(object)); - } - - /** - * Convert json to nbt - * - * @param element - json element that should be converted - * - * @return resulting nbt tag - */ - public static NbtTag toNbt(JsonElement element) { - if (element.isJsonObject()) { - return toNbtCompound(element.getAsJsonObject()); - } else if (element.isJsonArray()) { - return toNbtList(element.getAsJsonArray()); - } else if (element.isJsonPrimitive()) { - JsonPrimitive primitive = element.getAsJsonPrimitive(); - if (primitive.isBoolean()) { - return new NbtByte((byte) (primitive.getAsBoolean() ? 1 : 0)); - } else if (primitive.isString()) { - String input = primitive.getAsString(); - if (Strings.isNumeric(input)) { - return new NbtBigInt(input); - } else if (Strings.isDecimal(input)) { - return new NbtBigDecimal(input); - } - return new NbtString(input); - } else if (primitive.isNumber()) { - return NbtNumber.fromNumber(primitive.getAsNumber()); - } - } - return null; - } - - /** - * Convert a JsonObject to an NbtCompound - * - * @param object - JsonObject that should be converted - * - * @return resulting NbtCompound - */ - public static NbtCompound toNbtCompound(JsonObject object) { - NbtCompound compound = new NbtCompound(); - if (object.size() == 0) { - return compound; - } - for (String key : object.keySet()) { - NbtTag tag = toNbt(object.get(key)); - if (tag == null) { - continue; - } - compound.set(key, tag); - } - return compound; - } - - /** - * Convert a JsonArray to an NbtList - * - * @param array - JsonArray that should be converted - * - * @return resulting NbtList - */ - public static NbtList toNbtList(JsonArray array) { - NbtList[] lists = toNbtLists(array); - if (lists.length == 0) { - return new NbtList<>(); - } else if (lists.length == 1) { - return lists[0]; - } - NbtList> list = new NbtList<>(); - for (NbtList add : lists) { - list.add(add); - } - return list; - } - - /** - * Convert a JsonArray to an NbtList Array - * - * @param array - JsonArray that should be converted - * - * @return resulting NbtList Array that contains a List for each NbtType - */ - public static NbtList[] toNbtLists(JsonArray array) { - if (array.size() == 0) { - return new NbtList[0]; - } - HashMap> tags = new HashMap<>(); - for (int index = 0; index < array.size(); index++) { - NbtTag tag = toNbt(array.get(index)); - NbtType type = tag.getType(); - if (tags.containsKey(type)) { - tags.get(type).addTag(tag); - } else { - NbtList list = new NbtList<>(); - list.addTag(tag); - tags.put(type, list); - } - } - NbtList[] output = tags.values().toArray(new NbtList[0]); - tags.clear(); - return output; - } - - /** - * Convert nbt to json - * - * @param tag - nbt that should be converted - * - * @return resulting json - */ - public static JsonElement toJson(NbtTag tag) { - if (tag instanceof NbtCompound) { - return toJsonObject((NbtCompound) tag); - } else if (tag instanceof NbtList) { - return toJsonArray((NbtList) tag); - } - return GSON.toJsonTree(tag.getValue()); - } - - /** - * Convert an NbtCompound to a JsonObject - * - * @param compound - NbtCompound that should be converted - * - * @return resulting JsonObject - */ - public static JsonObject toJsonObject(NbtCompound compound) { - JsonObject object = new JsonObject(); - if (compound.size() == 0) { - return object; - } - for (String key : compound.getKeys()) { - object.add(key, toJson(compound.get(key))); - } - return object; - } - - /** - * Convert a NbtList to an JsonArray - * - * @param list - NbtList that should be converted - * - * @return resulting JsonArray - */ - public static JsonArray toJsonArray(NbtList list) { - JsonArray array = new JsonArray(); - if (list.isEmpty()) { - return array; - } - for (NbtTag tag : list) { - array.add(toJson(tag)); - } - return array; - } + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static Object fromJson(JsonElement element, Class classOfT) { + return GSON.fromJson(element, classOfT); + } + + /** + * Convert nbt to json and then serialize it with + * {@code fromJson(JsonElement, Class)} + * + * @param tag - Nbt to convert + * @param type - Type of in nbt serialized object + * + * @return the object + */ + public static Object fromNbt(NbtTag tag, Class type) { + return fromJson(toJson(tag), type); + } + + /** + * Serialize an object to json + * + * @param object - Object to serialize + * + * @return json that was created + */ + public static JsonElement toJson(Object object) { + if (object instanceof JsonElement) { + return (JsonElement) object; + } else if (object instanceof NbtTag) { + return toJson((NbtTag) object); + } + return GSON.toJsonTree(object); + } + + /** + * Serialize an object to nbt + * + * @param object - Object to serialize + * + * @return nbt that was created + */ + public static NbtTag toNbt(Object object) { + if (object instanceof JsonElement) { + return toNbt((JsonElement) object); + } else if (object instanceof NbtTag) { + return (NbtTag) object; + } + return toNbt(toJson(object)); + } + + /** + * Convert json to nbt + * + * @param element - json element that should be converted + * + * @return resulting nbt tag + */ + public static NbtTag toNbt(JsonElement element) { + if (element.isJsonObject()) { + return toNbtCompound(element.getAsJsonObject()); + } else if (element.isJsonArray()) { + return toNbtList(element.getAsJsonArray()); + } else if (element.isJsonPrimitive()) { + JsonPrimitive primitive = element.getAsJsonPrimitive(); + if (primitive.isBoolean()) { + return new NbtByte((byte) (primitive.getAsBoolean() ? 1 : 0)); + } else if (primitive.isString()) { + String input = primitive.getAsString(); + if (Strings.isNumeric(input)) { + return new NbtBigInt(input); + } else if (Strings.isDecimal(input)) { + return new NbtBigDecimal(input); + } + return new NbtString(input); + } else if (primitive.isNumber()) { + return NbtNumber.fromNumber(primitive.getAsNumber()); + } + } + return null; + } + + /** + * Convert a JsonObject to an NbtCompound + * + * @param object - JsonObject that should be converted + * + * @return resulting NbtCompound + */ + public static NbtCompound toNbtCompound(JsonObject object) { + NbtCompound compound = new NbtCompound(); + if (object.size() == 0) { + return compound; + } + for (String key : object.keySet()) { + NbtTag tag = toNbt(object.get(key)); + if (tag == null) { + continue; + } + compound.set(key, tag); + } + return compound; + } + + /** + * Convert a JsonArray to an NbtList + * + * @param array - JsonArray that should be converted + * + * @return resulting NbtList + */ + public static NbtList toNbtList(JsonArray array) { + NbtList[] lists = toNbtLists(array); + if (lists.length == 0) { + return new NbtList<>(); + } else if (lists.length == 1) { + return lists[0]; + } + NbtList> list = new NbtList<>(); + for (NbtList add : lists) { + list.add(add); + } + return list; + } + + /** + * Convert a JsonArray to an NbtList Array + * + * @param array - JsonArray that should be converted + * + * @return resulting NbtList Array that contains a List for each NbtType + */ + public static NbtList[] toNbtLists(JsonArray array) { + if (array.size() == 0) { + return new NbtList[0]; + } + HashMap> tags = new HashMap<>(); + for (int index = 0; index < array.size(); index++) { + NbtTag tag = toNbt(array.get(index)); + NbtType type = tag.getType(); + if (tags.containsKey(type)) { + tags.get(type).addTag(tag); + } else { + NbtList list = new NbtList<>(); + list.addTag(tag); + tags.put(type, list); + } + } + NbtList[] output = tags.values().toArray(new NbtList[0]); + tags.clear(); + return output; + } + + /** + * Convert nbt to json + * + * @param tag - nbt that should be converted + * + * @return resulting json + */ + public static JsonElement toJson(NbtTag tag) { + if (tag instanceof NbtCompound) { + return toJsonObject((NbtCompound) tag); + } else if (tag instanceof NbtList) { + return toJsonArray((NbtList) tag); + } + return GSON.toJsonTree(tag.getValue()); + } + + /** + * Convert an NbtCompound to a JsonObject + * + * @param compound - NbtCompound that should be converted + * + * @return resulting JsonObject + */ + public static JsonObject toJsonObject(NbtCompound compound) { + JsonObject object = new JsonObject(); + if (compound.size() == 0) { + return object; + } + for (String key : compound.getKeys()) { + object.add(key, toJson(compound.get(key))); + } + return object; + } + + /** + * Convert a NbtList to an JsonArray + * + * @param list - NbtList that should be converted + * + * @return resulting JsonArray + */ + public static JsonArray toJsonArray(NbtList list) { + JsonArray array = new JsonArray(); + if (list.isEmpty()) { + return array; + } + for (NbtTag tag : list) { + array.add(toJson(tag)); + } + return array; + } } diff --git a/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/JsonTools.java b/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/JsonTools.java index 9c79f34..25e9bd8 100644 --- a/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/JsonTools.java +++ b/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/JsonTools.java @@ -15,89 +15,93 @@ import com.google.gson.JsonPrimitive; import com.syntaxphoenix.syntaxapi.reflection.AbstractReflect; import com.syntaxphoenix.syntaxapi.reflection.Reflect; -import com.syntaxphoenix.syntaxapi.utils.java.Collect.CollectorImpl; import com.syntaxphoenix.syntaxapi.utils.java.Collect; +import com.syntaxphoenix.syntaxapi.utils.java.Collect.CollectorImpl; public class JsonTools { - public static final AbstractReflect JSON_PRIMITIVE = new Reflect(JsonPrimitive.class).searchConstructor("value", Object.class).searchField("value", - "value"); - public static final AbstractReflect JSON_OBJECT = new Reflect(JsonObject.class).searchField("map", "members"); + public static final AbstractReflect JSON_PRIMITIVE = new Reflect(JsonPrimitive.class).searchConstructor("value", Object.class) + .searchField("value", "value"); + public static final AbstractReflect JSON_OBJECT = new Reflect(JsonObject.class).searchField("map", "members"); - private static JsonParser parser = new JsonParser(); - private static Gson gson; + private static JsonParser parser = new JsonParser(); + private static Gson gson; - public static Gson getConfiguredGson() { - if (gson != null) { - return gson; - } - GsonBuilder builder = new GsonBuilder(); - builder.setPrettyPrinting(); - return gson = builder.create(); - } + public static Gson getConfiguredGson() { + if (gson != null) { + return gson; + } + GsonBuilder builder = new GsonBuilder(); + builder.setPrettyPrinting(); + return gson = builder.create(); + } - public static JsonParser getJsonParser() { - return parser; - } + public static JsonParser getJsonParser() { + return parser; + } - /** - * @param input the raw json string - * @return output the complex json object - */ - public static JsonObject readJson(String input) { - return getJsonParser().parse(input).getAsJsonObject(); - } + /** + * @param input the raw json string + * @return output the complex json object + */ + public static JsonObject readJson(String input) { + return getJsonParser().parse(input).getAsJsonObject(); + } - public static JsonPrimitive createPrimitive(Object object) { - if (object instanceof Character) { - return new JsonPrimitive((Character) object); - } - if (object instanceof String) { - return new JsonPrimitive((String) object); - } - if (object instanceof Number) { - return new JsonPrimitive((Number) object); - } - if (object instanceof Boolean) { - return new JsonPrimitive((Boolean) object); - } - return new JsonPrimitive(object.toString()); - } + public static JsonPrimitive createPrimitive(Object object) { + if (object instanceof Character) { + return new JsonPrimitive((Character) object); + } + if (object instanceof String) { + return new JsonPrimitive((String) object); + } + if (object instanceof Number) { + return new JsonPrimitive((Number) object); + } + if (object instanceof Boolean) { + return new JsonPrimitive((Boolean) object); + } + return new JsonPrimitive(object.toString()); + } - public static Object getContent(JsonPrimitive primitive) { - return JSON_PRIMITIVE.getFieldValue("value", primitive); - } + public static Object getContent(JsonPrimitive primitive) { + return JSON_PRIMITIVE.getFieldValue("value", primitive); + } - @SuppressWarnings("unchecked") - public static JsonObject merge(JsonObject output, JsonObject input) { - ((Map) JSON_OBJECT.getFieldValue("map", output)).putAll((Map) JSON_OBJECT.getFieldValue("map", input)); - return output; - } + @SuppressWarnings("unchecked") + public static JsonObject merge(JsonObject output, JsonObject input) { + ((Map) JSON_OBJECT.getFieldValue("map", output)) + .putAll((Map) JSON_OBJECT.getFieldValue("map", input)); + return output; + } - public static Collector>, JsonObject, JsonObject> toJsonObject() { - return new CollectorImpl>, JsonObject, JsonObject>((Supplier) JsonObject::new, (output, entry) -> { - if (entry == null || entry.getKey() == null) - return; - List list = entry.getValue(); - if (list.size() == 1) { - output.add(entry.getKey(), toJsonPrimitive(list.get(0))); - return; - } - output.add(entry.getKey(), list.stream().collect(toJsonArray())); - }, (left, right) -> { - return merge(left, right); - }, Collect.passthrough(), Collect.CH_ID); - } + public static Collector>, JsonObject, JsonObject> toJsonObject() { + return new CollectorImpl>, JsonObject, JsonObject>((Supplier) JsonObject::new, + (output, entry) -> { + if (entry == null || entry.getKey() == null) { + return; + } + List list = entry.getValue(); + if (list.size() == 1) { + output.add(entry.getKey(), toJsonPrimitive(list.get(0))); + return; + } + output.add(entry.getKey(), list.stream().collect(toJsonArray())); + }, (left, right) -> { + return merge(left, right); + }, Collect.passthrough(), Collect.CH_ID); + } - public static Collector toJsonArray() { - return new CollectorImpl<>((Supplier) JsonArray::new, (output, value) -> output.add(toJsonPrimitive(value)), (array1, array2) -> { - array1.addAll(array2); - return array1; - }, Collect.passthrough(), Collect.CH_ID); - } + public static Collector toJsonArray() { + return new CollectorImpl<>((Supplier) JsonArray::new, (output, value) -> output.add(toJsonPrimitive(value)), + (array1, array2) -> { + array1.addAll(array2); + return array1; + }, Collect.passthrough(), Collect.CH_ID); + } - public static JsonPrimitive toJsonPrimitive(String value) { - return createPrimitive(ValueIdentifier.identify(value)); - } + public static JsonPrimitive toJsonPrimitive(String value) { + return createPrimitive(ValueIdentifier.identify(value)); + } } diff --git a/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/ValueIdentifier.java b/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/ValueIdentifier.java index ca9607e..a481132 100644 --- a/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/ValueIdentifier.java +++ b/utils/json/json-tools/src/main/java/com/syntaxphoenix/syntaxapi/utils/json/ValueIdentifier.java @@ -7,46 +7,47 @@ public class ValueIdentifier { - public static Object identify(String value) { - if (value.length() == 1) - return value.charAt(0); - if (Strings.isBoolean(value)) { - return Boolean.valueOf(value); - } - if (Strings.isNumeric(value)) { - try { - return Byte.parseByte(value); - } catch (NumberFormatException e) { - } - try { - return Short.parseShort(value); - } catch (NumberFormatException e) { - } - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - } - try { - return Long.parseLong(value); - } catch (NumberFormatException e) { - } - return new BigInteger(value); - } - if (Strings.isDecimal(value)) { - String number = value.split("\\.")[0]; - try { - Integer.parseInt(number); - return Float.parseFloat(value); - } catch (NumberFormatException e) { - } - try { - Long.parseLong(number); - return Double.parseDouble(value); - } catch (NumberFormatException e) { - } - return new BigDecimal(value); - } - return value; - } + public static Object identify(String value) { + if (value.length() == 1) { + return value.charAt(0); + } + if (Strings.isBoolean(value)) { + return Boolean.valueOf(value); + } + if (Strings.isNumeric(value)) { + try { + return Byte.parseByte(value); + } catch (NumberFormatException e) { + } + try { + return Short.parseShort(value); + } catch (NumberFormatException e) { + } + try { + return Integer.parseInt(value); + } catch (NumberFormatException e) { + } + try { + return Long.parseLong(value); + } catch (NumberFormatException e) { + } + return new BigInteger(value); + } + if (Strings.isDecimal(value)) { + String number = value.split("\\.")[0]; + try { + Integer.parseInt(number); + return Float.parseFloat(value); + } catch (NumberFormatException e) { + } + try { + Long.parseLong(number); + return Double.parseDouble(value); + } catch (NumberFormatException e) { + } + return new BigDecimal(value); + } + return value; + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKey.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKey.java index 00d660d..76868a4 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKey.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKey.java @@ -2,9 +2,9 @@ public abstract class AbstractKey implements IKey { - @Override - public boolean equals(Object obj) { - return obj instanceof IKey && isSimilar((IKey) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof IKey && isSimilar((IKey) obj); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKeyed.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKeyed.java index 3c70874..b3fcf66 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKeyed.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractKeyed.java @@ -2,15 +2,15 @@ public abstract class AbstractKeyed implements IKeyed { - protected final IKey key; + protected final IKey key; - public AbstractKeyed(IKey key) { - this.key = key; - } + public AbstractKeyed(IKey key) { + this.key = key; + } - @Override - public IKey getKey() { - return key; - } + @Override + public IKey getKey() { + return key; + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamedKey.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamedKey.java index 3fac986..5f330b5 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamedKey.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamedKey.java @@ -2,9 +2,9 @@ public abstract class AbstractNamedKey implements INamedKey { - @Override - public boolean equals(Object obj) { - return obj instanceof INamedKey && isSame((INamedKey) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof INamedKey && isSame((INamedKey) obj); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespace.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespace.java index 97bdbb0..e1a7177 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespace.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespace.java @@ -2,9 +2,9 @@ public abstract class AbstractNamespace implements INamespace { - @Override - public boolean equals(Object obj) { - return obj instanceof INamespace && isSimilar((INamespace) obj); - } + @Override + public boolean equals(Object obj) { + return obj instanceof INamespace && isSimilar((INamespace) obj); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespaced.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespaced.java index b8644ac..220bf16 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespaced.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/AbstractNamespaced.java @@ -2,15 +2,15 @@ public abstract class AbstractNamespaced implements INamespaced { - protected final INamespace namespace; + protected final INamespace namespace; - public AbstractNamespaced(INamespace namespace) { - this.namespace = namespace; - } + public AbstractNamespaced(INamespace namespace) { + this.namespace = namespace; + } - @Override - public INamespace getNamespace() { - return namespace; - } + @Override + public INamespace getNamespace() { + return namespace; + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKey.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKey.java index db7af86..7033b2f 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKey.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKey.java @@ -2,22 +2,22 @@ public interface IKey extends INamespaced { - String getKey(); + String getKey(); - default boolean isSimilar(IKey key) { - return key != null && (key.getKey().equals(getKey()) && getNamespace().isSimilar(key.getNamespace())); - } + default boolean isSimilar(IKey key) { + return key != null && (key.getKey().equals(getKey()) && getNamespace().isSimilar(key.getNamespace())); + } - default int hash() { - return asString().hashCode(); - } + default int hash() { + return asString().hashCode(); + } - default String asString() { - return String.format(KeyConstants.KEY_FORMAT, getNamespace().getName(), getKey()); - } + default String asString() { + return String.format(KeyConstants.KEY_FORMAT, getNamespace().getName(), getKey()); + } - public static boolean isKey(String string) { - return KeyConstants.KEY_PATTERN.matcher(string).matches(); - } + public static boolean isKey(String string) { + return KeyConstants.KEY_PATTERN.matcher(string).matches(); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKeyed.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKeyed.java index fea2a63..68ef524 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKeyed.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/IKeyed.java @@ -2,6 +2,6 @@ public interface IKeyed { - IKey getKey(); + IKey getKey(); } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamedKey.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamedKey.java index 3461411..f93ce7e 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamedKey.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamedKey.java @@ -2,22 +2,22 @@ public interface INamedKey extends IKey { - String getName(); + String getName(); - default String asNamedString() { - return String.format(KeyConstants.NAMED_KEY_FORMAT, getNamespace().getName(), getKey(), getName()); - } + default String asNamedString() { + return String.format(KeyConstants.NAMED_KEY_FORMAT, getNamespace().getName(), getKey(), getName()); + } - default int hashNamed() { - return asNamedString().hashCode(); - } + default int hashNamed() { + return asNamedString().hashCode(); + } - default boolean isSame(INamedKey key) { - return isSimilar(key) && key.getName().equals(getName()); - } + default boolean isSame(INamedKey key) { + return isSimilar(key) && key.getName().equals(getName()); + } - public static boolean isNamedKey(String string) { - return KeyConstants.NAMED_KEY_PATTERN.matcher(string).matches(); - } + public static boolean isNamedKey(String string) { + return KeyConstants.NAMED_KEY_PATTERN.matcher(string).matches(); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespace.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespace.java index 6d8b218..37fe2a5 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespace.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespace.java @@ -4,28 +4,28 @@ public interface INamespace { - String getName(); + String getName(); - boolean contains(String key); + boolean contains(String key); - E createNamed(String key, String name); + E createNamed(String key, String name); - E create(String key); + E create(String key); - Optional option(String key); + Optional option(String key); - E get(String key); + E get(String key); - String[] getKeyspaces(); + String[] getKeyspaces(); - E[] getKeys(); + E[] getKeys(); - default int hash() { - return getName().hashCode(); - } + default int hash() { + return getName().hashCode(); + } - default boolean isSimilar(INamespace namespace) { - return namespace != null && getName().equals(namespace.getName()); - } + default boolean isSimilar(INamespace namespace) { + return namespace != null && getName().equals(namespace.getName()); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespaced.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespaced.java index 98a7e59..233e91f 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespaced.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/INamespaced.java @@ -2,6 +2,6 @@ public interface INamespaced { - INamespace getNamespace(); + INamespace getNamespace(); } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/KeyConstants.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/KeyConstants.java index f440a04..1f5512b 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/KeyConstants.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/KeyConstants.java @@ -4,13 +4,14 @@ public class KeyConstants { - public static final String KEY_FORMAT = "%s:%s"; - public static final String NAMED_KEY_FORMAT = "%s:%s#%s"; + public static final String KEY_FORMAT = "%s:%s"; + public static final String NAMED_KEY_FORMAT = "%s:%s#%s"; - public static final Pattern KEY_PATTERN = Pattern.compile("([a-z0-9._-]+):([a-z0-9/._-]+)"); - public static final Pattern NAMED_KEY_PATTERN = Pattern.compile("([a-z0-9._-]+):([a-z0-9/._-]+)#([a-zA-Z0-9/._-\\s]+)"); + public static final Pattern KEY_PATTERN = Pattern.compile("([a-z0-9._-]+):([a-z0-9/._-]+)"); + public static final Pattern NAMED_KEY_PATTERN = Pattern + .compile("([a-z0-9._-]+):([a-z0-9/._-]+)#([a-zA-Z0-9/._-\\s]+)"); - public static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); - public static final Pattern VALID_NAMESPACE = Pattern.compile("[a-z0-9._-]+"); + public static final Pattern VALID_KEY = Pattern.compile("[a-z0-9/._-]+"); + public static final Pattern VALID_NAMESPACE = Pattern.compile("[a-z0-9._-]+"); } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/Namespace.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/Namespace.java index f4bdbae..1393e03 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/Namespace.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/Namespace.java @@ -5,63 +5,63 @@ public final class Namespace extends AbstractNamespace { - private static final ConcurrentHashMap NAMESPACES = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap NAMESPACES = new ConcurrentHashMap<>(); - public static Namespace of(String name) { - if(NAMESPACES.containsKey(name)) { - return NAMESPACES.get(name); - } - Namespace namespace = new Namespace(name); - NAMESPACES.put(name, namespace); - return namespace; - } + public static Namespace of(String name) { + if (NAMESPACES.containsKey(name)) { + return NAMESPACES.get(name); + } + Namespace namespace = new Namespace(name); + NAMESPACES.put(name, namespace); + return namespace; + } - protected final String name; - protected final ConcurrentHashMap keys = new ConcurrentHashMap<>(); + protected final String name; + protected final ConcurrentHashMap keys = new ConcurrentHashMap<>(); - private Namespace(String name) { - this.name = name; - NAMESPACES.put(name, this); - } + private Namespace(String name) { + this.name = name; + NAMESPACES.put(name, this); + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public boolean contains(String key) { - return keys.containsKey(key); - } + @Override + public boolean contains(String key) { + return keys.containsKey(key); + } - @Override - public NamespacedKey createNamed(String key, String name) { - return keys.computeIfAbsent(key, compute -> new NamespacedKey(this, compute, name)); - } + @Override + public NamespacedKey createNamed(String key, String name) { + return keys.computeIfAbsent(key, compute -> new NamespacedKey(this, compute, name)); + } - @Override - public NamespacedKey create(String key) { - return keys.computeIfAbsent(key, compute -> new NamespacedKey(this, compute)); - } + @Override + public NamespacedKey create(String key) { + return keys.computeIfAbsent(key, compute -> new NamespacedKey(this, compute)); + } - @Override - public Optional option(String key) { - return Optional.ofNullable(keys.get(key)); - } + @Override + public Optional option(String key) { + return Optional.ofNullable(keys.get(key)); + } - @Override - public NamespacedKey get(String key) { - return keys.get(key); - } + @Override + public NamespacedKey get(String key) { + return keys.get(key); + } - @Override - public String[] getKeyspaces() { - return keys.keySet().toArray(new String[0]); - } + @Override + public String[] getKeyspaces() { + return keys.keySet().toArray(new String[0]); + } - @Override - public NamespacedKey[] getKeys() { - return keys.values().toArray(new NamespacedKey[0]); - } + @Override + public NamespacedKey[] getKeys() { + return keys.values().toArray(new NamespacedKey[0]); + } } diff --git a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/NamespacedKey.java b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/NamespacedKey.java index 22497d0..50ca59a 100644 --- a/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/NamespacedKey.java +++ b/utils/key/src/main/java/com/syntaxphoenix/syntaxapi/utils/key/NamespacedKey.java @@ -5,68 +5,68 @@ public final class NamespacedKey extends AbstractNamedKey { - public static NamespacedKey of(String namespace, String key) { - return Namespace.of(namespace).create(key); - } + public static NamespacedKey of(String namespace, String key) { + return Namespace.of(namespace).create(key); + } - public static NamespacedKey of(String namespace, String key, String name) { - return Namespace.of(namespace).createNamed(key, name); - } + public static NamespacedKey of(String namespace, String key, String name) { + return Namespace.of(namespace).createNamed(key, name); + } - public static NamespacedKey fromStringOrCompute(String string, Function mapper) { - NamespacedKey computed = fromString(string); - return computed == null ? mapper.apply(string) : computed; - } + public static NamespacedKey fromStringOrCompute(String string, Function mapper) { + NamespacedKey computed = fromString(string); + return computed == null ? mapper.apply(string) : computed; + } - public static NamespacedKey fromStringOrDefault(String string, NamespacedKey key) { - NamespacedKey computed = fromString(string); - return computed == null ? key : computed; - } + public static NamespacedKey fromStringOrDefault(String string, NamespacedKey key) { + NamespacedKey computed = fromString(string); + return computed == null ? key : computed; + } - public static NamespacedKey fromString(String string) { - Matcher keyMatcher = KeyConstants.KEY_PATTERN.matcher(string); - if (keyMatcher.matches()) { - String namespace = keyMatcher.group("Namespace"); - String key = keyMatcher.group("Key"); - return of(namespace, key); - } - keyMatcher = KeyConstants.NAMED_KEY_PATTERN.matcher(string); - if (keyMatcher.matches()) { - String namespace = keyMatcher.group("Namespace"); - String name = keyMatcher.group("Name"); - String key = keyMatcher.group("Key"); - return of(namespace, key, name); - } - return null; - } + public static NamespacedKey fromString(String string) { + Matcher keyMatcher = KeyConstants.KEY_PATTERN.matcher(string); + if (keyMatcher.matches()) { + String namespace = keyMatcher.group("Namespace"); + String key = keyMatcher.group("Key"); + return of(namespace, key); + } + keyMatcher = KeyConstants.NAMED_KEY_PATTERN.matcher(string); + if (keyMatcher.matches()) { + String namespace = keyMatcher.group("Namespace"); + String name = keyMatcher.group("Name"); + String key = keyMatcher.group("Key"); + return of(namespace, key, name); + } + return null; + } - private final Namespace namespace; - private final String name; - private final String key; + private final Namespace namespace; + private final String name; + private final String key; - protected NamespacedKey(Namespace namespace, String key) { - this(namespace, key, key.toUpperCase()); - } + protected NamespacedKey(Namespace namespace, String key) { + this(namespace, key, key.toUpperCase()); + } - protected NamespacedKey(Namespace namespace, String key, String name) { - this.namespace = namespace; - this.name = name; - this.key = key; - } + protected NamespacedKey(Namespace namespace, String key, String name) { + this.namespace = namespace; + this.name = name; + this.key = key; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public Namespace getNamespace() { - return namespace; - } + @Override + public Namespace getNamespace() { + return namespace; + } - @Override - public String getKey() { - return key; - } + @Override + public String getKey() { + return key; + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/BlockLocation.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/BlockLocation.java index 6f84f95..205f4c3 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/BlockLocation.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/BlockLocation.java @@ -6,81 +6,81 @@ */ public class BlockLocation extends Location { - /** - * - */ - - private long x = 0; - private long y = 0; - private long z = 0; - - /** - * - */ - - public BlockLocation() { - - } - - public BlockLocation(long x, long y, long z) { - this.x = x; - this.y = y; - this.z = z; - } - - public BlockLocation(VectorLocation position) { - this.x = position.getNormalizedX(); - this.y = position.getNormalizedY(); - this.z = position.getNormalizedZ(); - } - - /** - * - */ - - @Override - public long getNormalizedX() { - return x; - } - - @Override - public long getNormalizedY() { - return y; - } - - @Override - public long getNormalizedZ() { - return z; - } - - @Override - public double getX() { - return x; - } - - @Override - public double getY() { - return y; - } - - @Override - public double getZ() { - return z; - } - - @Override - public void setX(double x) { - this.x = (long) x; - } - - @Override - public void setY(double y) { - this.y = (long) y; - } - - @Override - public void setZ(double z) { - this.z = (long) z; - } + /** + * + */ + + private long x = 0; + private long y = 0; + private long z = 0; + + /** + * + */ + + public BlockLocation() { + + } + + public BlockLocation(long x, long y, long z) { + this.x = x; + this.y = y; + this.z = z; + } + + public BlockLocation(VectorLocation position) { + this.x = position.getNormalizedX(); + this.y = position.getNormalizedY(); + this.z = position.getNormalizedZ(); + } + + /** + * + */ + + @Override + public long getNormalizedX() { + return x; + } + + @Override + public long getNormalizedY() { + return y; + } + + @Override + public long getNormalizedZ() { + return z; + } + + @Override + public double getX() { + return x; + } + + @Override + public double getY() { + return y; + } + + @Override + public double getZ() { + return z; + } + + @Override + public void setX(double x) { + this.x = (long) x; + } + + @Override + public void setY(double y) { + this.y = (long) y; + } + + @Override + public void setZ(double z) { + this.z = (long) z; + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/Location.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/Location.java index 1a7f050..257432c 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/Location.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/Location.java @@ -6,22 +6,22 @@ */ public abstract class Location { - public abstract long getNormalizedX(); + public abstract long getNormalizedX(); - public abstract long getNormalizedY(); + public abstract long getNormalizedY(); - public abstract long getNormalizedZ(); + public abstract long getNormalizedZ(); - public abstract double getX(); + public abstract double getX(); - public abstract double getY(); + public abstract double getY(); - public abstract double getZ(); + public abstract double getZ(); - public abstract void setX(double x); + public abstract void setX(double x); - public abstract void setY(double y); + public abstract void setY(double y); - public abstract void setZ(double z); + public abstract void setZ(double z); } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/VectorLocation.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/VectorLocation.java index 288b002..1795390 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/VectorLocation.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/VectorLocation.java @@ -6,81 +6,81 @@ */ public class VectorLocation extends Location { - /** - * - */ - - private double x = 0; - private double y = 0; - private double z = 0; - - /** - * - */ - - public VectorLocation() { - - } - - public VectorLocation(double x, double y, double z) { - this.x = x; - this.y = y; - this.z = z; - } - - public VectorLocation(BlockLocation location) { - this.x = location.getX(); - this.y = location.getY(); - this.z = location.getZ(); - } - - /** - * - */ - - @Override - public long getNormalizedX() { - return (long) x; - } - - @Override - public long getNormalizedY() { - return (long) y; - } - - @Override - public long getNormalizedZ() { - return (long) z; - } - - @Override - public double getX() { - return x; - } - - @Override - public double getY() { - return y; - } - - @Override - public double getZ() { - return z; - } - - @Override - public void setX(double x) { - this.x = x; - } - - @Override - public void setY(double y) { - this.y = y; - } - - @Override - public void setZ(double z) { - this.z = z; - } + /** + * + */ + + private double x = 0; + private double y = 0; + private double z = 0; + + /** + * + */ + + public VectorLocation() { + + } + + public VectorLocation(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + + public VectorLocation(BlockLocation location) { + this.x = location.getX(); + this.y = location.getY(); + this.z = location.getZ(); + } + + /** + * + */ + + @Override + public long getNormalizedX() { + return (long) x; + } + + @Override + public long getNormalizedY() { + return (long) y; + } + + @Override + public long getNormalizedZ() { + return (long) z; + } + + @Override + public double getX() { + return x; + } + + @Override + public double getY() { + return y; + } + + @Override + public double getZ() { + return z; + } + + @Override + public void setX(double x) { + this.x = x; + } + + @Override + public void setY(double y) { + this.y = y; + } + + @Override + public void setZ(double z) { + this.z = z; + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridLayer.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridLayer.java index 9d644fa..40344c3 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridLayer.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridLayer.java @@ -5,200 +5,216 @@ public final class GridLayer { - private final ArrayList> rows = new ArrayList<>(); - private int y; - - /* - * - */ - - @SuppressWarnings("unchecked") - public GridRow[] getRows() { - return rows.toArray(new GridRow[0]); - } - - /* - * - */ - - public long getEntryCount() { - if (rows.isEmpty()) - return 0; - long output = 0; - for (GridRow row : rows) - output = +row.getEntryCount(); - return output; - } - - /* - * - */ - - public int getY() { - return y; - } - - protected void setY(int y) { - this.y = y; - } - - /* - * - */ - - public int getHeighestX() { - if (rows.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridRow row : rows) - if ((buffer = row.getX()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestX() { - if (rows.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridRow row : rows) - if ((buffer = row.getX()) < lowest) - lowest = buffer; - return lowest; - } - - public int getHeighestZ() { - if (rows.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridRow row : rows) - if ((buffer = row.getHeighestZ()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestZ() { - if (rows.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridRow row : rows) - if ((buffer = row.getLowestZ()) < lowest) - lowest = buffer; - return lowest; - } - - /* - * - */ - - public int getWidth() { - if (rows.isEmpty()) { - return 0; - } - int lowest = 0; - int heighest = 0; - for (GridRow row : rows) { - int depth = row.getX(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - public int getDepth() { - if (rows.isEmpty()) { - return 0; - } - int lowest = 0; - int heighest = 0; - for (GridRow row : rows) { - int depth = row.getDepth(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - /* - * - */ - - public void clear() { - rows.forEach(row -> row.clear()); - rows.clear(); - } - - public GridLayer set(int x, int z, V value) { - if (value == null) - return this; - Optional> option = getOptionalRow(x); - GridRow row; - if (!option.isPresent()) { - row = new GridRow<>(); - row.setX(x); - rows.add(row); - } else { - row = option.get(); - } - row.set(z, value); - return this; - } - - public GridLayer remove(int x) { - Optional> option = getOptionalRow(x); - if (option.isPresent()) { - rows.remove(option.get()); - } - return this; - } - - public GridLayer remove(int x, int z) { - Optional> option = getOptionalRow(x); - if (option.isPresent()) { - option.get().remove(z); - } - return this; - } - - public boolean contains(int x) { - return getOptionalRow(x).isPresent(); - } - - public boolean contains(int x, int z) { - Optional> row = getOptionalRow(x); - return row.isPresent() ? row.get().contains(z) : false; - } - - /* - * - */ - - public Optional> getOptionalRow(int x) { - return rows.stream().filter(row -> row.getX() == x).findFirst(); - } - - public Optional> getOptionalValue(int x, int z) { - Optional> option = getOptionalRow(x); - if (option.isPresent()) - return option.get().getOptionalValue(z); - return Optional.empty(); - } - - public GridRow getRow(int x) { - return getOptionalRow(x).orElse(null); - } - - public GridValue getValue(int x, int z) { - return getOptionalValue(x, z).orElse(null); - } + private final ArrayList> rows = new ArrayList<>(); + private int y; + + /* + * + */ + + @SuppressWarnings("unchecked") + public GridRow[] getRows() { + return rows.toArray(new GridRow[0]); + } + + /* + * + */ + + public long getEntryCount() { + if (rows.isEmpty()) { + return 0; + } + long output = 0; + for (GridRow row : rows) { + output = +row.getEntryCount(); + } + return output; + } + + /* + * + */ + + public int getY() { + return y; + } + + protected void setY(int y) { + this.y = y; + } + + /* + * + */ + + public int getHeighestX() { + if (rows.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridRow row : rows) { + if ((buffer = row.getX()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestX() { + if (rows.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridRow row : rows) { + if ((buffer = row.getX()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + public int getHeighestZ() { + if (rows.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridRow row : rows) { + if ((buffer = row.getHeighestZ()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestZ() { + if (rows.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridRow row : rows) { + if ((buffer = row.getLowestZ()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + /* + * + */ + + public int getWidth() { + if (rows.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridRow row : rows) { + int depth = row.getX(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + public int getDepth() { + if (rows.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridRow row : rows) { + int depth = row.getDepth(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + /* + * + */ + + public void clear() { + rows.forEach(row -> row.clear()); + rows.clear(); + } + + public GridLayer set(int x, int z, V value) { + if (value == null) { + return this; + } + Optional> option = getOptionalRow(x); + GridRow row; + if (!option.isPresent()) { + row = new GridRow<>(); + row.setX(x); + rows.add(row); + } else { + row = option.get(); + } + row.set(z, value); + return this; + } + + public GridLayer remove(int x) { + Optional> option = getOptionalRow(x); + if (option.isPresent()) { + rows.remove(option.get()); + } + return this; + } + + public GridLayer remove(int x, int z) { + Optional> option = getOptionalRow(x); + if (option.isPresent()) { + option.get().remove(z); + } + return this; + } + + public boolean contains(int x) { + return getOptionalRow(x).isPresent(); + } + + public boolean contains(int x, int z) { + Optional> row = getOptionalRow(x); + return row.isPresent() ? row.get().contains(z) : false; + } + + /* + * + */ + + public Optional> getOptionalRow(int x) { + return rows.stream().filter(row -> row.getX() == x).findFirst(); + } + + public Optional> getOptionalValue(int x, int z) { + Optional> option = getOptionalRow(x); + if (option.isPresent()) { + return option.get().getOptionalValue(z); + } + return Optional.empty(); + } + + public GridRow getRow(int x) { + return getOptionalRow(x).orElse(null); + } + + public GridValue getValue(int x, int z) { + return getOptionalValue(x, z).orElse(null); + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridMap.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridMap.java index 3ba0423..b482648 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridMap.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridMap.java @@ -5,305 +5,334 @@ public class GridMap { - private final GridType type; - - public GridType getType() { - return type; - } - - /* - * - */ - - private ArrayList> layers = new ArrayList<>(1); - - public GridMap(GridType type) { - this.type = type; - } - - /* - * - */ - - @SuppressWarnings("unchecked") - public GridLayer[] getLayers() { - return layers.toArray(new GridLayer[0]); - } - - /* - * - */ - - public long getEntryCount() { - if (layers.isEmpty()) - return 0; - long output = 0; - for (GridLayer layer : layers) - output = +layer.getEntryCount(); - return output; - } - - /* - * - */ - - public int getHeighestY() { - if (layers.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getY()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestY() { - if (layers.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getY()) < lowest) - lowest = buffer; - return lowest; - } - - public int getHeighestX() { - if (layers.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getHeighestX()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestX() { - if (layers.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getLowestX()) < lowest) - lowest = buffer; - return lowest; - } - - public int getHeighestZ() { - if (layers.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getHeighestZ()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestZ() { - if (layers.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridLayer layer : layers) - if ((buffer = layer.getLowestZ()) < lowest) - lowest = buffer; - return lowest; - } - - /* - * - */ - - public int getHeight() { - if (layers.isEmpty()) - return 0; - int lowest = 0; - int heighest = 0; - for (GridLayer layer : layers) { - int depth = layer.getY(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - public int getWidth() { - if (layers.isEmpty()) - return 0; - int lowest = 0; - int heighest = 0; - for (GridLayer layer : layers) { - int depth = layer.getWidth(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - public int getDepth() { - if (layers.isEmpty()) { - return 0; - } - int lowest = 0; - int heighest = 0; - for (GridLayer layer : layers) { - int depth = layer.getDepth(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - /* - * - */ - - public void clear() { - layers.forEach(layer -> layer.clear()); - layers.clear(); - } - - public GridMap set(int[] array, V value) { - if (array.length < 2) - return this; - return array.length == 2 ? set(array[0], array[1], value) : set(array[0], array[1], array[2], value); - } - - public GridMap set(int x, int z, V value) { - return set(x, 0, z, value); - } - - public GridMap set(int y, int x, int z, V value) { - if (value == null) - return this; - GridLayer layer; - if (type.is2D()) { - if (layers.isEmpty()) { - layer = new GridLayer<>(); - layer.setY(y); - layers.add(layer); - } else { - layer = layers.get(0); - } - } else { - Optional> option = getOptionalLayer(y); - if (!option.isPresent()) { - layer = new GridLayer<>(); - layer.setY(y); - layers.add(layer); - } else { - layer = option.get(); - } - } - layer.set(x, z, value); - return this; - } - - public GridMap remove(int y) { - Optional> option = getOptionalLayer(y); - if (option.isPresent()) { - layers.remove(option.get()); - } - return this; - } - - public GridMap remove(int y, int x) { - Optional> option = getOptionalLayer(y); - if (option.isPresent()) { - option.get().remove(x); - } - return this; - } - - public GridMap remove(int y, int x, int z) { - Optional> option = getOptionalLayer(y); - if (option.isPresent()) { - option.get().remove(x, z); - } - return this; - } - - public boolean contains(int y) { - return getOptionalLayer(y).isPresent(); - } - - public boolean contains(int y, int x) { - Optional> layer = getOptionalLayer(x); - return layer.isPresent() ? layer.get().contains(x) : false; - } - - public boolean contains(int y, int x, int z) { - Optional> layer = getOptionalLayer(x); - return layer.isPresent() ? layer.get().contains(x, z) : false; - } - - /* - * - */ - - public Optional> getOptionalLayer(int y) { - return layers.stream().filter(layer -> layer.getY() == y).findFirst(); - } - - public Optional> getOptionalRow(int y, int x) { - Optional> option = getOptionalLayer(y); - if (option.isPresent()) - return option.get().getOptionalRow(x); - return Optional.empty(); - } - - public Optional> getOptionalValue(int x, int z) { - Optional> option = getOptionalRow(0, x); - if (option.isPresent()) - return option.get().getOptionalValue(x); - return Optional.empty(); - } - - public Optional> getOptionalValue(int y, int x, int z) { - Optional> option = getOptionalRow(y, x); - if (option.isPresent()) - return option.get().getOptionalValue(x); - return Optional.empty(); - } - - public Optional> getOptionalValue(int[] location) { - if (location == null || location.length < 2) - return Optional.empty(); - if (location.length == 2) - return getOptionalValue(location[0], location[1]); - return getOptionalValue(location[0], location[1], location[2]); - } - - public GridLayer getLayer(int y) { - return getOptionalLayer(y).orElse(null); - } - - public GridRow getRow(int y, int x) { - return getOptionalRow(y, x).orElse(null); - } - - public GridValue getValue(int x, int z) { - return getOptionalValue(0, x, z).orElse(null); - } - - public GridValue getValue(int y, int x, int z) { - return getOptionalValue(y, x, z).orElse(null); - } - - public GridValue getValue(int[] location) { - return getOptionalValue(location).orElse(null); - } + private final GridType type; + + public GridType getType() { + return type; + } + + /* + * + */ + + private ArrayList> layers = new ArrayList<>(1); + + public GridMap(GridType type) { + this.type = type; + } + + /* + * + */ + + @SuppressWarnings("unchecked") + public GridLayer[] getLayers() { + return layers.toArray(new GridLayer[0]); + } + + /* + * + */ + + public long getEntryCount() { + if (layers.isEmpty()) { + return 0; + } + long output = 0; + for (GridLayer layer : layers) { + output = +layer.getEntryCount(); + } + return output; + } + + /* + * + */ + + public int getHeighestY() { + if (layers.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getY()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestY() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getY()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + public int getHeighestX() { + if (layers.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getHeighestX()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestX() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getLowestX()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + public int getHeighestZ() { + if (layers.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getHeighestZ()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestZ() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridLayer layer : layers) { + if ((buffer = layer.getLowestZ()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + /* + * + */ + + public int getHeight() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridLayer layer : layers) { + int depth = layer.getY(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + public int getWidth() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridLayer layer : layers) { + int depth = layer.getWidth(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + public int getDepth() { + if (layers.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridLayer layer : layers) { + int depth = layer.getDepth(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + /* + * + */ + + public void clear() { + layers.forEach(layer -> layer.clear()); + layers.clear(); + } + + public GridMap set(int[] array, V value) { + if (array.length < 2) { + return this; + } + return array.length == 2 ? set(array[0], array[1], value) : set(array[0], array[1], array[2], value); + } + + public GridMap set(int x, int z, V value) { + return set(x, 0, z, value); + } + + public GridMap set(int y, int x, int z, V value) { + if (value == null) { + return this; + } + GridLayer layer; + if (type.is2D()) { + if (layers.isEmpty()) { + layer = new GridLayer<>(); + layer.setY(y); + layers.add(layer); + } else { + layer = layers.get(0); + } + } else { + Optional> option = getOptionalLayer(y); + if (!option.isPresent()) { + layer = new GridLayer<>(); + layer.setY(y); + layers.add(layer); + } else { + layer = option.get(); + } + } + layer.set(x, z, value); + return this; + } + + public GridMap remove(int y) { + Optional> option = getOptionalLayer(y); + if (option.isPresent()) { + layers.remove(option.get()); + } + return this; + } + + public GridMap remove(int y, int x) { + Optional> option = getOptionalLayer(y); + if (option.isPresent()) { + option.get().remove(x); + } + return this; + } + + public GridMap remove(int y, int x, int z) { + Optional> option = getOptionalLayer(y); + if (option.isPresent()) { + option.get().remove(x, z); + } + return this; + } + + public boolean contains(int y) { + return getOptionalLayer(y).isPresent(); + } + + public boolean contains(int y, int x) { + Optional> layer = getOptionalLayer(x); + return layer.isPresent() ? layer.get().contains(x) : false; + } + + public boolean contains(int y, int x, int z) { + Optional> layer = getOptionalLayer(x); + return layer.isPresent() ? layer.get().contains(x, z) : false; + } + + /* + * + */ + + public Optional> getOptionalLayer(int y) { + return layers.stream().filter(layer -> layer.getY() == y).findFirst(); + } + + public Optional> getOptionalRow(int y, int x) { + Optional> option = getOptionalLayer(y); + if (option.isPresent()) { + return option.get().getOptionalRow(x); + } + return Optional.empty(); + } + + public Optional> getOptionalValue(int x, int z) { + Optional> option = getOptionalRow(0, x); + if (option.isPresent()) { + return option.get().getOptionalValue(x); + } + return Optional.empty(); + } + + public Optional> getOptionalValue(int y, int x, int z) { + Optional> option = getOptionalRow(y, x); + if (option.isPresent()) { + return option.get().getOptionalValue(x); + } + return Optional.empty(); + } + + public Optional> getOptionalValue(int[] location) { + if (location == null || location.length < 2) { + return Optional.empty(); + } + if (location.length == 2) { + return getOptionalValue(location[0], location[1]); + } + return getOptionalValue(location[0], location[1], location[2]); + } + + public GridLayer getLayer(int y) { + return getOptionalLayer(y).orElse(null); + } + + public GridRow getRow(int y, int x) { + return getOptionalRow(y, x).orElse(null); + } + + public GridValue getValue(int x, int z) { + return getOptionalValue(0, x, z).orElse(null); + } + + public GridValue getValue(int y, int x, int z) { + return getOptionalValue(y, x, z).orElse(null); + } + + public GridValue getValue(int[] location) { + return getOptionalValue(location).orElse(null); + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridRow.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridRow.java index 7eba445..050ddfc 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridRow.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridRow.java @@ -5,135 +5,142 @@ public final class GridRow { - private final ArrayList> values = new ArrayList<>(); - private int x; - - /* - * - */ - - @SuppressWarnings("unchecked") - public GridValue[] getValues() { - return values.toArray(new GridValue[0]); - } - - /* - * - */ - - public long getEntryCount() { - return values.size(); - } - - /* - * - */ - - public int getX() { - return x; - } - - protected void setX(int x) { - this.x = x; - } - - /* - * - */ - - public int getHeighestZ() { - if (values.isEmpty()) - return 0; - int heighest = 0; - int buffer; - for (GridValue value : values) - if ((buffer = value.getZ()) > heighest) - heighest = buffer; - return heighest; - } - - public int getLowestZ() { - if (values.isEmpty()) - return 0; - int lowest = 0; - int buffer; - for (GridValue value : values) - if ((buffer = value.getZ()) < lowest) - lowest = buffer; - return lowest; - } - - /* - * - */ - - public int getDepth() { - if (values.isEmpty()) { - return 0; - } - int lowest = 0; - int heighest = 0; - for (GridValue value : values) { - int depth = value.getZ(); - if (depth > heighest) { - heighest = depth; - } else if (depth < lowest) { - lowest = depth; - } - } - return Math.abs(lowest - heighest); - } - - /* - * - */ - - public void clear() { - values.clear(); - } - - public GridRow set(int z, V value) { - if (value == null) - return this; - Optional> option = getOptionalValue(z); - GridValue grid; - if (!option.isPresent()) { - grid = new GridValue<>(); - grid.setZ(z); - values.add(grid); - } else { - grid = option.get(); - } - grid.setValue(value); - return this; - } - - public GridRow remove(int z) { - Optional> option = getOptionalValue(z); - if (option.isPresent()) { - values.remove(option.get()); - } - return this; - } - - public boolean contains(int z) { - return getOptionalValue(z).isPresent(); - } - - public boolean contains(V value) { - return values.stream().anyMatch(grid -> grid.getValue().equals(value)); - } - - /* - * - */ - - public Optional> getOptionalValue(int z) { - return values.stream().filter(value -> value.getZ() == z).findFirst(); - } - - public GridValue getValue(int z) { - return getOptionalValue(z).orElse(null); - } + private final ArrayList> values = new ArrayList<>(); + private int x; + + /* + * + */ + + @SuppressWarnings("unchecked") + public GridValue[] getValues() { + return values.toArray(new GridValue[0]); + } + + /* + * + */ + + public long getEntryCount() { + return values.size(); + } + + /* + * + */ + + public int getX() { + return x; + } + + protected void setX(int x) { + this.x = x; + } + + /* + * + */ + + public int getHeighestZ() { + if (values.isEmpty()) { + return 0; + } + int heighest = 0; + int buffer; + for (GridValue value : values) { + if ((buffer = value.getZ()) > heighest) { + heighest = buffer; + } + } + return heighest; + } + + public int getLowestZ() { + if (values.isEmpty()) { + return 0; + } + int lowest = 0; + int buffer; + for (GridValue value : values) { + if ((buffer = value.getZ()) < lowest) { + lowest = buffer; + } + } + return lowest; + } + + /* + * + */ + + public int getDepth() { + if (values.isEmpty()) { + return 0; + } + int lowest = 0; + int heighest = 0; + for (GridValue value : values) { + int depth = value.getZ(); + if (depth > heighest) { + heighest = depth; + } else if (depth < lowest) { + lowest = depth; + } + } + return Math.abs(lowest - heighest); + } + + /* + * + */ + + public void clear() { + values.clear(); + } + + public GridRow set(int z, V value) { + if (value == null) { + return this; + } + Optional> option = getOptionalValue(z); + GridValue grid; + if (!option.isPresent()) { + grid = new GridValue<>(); + grid.setZ(z); + values.add(grid); + } else { + grid = option.get(); + } + grid.setValue(value); + return this; + } + + public GridRow remove(int z) { + Optional> option = getOptionalValue(z); + if (option.isPresent()) { + values.remove(option.get()); + } + return this; + } + + public boolean contains(int z) { + return getOptionalValue(z).isPresent(); + } + + public boolean contains(V value) { + return values.stream().anyMatch(grid -> grid.getValue().equals(value)); + } + + /* + * + */ + + public Optional> getOptionalValue(int z) { + return values.stream().filter(value -> value.getZ() == z).findFirst(); + } + + public GridValue getValue(int z) { + return getOptionalValue(z).orElse(null); + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridType.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridType.java index 98a6c26..50c2d7a 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridType.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridType.java @@ -2,21 +2,21 @@ public enum GridType { - GRID_2D(true), - GRID_3D; + GRID_2D(true), + GRID_3D; - private final boolean twoDimensions; + private final boolean twoDimensions; - private GridType() { - this.twoDimensions = false; - } + private GridType() { + this.twoDimensions = false; + } - private GridType(boolean twoDimensions) { - this.twoDimensions = twoDimensions; - } + private GridType(boolean twoDimensions) { + this.twoDimensions = twoDimensions; + } - public boolean is2D() { - return twoDimensions; - } + public boolean is2D() { + return twoDimensions; + } } diff --git a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridValue.java b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridValue.java index 9084663..6011394 100644 --- a/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridValue.java +++ b/utils/location/src/main/java/com/syntaxphoenix/syntaxapi/utils/position/grid/GridValue.java @@ -2,35 +2,36 @@ public final class GridValue { - private int z; - private V value; - - /* - * - */ - - public int getZ() { - return z; - } - - protected GridValue setZ(int z) { - this.z = z; - return this; - } - - /* - * - */ - - public V getValue() { - return value; - } - - protected GridValue setValue(V value) { - if (value == null) - return this; - this.value = value; - return this; - } + private int z; + private V value; + + /* + * + */ + + public int getZ() { + return z; + } + + protected GridValue setZ(int z) { + this.z = z; + return this; + } + + /* + * + */ + + public V getValue() { + return value; + } + + protected GridValue setValue(V value) { + if (value == null) { + return this; + } + this.value = value; + return this; + } } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/DefaultVersion.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/DefaultVersion.java index cc61fbc..98e64b2 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/DefaultVersion.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/DefaultVersion.java @@ -9,52 +9,52 @@ */ public class DefaultVersion extends Version { - public DefaultVersion() { - super(); - } - - public DefaultVersion(int major, int minor, int patch) { - super(major, minor, patch); - } - - /* - * - */ - - @Override - protected DefaultVersion init(int major, int minor, int patch) { - return new DefaultVersion(major, minor, patch); - } - - @Override - public VersionAnalyzer getAnalyzer() { - return formatted -> { - DefaultVersion version = new DefaultVersion(); - String[] parts = formatted.contains(".") ? formatted.split("\\.") - : new String[] { - formatted - }; - try { - if (parts.length == 1) { - version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); - } else if (parts.length == 2) { - version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); - version.setMinor(Strings.isNumeric(parts[1]) ? Integer.parseInt(parts[1]) : 0); - } else { - version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); - version.setMinor(Strings.isNumeric(parts[1]) ? Integer.parseInt(parts[1]) : 0); - version.setPatch(Strings.isNumeric(parts[2]) ? Integer.parseInt(parts[2]) : 0); - } - } catch (NumberFormatException ex) { - - } - return version; - }; - } - - @Override - public VersionFormatter getFormatter() { - return version -> version.getMajor() + "." + version.getMinor() + "." + version.getPatch(); - } + public DefaultVersion() { + super(); + } + + public DefaultVersion(int major, int minor, int patch) { + super(major, minor, patch); + } + + /* + * + */ + + @Override + protected DefaultVersion init(int major, int minor, int patch) { + return new DefaultVersion(major, minor, patch); + } + + @Override + public VersionAnalyzer getAnalyzer() { + return formatted -> { + DefaultVersion version = new DefaultVersion(); + String[] parts = formatted.contains(".") ? formatted.split("\\.") + : new String[] { + formatted + }; + try { + if (parts.length == 1) { + version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); + } else if (parts.length == 2) { + version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); + version.setMinor(Strings.isNumeric(parts[1]) ? Integer.parseInt(parts[1]) : 0); + } else { + version.setMajor(Strings.isNumeric(parts[0]) ? Integer.parseInt(parts[0]) : 0); + version.setMinor(Strings.isNumeric(parts[1]) ? Integer.parseInt(parts[1]) : 0); + version.setPatch(Strings.isNumeric(parts[2]) ? Integer.parseInt(parts[2]) : 0); + } + } catch (NumberFormatException ex) { + + } + return version; + }; + } + + @Override + public VersionFormatter getFormatter() { + return version -> version.getMajor() + "." + version.getMinor() + "." + version.getPatch(); + } } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/Version.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/Version.java index ca1de00..33302c2 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/Version.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/Version.java @@ -7,164 +7,176 @@ */ public abstract class Version implements Comparable { - private int major; - private int minor; - private int patch; - - /* - * - */ - - public Version() { - major = 0; - minor = 0; - patch = 0; - } - - public Version(int major, int minor, int patch) { - this.major = major; - this.minor = minor; - this.patch = patch; - } - - /* - * - */ - - public int getMajor() { - return major; - } - - public int getMinor() { - return minor; - } - - public int getPatch() { - return patch; - } - - /* - * - */ - - protected Version setMajor(int major) { - this.major = major; - return this; - } - - protected Version setMinor(int minor) { - this.minor = minor; - return this; - } - - protected Version setPatch(int patch) { - this.patch = patch; - return this; - } - - /* - * - */ - - // 1.5.3 (isHigher) 0.6.0 FALSCH - // f t f -> true - // ==> f - - -> false - // - // 1.5.3 (isHigher) 0.2.5 FALSCH - // f f t -> true - // ==> f - - -> false - // - // 1.5.3 (isHigher) 1.5.4 RICHTIG - // f f t -> true - // ==> f f t -> true - - public boolean isHigher(Version version) { - if (major > version.major) - return true; - if (major < version.major) - return false; - if (minor > version.minor) - return true; - if (minor < version.minor) - return false; - if (patch > version.patch) - return true; - return false; - } - - public boolean isSimilar(Version version) { - return major == version.major && minor == version.minor && patch == version.patch; - } - - public boolean isLower(Version version) { - if (major < version.major) - return true; - if (major > version.major) - return false; - if (minor < version.minor) - return true; - if (minor > version.minor) - return false; - if (patch < version.patch) - return true; - return false; - } - - /* - * - */ - - @Override - public boolean equals(Object obj) { - if (obj instanceof Version) { - return isSimilar((Version) obj); - } - return false; - } - - /* - * - */ - - @Override - public Version clone() { - return init(major, minor, patch); - } - - public Version update(int major, int minor, int patch) { - return init(this.major + major, this.minor + minor, this.patch + patch); - } - - protected abstract Version init(int major, int minor, int patch); - - /* - * - */ - - public abstract VersionAnalyzer getAnalyzer(); - - public abstract VersionFormatter getFormatter(); - - /* - * - */ - - @Override - public String toString() { - return getFormatter().format(this); - } - - /* - * - */ - - @Override - public int compareTo(Version version) { - if (isLower(version)) - return -1; - if (isHigher(version)) - return 1; - return 0; - } + private int major; + private int minor; + private int patch; + + /* + * + */ + + public Version() { + major = 0; + minor = 0; + patch = 0; + } + + public Version(int major, int minor, int patch) { + this.major = major; + this.minor = minor; + this.patch = patch; + } + + /* + * + */ + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getPatch() { + return patch; + } + + /* + * + */ + + protected Version setMajor(int major) { + this.major = major; + return this; + } + + protected Version setMinor(int minor) { + this.minor = minor; + return this; + } + + protected Version setPatch(int patch) { + this.patch = patch; + return this; + } + + /* + * + */ + + // 1.5.3 (isHigher) 0.6.0 FALSCH + // f t f -> true + // ==> f - - -> false + // + // 1.5.3 (isHigher) 0.2.5 FALSCH + // f f t -> true + // ==> f - - -> false + // + // 1.5.3 (isHigher) 1.5.4 RICHTIG + // f f t -> true + // ==> f f t -> true + + public boolean isHigher(Version version) { + if (major > version.major) { + return true; + } + if (major < version.major) { + return false; + } + if (minor > version.minor) { + return true; + } + if (minor < version.minor) { + return false; + } + if (patch > version.patch) { + return true; + } + return false; + } + + public boolean isSimilar(Version version) { + return major == version.major && minor == version.minor && patch == version.patch; + } + + public boolean isLower(Version version) { + if (major < version.major) { + return true; + } + if (major > version.major) { + return false; + } + if (minor < version.minor) { + return true; + } + if (minor > version.minor) { + return false; + } + if (patch < version.patch) { + return true; + } + return false; + } + + /* + * + */ + + @Override + public boolean equals(Object obj) { + if (obj instanceof Version) { + return isSimilar((Version) obj); + } + return false; + } + + /* + * + */ + + @Override + public Version clone() { + return init(major, minor, patch); + } + + public Version update(int major, int minor, int patch) { + return init(this.major + major, this.minor + minor, this.patch + patch); + } + + protected abstract Version init(int major, int minor, int patch); + + /* + * + */ + + public abstract VersionAnalyzer getAnalyzer(); + + public abstract VersionFormatter getFormatter(); + + /* + * + */ + + @Override + public String toString() { + return getFormatter().format(this); + } + + /* + * + */ + + @Override + public int compareTo(Version version) { + if (isLower(version)) { + return -1; + } + if (isHigher(version)) { + return 1; + } + return 0; + } } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionAnalyzer.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionAnalyzer.java index 777d058..67f75fd 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionAnalyzer.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionAnalyzer.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface VersionAnalyzer { - public Version analyze(String formatted); + public Version analyze(String formatted); } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionFormatter.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionFormatter.java index b8379e9..9633672 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionFormatter.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionFormatter.java @@ -8,6 +8,6 @@ @FunctionalInterface public interface VersionFormatter { - public String format(Version version); + public String format(Version version); } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionManager.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionManager.java index 4461699..088503c 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionManager.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionManager.java @@ -1,6 +1,6 @@ package com.syntaxphoenix.syntaxapi.version; -import static com.syntaxphoenix.syntaxapi.version.VersionState.*; +import static com.syntaxphoenix.syntaxapi.version.VersionState.NOT_COMPATIBLE; import java.util.ArrayList; import java.util.Collections; @@ -14,234 +14,247 @@ @SuppressWarnings("unchecked") public class VersionManager { - protected final EnumMap> versions = new EnumMap<>(VersionState.class); - - protected final VersionState unknown, higher, lower; - - public VersionManager() { - this(NOT_COMPATIBLE, NOT_COMPATIBLE, NOT_COMPATIBLE); - } - - public VersionManager(VersionState unknown, VersionState higher, VersionState lower) { - versions.put(VersionState.SUPPORTED, new ArrayList<>()); - versions.put(VersionState.NOT_SUPPORTED, new ArrayList<>()); - versions.put(VersionState.NOT_TESTED, new ArrayList<>()); - versions.put(VersionState.NOT_COMPATIBLE, new ArrayList<>()); - - this.unknown = unknown; - this.higher = higher; - this.lower = lower; - } - - /* - * - */ - - public VersionState getDefaultStateForUnknownVersions() { - return unknown; - } - - public VersionState getDefaultStateForHigherVersions() { - return higher; - } - - public VersionState getDefaultStateForLowerVersions() { - return lower; - } - - /* - * - */ - - public VersionManager sortAll() { - for (VersionState state : VersionState.values()) { - sort(state); - } - return this; - } - - public VersionManager sort(VersionState state) { - ArrayList versions = this.versions.get(state); - if (versions.isEmpty()) - return this; - Collections.sort(versions); - return this; - } - - /* - * - */ - - public VersionManager clearAll() { - for (VersionState state : VersionState.values()) { - clear(state); - } - return this; - } - - public VersionManager clear(VersionState state) { - ArrayList versions = this.versions.get(state); - if (versions.isEmpty()) - return this; - versions.clear(); - return this; - } - - /* - * - */ - - public VersionManager setAll(VersionState state, V... versions) { - for (V version : versions) { - set(state, version, false); - } - sort(state); - return this; - } - - public VersionManager set(VersionState state, V version) { - return set(state, version, true); - } - - public VersionManager set(VersionState state, V version, boolean sort) { - if (state == null) { - VersionState remove = getState(version); - if (remove != null) { - versions.get(remove).remove(version); - } - } else { - VersionState remove = getActualState(version); - if (remove != state) { - if (remove != null) { - versions.get(remove).remove(version); - } - versions.get(state).add(version); - } - } - if (sort) - sort(state); - return this; - } - - /* - * - */ - - public VersionManager addAll(V... versions) { - return setAll(unknown, versions); - } - - public VersionManager add(V version) { - return set(unknown, version); - } - - /* - * - */ - - public VersionManager removeAll(V... versions) { - return setAll(null, versions); - } - - public VersionManager remove(V version) { - return set(null, version); - } - - /* - * - */ - - public boolean contains(V version) { - return getActualState(version) != null; - } - - public boolean contains(VersionState state, V version) { - return versions.get(state).contains(version); - } - - /* - * - */ - - public V getHighestVersion(VersionState state) { - ArrayList versions = this.versions.get(state); - if (versions.isEmpty()) - return null; - return versions.get(versions.size() - 1); - } - - public V getHighestVersionOf(VersionState... states) { - if (states == null || states.length == 0) - return null; - if (states.length == 1) - return getLowestVersion(states[0]); - V highest = null; - for (int index = 0; index < states.length; index++) { - V current = getHighestVersion(states[index]); - if (highest != null && !current.isHigher(highest)) - continue; - highest = current; - } - return highest; - } - - public V getLowestVersion(VersionState state) { - ArrayList versions = this.versions.get(state); - if (versions.isEmpty()) - return null; - return versions.get(0); - } - - public V getLowestVersionOf(VersionState... states) { - if (states == null || states.length == 0) - return null; - if (states.length == 1) - return getLowestVersion(states[0]); - V lowest = null; - for (int index = 0; index < states.length; index++) { - V current = getLowestVersion(states[index]); - if (lowest != null && !current.isLower(lowest)) - continue; - lowest = current; - } - return lowest; - } - - /* - * - */ - - public ArrayList getVersions(VersionState state) { - return (ArrayList) this.versions.get(state).clone(); - } - - /* - * - */ - - public VersionState getActualState(V version) { - for (VersionState state : VersionState.values()) { - if (contains(state, version)) { - return state; - } - } - return null; - } - - public VersionState getState(V version) { - VersionState[] states = VersionState.values(); - for (int index = 0; index < states.length; index++) { - if (contains(states[index], version)) { - return states[index]; - } - } - V lowest = getLowestVersionOf(VersionState.SUPPORTED, VersionState.NOT_TESTED); - if (lowest != null && version.isLower(lowest)) - return lower; - V highest = getHighestVersionOf(VersionState.SUPPORTED, VersionState.NOT_TESTED); - if (highest != null && version.isHigher(highest)) - return higher; - return unknown; - } + protected final EnumMap> versions = new EnumMap<>(VersionState.class); + + protected final VersionState unknown, higher, lower; + + public VersionManager() { + this(NOT_COMPATIBLE, NOT_COMPATIBLE, NOT_COMPATIBLE); + } + + public VersionManager(VersionState unknown, VersionState higher, VersionState lower) { + versions.put(VersionState.SUPPORTED, new ArrayList<>()); + versions.put(VersionState.NOT_SUPPORTED, new ArrayList<>()); + versions.put(VersionState.NOT_TESTED, new ArrayList<>()); + versions.put(VersionState.NOT_COMPATIBLE, new ArrayList<>()); + + this.unknown = unknown; + this.higher = higher; + this.lower = lower; + } + + /* + * + */ + + public VersionState getDefaultStateForUnknownVersions() { + return unknown; + } + + public VersionState getDefaultStateForHigherVersions() { + return higher; + } + + public VersionState getDefaultStateForLowerVersions() { + return lower; + } + + /* + * + */ + + public VersionManager sortAll() { + for (VersionState state : VersionState.values()) { + sort(state); + } + return this; + } + + public VersionManager sort(VersionState state) { + ArrayList versions = this.versions.get(state); + if (versions.isEmpty()) { + return this; + } + Collections.sort(versions); + return this; + } + + /* + * + */ + + public VersionManager clearAll() { + for (VersionState state : VersionState.values()) { + clear(state); + } + return this; + } + + public VersionManager clear(VersionState state) { + ArrayList versions = this.versions.get(state); + if (versions.isEmpty()) { + return this; + } + versions.clear(); + return this; + } + + /* + * + */ + + public VersionManager setAll(VersionState state, V... versions) { + for (V version : versions) { + set(state, version, false); + } + sort(state); + return this; + } + + public VersionManager set(VersionState state, V version) { + return set(state, version, true); + } + + public VersionManager set(VersionState state, V version, boolean sort) { + if (state == null) { + VersionState remove = getState(version); + if (remove != null) { + versions.get(remove).remove(version); + } + } else { + VersionState remove = getActualState(version); + if (remove != state) { + if (remove != null) { + versions.get(remove).remove(version); + } + versions.get(state).add(version); + } + } + if (sort) { + sort(state); + } + return this; + } + + /* + * + */ + + public VersionManager addAll(V... versions) { + return setAll(unknown, versions); + } + + public VersionManager add(V version) { + return set(unknown, version); + } + + /* + * + */ + + public VersionManager removeAll(V... versions) { + return setAll(null, versions); + } + + public VersionManager remove(V version) { + return set(null, version); + } + + /* + * + */ + + public boolean contains(V version) { + return getActualState(version) != null; + } + + public boolean contains(VersionState state, V version) { + return versions.get(state).contains(version); + } + + /* + * + */ + + public V getHighestVersion(VersionState state) { + ArrayList versions = this.versions.get(state); + if (versions.isEmpty()) { + return null; + } + return versions.get(versions.size() - 1); + } + + public V getHighestVersionOf(VersionState... states) { + if (states == null || states.length == 0) { + return null; + } + if (states.length == 1) { + return getLowestVersion(states[0]); + } + V highest = null; + for (int index = 0; index < states.length; index++) { + V current = getHighestVersion(states[index]); + if (highest != null && !current.isHigher(highest)) { + continue; + } + highest = current; + } + return highest; + } + + public V getLowestVersion(VersionState state) { + ArrayList versions = this.versions.get(state); + if (versions.isEmpty()) { + return null; + } + return versions.get(0); + } + + public V getLowestVersionOf(VersionState... states) { + if (states == null || states.length == 0) { + return null; + } + if (states.length == 1) { + return getLowestVersion(states[0]); + } + V lowest = null; + for (int index = 0; index < states.length; index++) { + V current = getLowestVersion(states[index]); + if (lowest != null && !current.isLower(lowest)) { + continue; + } + lowest = current; + } + return lowest; + } + + /* + * + */ + + public ArrayList getVersions(VersionState state) { + return (ArrayList) this.versions.get(state).clone(); + } + + /* + * + */ + + public VersionState getActualState(V version) { + for (VersionState state : VersionState.values()) { + if (contains(state, version)) { + return state; + } + } + return null; + } + + public VersionState getState(V version) { + VersionState[] states = VersionState.values(); + for (int index = 0; index < states.length; index++) { + if (contains(states[index], version)) { + return states[index]; + } + } + V lowest = getLowestVersionOf(VersionState.SUPPORTED, VersionState.NOT_TESTED); + if (lowest != null && version.isLower(lowest)) { + return lower; + } + V highest = getHighestVersionOf(VersionState.SUPPORTED, VersionState.NOT_TESTED); + if (highest != null && version.isHigher(highest)) { + return higher; + } + return unknown; + } } diff --git a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionState.java b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionState.java index 73a82e9..33d88a6 100644 --- a/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionState.java +++ b/version/src/main/java/com/syntaxphoenix/syntaxapi/version/VersionState.java @@ -7,9 +7,9 @@ */ public enum VersionState { - SUPPORTED, - NOT_SUPPORTED, - NOT_TESTED, - NOT_COMPATIBLE; + SUPPORTED, + NOT_SUPPORTED, + NOT_TESTED, + NOT_COMPATIBLE; }