From 345383282c5e468add2ab0b2cd2f0c37ba3f0c78 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 17:59:58 +0000 Subject: [PATCH 1/7] Move to Java implementation of common utilities. Make closeable an auto-closeable and allow try-with-resources. Deprecate unused case insensitive strings for removal. --- .../ch/njol/skript/doc/Documentation.java | 8 ++--- src/main/java/ch/njol/skript/util/Utils.java | 2 +- src/main/java/ch/njol/util/Callback.java | 17 +++++++++-- .../ch/njol/util/CaseInsensitiveString.java | 30 +++++++++++-------- src/main/java/ch/njol/util/Closeable.java | 12 ++++---- src/main/java/ch/njol/util/StringUtils.java | 7 +++-- 6 files changed, 46 insertions(+), 30 deletions(-) diff --git a/src/main/java/ch/njol/skript/doc/Documentation.java b/src/main/java/ch/njol/skript/doc/Documentation.java index 73b158b1a9d..49d90a1f265 100644 --- a/src/main/java/ch/njol/skript/doc/Documentation.java +++ b/src/main/java/ch/njol/skript/doc/Documentation.java @@ -11,7 +11,6 @@ import ch.njol.skript.lang.function.Parameter; import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.Utils; -import ch.njol.util.Callback; import ch.njol.util.NonNullPair; import ch.njol.util.StringUtils; import ch.njol.util.coll.CollectionUtils; @@ -26,6 +25,7 @@ import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.ArrayList; +import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -187,7 +187,7 @@ protected static String cleanPatterns(String patterns, boolean escapeHTML) { cleanedPatterns = CP_PARSE_TAGS_PATTERN.matcher(cleanedPatterns).replaceAll(""); // Remove new parse tags, see https://regex101.com/r/mTebpn/1 cleanedPatterns = CP_EXTRA_OPTIONAL_PATTERN.matcher(cleanedPatterns).replaceAll("[$1]"); // Remove unnecessary parentheses such as [(script)] - Callback callback = m -> { // Replace optional parentheses with optional brackets + Function callback = m -> { // Replace optional parentheses with optional brackets String group = m.group(); boolean startToEnd = group.contains("(|"); // Due to regex limitation we search from the beginning to the end but if it has '|)' we will begin from the opposite direction @@ -246,9 +246,9 @@ protected static String cleanPatterns(String patterns, boolean escapeHTML) { assert cleanedPatterns != null; final String s = StringUtils.replaceAll(cleanedPatterns, "(?() { + new Function() { @Override - public String run(final Matcher m) { + public String apply(final Matcher m) { String s = m.group(1); if (s.startsWith("-")) s = s.substring(1); diff --git a/src/main/java/ch/njol/skript/util/Utils.java b/src/main/java/ch/njol/skript/util/Utils.java index d9704829b9b..0d6f81e9b6e 100644 --- a/src/main/java/ch/njol/skript/util/Utils.java +++ b/src/main/java/ch/njol/skript/util/Utils.java @@ -6,6 +6,7 @@ import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.CompletableFuture; +import java.util.function.Function; import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; @@ -30,7 +31,6 @@ import ch.njol.skript.localization.Language; import ch.njol.skript.localization.LanguageChangeListener; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Callback; import ch.njol.util.Checker; import ch.njol.util.NonNullPair; import ch.njol.util.Pair; diff --git a/src/main/java/ch/njol/util/Callback.java b/src/main/java/ch/njol/util/Callback.java index ac0ddadbdc8..64bdbf0d19b 100644 --- a/src/main/java/ch/njol/util/Callback.java +++ b/src/main/java/ch/njol/util/Callback.java @@ -1,10 +1,21 @@ package ch.njol.util; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.ApiStatus; + +import java.util.function.Function; + +@Deprecated +@FunctionalInterface +@ApiStatus.ScheduledForRemoval +public interface Callback extends Function { -public interface Callback { - @Nullable public R run(A arg); - + + @Override + default R apply(A a) { + return run(a); + } + } diff --git a/src/main/java/ch/njol/util/CaseInsensitiveString.java b/src/main/java/ch/njol/util/CaseInsensitiveString.java index 257fb791f47..bc4562eb9e2 100644 --- a/src/main/java/ch/njol/util/CaseInsensitiveString.java +++ b/src/main/java/ch/njol/util/CaseInsensitiveString.java @@ -1,5 +1,7 @@ package ch.njol.util; +import org.jetbrains.annotations.ApiStatus; + import java.io.Serializable; import java.util.Locale; @@ -9,36 +11,38 @@ /** * A string which is compared ignoring it's case. - * + * * @author Peter Güttinger */ +@Deprecated +@ApiStatus.ScheduledForRemoval public class CaseInsensitiveString implements Serializable, Comparable, CharSequence { - + private static final long serialVersionUID = 1205018864604639962L; - + private final String s; private final String lc; - + private final Locale locale; - + @SuppressWarnings("null") public CaseInsensitiveString(final String s) { this.s = s; locale = Locale.getDefault(); lc = "" + s.toLowerCase(locale); } - + public CaseInsensitiveString(final String s, final Locale locale) { this.s = s; this.locale = locale; lc = "" + s.toLowerCase(locale); } - + @Override public int hashCode() { return lc.hashCode(); } - + @SuppressWarnings("null") @Override public boolean equals(final @Nullable Object o) { @@ -48,27 +52,27 @@ public boolean equals(final @Nullable Object o) { return ((CharSequence) o).toString().toLowerCase(locale).equals(lc); return false; } - + @Override public String toString() { return s; } - + @Override public char charAt(final int i) { return s.charAt(i); } - + @Override public int length() { return s.length(); } - + @Override public CaseInsensitiveString subSequence(final int start, final int end) { return new CaseInsensitiveString("" + s.substring(start, end), locale); } - + @SuppressWarnings("null") @Override public int compareTo(final CharSequence s) { diff --git a/src/main/java/ch/njol/util/Closeable.java b/src/main/java/ch/njol/util/Closeable.java index 11c7c358c09..75ed886ac20 100644 --- a/src/main/java/ch/njol/util/Closeable.java +++ b/src/main/java/ch/njol/util/Closeable.java @@ -2,15 +2,15 @@ /** * Like {@link java.io.Closeable}, but not used for resources, thus it neither throws checked exceptions nor causes resource leak warnings. - * - * @author Peter Güttinger + * + * This is an auto-closeable resource and so may be used within a try-with-resources section for automatic disposal. */ -public interface Closeable { - +public interface Closeable extends AutoCloseable { + /** * Closes this object. This method may be called multiple times and may or may not have an effect on subsequent calls (e.g. a task might be stopped, but resumed later and * stopped again). */ - public void close(); - + void close(); + } diff --git a/src/main/java/ch/njol/util/StringUtils.java b/src/main/java/ch/njol/util/StringUtils.java index ebd4636d69d..6a48d73b635 100644 --- a/src/main/java/ch/njol/util/StringUtils.java +++ b/src/main/java/ch/njol/util/StringUtils.java @@ -2,6 +2,7 @@ import java.util.Iterator; import java.util.Locale; +import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -46,7 +47,7 @@ public static String fancyOrderNumber(int i) { */ @SuppressWarnings("null") @Nullable - public static String replaceAll(final CharSequence string, final String regex, final Callback callback) { + public static String replaceAll(final CharSequence string, final String regex, final Function callback) { return replaceAll(string, Pattern.compile(regex), callback); } @@ -60,11 +61,11 @@ public static String replaceAll(final CharSequence string, final String regex, f * @return */ @Nullable - public static String replaceAll(final CharSequence string, final Pattern regex, final Callback callback) { + public static String replaceAll(final CharSequence string, final Pattern regex, final Function callback) { final Matcher m = regex.matcher(string); final StringBuffer sb = new StringBuffer(); while (m.find()) { - final String r = callback.run(m); + final String r = callback.apply(m); if (r == null) return null; m.appendReplacement(sb, r); From 7e2021ac9b81d3474e85103eac0d66d60d0cfc19 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:01:26 +0000 Subject: [PATCH 2/7] Deprecate outdated utils/vector math (#6664) * Mark VectorMath as internal * Replace usages --- .../expressions/ExprVectorCylindrical.java | 25 ++- .../ExprVectorFromYawAndPitch.java | 50 +++++- .../expressions/ExprVectorSpherical.java | 28 ++- .../njol/skript/expressions/ExprYawPitch.java | 100 ++++++++--- src/main/java/ch/njol/util/VectorMath.java | 166 ++++-------------- 5 files changed, 203 insertions(+), 166 deletions(-) diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java index 476d785bec2..be649dd4a4a 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java @@ -14,8 +14,11 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; -import ch.njol.util.VectorMath; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.util.Vector; +import org.eclipse.jdt.annotation.Nullable; +import org.jetbrains.annotations.ApiStatus; @Name("Vectors - Cylindrical Shape") @Description("Forms a 'cylindrical shaped' vector using yaw to manipulate the current point.") @@ -27,6 +30,8 @@ @Since("2.2-dev28") public class ExprVectorCylindrical extends SimpleExpression { + private static final double DEG_TO_RAD = Math.PI / 180; + static { Skript.registerExpression(ExprVectorCylindrical.class, Vector.class, ExpressionType.SIMPLE, "[a] [new] cylindrical vector [from|with] [radius] %number%, [yaw] %number%(,[ and]| and) [height] %number%"); @@ -52,7 +57,7 @@ protected Vector[] get(Event event) { Number height = this.height.getSingle(event); if (radius == null || yaw == null || height == null) return null; - return CollectionUtils.array(VectorMath.fromCylindricalCoordinates(radius.doubleValue(), VectorMath.fromSkriptYaw(yaw.floatValue()), height.doubleValue())); + return CollectionUtils.array(fromCylindricalCoordinates(radius.doubleValue(), fromSkriptYaw(yaw.floatValue()), height.doubleValue())); } @Override @@ -71,4 +76,20 @@ public String toString(@Nullable Event event, boolean debug) { yaw.toString(event, debug) + " and height " + height.toString(event, debug); } + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static Vector fromCylindricalCoordinates(double radius, double phi, double height) { + double r = Math.abs(radius); + double p = phi * DEG_TO_RAD; + double x = r * Math.cos(p); + double z = r * Math.sin(p); + return new Vector(x, height, z); + } + + private static float fromSkriptYaw(float yaw) { + return yaw > 270 + ? yaw - 270 + : yaw + 90; + } + } diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java index f98cb52838e..d7b065e013d 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java @@ -14,8 +14,11 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; -import ch.njol.util.VectorMath; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.util.Vector; +import org.eclipse.jdt.annotation.Nullable; +import org.jetbrains.annotations.ApiStatus; @Name("Vectors - Vector from Pitch and Yaw") @Description("Creates a vector from a yaw and pitch value.") @@ -23,6 +26,8 @@ @Since("2.2-dev28") public class ExprVectorFromYawAndPitch extends SimpleExpression { + private static final double DEG_TO_RAD = Math.PI / 180; + static { Skript.registerExpression(ExprVectorFromYawAndPitch.class, Vector.class, ExpressionType.COMBINED, "[a] [new] vector (from|with) yaw %number% and pitch %number%"); @@ -46,9 +51,9 @@ protected Vector[] get(Event event) { Number skriptPitch = pitch.getSingle(event); if (skriptYaw == null || skriptPitch == null) return null; - float yaw = VectorMath.fromSkriptYaw(VectorMath.wrapAngleDeg(skriptYaw.floatValue())); - float pitch = VectorMath.fromSkriptPitch(VectorMath.wrapAngleDeg(skriptPitch.floatValue())); - return CollectionUtils.array(VectorMath.fromYawAndPitch(yaw, pitch)); + float yaw = fromSkriptYaw(wrapAngleDeg(skriptYaw.floatValue())); + float pitch = fromSkriptPitch(wrapAngleDeg(skriptPitch.floatValue())); + return CollectionUtils.array(fromYawAndPitch(yaw, pitch)); } @Override @@ -66,4 +71,41 @@ public String toString(@Nullable Event event, boolean debug) { return "vector from yaw " + yaw.toString(event, debug) + " and pitch " + pitch.toString(event, debug); } + private static Vector fromYawAndPitch(float yaw, float pitch) { + double y = Math.sin(pitch * DEG_TO_RAD); + double div = Math.cos(pitch * DEG_TO_RAD); + double x = Math.cos(yaw * DEG_TO_RAD); + double z = Math.sin(yaw * DEG_TO_RAD); + x *= div; + z *= div; + return new Vector(x,y,z); + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float wrapAngleDeg(float angle) { + angle %= 360f; + if (angle <= -180) { + return angle + 360; + } else if (angle > 180) { + return angle - 360; + } else { + return angle; + } + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float fromSkriptYaw(float yaw) { + return yaw > 270 + ? yaw - 270 + : yaw + 90; + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float fromSkriptPitch(float pitch) { + return -pitch; + } + } diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java index cf19b65d047..250fa602a72 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java @@ -14,8 +14,11 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; -import ch.njol.util.VectorMath; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.util.Vector; +import org.eclipse.jdt.annotation.Nullable; +import org.jetbrains.annotations.ApiStatus; @Name("Vectors - Spherical Shape") @Description("Forms a 'spherical shaped' vector using yaw and pitch to manipulate the current point.") @@ -27,6 +30,8 @@ @Since("2.2-dev28") public class ExprVectorSpherical extends SimpleExpression { + private static final double DEG_TO_RAD = Math.PI / 180; + static { Skript.registerExpression(ExprVectorSpherical.class, Vector.class, ExpressionType.SIMPLE, "[a] [new] spherical vector [(from|with)] [radius] %number%, [yaw] %number%(,[ and]| and) [pitch] %number%"); @@ -52,7 +57,7 @@ protected Vector[] get(Event event) { Number pitch = this.pitch.getSingle(event); if (radius == null || yaw == null || pitch == null) return null; - return CollectionUtils.array(VectorMath.fromSphericalCoordinates(radius.doubleValue(), VectorMath.fromSkriptYaw(yaw.floatValue()), pitch.floatValue() + 90)); + return CollectionUtils.array(fromSphericalCoordinates(radius.doubleValue(), fromSkriptYaw(yaw.floatValue()), pitch.floatValue() + 90)); } @Override @@ -71,4 +76,23 @@ public String toString(@Nullable Event event, boolean debug) { " and pitch" + pitch.toString(event, debug); } + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static Vector fromSphericalCoordinates(double radius, double theta, double phi) { + double r = Math.abs(radius); + double t = theta * DEG_TO_RAD; + double p = phi * DEG_TO_RAD; + double sinp = Math.sin(p); + double x = r * sinp * Math.cos(t); + double y = r * Math.cos(p); + double z = r * sinp * Math.sin(t); + return new Vector(x, y, z); + } + + private static float fromSkriptYaw(float yaw) { + return yaw > 270 + ? yaw - 270 + : yaw + 90; + } + } diff --git a/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java b/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java index 0ec30f2048c..3d5ffe12300 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java +++ b/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java @@ -1,14 +1,5 @@ package ch.njol.skript.expressions; -import ch.njol.skript.ServerPlatform; -import ch.njol.skript.Skript; -import ch.njol.skript.doc.RequiredPlugins; -import ch.njol.util.VectorMath; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; - import ch.njol.skript.classes.Changer.ChangeMode; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -19,8 +10,10 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.Location; +import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.ApiStatus; @Name("Yaw / Pitch") @Description({ @@ -40,6 +33,9 @@ @RequiredPlugins("Paper 1.19+ (player changers)") public class ExprYawPitch extends SimplePropertyExpression { + private static final double DEG_TO_RAD = Math.PI / 180; + private static final double RAD_TO_DEG = 180 / Math.PI; + static { register(ExprYawPitch.class, Float.class, "(:yaw|pitch)", "entities/locations/vectors"); } @@ -68,10 +64,10 @@ public Float convert(Object object) { ? normalizeYaw(location.getYaw()) : location.getPitch(); } else if (object instanceof Vector) { - Vector vector = (Vector) object; - return usesYaw - ? VectorMath.skriptYaw((VectorMath.getYaw(vector))) - : VectorMath.skriptPitch(VectorMath.getPitch(vector)); + Vector vector = ((Vector) object); + if (usesYaw) + return skriptYaw(getYaw(vector)); + return skriptPitch(getPitch(vector)); } return null; } @@ -174,26 +170,28 @@ private void changeForLocation(Location location, float value, ChangeMode mode) } } - private void changeForVector(Vector vector, float value, ChangeMode mode) { - float yaw = VectorMath.getYaw(vector); - float pitch = VectorMath.getPitch(vector); + private void changeVector(Vector vector, float n, ChangeMode mode) { + float yaw = getYaw(vector); + float pitch = getPitch(vector); switch (mode) { case REMOVE: value = -value; // $FALL-THROUGH$ case ADD: - if (usesYaw) { - yaw += value; - } else { - // Subtracting because of Minecraft's upside-down pitch. - pitch -= value; - } + if (usesYaw) + yaw += n; + else + pitch -= n; // Negative because of Minecraft's / Skript's upside down pitch + Vector newVector = fromYawAndPitch(yaw, pitch).multiply(vector.length()); + vector.copy(newVector); break; case SET: if (usesYaw) - yaw = VectorMath.fromSkriptYaw(value); + yaw = fromSkriptYaw(n); else - pitch = VectorMath.fromSkriptPitch(value); + pitch = fromSkriptPitch(n); + newVector = fromYawAndPitch(yaw, pitch).multiply(vector.length()); + vector.copy(newVector); } Vector newVector = VectorMath.fromYawAndPitch(yaw, pitch).multiply(vector.length()); VectorMath.copyVector(vector, newVector); @@ -214,4 +212,56 @@ protected String getPropertyName() { return usesYaw ? "yaw" : "pitch"; } + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static Vector fromYawAndPitch(float yaw, float pitch) { + double y = Math.sin(pitch * DEG_TO_RAD); + double div = Math.cos(pitch * DEG_TO_RAD); + double x = Math.cos(yaw * DEG_TO_RAD); + double z = Math.sin(yaw * DEG_TO_RAD); + x *= div; + z *= div; + return new Vector(x,y,z); + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float getYaw(Vector vector) { + if (((Double) vector.getX()).equals((double) 0) && ((Double) vector.getZ()).equals((double) 0)){ + return 0; + } + return (float) (Math.atan2(vector.getZ(), vector.getX()) * RAD_TO_DEG); + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float getPitch(Vector vector) { + double xy = Math.sqrt(vector.getX() * vector.getX() + vector.getZ() * vector.getZ()); + return (float) (Math.atan(vector.getY() / xy) * RAD_TO_DEG); + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float skriptYaw(float yaw) { + return yaw < 90 + ? yaw + 270 + : yaw - 90; + } + + // TODO Mark as private next version after VectorMath deletion + @ApiStatus.Internal + public static float skriptPitch(float pitch) { + return -pitch; + } + + private static float fromSkriptYaw(float yaw) { + return yaw > 270 + ? yaw - 270 + : yaw + 90; + } + + private static float fromSkriptPitch(float pitch) { + return -pitch; + } + } diff --git a/src/main/java/ch/njol/util/VectorMath.java b/src/main/java/ch/njol/util/VectorMath.java index 553d7334d2a..a2e377d221f 100644 --- a/src/main/java/ch/njol/util/VectorMath.java +++ b/src/main/java/ch/njol/util/VectorMath.java @@ -1,183 +1,83 @@ package ch.njol.util; +import ch.njol.skript.effects.EffVectorRotateAroundAnother; +import ch.njol.skript.effects.EffVectorRotateXYZ; +import ch.njol.skript.expressions.ExprVectorCylindrical; +import ch.njol.skript.expressions.ExprVectorFromYawAndPitch; +import ch.njol.skript.expressions.ExprVectorSpherical; +import ch.njol.skript.expressions.ExprYawPitch; import org.bukkit.util.Vector; +import org.jetbrains.annotations.ApiStatus; -/** - * @author bi0qaw - */ -public class VectorMath { +@Deprecated +@ApiStatus.ScheduledForRemoval +public final class VectorMath { public static final double PI = Math.PI; public static final double HALF_PI = PI / 2; - public static final double DEG_TO_RAD = PI / 180; - public static final double RAD_TO_DEG = 180 / PI; + public static final double DEG_TO_RAD = Math.PI / 180; + public static final double RAD_TO_DEG = 180 / Math.PI; + + private VectorMath() {} public static Vector fromSphericalCoordinates(double radius, double theta, double phi) { - double r = Math.abs(radius); - double t = theta * DEG_TO_RAD; - double p = phi * DEG_TO_RAD; - double sinp = Math.sin(p); - double x = r * sinp * Math.cos(t); - double y = r * Math.cos(p); - double z = r * sinp * Math.sin(t); - return new Vector(x, y, z); + return ExprVectorSpherical.fromSphericalCoordinates(radius, theta, phi); } public static Vector fromCylindricalCoordinates(double radius, double phi, double height) { - double r = Math.abs(radius); - double p = phi * DEG_TO_RAD; - double x = r * Math.cos(p); - double z = r * Math.sin(p); - return new Vector(x, height, z); - + return ExprVectorCylindrical.fromCylindricalCoordinates(radius, phi, height); } public static Vector fromYawAndPitch(float yaw, float pitch) { - double y = Math.sin(pitch * DEG_TO_RAD); - double div = Math.cos(pitch * DEG_TO_RAD); - double x = Math.cos(yaw * DEG_TO_RAD); - double z = Math.sin(yaw * DEG_TO_RAD); - x *= div; - z *= div; - return new Vector(x,y,z); + return ExprYawPitch.fromYawAndPitch(yaw, pitch); } public static float getYaw(Vector vector) { - if (((Double) vector.getX()).equals((double) 0) && ((Double) vector.getZ()).equals((double) 0)){ - return 0; - } - return (float) (Math.atan2(vector.getZ(), vector.getX()) * RAD_TO_DEG); + return ExprYawPitch.getYaw(vector); } public static float getPitch(Vector vector) { - double xy = Math.sqrt(vector.getX() * vector.getX() + vector.getZ() * vector.getZ()); - return (float) (Math.atan(vector.getY() / xy) * RAD_TO_DEG); - } - - public static Vector setYaw(Vector vector, float yaw) { - vector = fromYawAndPitch(yaw, getPitch(vector)); - return vector; - } - - public static Vector setPitch(Vector vector, float pitch) { - vector = fromYawAndPitch(getYaw(vector), pitch); - return vector; + return ExprYawPitch.getPitch(vector); } public static Vector rotX(Vector vector, double angle) { - double sin = Math.sin(angle * DEG_TO_RAD); - double cos = Math.cos(angle * DEG_TO_RAD); - Vector vy = new Vector(0, cos, -sin); - Vector vz = new Vector(0, sin, cos); - Vector clone = vector.clone(); - vector.setY(clone.dot(vy)); - vector.setZ(clone.dot(vz)); - return vector; + return EffVectorRotateXYZ.rotX(vector, angle); } public static Vector rotY(Vector vector, double angle) { - double sin = Math.sin(angle * DEG_TO_RAD); - double cos = Math.cos(angle * DEG_TO_RAD); - Vector vx = new Vector(cos, 0, sin); - Vector vz = new Vector(-sin, 0, cos); - Vector clone = vector.clone(); - vector.setX(clone.dot(vx)); - vector.setZ(clone.dot(vz)); - return vector; + return EffVectorRotateXYZ.rotY(vector, angle); } public static Vector rotZ(Vector vector, double angle) { - double sin = Math.sin(angle * DEG_TO_RAD); - double cos = Math.cos(angle * DEG_TO_RAD); - Vector vx = new Vector(cos, -sin, 0); - Vector vy = new Vector(sin, cos, 0); - Vector clone = vector.clone(); - vector.setX(clone.dot(vx)); - vector.setY(clone.dot(vy)); - return vector; + return EffVectorRotateXYZ.rotZ(vector, angle); } public static Vector rot(Vector vector, Vector axis, double angle) { - double sin = Math.sin(angle * DEG_TO_RAD); - double cos = Math.cos(angle * DEG_TO_RAD); - Vector a = axis.clone().normalize(); - double ax = a.getX(); - double ay = a.getY(); - double az = a.getZ(); - Vector rotx = new Vector(cos+ax*ax*(1-cos), ax*ay*(1-cos)-az*sin, ax*az*(1-cos)+ay*sin); - Vector roty = new Vector(ay*ax*(1-cos)+az*sin, cos+ay*ay*(1-cos), ay*az*(1-cos)-ax*sin); - Vector rotz = new Vector(az*ax*(1-cos)-ay*sin, az*ay*(1-cos)+ax*sin, cos+az*az*(1-cos)); - double x = rotx.dot(vector); - double y = roty.dot(vector); - double z = rotz.dot(vector); - vector.setX(x).setY(y).setZ(z); - return vector; - } - - public static float notchYaw(float yaw){ - float y = yaw - 90; - if (y < -180){ - y += 360; - } - return y; + return EffVectorRotateAroundAnother.rot(vector, axis, angle); } - public static float notchPitch(float pitch){ - return -pitch; + public static float skriptYaw(float yaw) { + return ExprYawPitch.skriptYaw(yaw); } - public static float fromNotchYaw(float notchYaw){ - float y = notchYaw + 90; - if (y > 180){ - y -= 360; - } - return y; + public static float skriptPitch(float pitch) { + return ExprYawPitch.skriptPitch(pitch); } - public static float fromNotchPitch(float notchPitch){ - return -notchPitch; + public static float fromSkriptYaw(float yaw) { + return ExprVectorFromYawAndPitch.fromSkriptYaw(yaw); } - public static float skriptYaw(float yaw){ - float y = yaw - 90; - if (y < 0){ - y += 360; - } - return y; - } - - public static float skriptPitch(float pitch){ - return -pitch; - } - - public static float fromSkriptYaw(float yaw){ - float y = yaw + 90; - if (y > 360){ - y -= 360; - } - return y; - } - - public static float fromSkriptPitch(float pitch){ - return -pitch; + public static float fromSkriptPitch(float pitch) { + return ExprVectorFromYawAndPitch.fromSkriptPitch(pitch); } public static float wrapAngleDeg(float angle) { - angle %= 360f; - if (angle <= -180) { - return angle + 360; - } else if (angle > 180) { - return angle - 360; - } else { - return angle; - } + return ExprVectorFromYawAndPitch.wrapAngleDeg(angle); } - /** - * Copies vector components of {@code vector2} into {@code vector1}. - */ public static void copyVector(Vector vector1, Vector vector2) { - vector1.setX(vector2.getX()).setY(vector2.getY()).setZ(vector2.getZ()); + vector1.copy(vector2); } /** From 8d38f9d05b436ad58c9e23f37765a7b0fa705a58 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:02:11 +0000 Subject: [PATCH 3/7] Deprecate and replace Setter with Java's Consumer. (#6667) * Make Setter a Consumer. * Remove Setter from Option. * Remove setter from entry validator. * Remove setter from enum entry validator. * Remove setter from parsed entry validator. * Remove setter from parsed section validator. --- .../java/ch/njol/skript/config/Option.java | 31 +++++++++-------- .../config/validate/EntryValidator.java | 21 ++++++------ .../config/validate/EnumEntryValidator.java | 23 ++++++------- .../config/validate/ParsedEntryValidator.java | 17 +++++----- .../config/validate/SectionValidator.java | 34 +++++++++---------- src/main/java/ch/njol/util/Setter.java | 22 ++++++++---- 6 files changed, 79 insertions(+), 69 deletions(-) diff --git a/src/main/java/ch/njol/skript/config/Option.java b/src/main/java/ch/njol/skript/config/Option.java index e1f3e441573..def15007e27 100644 --- a/src/main/java/ch/njol/skript/config/Option.java +++ b/src/main/java/ch/njol/skript/config/Option.java @@ -1,11 +1,12 @@ package ch.njol.skript.config; +import java.util.Locale; +import java.util.function.Consumer; import ch.njol.skript.Skript; import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.classes.Parser; import ch.njol.skript.lang.ParseContext; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Setter; import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.converter.Converter; @@ -15,19 +16,19 @@ * @author Peter Güttinger */ public class Option { - + public final String key; private boolean optional = false; - + @Nullable private String value = null; private final Converter parser; private final T defaultValue; private T parsedValue; - + @Nullable - private Setter setter; - + private Consumer setter; + public Option(final String key, final T defaultValue) { this.key = "" + key.toLowerCase(Locale.ENGLISH); this.defaultValue = defaultValue; @@ -60,24 +61,24 @@ public T convert(final String s) { }; } } - + public Option(final String key, final T defaultValue, final Converter parser) { this.key = "" + key.toLowerCase(Locale.ENGLISH); this.defaultValue = defaultValue; parsedValue = defaultValue; this.parser = parser; } - - public final Option setter(final Setter setter) { + + public final Option setter(final Consumer setter) { this.setter = setter; return this; } - + public final Option optional(final boolean optional) { this.optional = optional; return this; } - + public final void set(final Config config, final String path) { final String oldValue = value; value = config.getByPath(path + key); @@ -91,12 +92,12 @@ public final void set(final Config config, final String path) { onValueChange(); } } - + protected void onValueChange() { if (setter != null) - setter.set(parsedValue); + setter.accept(parsedValue); } - + public final T value() { return parsedValue; } @@ -108,5 +109,5 @@ public final T defaultValue() { public final boolean isOptional() { return optional; } - + } diff --git a/src/main/java/ch/njol/skript/config/validate/EntryValidator.java b/src/main/java/ch/njol/skript/config/validate/EntryValidator.java index 05f40feb641..c1595bf2d19 100644 --- a/src/main/java/ch/njol/skript/config/validate/EntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/EntryValidator.java @@ -6,24 +6,25 @@ import ch.njol.skript.config.EntryNode; import ch.njol.skript.config.Node; import ch.njol.skript.log.SkriptLogger; -import ch.njol.util.Setter; + +import java.util.function.Consumer; /** * @author Peter Güttinger */ public class EntryValidator implements NodeValidator { - + @Nullable - private final Setter setter; - + private final Consumer setter; + public EntryValidator() { setter = null; } - - public EntryValidator(final Setter setter) { + + public EntryValidator(final Consumer setter) { this.setter = setter; } - + @Override public boolean validate(final Node node) { if (!(node instanceof EntryNode)) { @@ -31,10 +32,10 @@ public boolean validate(final Node node) { return false; } if (setter != null) - setter.set(((EntryNode) node).getValue()); + setter.accept(((EntryNode) node).getValue()); return true; } - + public static void notAnEntryError(final Node node) { notAnEntryError(node, node.getConfig().getSeparator()); } @@ -43,5 +44,5 @@ public static void notAnEntryError(final Node node, String separator) { SkriptLogger.setNode(node); Skript.error("'" + node.getKey() + "' is not an entry (like 'name " + separator + " value')"); } - + } diff --git a/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java b/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java index ccdbf71a612..26015cd898f 100644 --- a/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java @@ -1,25 +1,24 @@ package ch.njol.skript.config.validate; import java.util.Locale; +import java.util.function.Consumer; import org.jetbrains.annotations.Nullable; import ch.njol.skript.Skript; import ch.njol.skript.config.EntryNode; import ch.njol.skript.config.Node; -import ch.njol.util.Setter; /** * @author Peter Güttinger */ public class EnumEntryValidator> extends EntryValidator { - + private final Class enumType; - private final Setter setter; - @Nullable - private String allowedValues = null; - - public EnumEntryValidator(final Class enumType, final Setter setter) { + private final Consumer setter; + private @Nullable String allowedValues = null; + + public EnumEntryValidator(final Class enumType, final Consumer setter) { assert enumType != null; this.enumType = enumType; this.setter = setter; @@ -33,14 +32,14 @@ public EnumEntryValidator(final Class enumType, final Setter setter) { allowedValues = "" + b.toString(); } } - - public EnumEntryValidator(final Class enumType, final Setter setter, final String allowedValues) { + + public EnumEntryValidator(final Class enumType, final Consumer setter, final String allowedValues) { assert enumType != null; this.enumType = enumType; this.setter = setter; this.allowedValues = allowedValues; } - + @Override public boolean validate(final Node node) { if (!super.validate(node)) @@ -50,12 +49,12 @@ public boolean validate(final Node node) { final E e = Enum.valueOf(enumType, n.getValue().toUpperCase(Locale.ENGLISH).replace(' ', '_')); assert e != null; // if (setter != null) - setter.set(e); + setter.accept(e); } catch (final IllegalArgumentException e) { Skript.error("'" + n.getValue() + "' is not a valid value for '" + n.getKey() + "'" + (allowedValues == null ? "" : ". Allowed values are: " + allowedValues)); return false; } return true; } - + } diff --git a/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java b/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java index 3f382739fe8..c6b84711fbe 100644 --- a/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java @@ -4,23 +4,24 @@ import ch.njol.skript.config.EntryNode; import ch.njol.skript.config.Node; import ch.njol.skript.lang.ParseContext; -import ch.njol.util.Setter; + +import java.util.function.Consumer; /** * @author Peter Güttinger */ public class ParsedEntryValidator extends EntryValidator { - + private final Parser parser; - private final Setter setter; - - public ParsedEntryValidator(final Parser parser, final Setter setter) { + private final Consumer setter; + + public ParsedEntryValidator(final Parser parser, final Consumer setter) { assert parser != null; assert setter != null; this.parser = parser; this.setter = setter; } - + @Override public boolean validate(final Node node) { if (!super.validate(node)) @@ -28,8 +29,8 @@ public boolean validate(final Node node) { final T t = parser.parse(((EntryNode) node).getValue(), ParseContext.CONFIG); if (t == null) return false; - setter.set(t); + setter.accept(t); return true; } - + } diff --git a/src/main/java/ch/njol/skript/config/validate/SectionValidator.java b/src/main/java/ch/njol/skript/config/validate/SectionValidator.java index 1c5482aa39c..916f932dc74 100644 --- a/src/main/java/ch/njol/skript/config/validate/SectionValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/SectionValidator.java @@ -3,6 +3,7 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map.Entry; +import java.util.function.Consumer; import ch.njol.skript.Skript; import ch.njol.skript.classes.Parser; @@ -10,56 +11,55 @@ import ch.njol.skript.config.Node; import ch.njol.skript.config.SectionNode; import ch.njol.skript.log.SkriptLogger; -import ch.njol.util.Setter; /** * @author Peter Güttinger */ public class SectionValidator implements NodeValidator { - + private final static class NodeInfo { public NodeValidator v; public boolean optional; - + public NodeInfo(final NodeValidator v, final boolean optional) { this.v = v; this.optional = optional; } } - + private final HashMap nodes = new HashMap<>(); private boolean allowUndefinedSections = false; private boolean allowUndefinedEntries = false; - + public SectionValidator() {} - + public SectionValidator addNode(final String name, final NodeValidator v, final boolean optional) { assert name != null; assert v != null; nodes.put(name.toLowerCase(Locale.ENGLISH), new NodeInfo(v, optional)); return this; } - + public SectionValidator addEntry(final String name, final boolean optional) { addNode(name, new EntryValidator(), optional); return this; } - - public SectionValidator addEntry(final String name, final Setter setter, final boolean optional) { + + public SectionValidator addEntry(final String name, final Consumer setter, final boolean optional) { addNode(name, new EntryValidator(setter), optional); return this; } - - public SectionValidator addEntry(final String name, final Parser parser, final Setter setter, final boolean optional) { + + public SectionValidator addEntry(final String name, final Parser parser, final Consumer setter, final boolean optional) { addNode(name, new ParsedEntryValidator<>(parser, setter), optional); return this; } - + public SectionValidator addSection(final String name, final boolean optional) { addNode(name, new SectionValidator().setAllowUndefinedEntries(true).setAllowUndefinedSections(true), optional); return this; } - + @Override public boolean validate(final Node node) { if (!(node instanceof SectionNode)) { @@ -93,20 +93,20 @@ public boolean validate(final Node node) { SkriptLogger.setNode(null); return ok; } - + public static void notASectionError(final Node node) { SkriptLogger.setNode(node); Skript.error("'" + node.getKey() + "' is not a section (like 'name:', followed by one or more indented lines)"); } - + public SectionValidator setAllowUndefinedSections(final boolean b) { allowUndefinedSections = b; return this; } - + public SectionValidator setAllowUndefinedEntries(final boolean b) { allowUndefinedEntries = b; return this; } - + } diff --git a/src/main/java/ch/njol/util/Setter.java b/src/main/java/ch/njol/util/Setter.java index 6edc10a723a..4b285941068 100644 --- a/src/main/java/ch/njol/util/Setter.java +++ b/src/main/java/ch/njol/util/Setter.java @@ -1,10 +1,18 @@ package ch.njol.util; -/** - * @author Peter Güttinger - */ -public interface Setter { - - public void set(T t); - +import org.jetbrains.annotations.ApiStatus; + +import java.util.function.Consumer; + +@Deprecated +@FunctionalInterface +@ApiStatus.ScheduledForRemoval +public interface Setter extends Consumer { + + void set(T t); + + @Override + default void accept(T t) { + this.set(t); + } } From 48dcd788f3e7669fd1c3eb045c1297c68f41bde0 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:07:43 +0000 Subject: [PATCH 4/7] Deprecate Checker and replace with Java's Predicate. (#6663) * Make checker a Java predicate. * Deprecate unused Njol predicate for removal. * Make checker extensions use predicate directly. * Remove checker from expression. * Remove checker from utils. * Deprecate Checker for removal. * Abstract checker to predicate from simple syntax * Remove remaining uses of checker. --- .../skript/classes/SerializableChecker.java | 8 ++- .../njol/skript/conditions/CondCompare.java | 51 +++++++++--------- .../njol/skript/conditions/CondIsOfType.java | 24 ++++----- .../conditions/base/PropertyCondition.java | 11 ++-- .../ch/njol/skript/entity/EndermanData.java | 43 ++++++++------- .../java/ch/njol/skript/events/EvtClick.java | 41 ++++++++++----- .../skript/events/EvtEntityBlockChange.java | 8 +-- .../ch/njol/skript/events/EvtGameMode.java | 16 +++--- .../njol/skript/events/EvtWeatherChange.java | 17 +++--- .../arithmetic/ArithmeticChain.java | 6 +-- .../regions/conditions/CondCanBuild.java | 21 ++++---- .../regions/conditions/CondIsMember.java | 21 ++++---- .../conditions/CondRegionContains.java | 21 ++++---- .../java/ch/njol/skript/lang/Condition.java | 8 +-- .../java/ch/njol/skript/lang/Expression.java | 52 +++++++++---------- .../ch/njol/skript/lang/ExpressionList.java | 5 +- .../ch/njol/skript/lang/UnparsedLiteral.java | 6 +-- .../java/ch/njol/skript/lang/Variable.java | 8 +-- .../ch/njol/skript/lang/VariableString.java | 6 +-- .../skript/lang/util/ConvertedExpression.java | 11 ++-- .../skript/lang/util/ConvertedLiteral.java | 6 +-- .../skript/lang/util/SimpleExpression.java | 18 +++---- .../njol/skript/lang/util/SimpleLiteral.java | 6 +-- src/main/java/ch/njol/skript/util/Utils.java | 9 ++-- src/main/java/ch/njol/util/Checker.java | 19 +++++-- .../java/ch/njol/util/NullableChecker.java | 12 +++-- src/main/java/ch/njol/util/Predicate.java | 9 +++- 27 files changed, 255 insertions(+), 208 deletions(-) diff --git a/src/main/java/ch/njol/skript/classes/SerializableChecker.java b/src/main/java/ch/njol/skript/classes/SerializableChecker.java index 216e2b750b1..58420e2e59e 100644 --- a/src/main/java/ch/njol/skript/classes/SerializableChecker.java +++ b/src/main/java/ch/njol/skript/classes/SerializableChecker.java @@ -1,9 +1,13 @@ package ch.njol.skript.classes; -import ch.njol.util.Checker; +import org.jetbrains.annotations.ApiStatus; + +import java.util.function.Predicate; /** * @author Peter Güttinger */ @Deprecated -public interface SerializableChecker extends Checker {} +@FunctionalInterface +@ApiStatus.ScheduledForRemoval +public interface SerializableChecker extends ch.njol.util.Checker, Predicate {} diff --git a/src/main/java/ch/njol/skript/conditions/CondCompare.java b/src/main/java/ch/njol/skript/conditions/CondCompare.java index bcdc9556de9..58aa9501e62 100644 --- a/src/main/java/ch/njol/skript/conditions/CondCompare.java +++ b/src/main/java/ch/njol/skript/conditions/CondCompare.java @@ -29,10 +29,11 @@ import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.Patterns; import ch.njol.skript.util.Utils; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.skriptlang.skript.lang.util.Cyclical; +import java.util.function.Predicate; + @Name("Comparison") @Description({"A very general condition, it simply compares two values. Usually you can only compare for equality (e.g. block is/isn't of <type>), " + "but some values can also be compared using greater than/less than. In that case you can also test for whether an object is between two others.", @@ -44,7 +45,7 @@ "the creature is not an enderman or an ender dragon"}) @Since("1.0") public class CondCompare extends Condition implements VerboseAssert { - + private final static Patterns patterns = new Patterns<>(new Object[][]{ {"(1¦neither|) %objects% ((is|are)(|2¦(n't| not|4¦ neither)) ((greater|more|higher|bigger|larger) than|above)|\\>) %objects%", Relation.GREATER}, {"(1¦neither|) %objects% ((is|are)(|2¦(n't| not|4¦ neither)) (greater|more|higher|bigger|larger|above) [than] or (equal to|the same as)|\\>=) %objects%", Relation.GREATER_OR_EQUAL}, @@ -54,7 +55,7 @@ public class CondCompare extends Condition implements VerboseAssert { {"(1¦neither|) %objects% (is|are|=) [(equal to|the same as)] %objects%", Relation.EQUAL}, {"(1¦neither|) %objects% (is|are) between %objects% and %objects%", Relation.EQUAL}, {"(1¦neither|) %objects% (2¦)(is not|are not|isn't|aren't) between %objects% and %objects%", Relation.EQUAL}, - + {"(1¦neither|) %objects@-1% (was|were)(|2¦(n't| not|4¦ neither)) ((greater|more|higher|bigger|larger) than|above) %objects%", Relation.GREATER}, {"(1¦neither|) %objects@-1% (was|were)(|2¦(n't| not|4¦ neither)) (greater|more|higher|bigger|larger|above) [than] or (equal to|the same as) %objects%", Relation.GREATER_OR_EQUAL}, {"(1¦neither|) %objects@-1% (was|were)(|2¦(n't| not|4¦ neither)) ((less|smaller|lower) than|below) %objects%", Relation.SMALLER}, @@ -63,7 +64,7 @@ public class CondCompare extends Condition implements VerboseAssert { {"(1¦neither|) %objects@-1% (was|were) [(equal to|the same as)] %objects%", Relation.EQUAL}, {"(1¦neither|) %objects@-1% (was|were) between %objects% and %objects%", Relation.EQUAL}, {"(1¦neither|) %objects@-1% (2¦)(was not|were not|wasn't|weren't) between %objects% and %objects%", Relation.EQUAL}, - + {"(1¦neither|) %objects@1% (will be|2¦(will (not|4¦neither) be|won't be)) ((greater|more|higher|bigger|larger) than|above) %objects%", Relation.GREATER}, {"(1¦neither|) %objects@1% (will be|2¦(will (not|4¦neither) be|won't be)) (greater|more|higher|bigger|larger|above) [than] or (equal to|the same as) %objects%", Relation.GREATER_OR_EQUAL}, {"(1¦neither|) %objects@1% (will be|2¦(will (not|4¦neither) be|won't be)) ((less|smaller|lower) than|below) %objects%", Relation.SMALLER}, @@ -73,11 +74,11 @@ public class CondCompare extends Condition implements VerboseAssert { {"(1¦neither|) %objects@1% will be between %objects% and %objects%", Relation.EQUAL}, {"(1¦neither|) %objects@1% (2¦)(will not be|won't be) between %objects% and %objects%", Relation.EQUAL} }); - + static { Skript.registerCondition(CondCompare.class, ConditionType.PATTERN_MATCHES_EVERYTHING, patterns.getPatterns()); } - + private Expression first; private Expression second; @@ -89,7 +90,7 @@ public class CondCompare extends Condition implements VerboseAssert { @Nullable @SuppressWarnings("rawtypes") private Comparator comparator; - + @Override public boolean init(final Expression[] vars, final int matchedPattern, final Kleenean isDelayed, final ParseResult parser) { first = vars[0]; @@ -132,16 +133,16 @@ public boolean init(final Expression[] vars, final int matchedPattern, final } } } - + return true; } - + public static String f(final Expression e) { if (e.getReturnType() == Object.class) return e.toString(null, false); return Classes.getSuperClassInfo(e.getReturnType()).getName().withIndefiniteArticle(); } - + @SuppressWarnings("unchecked") private boolean init(String expr) { Expression third = this.third; @@ -197,11 +198,11 @@ private boolean init(String expr) { * SkriptParser sees that CondCompare takes two objects. Most of the time, * this works fine. However, when there are multiple conflicting literals, * it just picks one of them at random. - * + * * If our other parameter is not a literal, we can try parsing the other * explicitly with same return type. This is not guaranteed to succeed, * but will in work in some cases that were previously ambiguous. - * + * * Some damage types not working (issue #2184) would be a good example * of issues that SkriptParser's lack of context can cause. */ @@ -216,7 +217,7 @@ private boolean init(String expr) { comparator = Comparators.getComparator(first.getReturnType(), secondReturnType); } } - + } return comparator != null; @@ -253,7 +254,7 @@ private SimpleLiteral reparseLiteral(Class type, Expression express * For example 'fire' will be VisualEffect without this, but if the user attempts to compare 'fire' * with a block. This method will see if 'fire' can be compared to the block, and it will find ItemType. * Essentially solving something a human sees as comparable, but Skript doesn't understand. - * + * * @param one The UnparsedLiteral expression to attempt to reconstruct. * @param two any expression to grab the return type from. * @return The newly formed Literal, will be SimpleLiteral in most cases. @@ -287,7 +288,7 @@ private Literal attemptReconstruction(UnparsedLiteral one, Expression two) /* * # := condition (e.g. is, is less than, contains, is enchanted with, has permission, etc.) * !# := not # - * + * * a and b # x === a # x && b # x * a or b # x === a # x || b # x * a # x and y === a # x && a # y @@ -298,25 +299,25 @@ private Literal attemptReconstruction(UnparsedLiteral one, Expression two) * a and b # x or y === a # x or y && b # x or y * a or b # x and y === a # x and y || b # x and y * a or b # x or y === a # x or y || b # x or y - * - * + * + * * a and b !# x === a !# x && b !# x * neither a nor b # x === a !# x && b !# x // nor = and * a or b !# x === a !# x || b !# x - * + * * a !# x and y === a !# x || a !# y // e.g. "player doesn't have 2 emeralds and 5 gold ingots" == "NOT(player has 2 emeralds and 5 gold ingots)" == "player doesn't have 2 emeralds OR player doesn't have 5 gold ingots" * a # neither x nor y === a !# x && a !# y // nor = or // e.g. "player has neither 2 emeralds nor 5 gold ingots" == "player doesn't have 2 emeralds AND player doesn't have 5 gold ingots" * a # neither x nor y === a !# x && a !# y // nor = or // e.g. "player is neither the attacker nor the victim" == "player is not the attacker AND player is not the victim" * a !# x or y === a !# x && a !# y // e.g. "player doesn't have 2 emeralds or 5 gold ingots" == "NOT(player has 2 emeralds or 5 gold ingots)" == "player doesn't have 2 emeralds AND player doesn't have 5 gold ingots" - * + * * a and b !# x and y === a !# x and y && b !# x and y === (a !# x || a !# y) && (b !# x || b !# y) * a and b !# x or y === a !# x or y && b !# x or y * a and b # neither x nor y === a # neither x nor y && b # neither x nor y - * + * * a or b !# x and y === a !# x and y || b !# x and y * a or b !# x or y === a !# x or y || b !# x or y * a or b # neither x nor y === a # neither x nor y || b # neither x nor y - * + * * neither a nor b # x and y === a !# x and y && b !# x and y // nor = and * neither a nor b # x or y === a !# x or y && b !# x or y // nor = and */ @@ -331,11 +332,11 @@ public boolean check(final Event event) { second.getAnd() && !second.isSingle()) return compareLists(event); - return first.check(event, (Checker) o1 -> - second.check(event, (Checker) o2 -> { + return first.check(event, (Predicate) o1 -> + second.check(event, (Predicate) o2 -> { if (third == null) return relation.isImpliedBy(comparator != null ? comparator.compare(o1, o2) : Comparators.compare(o1, o2)); - return third.check(event, (Checker) o3 -> { + return third.check(event, (Predicate) o3 -> { boolean isBetween; if (comparator != null) { if (o1 instanceof Cyclical && o2 instanceof Cyclical && o3 instanceof Cyclical) { @@ -416,5 +417,5 @@ public String toString(final @Nullable Event event, final boolean debug) { s += " (comparator: " + comparator + ")"; return s; } - + } diff --git a/src/main/java/ch/njol/skript/conditions/CondIsOfType.java b/src/main/java/ch/njol/skript/conditions/CondIsOfType.java index f3c18f3fa4f..dbc1b163ce8 100644 --- a/src/main/java/ch/njol/skript/conditions/CondIsOfType.java +++ b/src/main/java/ch/njol/skript/conditions/CondIsOfType.java @@ -18,9 +18,9 @@ import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; +import java.util.function.Predicate; @Name("Is of Type") @Description("Checks whether an item or an entity is of the given type. This is mostly useful for variables," + " as you can use the general 'is' condition otherwise (e.g. 'victim is a creeper').") @@ -28,7 +28,7 @@ "victim is of type {villager type}"}) @Since("1.4") public class CondIsOfType extends Condition { - + static { PropertyCondition.register(CondIsOfType.class, "of type[s] %itemtypes/entitydatas%", "itemstacks/entities"); } @@ -37,7 +37,7 @@ public class CondIsOfType extends Condition { private Expression what; @SuppressWarnings("NotNullFieldNotInitialized") private Expression types; - + @SuppressWarnings("null") @Override public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { @@ -46,14 +46,14 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye setNegated(matchedPattern == 1); return true; } - + @Override - public boolean check(Event event) { - return what.check(event, - (Checker) o1 -> types.check(event, - (Checker) o2 -> { - if (o2 instanceof ItemType && o1 instanceof ItemStack) { - return ((ItemType) o2).isSupertypeOf(new ItemType((ItemStack) o1)); + public boolean check(final Event e) { + return what.check(e, + (Predicate) o1 -> types.check(e, + (Predicate) o2 -> { + if (o2 instanceof ItemType && o1 instanceof ItemType) { + return ((ItemType) o2).isSupertypeOf((ItemType) o1); } else if (o2 instanceof EntityData && o1 instanceof Entity) { return ((EntityData) o2).isInstance((Entity) o1); } else if (o2 instanceof ItemType && o1 instanceof Entity) { @@ -64,11 +64,11 @@ public boolean check(Event event) { }), isNegated()); } - + @Override public String toString(@Nullable Event event, boolean debug) { return PropertyCondition.toString(this, PropertyType.BE, event, debug, what, "of " + (types.isSingle() ? "type " : "types ") + types.toString(event, debug)); } - + } diff --git a/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java b/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java index d539273f252..dadc7f71d47 100644 --- a/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java +++ b/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java @@ -8,13 +8,14 @@ import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.jetbrains.annotations.ApiStatus; import org.skriptlang.skript.registration.SyntaxInfo; import org.skriptlang.skript.registration.SyntaxRegistry; import org.skriptlang.skript.util.Priority; +import java.util.function.Predicate; + /** * This class can be used for an easier writing of conditions that contain only one type in the pattern, * and are in one of the following forms: @@ -38,7 +39,7 @@ * {@link PropertyCondition#register(Class, String, String)}, be aware that there can only be two patterns - * the first one needs to be a non-negated one and a negated one. */ -public abstract class PropertyCondition extends Condition implements Checker { +public abstract class PropertyCondition extends Condition implements ch.njol.util.Checker, Predicate { /** * A priority for {@link PropertyCondition}s. @@ -190,9 +191,13 @@ public final boolean check(Event event) { return expr.check(event, this, isNegated()); } - @Override public abstract boolean check(T value); + @Override + public final boolean test(T value) { + return this.check(value); + } + protected abstract String getPropertyName(); protected PropertyType getPropertyType() { diff --git a/src/main/java/ch/njol/skript/entity/EndermanData.java b/src/main/java/ch/njol/skript/entity/EndermanData.java index d5e9fa8984b..15cd38aff65 100644 --- a/src/main/java/ch/njol/skript/entity/EndermanData.java +++ b/src/main/java/ch/njol/skript/entity/EndermanData.java @@ -1,6 +1,7 @@ package ch.njol.skript.entity; import java.util.Arrays; +import java.util.function.Predicate; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -10,32 +11,30 @@ import org.bukkit.material.MaterialData; import org.jetbrains.annotations.Nullable; -import ch.njol.skript.Skript; import ch.njol.skript.aliases.ItemType; import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.skript.localization.ArgsMessage; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Checker; import ch.njol.util.coll.CollectionUtils; @SuppressWarnings("deprecation") public class EndermanData extends EntityData { - + static { EntityData.register(EndermanData.class, "enderman", Enderman.class, "enderman"); } @Nullable private ItemType[] hand = null; - + public EndermanData() {} - + public EndermanData(@Nullable ItemType[] hand) { this.hand = hand; } - + @SuppressWarnings("unchecked") @Override protected boolean init(final Literal[] exprs, final int matchedPattern, final ParseResult parseResult) { @@ -43,7 +42,7 @@ protected boolean init(final Literal[] exprs, final int matchedPattern, final hand = ((Literal) exprs[0]).getAll(); return true; } - + @Override protected boolean init(final @Nullable Class c, final @Nullable Enderman e) { if (e != null) { @@ -56,7 +55,7 @@ protected boolean init(final @Nullable Class c, final @Nulla } return true; } - + @Override public void set(final Enderman entity) { if (hand != null) { @@ -68,28 +67,28 @@ public void set(final Enderman entity) { entity.setCarriedBlock(Bukkit.createBlockData(i.getType())); } } - + } - + @Override public boolean match(final Enderman entity) { - return hand == null || SimpleExpression.check(hand, new Checker() { + return hand == null || SimpleExpression.check(hand, new Predicate() { @SuppressWarnings("null") @Override - public boolean check(final @Nullable ItemType t) { + public boolean test(final @Nullable ItemType t) { // TODO {Block/Material}Data -> Material conversion is not 100% accurate, needs a better solution return t != null && t.isOfType(entity.getCarriedBlock().getMaterial()); } }, false, false); } - + @Override public Class getType() { return Enderman.class; } - + private final static ArgsMessage format = new ArgsMessage("entities.enderman.format"); - + @Override public String toString(final int flags) { final ItemType[] hand = this.hand; @@ -97,12 +96,12 @@ public String toString(final int flags) { return super.toString(flags); return format.toString(super.toString(flags), Classes.toString(hand, false)); } - + @Override protected int hashCode_i() { return Arrays.hashCode(hand); } - + @Override protected boolean equals_i(final EntityData obj) { if (!(obj instanceof EndermanData)) @@ -110,7 +109,7 @@ protected boolean equals_i(final EntityData obj) { final EndermanData other = (EndermanData) obj; return Arrays.equals(hand, other.hand); } - + // if (hand == null) // return ""; // final StringBuilder b = new StringBuilder(); @@ -144,23 +143,23 @@ protected boolean deserialize(final String s) { } return false; } - + private boolean isSubhand(final @Nullable ItemType[] sub) { if (hand != null) return sub != null && ItemType.isSubset(hand, sub); return true; } - + @Override public boolean isSupertypeOf(final EntityData e) { if (e instanceof EndermanData) return isSubhand(((EndermanData) e).hand); return false; } - + @Override public EntityData getSuperType() { return new EndermanData(hand); } - + } diff --git a/src/main/java/ch/njol/skript/events/EvtClick.java b/src/main/java/ch/njol/skript/events/EvtClick.java index ed455173889..d0d903ef245 100644 --- a/src/main/java/ch/njol/skript/events/EvtClick.java +++ b/src/main/java/ch/njol/skript/events/EvtClick.java @@ -26,9 +26,10 @@ import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.coll.CollectionUtils; +import java.util.function.Predicate; + public class EvtClick extends SkriptEvent { /** @@ -119,17 +120,17 @@ public boolean check(Event event) { if (!(clicked instanceof ArmorStand)) return false; } - + if (click == LEFT) // Lefts clicks on entities don't work return false; - + // PlayerInteractAtEntityEvent called only once for armor stands if (!(event instanceof PlayerInteractAtEntityEvent)) { if (!interactTracker.checkEvent(interactEntityEvent.getPlayer(), interactEntityEvent, interactEntityEvent.getHand())) { return false; // Not first event this tick } } - + entity = clicked; block = null; } else if (event instanceof PlayerInteractEvent interactEvent) { @@ -159,25 +160,41 @@ public boolean check(Event event) { return false; } - Checker checker = itemType -> { - if (event instanceof PlayerInteractEvent interactEvent) { - return itemType.isOfType(interactEvent.getItem()); - } else { - PlayerInventory invi = ((PlayerInteractEntityEvent) event).getPlayer().getInventory(); - ItemStack item = ((PlayerInteractEntityEvent) event).getHand() == EquipmentSlot.HAND - ? invi.getItemInMainHand() : invi.getItemInOffHand(); - return itemType.isOfType(item); + if (tools != null && !tools.check(event, new Predicate() { + @Override + public boolean test(final ItemType t) { + if (event instanceof PlayerInteractEvent) { + return t.isOfType(((PlayerInteractEvent) event).getItem()); + } else { // PlayerInteractEntityEvent doesn't have item associated with it + PlayerInventory invi = ((PlayerInteractEntityEvent) event).getPlayer().getInventory(); + ItemStack item = ((PlayerInteractEntityEvent) event).getHand() == EquipmentSlot.HAND + ? invi.getItemInMainHand() : invi.getItemInOffHand(); + return t.isOfType(item); + } } }; if (tools != null && !tools.check(event, checker)) return false; +<<<<<<< + +======= + } +>>>>>>> if (type != null) { +<<<<<<< BlockData blockDataCheck = block != null ? block.getBlockData() : null; return type.check(event, new Checker() { +======= + return type.check(event, new Predicate() { +>>>>>>> @Override +<<<<<<< public boolean check(Object object) { +======= + public boolean test(final Object o) { +>>>>>>> if (entity != null) { if (object instanceof EntityData entityData) { return entityData.isInstance(entity); diff --git a/src/main/java/ch/njol/skript/events/EvtEntityBlockChange.java b/src/main/java/ch/njol/skript/events/EvtEntityBlockChange.java index aa09ffcdf52..42253f5ab53 100644 --- a/src/main/java/ch/njol/skript/events/EvtEntityBlockChange.java +++ b/src/main/java/ch/njol/skript/events/EvtEntityBlockChange.java @@ -6,7 +6,6 @@ import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import org.bukkit.entity.Enderman; import org.bukkit.entity.FallingBlock; @@ -17,6 +16,7 @@ import org.jetbrains.annotations.Nullable; import java.util.Locale; +import java.util.function.Predicate; public class EvtEntityBlockChange extends SkriptEvent { @@ -56,14 +56,14 @@ private enum ChangeEvent { GENERIC("(entity|%*-entitydatas%) chang(e|ing) block[s]"); @Nullable - private final Checker checker; + private final Predicate checker; private final String pattern; ChangeEvent(String pattern) { this(pattern, null); } - ChangeEvent(String pattern, @Nullable Checker checker) { + ChangeEvent(String pattern, @Nullable Predicate checker) { this.pattern = pattern; this.checker = checker; } @@ -98,7 +98,7 @@ public boolean check(Event event) { return false; if (this.event.checker == null) return true; - return this.event.checker.check((EntityChangeBlockEvent) event); + return this.event.checker.test((EntityChangeBlockEvent) event); } @Override diff --git a/src/main/java/ch/njol/skript/events/EvtGameMode.java b/src/main/java/ch/njol/skript/events/EvtGameMode.java index 26eaf30d5ec..8c9174043ad 100644 --- a/src/main/java/ch/njol/skript/events/EvtGameMode.java +++ b/src/main/java/ch/njol/skript/events/EvtGameMode.java @@ -1,6 +1,7 @@ package ch.njol.skript.events; import java.util.Locale; +import java.util.function.Predicate; import org.bukkit.GameMode; import org.bukkit.event.Event; @@ -11,7 +12,6 @@ import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; /** * @author Peter Güttinger @@ -23,33 +23,33 @@ public final class EvtGameMode extends SkriptEvent { .examples("on gamemode change:", "on gamemode change to adventure:") .since("1.0"); } - + @Nullable private Literal mode; - + @SuppressWarnings("unchecked") @Override public boolean init(final Literal[] args, final int matchedPattern, final ParseResult parser) { mode = (Literal) args[0]; return true; } - + @Override public boolean check(final Event e) { if (mode != null) { - return mode.check(e, new Checker() { + return mode.check(e, new Predicate() { @Override - public boolean check(final GameMode m) { + public boolean test(final GameMode m) { return ((PlayerGameModeChangeEvent) e).getNewGameMode().equals(m); } }); } return true; } - + @Override public String toString(final @Nullable Event e, final boolean debug) { return "gamemode change" + (mode != null ? " to " + mode.toString().toLowerCase(Locale.ENGLISH) : ""); } - + } diff --git a/src/main/java/ch/njol/skript/events/EvtWeatherChange.java b/src/main/java/ch/njol/skript/events/EvtWeatherChange.java index f68dd416eaa..497aecc8870 100644 --- a/src/main/java/ch/njol/skript/events/EvtWeatherChange.java +++ b/src/main/java/ch/njol/skript/events/EvtWeatherChange.java @@ -10,9 +10,10 @@ import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.util.WeatherType; -import ch.njol.util.Checker; import ch.njol.util.coll.CollectionUtils; +import java.util.function.Predicate; + /** * @author Peter Güttinger */ @@ -24,16 +25,16 @@ public class EvtWeatherChange extends SkriptEvent { .examples("on weather change:", "on weather change to sunny:") .since("1.0"); } - + @Nullable private Literal types; - + @Override public boolean init(final Literal[] args, final int matchedPattern, final ParseResult parser) { types = (Literal) args[0]; return true; } - + @SuppressWarnings("null") @Override public boolean check(final Event e) { @@ -43,17 +44,17 @@ public boolean check(final Event e) { return false; final boolean rain = e instanceof WeatherChangeEvent ? ((WeatherChangeEvent) e).toWeatherState() : ((ThunderChangeEvent) e).getWorld().hasStorm(); final boolean thunder = e instanceof ThunderChangeEvent ? ((ThunderChangeEvent) e).toThunderState() : ((WeatherChangeEvent) e).getWorld().isThundering(); - return types.check(e, new Checker() { + return types.check(e, new Predicate() { @Override - public boolean check(final WeatherType t) { + public boolean test(final WeatherType t) { return t.isWeather(rain, thunder); } }); } - + @Override public String toString(final @Nullable Event e, final boolean debug) { return "weather change" + (types == null ? "" : " to " + types); } - + } diff --git a/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java b/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java index f003f80441d..e501127cfc0 100644 --- a/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java +++ b/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java @@ -2,12 +2,12 @@ import java.util.List; import java.util.function.Function; +import java.util.function.Predicate; import org.bukkit.event.Event; import ch.njol.skript.lang.Expression; import ch.njol.skript.util.Utils; -import ch.njol.util.Checker; import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.arithmetic.Operation; import org.skriptlang.skript.lang.arithmetic.OperationInfo; @@ -25,7 +25,7 @@ public class ArithmeticChain implements ArithmeticGettable { @SuppressWarnings("unchecked") - private static final Checker[] CHECKERS = new Checker[] { + private static final Predicate[] CHECKERS = new Predicate[] { o -> o.equals(Operator.ADDITION) || o.equals(Operator.SUBTRACTION), o -> o.equals(Operator.MULTIPLICATION) || o.equals(Operator.DIVISION), o -> o.equals(Operator.EXPONENTIATION) @@ -111,7 +111,7 @@ public Class getReturnType() { @Nullable @SuppressWarnings("unchecked") public static ArithmeticGettable parse(List chain) { - for (Checker checker : CHECKERS) { + for (Predicate checker : CHECKERS) { int lastIndex = Utils.findLastIndex(chain, checker); if (lastIndex != -1) { diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java index adfc02fa728..5eefd224aa6 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java @@ -11,13 +11,14 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.util.Direction; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import java.util.function.Predicate; + /** * @author Peter Güttinger */ @@ -43,12 +44,12 @@ public class CondCanBuild extends Condition { "%players% (can|(is|are) allowed to) build %directions% %locations%", "%players% (can('t|not)|(is|are)(n't| not) allowed to) build %directions% %locations%"); } - + @SuppressWarnings("null") private Expression players; @SuppressWarnings("null") Expression locations; - + @SuppressWarnings({"unchecked", "null"}) @Override public boolean init(final Expression[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) { @@ -57,25 +58,25 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final setNegated(matchedPattern == 1); return true; } - + @Override public boolean check(final Event e) { - return players.check(e, new Checker() { + return players.check(e, new Predicate() { @Override - public boolean check(final Player p) { - return locations.check(e, new Checker() { + public boolean test(final Player p) { + return locations.check(e, new Predicate() { @Override - public boolean check(final Location l) { + public boolean test(final Location l) { return RegionsPlugin.canBuild(p, l); } }, isNegated()); } }); } - + @Override public String toString(final @Nullable Event e, final boolean debug) { return players.toString(e, debug) + " can build " + locations.toString(e, debug); } - + } diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java index fa7070d103e..e6711cd7fe7 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java @@ -10,12 +10,13 @@ import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.OfflinePlayer; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import java.util.function.Predicate; + /** * @author Peter Güttinger */ @@ -36,14 +37,14 @@ public class CondIsMember extends Condition { "%offlineplayers% (is|are) (0¦[a] member|1¦[(the|an)] owner) of [[the] region] %regions%", "%offlineplayers% (is|are)(n't| not) (0¦[a] member|1¦[(the|an)] owner) of [[the] region] %regions%"); } - + @SuppressWarnings("null") private Expression players; @SuppressWarnings("null") Expression regions; - + boolean owner; - + @SuppressWarnings({"null", "unchecked"}) @Override public boolean init(final Expression[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) { @@ -53,22 +54,22 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final setNegated(matchedPattern == 1); return true; } - + @Override public boolean check(final Event e) { - return players.check(e, new Checker() { + return players.check(e, new Predicate() { @Override - public boolean check(final OfflinePlayer p) { - return regions.check(e, new Checker() { + public boolean test(final OfflinePlayer p) { + return regions.check(e, new Predicate() { @Override - public boolean check(final Region r) { + public boolean test(final Region r) { return owner ? r.isOwner(p) : r.isMember(p); } }, isNegated()); } }); } - + @Override public String toString(final @Nullable Event e, final boolean debug) { return players.toString(e, debug) + " " + (players.isSingle() ? "is" : "are") + (isNegated() ? " not" : "") + " " + (owner ? "owner" : "member") + (players.isSingle() ? "" : "s") + " of " + regions.toString(e, debug); diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java index 177e731c354..55828245e66 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java @@ -11,12 +11,13 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.util.Direction; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.Location; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import java.util.function.Predicate; + /** * @author Peter Güttinger */ @@ -40,12 +41,12 @@ public class CondRegionContains extends Condition { "[[the] region] %regions% contain[s] %directions% %locations%", "%locations% (is|are) ([contained] in|part of) [[the] region] %regions%", "[[the] region] %regions% (do|does)(n't| not) contain %directions% %locations%", "%locations% (is|are)(n't| not) (contained in|part of) [[the] region] %regions%"); } - + @SuppressWarnings("null") private Expression regions; @SuppressWarnings("null") Expression locs; - + @SuppressWarnings({"unchecked", "null"}) @Override public boolean init(final Expression[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) { @@ -59,25 +60,25 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final setNegated(matchedPattern >= 2); return true; } - + @Override public boolean check(final Event e) { - return regions.check(e, new Checker() { + return regions.check(e, new Predicate() { @Override - public boolean check(final Region r) { - return locs.check(e, new Checker() { + public boolean test(final Region r) { + return locs.check(e, new Predicate() { @Override - public boolean check(final Location l) { + public boolean test(final Location l) { return r.contains(l); } }, isNegated()); } }); } - + @Override public String toString(final @Nullable Event e, final boolean debug) { return regions.toString(e, debug) + " contain" + (regions.isSingle() ? "s" : "") + " " + locs.toString(e, debug); } - + } diff --git a/src/main/java/ch/njol/skript/lang/Condition.java b/src/main/java/ch/njol/skript/lang/Condition.java index 31a1810d2b0..65a89b7dfa2 100644 --- a/src/main/java/ch/njol/skript/lang/Condition.java +++ b/src/main/java/ch/njol/skript/lang/Condition.java @@ -3,7 +3,6 @@ import ch.njol.skript.Skript; import ch.njol.skript.conditions.base.PropertyCondition; import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import org.jetbrains.annotations.ApiStatus; @@ -13,6 +12,7 @@ import org.skriptlang.skript.util.Priority; import java.util.Iterator; +import java.util.function.Predicate; /** * A condition which must be fulfilled for the trigger to continue. If the condition is in a section the behaviour depends on the section. @@ -65,8 +65,8 @@ protected Condition() {} * Checks whether this condition is satisfied with the given event. This should not alter the event or the world in any way, as conditions are only checked until one returns * false. All subsequent conditions of the same trigger will then be omitted.
*
- * You might want to use {@link SimpleExpression#check(Event, Checker)} - * + * You might want to use {@link SimpleExpression#check(Event, Predicate)} + * * @param event the event to check * @return true if the condition is satisfied, false otherwise or if the condition doesn't apply to this event. */ @@ -83,7 +83,7 @@ public final boolean run(Event event) { } /** - * Sets the negation state of this condition. This will change the behaviour of {@link Expression#check(Event, Checker, boolean)}. + * Sets the negation state of this condition. This will change the behaviour of {@link Expression#check(Event, Predicate, boolean)}. */ protected final void setNegated(boolean invert) { negated = invert; diff --git a/src/main/java/ch/njol/skript/lang/Expression.java b/src/main/java/ch/njol/skript/lang/Expression.java index 6b853136ee0..e286e95c879 100644 --- a/src/main/java/ch/njol/skript/lang/Expression.java +++ b/src/main/java/ch/njol/skript/lang/Expression.java @@ -10,7 +10,6 @@ import ch.njol.skript.log.ErrorQuality; import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.slot.Slot; -import ch.njol.util.Checker; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.ApiStatus; @@ -25,6 +24,7 @@ import java.util.Map; import java.util.Optional; import java.util.Spliterators; +import java.util.function.Predicate; import java.util.function.Function; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -44,8 +44,8 @@ public interface Expression extends SyntaxElement, Debuggable, Loopable { * This method may only return null if it always returns null for the given event, i.e. it is equivalent to getting a random element out of {@link #getAll(Event)} or null iff * that array is empty. *

- * Do not use this in conditions, use {@link #check(Event, Checker, boolean)} instead. - * + * Do not use this in conditions, use {@link #check(Event, Predicate, boolean)} instead. + * * @param event The event * @return The value or null if this expression doesn't have any value for the event * @throws UnsupportedOperationException (optional) if this was called on a non-single expression @@ -55,7 +55,7 @@ public interface Expression extends SyntaxElement, Debuggable, Loopable { /** * Get an optional of the single value of this expression. *

- * Do not use this in conditions, use {@link #check(Event, Checker, boolean)} instead. + * Do not use this in conditions, use {@link #check(Event, Predicate, boolean)} instead. * * @param event the event * @return an {@link Optional} containing the {@link #getSingle(Event) single value} of this expression for this event. @@ -70,8 +70,8 @@ default Optional getOptionalSingle(Event event) { *

* The returned array must not contain any null values. *

- * Do not use this in conditions, use {@link #check(Event, Checker, boolean)} instead. - * + * Do not use this in conditions, use {@link #check(Event, Predicate, boolean)} instead. + * * @param event The event * @return An array of values of this expression which must neither be null nor contain nulls, and which must not be an internal array. */ @@ -80,7 +80,7 @@ default Optional getOptionalSingle(Event event) { /** * Gets all possible return values of this expression, i.e. it returns the same as {@link #getArray(Event)} if {@link #getAnd()} is true, otherwise all possible values for * {@link #getSingle(Event)}. - * + * * @param event The event * @return An array of all possible values of this expression for the given event which must neither be null nor contain nulls, and which must not be an internal array. */ @@ -124,29 +124,29 @@ default boolean canBeSingle() { * or as the innermost check of nested checks. *

* Usual implementation (may differ, e.g. may return false for nonexistent values independent of negated): - * + * *

-	 * return negated ^ {@link #check(Event, Checker)};
+	 * return negated ^ {@link #check(Event, Predicate)};
 	 * 
- * + * * @param event The event to be used for evaluation * @param checker The checker that determines whether this expression matches * @param negated The checking condition's negated state. This is used to invert the output of the checker if set to true (i.e. negated ^ checker.check(...)) * @return Whether this expression matches or doesn't match the given checker depending on the condition's negated state. - * @see SimpleExpression#check(Object[], Checker, boolean, boolean) + * @see SimpleExpression#check(Object[], Predicate, boolean, boolean) */ - boolean check(Event event, Checker checker, boolean negated); + boolean check(Event event, Predicate checker, boolean negated); /** - * Checks this expression against the given checker. This method must only be used around other checks, use {@link #check(Event, Checker, boolean)} for a simple check or the + * Checks this expression against the given checker. This method must only be used around other checks, use {@link #check(Event, Predicate, boolean)} for a simple check or the * innermost check of a nested check. - * + * * @param event The event to be used for evaluation * @param checker A checker that determines whether this expression matches * @return Whether this expression matches the given checker - * @see SimpleExpression#check(Object[], Checker, boolean, boolean) + * @see SimpleExpression#check(Object[], Predicate, boolean, boolean) */ - boolean check(Event event, Checker checker); + boolean check(Event event, Predicate checker); /** * Tries to convert this expression to the given type. This method can print an error prior to returning null to specify the cause. @@ -156,7 +156,7 @@ default boolean canBeSingle() { *

* The returned expression should delegate this method to the original expression's method to prevent excessive converted expression chains (see also * {@link ConvertedExpression}). - * + * * @param to The desired return type of the returned expression * @return Expression with the desired return type or null if the expression can't be converted to the given type. Returns the expression itself if it already returns the * desired type. @@ -168,7 +168,7 @@ default boolean canBeSingle() { /** * Gets the return type of this expression. - * + * * @return A supertype of any objects returned by {@link #getSingle(Event)} and the component type of any arrays returned by {@link #getArray(Event)} */ Class getReturnType(); @@ -201,11 +201,11 @@ default boolean canReturn(Class returnType) { /** * Returns true if this expression returns all possible values, false if it only returns some of them. *

- * This method significantly influences {@link #check(Event, Checker)}, {@link #check(Event, Checker, boolean)} and {@link CondIsSet} and thus breaks conditions that use this + * This method significantly influences {@link #check(Event, Predicate)}, {@link #check(Event, Predicate, boolean)} and {@link CondIsSet} and thus breaks conditions that use this * expression if it returns a wrong value. *

* This method must return true if this is a {@link #isSingle() single} expression. // TODO make this method irrelevant for single expressions - * + * * @return Whether this expression returns all values at once or only part of them. */ boolean getAnd(); @@ -218,7 +218,7 @@ default boolean canReturn(Class returnType) { *

* If this method returns false the expression will be discarded and an error message is printed. Custom error messages must be of {@link ErrorQuality#SEMANTIC_ERROR} to be * printed (NB: {@link Skript#error(String)} always creates semantic errors). - * + * * @param time -1 for past or 1 for future. 0 is never passed to this method as it represents the default state. * @return Whether this expression has distinct time states, e.g. a player never changes but a block can. This should be sensitive for the event (using * {@link ch.njol.skript.lang.parser.ParserInstance#isCurrentEvent(Class)}). @@ -238,7 +238,7 @@ default boolean canReturn(Class returnType) { * Returns whether this value represents the default value of its type for the event, i.e. it can be replaced with a call to event.getXyz() if one knows the event & value type. *

* This method might be removed in the future as it's better to check whether value == event.getXyz() for every value an expression returns. - * + * * @return Whether this is the return types' default expression */ boolean isDefault(); @@ -247,7 +247,7 @@ default boolean canReturn(Class returnType) { * Returns the original expression that was parsed, i.e. without any conversions done. *

* This method is undefined for simplified expressions. - * + * * @return The unconverted source expression of this expression or this expression itself if it was never converted. */ Expression getSource(); @@ -258,7 +258,7 @@ default boolean canReturn(Class returnType) { * After this method was used the toString methods are likely not useful anymore. *

* This method is not yet used but will be used to improve efficiency in the future. - * + * * @return A reference to a simpler version of this expression. Can change this expression directly and return itself if applicable, i.e. no references to the expression before * this method call should be kept! */ @@ -274,7 +274,7 @@ default boolean canReturn(Class returnType) { * super.change(...). *

* Unlike {@link Changer#acceptChange(ChangeMode)} this method may print errors. - * + * * @param mode The mode to check * @return An array of types that {@link #change(Event, Object[], ChangeMode)} accepts as its delta parameter (which can be arrays to denote that multiple of * that type are accepted), or null if the given mode is not supported. For {@link ChangeMode#DELETE} and {@link ChangeMode#RESET} this can return any non-null array to @@ -299,7 +299,7 @@ default Map[]> getAcceptedChangeModes() { /** * Changes the expression's value by the given amount. This will only be called on supported modes and with the desired delta type as returned by * {@link #acceptChange(ChangeMode)} - * + * * @param event The event * @param delta An array with one or more instances of one or more of the classes returned by {@link #acceptChange(ChangeMode)} for the given change mode (null for * {@link ChangeMode#DELETE} and {@link ChangeMode#RESET}). This can be a Object[], thus casting is not allowed. diff --git a/src/main/java/ch/njol/skript/lang/ExpressionList.java b/src/main/java/ch/njol/skript/lang/ExpressionList.java index ccd9efcb50a..3a09e70630b 100644 --- a/src/main/java/ch/njol/skript/lang/ExpressionList.java +++ b/src/main/java/ch/njol/skript/lang/ExpressionList.java @@ -5,7 +5,6 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleLiteral; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; @@ -136,12 +135,12 @@ public boolean isSingle() { } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return CollectionUtils.check(expressions, expr -> expr.check(event, checker) ^ negated, and); } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { return check(event, checker, false); } diff --git a/src/main/java/ch/njol/skript/lang/UnparsedLiteral.java b/src/main/java/ch/njol/skript/lang/UnparsedLiteral.java index 202fab7fee9..259305a3aab 100644 --- a/src/main/java/ch/njol/skript/lang/UnparsedLiteral.java +++ b/src/main/java/ch/njol/skript/lang/UnparsedLiteral.java @@ -8,13 +8,13 @@ import ch.njol.skript.log.ParseLogHandler; import ch.njol.skript.log.SkriptLogger; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import ch.njol.util.coll.iterator.NonNullIterator; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import java.util.function.Predicate; import java.util.logging.Level; /** @@ -167,12 +167,12 @@ public Class[] acceptChange(ChangeMode mode) { } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { throw invalidAccessException(); } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { throw invalidAccessException(); } diff --git a/src/main/java/ch/njol/skript/lang/Variable.java b/src/main/java/ch/njol/skript/lang/Variable.java index 95e1331fd3c..95fb0f6c59b 100644 --- a/src/main/java/ch/njol/skript/lang/Variable.java +++ b/src/main/java/ch/njol/skript/lang/Variable.java @@ -4,6 +4,9 @@ import java.util.*; import java.util.Map.Entry; import java.util.regex.Pattern; +import java.util.NoSuchElementException; +import java.util.TreeMap; +import java.util.function.Predicate; import java.util.function.Function; import ch.njol.skript.Skript; @@ -26,7 +29,6 @@ import ch.njol.skript.util.Utils; import ch.njol.skript.variables.TypeHints; import ch.njol.skript.variables.Variables; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.Pair; import ch.njol.util.StringUtils; @@ -730,12 +732,12 @@ public boolean isIndexLoop(String input) { } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return SimpleExpression.check(getAll(event), checker, negated, getAnd()); } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { return SimpleExpression.check(getAll(event), checker, false, getAnd()); } diff --git a/src/main/java/ch/njol/skript/lang/VariableString.java b/src/main/java/ch/njol/skript/lang/VariableString.java index cbbddd753fd..db6b1173e82 100644 --- a/src/main/java/ch/njol/skript/lang/VariableString.java +++ b/src/main/java/ch/njol/skript/lang/VariableString.java @@ -17,7 +17,6 @@ import ch.njol.skript.util.Utils; import ch.njol.skript.util.chat.ChatMessages; import ch.njol.skript.util.chat.MessageComponent; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.StringUtils; import ch.njol.util.coll.CollectionUtils; @@ -33,6 +32,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; +import java.util.function.Predicate; import java.util.stream.Collectors; /** @@ -637,12 +637,12 @@ public boolean isSingle() { } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return SimpleExpression.check(getAll(event), checker, negated, false); } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { return SimpleExpression.check(getAll(event), checker, false, false); } diff --git a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java index 9c17a103c67..e1b889b8742 100644 --- a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java +++ b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java @@ -6,8 +6,6 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.Classes; -import ch.njol.skript.util.Utils; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; @@ -23,6 +21,7 @@ import java.util.List; import java.util.NoSuchElementException; import java.util.stream.Collectors; +import java.util.function.Predicate; /** * Represents a expression converted to another type. This, and not Expression, is the required return type of {@link SimpleExpression#getConvertedExpr(Class...)} because this @@ -187,18 +186,18 @@ public T[] getAll(Event event) { } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return negated ^ check(event, checker); } @Override - public boolean check(Event event, Checker checker) { - return source.check(event, (Checker) value -> { + public boolean check(Event event, Predicate checker) { + return source.check(event, (Predicate) value -> { T convertedValue = converter.convert(value); if (convertedValue == null) { return false; } - return checker.check(convertedValue); + return checker.test(convertedValue); }); } diff --git a/src/main/java/ch/njol/skript/lang/util/ConvertedLiteral.java b/src/main/java/ch/njol/skript/lang/util/ConvertedLiteral.java index 4336f9cca26..d28effb9faf 100644 --- a/src/main/java/ch/njol/skript/lang/util/ConvertedLiteral.java +++ b/src/main/java/ch/njol/skript/lang/util/ConvertedLiteral.java @@ -3,7 +3,6 @@ import ch.njol.skript.SkriptAPIException; import ch.njol.skript.lang.Literal; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Checker; import ch.njol.util.coll.CollectionUtils; import ch.njol.util.coll.iterator.ArrayIterator; import org.bukkit.event.Event; @@ -12,6 +11,7 @@ import org.skriptlang.skript.lang.converter.Converters; import java.util.Iterator; +import java.util.function.Predicate; /** * @see SimpleLiteral @@ -73,12 +73,12 @@ public T getSingle(Event event) { } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { return SimpleExpression.check(data, checker, false, getAnd()); } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return SimpleExpression.check(data, checker, negated, getAnd()); } diff --git a/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java b/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java index ba08a0f8c61..94175bf1557 100644 --- a/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java +++ b/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java @@ -10,7 +10,6 @@ import ch.njol.skript.lang.Loopable; import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.Utils; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import ch.njol.util.coll.iterator.ArrayIterator; @@ -23,10 +22,11 @@ import java.lang.reflect.Array; import java.util.Arrays; import java.util.Iterator; +import java.util.function.Predicate; /** * An implementation of the {@link Expression} interface. You should usually extend this class to make a new expression. - * + * * @see Skript#registerExpression(Class, Class, ExpressionType, String...) */ public abstract class SimpleExpression implements Expression { @@ -119,24 +119,24 @@ public final T[] getArray(Event event) { /** * This is the internal method to get an expression's values.
* To get the expression's value from the outside use {@link #getSingle(Event)} or {@link #getArray(Event)}. - * + * * @param event The event with which this expression is evaluated. * @return An array of values for this event. May not contain nulls. */ protected abstract T @Nullable [] get(Event event); @Override - public final boolean check(Event event, Checker checker) { + public final boolean check(Event event, Predicate checker) { return check(event, checker, false); } @Override - public final boolean check(Event event, Checker checker, boolean negated) { + public final boolean check(Event event, Predicate checker, boolean negated) { return check(get(event), checker, negated, getAnd()); } // TODO return a kleenean (UNKNOWN if 'values' is null or empty) - public static boolean check(T @Nullable [] values, Checker checker, boolean invert, boolean and) { + public static boolean check(@Nullable T[] values, Predicate checker, boolean invert, boolean and) { if (values == null) return invert; boolean hasElement = false; @@ -144,7 +144,7 @@ public static boolean check(T @Nullable [] values, Checker checke if (value == null) continue; hasElement = true; - boolean b = checker.check(value); + boolean b = checker.test(value); if (and && !b) return invert; if (!and && b) @@ -159,7 +159,7 @@ public static boolean check(T @Nullable [] values, Checker checke * Converts this expression to another type. Unless the expression is special, the default implementation is sufficient. *

* This method is never called with a supertype of the return type of this expression, or the return type itself. - * + * * @param to The desired return type of the returned expression * @return Expression with the desired return type or null if it can't be converted to the given type * @see Expression#getConvertedExpression(Class...) @@ -218,7 +218,7 @@ public void change(Event event, Object @Nullable [] delta, ChangeMode mode) { * {@inheritDoc} *

* This implementation sets the time but returns false. - * + * * @see #setTime(int, Class, Expression...) * @see #setTime(int, Expression, Class...) */ diff --git a/src/main/java/ch/njol/skript/lang/util/SimpleLiteral.java b/src/main/java/ch/njol/skript/lang/util/SimpleLiteral.java index 64872659b2b..fdb2235b34b 100644 --- a/src/main/java/ch/njol/skript/lang/util/SimpleLiteral.java +++ b/src/main/java/ch/njol/skript/lang/util/SimpleLiteral.java @@ -11,7 +11,6 @@ import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.StringMode; import ch.njol.skript.util.Utils; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import ch.njol.util.coll.iterator.NonNullIterator; @@ -21,6 +20,7 @@ import java.lang.reflect.Array; import java.util.Arrays; +import java.util.function.Predicate; /** * Represents a literal, i.e. a static value like a number or a string. @@ -150,12 +150,12 @@ public boolean isDefault() { } @Override - public boolean check(Event event, Checker checker, boolean negated) { + public boolean check(Event event, Predicate checker, boolean negated) { return SimpleExpression.check(data, checker, negated, getAnd()); } @Override - public boolean check(Event event, Checker checker) { + public boolean check(Event event, Predicate checker) { return SimpleExpression.check(data, checker, false, getAnd()); } diff --git a/src/main/java/ch/njol/skript/util/Utils.java b/src/main/java/ch/njol/skript/util/Utils.java index 0d6f81e9b6e..7cf915961bf 100644 --- a/src/main/java/ch/njol/skript/util/Utils.java +++ b/src/main/java/ch/njol/skript/util/Utils.java @@ -31,7 +31,6 @@ import ch.njol.skript.localization.Language; import ch.njol.skript.localization.LanguageChangeListener; import ch.njol.skript.registrations.Classes; -import ch.njol.util.Checker; import ch.njol.util.NonNullPair; import ch.njol.util.Pair; import ch.njol.util.StringUtils; @@ -797,16 +796,16 @@ public static Class classForName(String name) { } /** - * Finds the index of the last in a {@link List} that matches the given {@link Checker}. + * Finds the index of the last in a {@link List} that matches the given {@link Predicate}. * * @param list the {@link List} to search. - * @param checker the {@link Checker} to match elements against. + * @param checker the {@link Predicate} to match elements against. * @return the index of the element found, or -1 if no matching element was found. */ - public static int findLastIndex(List list, Checker checker) { + public static int findLastIndex(List list, Predicate checker) { int lastIndex = -1; for (int i = 0; i < list.size(); i++) { - if (checker.check(list.get(i))) + if (checker.test(list.get(i))) lastIndex = i; } return lastIndex; diff --git a/src/main/java/ch/njol/util/Checker.java b/src/main/java/ch/njol/util/Checker.java index 0b7f5bb0098..a4ba070f4e0 100644 --- a/src/main/java/ch/njol/util/Checker.java +++ b/src/main/java/ch/njol/util/Checker.java @@ -1,8 +1,19 @@ package ch.njol.util; +import org.jetbrains.annotations.ApiStatus; + +import java.util.function.Predicate; + +@Deprecated @FunctionalInterface -public interface Checker { - - public boolean check(T o); - +@ApiStatus.ScheduledForRemoval +public interface Checker extends Predicate { + + boolean check(T o); + + @Override + default boolean test(T t) { + return this.check(t); + } + } diff --git a/src/main/java/ch/njol/util/NullableChecker.java b/src/main/java/ch/njol/util/NullableChecker.java index c260d14f41d..0707c3bb10f 100644 --- a/src/main/java/ch/njol/util/NullableChecker.java +++ b/src/main/java/ch/njol/util/NullableChecker.java @@ -2,16 +2,18 @@ import org.jetbrains.annotations.Nullable; -public interface NullableChecker extends Checker { - +import java.util.function.Predicate; + +public interface NullableChecker extends ch.njol.util.Checker, Predicate { + @Override - public boolean check(@Nullable T o); - + boolean check(@Nullable T o); + public static final NullableChecker nullChecker = new NullableChecker() { @Override public boolean check(final @Nullable Object o) { return o != null; } }; - + } diff --git a/src/main/java/ch/njol/util/Predicate.java b/src/main/java/ch/njol/util/Predicate.java index be2607af2f4..f5e80de8c81 100644 --- a/src/main/java/ch/njol/util/Predicate.java +++ b/src/main/java/ch/njol/util/Predicate.java @@ -1,12 +1,17 @@ package ch.njol.util; +import org.jetbrains.annotations.ApiStatus; + import javax.annotation.Nullable; /** * @author Peter G�ttinger * */ -public abstract interface Predicate { - public abstract boolean test(@Nullable T paramT); +@Deprecated +@FunctionalInterface +@ApiStatus.ScheduledForRemoval +public interface Predicate extends java.util.function.Predicate { + boolean test(@Nullable T paramT); } From 8524c0abf684504abbdbe14265e187acfb02ea64 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:08:56 +0000 Subject: [PATCH 5/7] Deprecate outdated utils/validate (#6666) * Mark Validate as internal * Schedule for removal + change usages * Use preconditions --- .../java/ch/njol/skript/command/Commands.java | 4 +- .../ch/njol/skript/command/ScriptCommand.java | 10 ++++- .../events/bukkit/PreScriptLoadEvent.java | 10 ++--- src/main/java/ch/njol/util/Validate.java | 43 ++++++++++--------- 4 files changed, 37 insertions(+), 30 deletions(-) diff --git a/src/main/java/ch/njol/skript/command/Commands.java b/src/main/java/ch/njol/skript/command/Commands.java index e3d4cd8023e..ec4c4f6595d 100644 --- a/src/main/java/ch/njol/skript/command/Commands.java +++ b/src/main/java/ch/njol/skript/command/Commands.java @@ -12,7 +12,7 @@ import ch.njol.skript.log.SkriptLogger; import ch.njol.skript.util.SkriptColor; import ch.njol.skript.variables.Variables; -import org.apache.commons.lang.Validate; +import com.google.common.base.Preconditions; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; @@ -321,7 +321,7 @@ public CommandAliasHelpTopic(String alias, String aliasFor, HelpMap helpMap) { this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor; this.helpMap = helpMap; name = alias.startsWith("/") ? alias : "/" + alias; - Validate.isTrue(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself"); + Preconditions.checkState(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself"); shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor; } diff --git a/src/main/java/ch/njol/skript/command/ScriptCommand.java b/src/main/java/ch/njol/skript/command/ScriptCommand.java index facd915eb9c..48d6c01dbbc 100644 --- a/src/main/java/ch/njol/skript/command/ScriptCommand.java +++ b/src/main/java/ch/njol/skript/command/ScriptCommand.java @@ -25,7 +25,7 @@ import ch.njol.skript.util.chat.MessageComponent; import ch.njol.skript.variables.Variables; import ch.njol.util.StringUtils; -import ch.njol.util.Validate; +import com.google.common.base.Preconditions; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; @@ -147,7 +147,13 @@ public ScriptCommand( @Nullable VariableString cooldownMessage, String cooldownBypass, @Nullable VariableString cooldownStorage, int executableBy, SectionNode node ) { - Validate.notNull(name, pattern, arguments, description, usage, aliases, node); + Preconditions.checkNotNull(name); + Preconditions.checkNotNull(pattern); + Preconditions.checkNotNull(arguments); + Preconditions.checkNotNull(description); + Preconditions.checkNotNull(usage); + Preconditions.checkNotNull(aliases); + Preconditions.checkNotNull(node); this.name = name; label = "" + name.toLowerCase(Locale.ENGLISH); this.permission = permission; diff --git a/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java b/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java index 7237cb0f07e..a80607e812f 100644 --- a/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java +++ b/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java @@ -1,14 +1,12 @@ package ch.njol.skript.events.bukkit; -import java.util.List; - +import ch.njol.skript.config.Config; +import com.google.common.base.Preconditions; import org.bukkit.Bukkit; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; -import ch.njol.skript.config.Config; -import ch.njol.util.Validate; -import ch.njol.skript.ScriptLoader; +import java.util.List; /** * This event has no guarantee of being on the main thread. @@ -22,7 +20,7 @@ public class PreScriptLoadEvent extends Event { public PreScriptLoadEvent(List scripts) { super(!Bukkit.isPrimaryThread()); - Validate.notNull(scripts); + Preconditions.checkNotNull(scripts); this.scripts = scripts; } diff --git a/src/main/java/ch/njol/util/Validate.java b/src/main/java/ch/njol/util/Validate.java index 0f73e980f60..b1cd7c7c15b 100644 --- a/src/main/java/ch/njol/util/Validate.java +++ b/src/main/java/ch/njol/util/Validate.java @@ -1,63 +1,66 @@ package ch.njol.util; +import org.eclipse.jdt.annotation.Nullable; +import org.jetbrains.annotations.ApiStatus; + import java.util.Collection; import org.jetbrains.annotations.Nullable; +@Deprecated +@ApiStatus.ScheduledForRemoval +public final class Validate { -/** - * @author Peter Güttinger - */ -public abstract class Validate { - - public static void notNull(final Object... objects) { + private Validate() {} + + public static void notNull(Object... objects) { for (int i = 0; i < objects.length; i++) { if (objects[i] == null) throw new IllegalArgumentException("the " + StringUtils.fancyOrderNumber(i + 1) + " parameter must not be null"); } } - public static void notNull(final @Nullable Object object, final String name) { + public static void notNull(@Nullable Object object, String name) { if (object == null) throw new IllegalArgumentException(name + " must not be null"); } - public static void isTrue(final boolean b, final String error) { - if (!b) + public static void isTrue(boolean value, String error) { + if (!value) throw new IllegalArgumentException(error); } - public static void isFalse(final boolean b, final String error) { - if (b) + public static void isFalse(boolean value, String error) { + if (value) throw new IllegalArgumentException(error); } - public static void notNullOrEmpty(final @Nullable String s, final String name) { - if (s == null || s.isEmpty()) + public static void notNullOrEmpty(@Nullable String value, final String name) { + if (value == null || value.isEmpty()) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - public static void notNullOrEmpty(final @Nullable Object[] array, final String name) { + public static void notNullOrEmpty(Object @Nullable [] array, String name) { if (array == null || array.length == 0) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - public static void notNullOrEmpty(final @Nullable Collection collection, final String name) { + public static void notNullOrEmpty(@Nullable Collection collection, String name) { if (collection == null || collection.isEmpty()) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - public static void notEmpty(final @Nullable String s, final String name) { - if (s != null && s.isEmpty()) + public static void notEmpty(@Nullable String value, String name) { + if (value != null && value.isEmpty()) throw new IllegalArgumentException(name + " must not be empty"); } - public static void notEmpty(final Object[] array, final String name) { + public static void notEmpty(Object[] array, String name) { if (array.length == 0) throw new IllegalArgumentException(name + " must not be empty"); } - public static void notEmpty(final int[] nums, final String name) { - if (nums.length == 0) + public static void notEmpty(int[] array, String name) { + if (array.length == 0) throw new IllegalArgumentException(name + " must not be empty"); } From 8871bb1a5c370af4cbf31c72fae848f86d8bb5a0 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:09:51 +0000 Subject: [PATCH 6/7] Remove Java 6 support in file utils. (#6668) --- .../java/ch/njol/skript/events/EvtClick.java | 88 +++++++------------ .../expressions/ExprVectorCylindrical.java | 6 +- .../ExprVectorFromYawAndPitch.java | 6 +- .../expressions/ExprVectorSpherical.java | 6 +- .../njol/skript/expressions/ExprYawPitch.java | 79 ++++++++--------- .../ch/njol/skript/lang/ExpressionList.java | 1 + .../skript/lang/util/ConvertedExpression.java | 1 + .../java/ch/njol/skript/util/FileUtils.java | 81 ++--------------- src/main/java/ch/njol/util/Validate.java | 24 +++-- src/main/java/ch/njol/util/VectorMath.java | 54 +++++++++--- 10 files changed, 138 insertions(+), 208 deletions(-) diff --git a/src/main/java/ch/njol/skript/events/EvtClick.java b/src/main/java/ch/njol/skript/events/EvtClick.java index d0d903ef245..ab4a0159255 100644 --- a/src/main/java/ch/njol/skript/events/EvtClick.java +++ b/src/main/java/ch/njol/skript/events/EvtClick.java @@ -1,6 +1,15 @@ package ch.njol.skript.events; +import ch.njol.skript.Skript; +import ch.njol.skript.aliases.ItemType; +import ch.njol.skript.bukkitutil.ClickEventTracker; +import ch.njol.skript.classes.data.DefaultComparators; +import ch.njol.skript.entity.EntityData; +import ch.njol.skript.lang.Literal; +import ch.njol.skript.lang.SkriptEvent; +import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Predicate; +import ch.njol.util.coll.CollectionUtils; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.entity.ArmorStand; @@ -18,18 +27,6 @@ import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.comparator.Relation; -import ch.njol.skript.Skript; -import ch.njol.skript.aliases.ItemType; -import ch.njol.skript.bukkitutil.ClickEventTracker; -import ch.njol.skript.classes.data.DefaultComparators; -import ch.njol.skript.entity.EntityData; -import ch.njol.skript.lang.Literal; -import ch.njol.skript.lang.SkriptEvent; -import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.coll.CollectionUtils; - -import java.util.function.Predicate; - public class EvtClick extends SkriptEvent { /** @@ -109,10 +106,10 @@ public boolean init(Literal[] args, int matchedPattern, ParseResult parseResu public boolean check(Event event) { Block block; Entity entity; - + if (event instanceof PlayerInteractEntityEvent interactEntityEvent) { Entity clicked = interactEntityEvent.getRightClicked(); - + // Usually, don't handle these events if (interactEntityEvent instanceof PlayerInteractAtEntityEvent) { // But armor stands are an exception @@ -146,13 +143,13 @@ public boolean check(Event event) { } if ((this.click & click) == 0) return false; // We don't want to handle this kind of events - + EquipmentSlot hand = interactEvent.getHand(); assert hand != null; // Not PHYSICAL interaction if (!interactTracker.checkEvent(interactEvent.getPlayer(), interactEvent, hand)) { return false; // Not first event this tick } - + block = interactEvent.getClickedBlock(); entity = null; } else { @@ -160,55 +157,36 @@ public boolean check(Event event) { return false; } - if (tools != null && !tools.check(event, new Predicate() { - @Override - public boolean test(final ItemType t) { - if (event instanceof PlayerInteractEvent) { - return t.isOfType(((PlayerInteractEvent) event).getItem()); - } else { // PlayerInteractEntityEvent doesn't have item associated with it - PlayerInventory invi = ((PlayerInteractEntityEvent) event).getPlayer().getInventory(); - ItemStack item = ((PlayerInteractEntityEvent) event).getHand() == EquipmentSlot.HAND - ? invi.getItemInMainHand() : invi.getItemInOffHand(); - return t.isOfType(item); - } + Predicate checker = itemType -> { + if (event instanceof PlayerInteractEvent interactEvent) { + return itemType.isOfType(interactEvent.getItem()); + } else { + PlayerInventory invi = ((PlayerInteractEntityEvent) event).getPlayer().getInventory(); + ItemStack item = ((PlayerInteractEntityEvent) event).getHand() == EquipmentSlot.HAND + ? invi.getItemInMainHand() : invi.getItemInOffHand(); + return itemType.isOfType(item); } }; if (tools != null && !tools.check(event, checker)) return false; -<<<<<<< -======= - } - ->>>>>>> if (type != null) { -<<<<<<< BlockData blockDataCheck = block != null ? block.getBlockData() : null; - return type.check(event, new Checker() { -======= - return type.check(event, new Predicate() { ->>>>>>> - @Override -<<<<<<< - public boolean check(Object object) { -======= - public boolean test(final Object o) { ->>>>>>> - if (entity != null) { - if (object instanceof EntityData entityData) { - return entityData.isInstance(entity); - } else { - Relation compare = DefaultComparators.entityItemComparator.compare(EntityData.fromEntity(entity), (ItemType) object); - return Relation.EQUAL.isImpliedBy(compare); - } - } else if (object instanceof ItemType itemType) { - return itemType.isOfType(block); - } else if (blockDataCheck != null && object instanceof BlockData blockData) { - return blockDataCheck.matches(blockData); + return type.check(event, (Predicate) object -> { + if (entity != null) { + if (object instanceof EntityData entityData) { + return entityData.isInstance(entity); + } else { + Relation compare = DefaultComparators.entityItemComparator.compare(EntityData.fromEntity(entity), (ItemType) object); + return Relation.EQUAL.isImpliedBy(compare); } - return false; + } else if (object instanceof ItemType itemType) { + return itemType.isOfType(block); + } else if (blockDataCheck != null && object instanceof BlockData blockData) { + return blockDataCheck.matches(blockData); } + return false; }); } return true; diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java index be649dd4a4a..b8b9b84ab6c 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java @@ -1,9 +1,5 @@ package ch.njol.skript.expressions; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -17,8 +13,8 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.eclipse.jdt.annotation.Nullable; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; @Name("Vectors - Cylindrical Shape") @Description("Forms a 'cylindrical shaped' vector using yaw to manipulate the current point.") diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java index d7b065e013d..a0892371c1d 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java @@ -1,9 +1,5 @@ package ch.njol.skript.expressions; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -17,8 +13,8 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.eclipse.jdt.annotation.Nullable; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; @Name("Vectors - Vector from Pitch and Yaw") @Description("Creates a vector from a yaw and pitch value.") diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java index 250fa602a72..e624663e00a 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java @@ -1,9 +1,5 @@ package ch.njol.skript.expressions; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -17,8 +13,8 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.eclipse.jdt.annotation.Nullable; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; @Name("Vectors - Spherical Shape") @Description("Forms a 'spherical shaped' vector using yaw and pitch to manipulate the current point.") diff --git a/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java b/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java index 3d5ffe12300..b28558338b5 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java +++ b/src/main/java/ch/njol/skript/expressions/ExprYawPitch.java @@ -1,33 +1,35 @@ package ch.njol.skript.expressions; +import ch.njol.skript.ServerPlatform; +import ch.njol.skript.Skript; import ch.njol.skript.classes.Changer.ChangeMode; -import ch.njol.skript.doc.Description; -import ch.njol.skript.doc.Examples; -import ch.njol.skript.doc.Name; -import ch.njol.skript.doc.Since; +import ch.njol.skript.doc.*; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.Location; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.util.Vector; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; @Name("Yaw / Pitch") @Description({ - "The yaw or pitch of a location or vector.", - "A yaw of 0 or 360 represents the positive z direction. Adding a positive number to the yaw of a player will rotate it clockwise.", - "A pitch of 90 represents the negative y direction, or downward facing. A pitch of -90 represents upward facing. Adding a positive number to the pitch will rotate the direction downwards.", - "Only Paper 1.19+ users may directly change the yaw/pitch of players." + "The yaw or pitch of a location or vector.", + "A yaw of 0 or 360 represents the positive z direction. Adding a positive number to the yaw of a player will rotate it clockwise.", + "A pitch of 90 represents the negative y direction, or downward facing. A pitch of -90 represents upward facing. Adding a positive number to the pitch will rotate the direction downwards.", + "Only Paper 1.19+ users may directly change the yaw/pitch of players." }) @Examples({ - "log \"%player%: %location of player%, %player's yaw%, %player's pitch%\" to \"playerlocs.log\"", - "set {_yaw} to yaw of player", - "set {_p} to pitch of target entity", - "set pitch of player to -90 # Makes the player look upwards, Paper 1.19+ only", - "add 180 to yaw of target of player # Makes the target look behind themselves" + "log \"%player%: %location of player%, %player's yaw%, %player's pitch%\" to \"playerlocs.log\"", + "set {_yaw} to yaw of player", + "set {_p} to pitch of target entity", + "set pitch of player to -90 # Makes the player look upwards, Paper 1.19+ only", + "add 180 to yaw of target of player # Makes the target look behind themselves" }) @Since("2.0, 2.2-dev28 (vector yaw/pitch), 2.9.0 (entity changers)") @RequiredPlugins("Paper 1.19+ (player changers)") @@ -56,18 +58,16 @@ public Float convert(Object object) { if (object instanceof Entity) { Location location = ((Entity) object).getLocation(); return usesYaw - ? normalizeYaw(location.getYaw()) - : location.getPitch(); - } else if (object instanceof Location) { - Location location = (Location) object; + ? normalizeYaw(location.getYaw()) + : location.getPitch(); + } else if (object instanceof Location location) { return usesYaw - ? normalizeYaw(location.getYaw()) - : location.getPitch(); - } else if (object instanceof Vector) { - Vector vector = ((Vector) object); - if (usesYaw) - return skriptYaw(getYaw(vector)); - return skriptPitch(getPitch(vector)); + ? normalizeYaw(location.getYaw()) + : location.getPitch(); + } else if (object instanceof Vector vector) { + return usesYaw + ? skriptYaw((getYaw(vector))) + : skriptPitch(getPitch(vector)); } return null; } @@ -97,7 +97,7 @@ public void change(Event event, @Nullable Object[] delta, ChangeMode mode) { for (Object object : getExpr().getArray(event)) { if (object instanceof Player && !SUPPORTS_PLAYERS) continue; - + if (object instanceof Entity) { changeForEntity((Entity) object, value, mode); } else if (object instanceof Location) { @@ -170,7 +170,7 @@ private void changeForLocation(Location location, float value, ChangeMode mode) } } - private void changeVector(Vector vector, float n, ChangeMode mode) { + private void changeForVector(Vector vector, float value, ChangeMode mode) { float yaw = getYaw(vector); float pitch = getPitch(vector); switch (mode) { @@ -178,23 +178,21 @@ private void changeVector(Vector vector, float n, ChangeMode mode) { value = -value; // $FALL-THROUGH$ case ADD: - if (usesYaw) - yaw += n; - else - pitch -= n; // Negative because of Minecraft's / Skript's upside down pitch - Vector newVector = fromYawAndPitch(yaw, pitch).multiply(vector.length()); - vector.copy(newVector); + if (usesYaw) { + yaw += value; + } else { + // Subtracting because of Minecraft's upside-down pitch. + pitch -= value; + } break; case SET: if (usesYaw) - yaw = fromSkriptYaw(n); + yaw = fromSkriptYaw(value); else - pitch = fromSkriptPitch(n); - newVector = fromYawAndPitch(yaw, pitch).multiply(vector.length()); - vector.copy(newVector); + pitch = fromSkriptPitch(value); } - Vector newVector = VectorMath.fromYawAndPitch(yaw, pitch).multiply(vector.length()); - VectorMath.copyVector(vector, newVector); + Vector newVector = fromYawAndPitch(yaw, pitch).multiply(vector.length()); + vector.copy(newVector); } private static float normalizeYaw(float yaw) { @@ -254,14 +252,13 @@ public static float skriptPitch(float pitch) { return -pitch; } - private static float fromSkriptYaw(float yaw) { + public static float fromSkriptYaw(float yaw) { return yaw > 270 ? yaw - 270 : yaw + 90; } - private static float fromSkriptPitch(float pitch) { + public static float fromSkriptPitch(float pitch) { return -pitch; } - } diff --git a/src/main/java/ch/njol/skript/lang/ExpressionList.java b/src/main/java/ch/njol/skript/lang/ExpressionList.java index 3a09e70630b..a6c715a2155 100644 --- a/src/main/java/ch/njol/skript/lang/ExpressionList.java +++ b/src/main/java/ch/njol/skript/lang/ExpressionList.java @@ -13,6 +13,7 @@ import java.lang.reflect.Array; import java.util.*; +import java.util.function.Predicate; /** * A list of expressions. diff --git a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java index e1b889b8742..e76ff438747 100644 --- a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java +++ b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java @@ -6,6 +6,7 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.Classes; +import ch.njol.skript.util.Utils; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; diff --git a/src/main/java/ch/njol/skript/util/FileUtils.java b/src/main/java/ch/njol/skript/util/FileUtils.java index a808611253d..2e9b7bd8e48 100644 --- a/src/main/java/ch/njol/skript/util/FileUtils.java +++ b/src/main/java/ch/njol/skript/util/FileUtils.java @@ -1,7 +1,6 @@ package ch.njol.skript.util; import java.io.File; -import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -21,18 +20,6 @@ */ public abstract class FileUtils { - private static boolean RUNNINGJAVA6 = true;// = System.getProperty("java.version").startsWith("1.6"); // doesn't work reliably? - static { - try { - new File(".").toPath(); - RUNNINGJAVA6 = false; - } catch (final NoSuchMethodError e) { - RUNNINGJAVA6 = true; - } catch (final Exception e) { - RUNNINGJAVA6 = false; - } - } - private FileUtils() {} private final static SimpleDateFormat backupFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); @@ -49,9 +36,9 @@ public static String getBackupSuffix() { /** * Deletes files in backup directory to meet desired target, starting from oldest to newest * - * @param csvFile Variable file in order to get 'backups' directory - * @param toKeep Integer of how many files are to be left remaining - * @throws IOException If 'backups' directory is not found + * @param varFile Variable file in order to get 'backups' directory + * @param toKeep Integer of how many files are to be left remaining + * @throws IOException If 'backups' directory is not found * @throws IllegalArgumentException If 'toKeep' parameter is less than 0 */ public static void backupPurge(File varFile, int toKeep) throws IOException, IllegalArgumentException { @@ -90,60 +77,15 @@ public static File backup(final File f) throws IOException { public static File move(final File from, final File to, final boolean replace) throws IOException { if (!replace && to.exists()) throw new IOException("Can't rename " + from.getName() + " to " + to.getName() + ": The target file already exists"); - if (!RUNNINGJAVA6) { - if (replace) - Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - else - Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE); - } else { - File moveTo = null; - if (replace && to.exists()) { - moveTo = new File(to.getAbsolutePath() + ".old0"); - int i = 0; - while (moveTo.exists() && i < 1000) - moveTo = new File(to.getAbsolutePath() + ".old" + (++i)); - if (i == 999 || !to.renameTo(moveTo)) - throw new IOException("Can't rename " + from.getName() + " to " + to.getName() + ": Cannot temporarily rename the target file"); - } - if (!from.renameTo(to)) { - if (moveTo != null) - moveTo.renameTo(to); - throw new IOException("Can't rename " + from.getName() + " to " + to.getName()); - } - if (moveTo != null) - moveTo.delete(); - } + if (replace) + Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + else + Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE); return to; } public static void copy(final File from, final File to) throws IOException { - if (!RUNNINGJAVA6) { - Files.copy(from.toPath(), to.toPath(), StandardCopyOption.COPY_ATTRIBUTES); - } else { - FileInputStream in = null; - FileOutputStream out = null; - try { - in = new FileInputStream(from); - out = new FileOutputStream(to); - final byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = in.read(buffer)) != -1) - out.write(buffer, 0, bytesRead); - } catch (final Exception e) { - throw new IOException("Can't copy " + from.getName() + " to " + to.getName() + ": " + e.getLocalizedMessage(), e); - } finally { - if (in != null) { - try { - in.close(); - } catch (final IOException e) {} - } - if (out != null) { - try { - out.close(); - } catch (final IOException e) {} - } - } - } + Files.copy(from.toPath(), to.toPath(), StandardCopyOption.COPY_ATTRIBUTES); } /** @@ -181,17 +123,12 @@ public static Collection renameAll(final File directory, final Converter 0) { out.write(buffer, 0, read); } - } finally { - if (out != null) - out.close(); } } diff --git a/src/main/java/ch/njol/util/Validate.java b/src/main/java/ch/njol/util/Validate.java index b1cd7c7c15b..293796a533a 100644 --- a/src/main/java/ch/njol/util/Validate.java +++ b/src/main/java/ch/njol/util/Validate.java @@ -1,11 +1,9 @@ package ch.njol.util; -import org.eclipse.jdt.annotation.Nullable; import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Nullable; import java.util.Collection; - -import org.jetbrains.annotations.Nullable; @Deprecated @ApiStatus.ScheduledForRemoval public final class Validate { @@ -18,50 +16,50 @@ public static void notNull(Object... objects) { throw new IllegalArgumentException("the " + StringUtils.fancyOrderNumber(i + 1) + " parameter must not be null"); } } - + public static void notNull(@Nullable Object object, String name) { if (object == null) throw new IllegalArgumentException(name + " must not be null"); } - + public static void isTrue(boolean value, String error) { if (!value) throw new IllegalArgumentException(error); } - + public static void isFalse(boolean value, String error) { if (value) throw new IllegalArgumentException(error); } - + public static void notNullOrEmpty(@Nullable String value, final String name) { if (value == null || value.isEmpty()) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - + public static void notNullOrEmpty(Object @Nullable [] array, String name) { if (array == null || array.length == 0) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - + public static void notNullOrEmpty(@Nullable Collection collection, String name) { if (collection == null || collection.isEmpty()) throw new IllegalArgumentException(name + " must neither be null nor empty"); } - + public static void notEmpty(@Nullable String value, String name) { if (value != null && value.isEmpty()) throw new IllegalArgumentException(name + " must not be empty"); } - + public static void notEmpty(Object[] array, String name) { if (array.length == 0) throw new IllegalArgumentException(name + " must not be empty"); } - + public static void notEmpty(int[] array, String name) { if (array.length == 0) throw new IllegalArgumentException(name + " must not be empty"); } - + } diff --git a/src/main/java/ch/njol/util/VectorMath.java b/src/main/java/ch/njol/util/VectorMath.java index a2e377d221f..7ca9636e1cb 100644 --- a/src/main/java/ch/njol/util/VectorMath.java +++ b/src/main/java/ch/njol/util/VectorMath.java @@ -1,22 +1,18 @@ package ch.njol.util; -import ch.njol.skript.effects.EffVectorRotateAroundAnother; -import ch.njol.skript.effects.EffVectorRotateXYZ; import ch.njol.skript.expressions.ExprVectorCylindrical; import ch.njol.skript.expressions.ExprVectorFromYawAndPitch; import ch.njol.skript.expressions.ExprVectorSpherical; import ch.njol.skript.expressions.ExprYawPitch; import org.bukkit.util.Vector; -import org.jetbrains.annotations.ApiStatus; -@Deprecated -@ApiStatus.ScheduledForRemoval +@Deprecated(forRemoval = true) public final class VectorMath { public static final double PI = Math.PI; public static final double HALF_PI = PI / 2; public static final double DEG_TO_RAD = Math.PI / 180; - public static final double RAD_TO_DEG = 180 / Math.PI; + public static final double RAD_TO_DEG = 180 / Math.PI; private VectorMath() {} @@ -41,19 +37,53 @@ public static float getPitch(Vector vector) { } public static Vector rotX(Vector vector, double angle) { - return EffVectorRotateXYZ.rotX(vector, angle); + double sin = Math.sin(angle * DEG_TO_RAD); + double cos = Math.cos(angle * DEG_TO_RAD); + Vector vy = new Vector(0, cos, -sin); + Vector vz = new Vector(0, sin, cos); + Vector clone = vector.clone(); + vector.setY(clone.dot(vy)); + vector.setZ(clone.dot(vz)); + return vector; } public static Vector rotY(Vector vector, double angle) { - return EffVectorRotateXYZ.rotY(vector, angle); + double sin = Math.sin(angle * DEG_TO_RAD); + double cos = Math.cos(angle * DEG_TO_RAD); + Vector vx = new Vector(cos, 0, sin); + Vector vz = new Vector(-sin, 0, cos); + Vector clone = vector.clone(); + vector.setX(clone.dot(vx)); + vector.setZ(clone.dot(vz)); + return vector; } public static Vector rotZ(Vector vector, double angle) { - return EffVectorRotateXYZ.rotZ(vector, angle); + double sin = Math.sin(angle * DEG_TO_RAD); + double cos = Math.cos(angle * DEG_TO_RAD); + Vector vx = new Vector(cos, -sin, 0); + Vector vy = new Vector(sin, cos, 0); + Vector clone = vector.clone(); + vector.setX(clone.dot(vx)); + vector.setY(clone.dot(vy)); + return vector; } public static Vector rot(Vector vector, Vector axis, double angle) { - return EffVectorRotateAroundAnother.rot(vector, axis, angle); + double sin = Math.sin(angle * DEG_TO_RAD); + double cos = Math.cos(angle * DEG_TO_RAD); + Vector a = axis.clone().normalize(); + double ax = a.getX(); + double ay = a.getY(); + double az = a.getZ(); + Vector rotx = new Vector(cos+ax*ax*(1-cos), ax*ay*(1-cos)-az*sin, ax*az*(1-cos)+ay*sin); + Vector roty = new Vector(ay*ax*(1-cos)+az*sin, cos+ay*ay*(1-cos), ay*az*(1-cos)-ax*sin); + Vector rotz = new Vector(az*ax*(1-cos)-ay*sin, az*ay*(1-cos)+ax*sin, cos+az*az*(1-cos)); + double x = rotx.dot(vector); + double y = roty.dot(vector); + double z = rotz.dot(vector); + vector.setX(x).setY(y).setZ(z); + return vector; } public static float skriptYaw(float yaw) { @@ -65,11 +95,11 @@ public static float skriptPitch(float pitch) { } public static float fromSkriptYaw(float yaw) { - return ExprVectorFromYawAndPitch.fromSkriptYaw(yaw); + return ExprYawPitch.fromSkriptYaw(yaw); } public static float fromSkriptPitch(float pitch) { - return ExprVectorFromYawAndPitch.fromSkriptPitch(pitch); + return ExprYawPitch.fromSkriptPitch(pitch); } public static float wrapAngleDeg(float angle) { From bf70e64dd3ee62189b4e733b4ac9c3b1474f4ac8 Mon Sep 17 00:00:00 2001 From: Moderocky Date: Wed, 1 Jan 2025 18:20:56 +0000 Subject: [PATCH 7/7] Finish removing unused utilities. --- .../java/ch/njol/skript/ScriptLoader.java | 260 +----------------- src/main/java/ch/njol/skript/Skript.java | 12 +- .../java/ch/njol/skript/SkriptConfig.java | 5 - .../ch/njol/skript/classes/Arithmetic.java | 24 -- .../njol/skript/classes/ChainedConverter.java | 49 ---- .../ch/njol/skript/classes/ClassInfo.java | 50 ---- .../java/ch/njol/skript/classes/Cloner.java | 5 +- .../ch/njol/skript/classes/Comparator.java | 218 --------------- .../ch/njol/skript/classes/Converter.java | 173 ------------ .../skript/classes/InverseComparator.java | 31 --- .../njol/skript/classes/NumberArithmetic.java | 57 ---- .../skript/classes/SerializableChanger.java | 7 - .../skript/classes/SerializableChecker.java | 6 +- .../skript/classes/SerializableGetter.java | 7 - .../skript/classes/VectorArithmethic.java | 40 --- .../java/ch/njol/skript/command/Commands.java | 3 +- .../njol/skript/conditions/CondCompare.java | 1 - .../skript/conditions/CondIsDivisibleBy.java | 1 - .../njol/skript/conditions/CondIsOfType.java | 50 ++-- .../conditions/base/PropertyCondition.java | 29 +- .../java/ch/njol/skript/config/Option.java | 14 +- .../config/validate/EntryValidator.java | 11 +- .../config/validate/EnumEntryValidator.java | 4 +- .../config/validate/ParsedEntryValidator.java | 9 +- .../config/validate/SectionValidator.java | 3 - .../ch/njol/skript/doc/Documentation.java | 61 ++-- .../java/ch/njol/skript/effects/EffLog.java | 17 +- .../ch/njol/skript/entity/EndermanData.java | 30 +- .../ch/njol/skript/entity/EntityData.java | 4 +- .../java/ch/njol/skript/events/EvtClick.java | 29 +- .../ch/njol/skript/events/EvtGameMode.java | 7 +- .../njol/skript/events/EvtWeatherChange.java | 16 +- .../events/bukkit/PreScriptLoadEvent.java | 5 +- .../skript/expressions/ExprDifference.java | 3 - .../ch/njol/skript/expressions/ExprNamed.java | 1 - .../njol/skript/expressions/ExprTarget.java | 14 - .../ch/njol/skript/expressions/ExprTool.java | 1 - .../expressions/ExprVectorAngleBetween.java | 12 +- .../expressions/ExprVectorCylindrical.java | 11 +- .../ExprVectorFromYawAndPitch.java | 33 +-- .../skript/expressions/ExprVectorLength.java | 5 +- .../expressions/ExprVectorNormalize.java | 10 +- .../expressions/ExprVectorSpherical.java | 12 +- .../arithmetic/ArithmeticChain.java | 13 +- .../expressions/base/PropertyExpression.java | 5 +- .../base/SimplePropertyExpression.java | 3 +- .../regions/conditions/CondCanBuild.java | 37 +-- .../regions/conditions/CondIsMember.java | 16 +- .../conditions/CondRegionContains.java | 23 +- .../java/ch/njol/skript/lang/Expression.java | 14 +- .../ch/njol/skript/lang/ExpressionList.java | 1 - .../java/ch/njol/skript/lang/Variable.java | 12 +- .../skript/lang/util/ConvertedExpression.java | 8 +- .../skript/lang/util/SimpleExpression.java | 5 +- .../ch/njol/skript/localization/Language.java | 2 +- .../localization/LanguageChangeListener.java | 1 + .../skript/registrations/Comparators.java | 102 ------- .../njol/skript/registrations/Converters.java | 192 ------------- .../java/ch/njol/skript/util/FileUtils.java | 15 +- src/main/java/ch/njol/skript/util/Getter.java | 2 +- .../njol/skript/util/PotionEffectUtils.java | 28 +- src/main/java/ch/njol/skript/util/Slot.java | 10 - .../ch/njol/skript/util/StructureType.java | 8 +- src/main/java/ch/njol/skript/util/Task.java | 1 + src/main/java/ch/njol/skript/util/Utils.java | 89 +++--- .../njol/skript/util/chat/ChatMessages.java | 32 +-- .../ch/njol/skript/variables/SQLStorage.java | 183 +----------- .../skript/variables/VariablesStorage.java | 2 +- src/main/java/ch/njol/util/Callback.java | 6 +- .../ch/njol/util/CaseInsensitiveString.java | 9 +- src/main/java/ch/njol/util/Checker.java | 8 +- src/main/java/ch/njol/util/Closeable.java | 2 + src/main/java/ch/njol/util/LoggerFilter.java | 11 +- src/main/java/ch/njol/util/Math2.java | 87 ------ src/main/java/ch/njol/util/NonNullPair.java | 3 +- .../java/ch/njol/util/NullableChecker.java | 14 +- src/main/java/ch/njol/util/Pair.java | 6 + src/main/java/ch/njol/util/Predicate.java | 6 +- src/main/java/ch/njol/util/Setter.java | 8 +- src/main/java/ch/njol/util/StringUtils.java | 117 ++++---- src/main/java/ch/njol/util/Validate.java | 8 +- .../java/ch/njol/util/coll/BidiHashMap.java | 52 ++-- src/main/java/ch/njol/util/coll/BidiMap.java | 3 +- .../java/ch/njol/util/coll/CyclicList.java | 3 +- .../ch/njol/util/coll/ReversedListView.java | 3 +- .../util/coll/iterator/CombinedIterator.java | 3 +- .../util/coll/iterator/ImprovedIterator.java | 4 + .../coll/iterator/ReversedListIterator.java | 3 +- .../njol/yggdrasil/util/JREFieldHandler.java | 98 ------- .../ch/njol/yggdrasil/util/package-info.java | 24 -- .../skript/lang/converter/Converters.java | 7 +- .../skript/lang/structure/Structure.java | 4 +- 92 files changed, 436 insertions(+), 2197 deletions(-) delete mode 100644 src/main/java/ch/njol/skript/classes/Arithmetic.java delete mode 100644 src/main/java/ch/njol/skript/classes/ChainedConverter.java delete mode 100644 src/main/java/ch/njol/skript/classes/Comparator.java delete mode 100644 src/main/java/ch/njol/skript/classes/Converter.java delete mode 100644 src/main/java/ch/njol/skript/classes/InverseComparator.java delete mode 100644 src/main/java/ch/njol/skript/classes/NumberArithmetic.java delete mode 100644 src/main/java/ch/njol/skript/classes/SerializableChanger.java delete mode 100644 src/main/java/ch/njol/skript/classes/SerializableGetter.java delete mode 100644 src/main/java/ch/njol/skript/classes/VectorArithmethic.java delete mode 100644 src/main/java/ch/njol/skript/registrations/Converters.java delete mode 100644 src/main/java/ch/njol/skript/util/Slot.java delete mode 100644 src/main/java/ch/njol/yggdrasil/util/JREFieldHandler.java delete mode 100644 src/main/java/ch/njol/yggdrasil/util/package-info.java diff --git a/src/main/java/ch/njol/skript/ScriptLoader.java b/src/main/java/ch/njol/skript/ScriptLoader.java index 56a9822e593..ef52d431f71 100644 --- a/src/main/java/ch/njol/skript/ScriptLoader.java +++ b/src/main/java/ch/njol/skript/ScriptLoader.java @@ -459,6 +459,7 @@ public static CompletableFuture loadScripts(Set files, OpenClo * and closed after the {@link Structure#postLoad()} stage. * @return Info on the loaded scripts. */ + @SuppressWarnings("removal") private static CompletableFuture loadScripts(List configs, OpenCloseable openCloseable) { if (configs.isEmpty()) // Nothing to load return CompletableFuture.completedFuture(new ScriptInfo()); @@ -1189,265 +1190,6 @@ public static EventRegistry eventRegistry() { return eventRegistry; } - /* - * Deprecated stuff - * - * These fields / methods are from the old version of ScriptLoader, - * and are merely here for backwards compatibility. - * - * Some methods have been replaced by ParserInstance, some - * by new methods in this class. - */ - - /** - * Unloads the provided script. - * @param scriptFile The file representing the script to unload. - * @return Statistics for the unloaded script. - * @deprecated Use {@link #unloadScript(Script)}. - */ - @Deprecated - public static ScriptInfo unloadScript(File scriptFile) { - Script script = getScript(scriptFile); - if (script != null) - return unloadScript(script); - return new ScriptInfo(); - } - - /** - * Unloads all scripts present in the provided folder. - * @param folder The folder containing scripts to unload. - * @return Combined statistics for the unloaded scripts. - * This data is calculated by using {@link ScriptInfo#add(ScriptInfo)}. - * @deprecated Use {@link #unloadScripts(Set)}. - */ - @Deprecated - private static ScriptInfo unloadScripts(File folder) { - return unloadScripts(getScripts(folder)); - } - - /** - * Reloads a single script. - * @param scriptFile The file representing the script to reload. - * @return Future of statistics of the newly loaded script. - * @deprecated Use {@link #reloadScript(Script, OpenCloseable)}. - */ - @Deprecated - public static CompletableFuture reloadScript(File scriptFile, OpenCloseable openCloseable) { - unloadScript(scriptFile); - return loadScripts(scriptFile, openCloseable); - } - - /** - * Reloads all scripts in the given folder and its subfolders. - * @param folder A folder. - * @return Future of statistics of newly loaded scripts. - * @deprecated Use {@link #reloadScripts}. - */ - @Deprecated - public static CompletableFuture reloadScripts(File folder, OpenCloseable openCloseable) { - unloadScripts(folder); - return loadScripts(folder, openCloseable); - } - - /** - * @deprecated Use {@link #getLoadedScripts()}.size(). - */ - @Deprecated - public static int loadedScripts() { - return getLoadedScripts().size(); - } - - /** - * @deprecated Use {@link #getLoadedScripts()} and {@link Script#getStructures()}.size(). - * Please note that a Structure may have multiple triggers, and this is only an estimate. - */ - @Deprecated - public static int loadedTriggers() { - int loaded = 0; - for (Script script : getLoadedScripts()) - loaded += script.getStructures().size(); - return loaded; - } - - /** - * @deprecated Use {@link #loadScripts(File, OpenCloseable)} - */ - @Deprecated - static void loadScripts() { - unloadScripts(getLoadedScripts()); - loadScripts(Skript.getInstance().getScriptsFolder(), OpenCloseable.EMPTY).join(); - } - - /** - * @deprecated Callers should not be using configs. Use {@link #loadScripts(Set, OpenCloseable)}. - */ - @Deprecated - public static ScriptInfo loadScripts(List configs) { - return loadScripts(configs, OpenCloseable.EMPTY).join(); - } - - /** - * @deprecated Callers should not be using configs. Use {@link #loadScripts(Set, OpenCloseable)}. - * @see RetainingLogHandler - */ - @Deprecated - public static ScriptInfo loadScripts(List configs, List logOut) { - RetainingLogHandler logHandler = new RetainingLogHandler(); - try { - return loadScripts(configs, logHandler).join(); - } finally { - logOut.addAll(logHandler.getLog()); - } - } - - /** - * @deprecated Callers should not be using configs. Use {@link #loadScripts(Set, OpenCloseable)}. - */ - @Deprecated - public static ScriptInfo loadScripts(Config... configs) { - return loadScripts(Arrays.asList(configs), OpenCloseable.EMPTY).join(); - } - - /** - * @deprecated Use {@link #reloadScript(Script, OpenCloseable)}. - */ - @Deprecated - public static ScriptInfo reloadScript(File script) { - return reloadScript(script, OpenCloseable.EMPTY).join(); - } - - /** - * @deprecated Use {@link #reloadScripts(Set, OpenCloseable)}. - */ - @Deprecated - public static ScriptInfo reloadScripts(File folder) { - return reloadScripts(folder, OpenCloseable.EMPTY).join(); - } - - /** - * @deprecated Use {@link ParserInstance#getHasDelayBefore()}. - */ - @Deprecated - public static Kleenean getHasDelayBefore() { - return getParser().getHasDelayBefore(); - } - - /** - * @deprecated Use {@link ParserInstance#setHasDelayBefore(Kleenean)}. - */ - @Deprecated - public static void setHasDelayBefore(Kleenean hasDelayBefore) { - getParser().setHasDelayBefore(hasDelayBefore); - } - - /** - * @deprecated Use {@link ParserInstance#getCurrentScript()}. - */ - @Nullable - @Deprecated - public static Config getCurrentScript() { - ParserInstance parser = getParser(); - return parser.isActive() ? parser.getCurrentScript().getConfig() : null; - } - - /** - * @deprecated Addons should no longer be modifying this. - */ - @Deprecated - public static void setCurrentScript(@Nullable Config currentScript) { - getParser().setCurrentScript(currentScript); - } - - /** - * @deprecated Use {@link ParserInstance#getCurrentSections()}. - */ - @Deprecated - public static List getCurrentSections() { - return getParser().getCurrentSections(); - } - - /** - * @deprecated Use {@link ParserInstance#setCurrentSections(List)}. - */ - @Deprecated - public static void setCurrentSections(List currentSections) { - getParser().setCurrentSections(currentSections); - } - - /** - * @deprecated Use {@link ParserInstance#getCurrentSections(Class)}. - */ - @Deprecated - public static List getCurrentLoops() { - return getParser().getCurrentSections(SecLoop.class); - } - - /** - * @deprecated Never use this method, it has no effect. - */ - @Deprecated - public static void setCurrentLoops(List currentLoops) { } - - /** - * @deprecated Use {@link ParserInstance#getCurrentEventName()}. - */ - @Nullable - @Deprecated - public static String getCurrentEventName() { - return getParser().getCurrentEventName(); - } - - /** - * @deprecated Use {@link ParserInstance#setCurrentEvent(String, Class[])}. - */ - @SafeVarargs - @Deprecated - public static void setCurrentEvent(String name, @Nullable Class... events) { - getParser().setCurrentEvent(name, events); - } - - /** - * @deprecated Use {@link ParserInstance#deleteCurrentEvent()}. - */ - @Deprecated - public static void deleteCurrentEvent() { - getParser().deleteCurrentEvent(); - } - - /** - * @deprecated Use {@link ParserInstance#isCurrentEvent(Class)} - */ - @Deprecated - public static boolean isCurrentEvent(@Nullable Class event) { - return getParser().isCurrentEvent(event); - } - - /** - * @deprecated Use {@link ParserInstance#isCurrentEvent(Class[])}. - */ - @SafeVarargs - @Deprecated - public static boolean isCurrentEvent(Class... events) { - return getParser().isCurrentEvent(events); - } - - /** - * @deprecated Use {@link ParserInstance#getCurrentEvents()}. - */ - @Nullable - @Deprecated - public static Class[] getCurrentEvents() { - return getParser().getCurrentEvents(); - } - - /** - * @deprecated This method has no functionality, it just returns its input. - */ - @Deprecated - public static Config loadStructure(Config config) { - return config; - } - /** * Gets a script's file from its name, if one exists. * @param script The script name/path diff --git a/src/main/java/ch/njol/skript/Skript.java b/src/main/java/ch/njol/skript/Skript.java index 4394ef7997c..d8dede7718d 100644 --- a/src/main/java/ch/njol/skript/Skript.java +++ b/src/main/java/ch/njol/skript/Skript.java @@ -1124,7 +1124,7 @@ public static Metrics getMetrics() { return metrics; } - @SuppressWarnings("null") + @SuppressWarnings({"null", "removal"}) private final static Collection closeOnDisable = Collections.synchronizedCollection(new ArrayList()); /** @@ -1134,6 +1134,7 @@ public static Metrics getMetrics() { * * @param closeable */ + @SuppressWarnings("removal") public static void closeOnDisable(final Closeable closeable) { closeOnDisable.add(closeable); } @@ -1217,6 +1218,7 @@ private void beforeDisable() { } @Override + @SuppressWarnings("removal") public void onDisable() { if (disabled) return; @@ -1336,7 +1338,7 @@ private static void stopAcceptingRegistrations() { /** * Registers an addon to Skript. This is currently not required for addons to work, but the returned {@link SkriptAddon} provides useful methods for registering syntax elements * and adding new strings to Skript's localization system (e.g. the required "types.[type]" strings for registered classes). - * + * * @param plugin The plugin */ public static SkriptAddon registerAddon(JavaPlugin plugin) { @@ -1420,7 +1422,7 @@ private static SyntaxOrigin getSyntaxOrigin(JavaPlugin plugin) { /** * Registers a {@link Condition}. - * + * * @param conditionClass The condition's class * @param patterns Skript patterns to match this condition */ @@ -1447,7 +1449,7 @@ public static void registerCondition(Class conditionCla /** * Registers an {@link Effect}. - * + * * @param effectClass The effect's class * @param patterns Skript patterns to match this effect */ @@ -1508,7 +1510,7 @@ public static void registerSection(Class sectionClass, St /** * Registers an expression. - * + * * @param expressionType The expression's class * @param returnType The superclass of all values returned by the expression * @param type The expression's {@link ExpressionType type}. This is used to determine in which order to try to parse expressions. diff --git a/src/main/java/ch/njol/skript/SkriptConfig.java b/src/main/java/ch/njol/skript/SkriptConfig.java index 9cb61dd87b4..d2f3903a12b 100644 --- a/src/main/java/ch/njol/skript/SkriptConfig.java +++ b/src/main/java/ch/njol/skript/SkriptConfig.java @@ -138,11 +138,6 @@ public static EventRegistry eventRegistry() { public static final Option effectCommandToken = new Option<>("effect command token", "!"); public static final Option allowOpsToUseEffectCommands = new Option<>("allow ops to use effect commands", false); - /* - * @deprecated Will be removed in 2.8.0. Use {@link #logEffectCommands} instead. - */ - @Deprecated - public static final Option logPlayerCommands = new Option<>("log player commands", false).optional(true); public static final Option logEffectCommands = new Option<>("log effect commands", false); // everything handled by Variables diff --git a/src/main/java/ch/njol/skript/classes/Arithmetic.java b/src/main/java/ch/njol/skript/classes/Arithmetic.java deleted file mode 100644 index f381e012d52..00000000000 --- a/src/main/java/ch/njol/skript/classes/Arithmetic.java +++ /dev/null @@ -1,24 +0,0 @@ -package ch.njol.skript.classes; - -/** - * Represents arithmetic for certain two types. Multiplication, division and - * power of methods are optional and may throw UnsupportedOperationExceptions. - * @param the type of the absolute value - * @param the type of the relative value - */ -@Deprecated -public interface Arithmetic { - - public R difference(A first, A second); - - public A add(A value, R difference); - - public A subtract(A value, R difference); - - public A multiply(A value, R multiplier); - - public A divide(A value, R divider); - - public A power(A value, R exponent); - -} diff --git a/src/main/java/ch/njol/skript/classes/ChainedConverter.java b/src/main/java/ch/njol/skript/classes/ChainedConverter.java deleted file mode 100644 index 418d8620d31..00000000000 --- a/src/main/java/ch/njol/skript/classes/ChainedConverter.java +++ /dev/null @@ -1,49 +0,0 @@ -package ch.njol.skript.classes; - -import org.jetbrains.annotations.Nullable; - -import org.skriptlang.skript.lang.converter.Converters; - -/** - * Used to chain convertes to build a single converter. This is automatically created when a new converter is added. - * - * @author Peter Güttinger - * @param same as Converter's (from) - * @param the middle type, i.e. the type the first converter converts to and the second converter comverts from. - * @param same as Converter's (to) - * @see Converters#registerConverter(Class, Class, Converter) - * @see Converter - * @deprecated Use {@link org.skriptlang.skript.lang.converter.Converter} - */ -@Deprecated -public final class ChainedConverter implements Converter { - - private final Converter first; - private final Converter second; - - public ChainedConverter(final Converter first, final Converter second) { - assert first != null; - assert second != null; - this.first = first; - this.second = second; - } - - @SuppressWarnings("unchecked") - public static ChainedConverter newInstance(final Converter first, final Converter second) { - return new ChainedConverter<>((Converter) first, (Converter) second); - } - - @Override - @Nullable - public T convert(final F f) { - final M m = first.convert(f); - if (m == null) - return null; - return second.convert(m); - } - - @Override - public String toString() { - return "ChainedConverter{first=" + first + ",second=" + second + "}"; - } -} diff --git a/src/main/java/ch/njol/skript/classes/ClassInfo.java b/src/main/java/ch/njol/skript/classes/ClassInfo.java index 3c96028c58a..75c97818f65 100644 --- a/src/main/java/ch/njol/skript/classes/ClassInfo.java +++ b/src/main/java/ch/njol/skript/classes/ClassInfo.java @@ -11,8 +11,6 @@ import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.skriptlang.skript.lang.arithmetic.Arithmetics; -import org.skriptlang.skript.lang.arithmetic.Operator; import java.util.Arrays; import java.util.HashSet; @@ -55,8 +53,6 @@ public class ClassInfo implements Debuggable { @Nullable private Class serializeAs = null; - @Nullable - private Arithmetic math = null; @Nullable private Class mathRelativeType = null; @@ -91,14 +87,6 @@ public ClassInfo(final Class c, final String codeName) { name = new Noun("types." + codeName); } - /** - * Incorrect spelling in method name. This will be removed in the future. - */ - @Deprecated - public static boolean isVaildCodeName(final String name) { - return isValidCodeName(name); - } - public static boolean isValidCodeName(final String name) { return name.matches("(?:any-)?[a-z0-9]+"); } @@ -195,32 +183,12 @@ public ClassInfo serializeAs(final Class serializeAs) { return this; } - @Deprecated - public ClassInfo changer(final SerializableChanger changer) { - return changer((Changer) changer); - } - public ClassInfo changer(final Changer changer) { assert this.changer == null; this.changer = changer; return this; } - @Deprecated - @SuppressWarnings("unchecked") - public ClassInfo math(final Class relativeType, final Arithmetic math) { - assert this.math == null; - this.math = math; - mathRelativeType = relativeType; - Arithmetics.registerOperation(Operator.ADDITION, c, relativeType, (left, right) -> (T) math.add(left, right)); - Arithmetics.registerOperation(Operator.SUBTRACTION, c, relativeType, (left, right) -> (T) math.subtract(left, right)); - Arithmetics.registerOperation(Operator.MULTIPLICATION, c, relativeType, (left, right) -> (T) math.multiply(left, right)); - Arithmetics.registerOperation(Operator.DIVISION, c, relativeType, (left, right) -> (T) math.divide(left, right)); - Arithmetics.registerOperation(Operator.EXPONENTIATION, c, relativeType, (left, right) -> (T) math.power(left, right)); - Arithmetics.registerDifference(c, relativeType, math::difference); - return this; - } - /** * Use this as {@link #name(String)} to suppress warnings about missing documentation. */ @@ -377,24 +345,6 @@ public Class getSerializeAs() { return serializeAs; } - @Nullable - @Deprecated - public Arithmetic getMath() { - return math; - } - - @Nullable - @Deprecated - public Arithmetic getRelativeMath() { - return (Arithmetic) math; - } - - @Nullable - @Deprecated - public Class getMathRelativeType() { - return mathRelativeType; - } - @Nullable public String[] getDescription() { return description; diff --git a/src/main/java/ch/njol/skript/classes/Cloner.java b/src/main/java/ch/njol/skript/classes/Cloner.java index 6f1e35d2d22..f68fa24b193 100644 --- a/src/main/java/ch/njol/skript/classes/Cloner.java +++ b/src/main/java/ch/njol/skript/classes/Cloner.java @@ -4,8 +4,9 @@ * An interface for optionally cloning an object, * should return the given object if no cloning is required. */ +@FunctionalInterface public interface Cloner { - + T clone(T t); - + } diff --git a/src/main/java/ch/njol/skript/classes/Comparator.java b/src/main/java/ch/njol/skript/classes/Comparator.java deleted file mode 100644 index 31e8ac607e0..00000000000 --- a/src/main/java/ch/njol/skript/classes/Comparator.java +++ /dev/null @@ -1,218 +0,0 @@ -package ch.njol.skript.classes; - -/** - * Used to compare two objects of a different or the same type. - * @deprecated Use {@link org.skriptlang.skript.lang.comparator.Comparators} - */ -@Deprecated -public interface Comparator { - - /** - * represents a relation between two objects. - */ - @Deprecated - public static enum Relation { - EQUAL, NOT_EQUAL, GREATER, GREATER_OR_EQUAL, SMALLER, SMALLER_OR_EQUAL; - - /** - * Returns EQUAL for true or NOT_EQUAL for false - * - * @param b - * @return b ? Relation.EQUAL : Relation.NOT_EQUAL - */ - public static Relation get(final boolean b) { - return b ? Relation.EQUAL : Relation.NOT_EQUAL; - } - - /** - * Gets a Relation from a difference: If i is 0, EQUAL is returned, if i is greater than 0, GREATER is returned, otherwise SMALLER. - * - * @param i - * @return i == 0 ? Relation.EQUAL : i > 0 ? Relation.GREATER : Relation.SMALLER - */ - public static Relation get(final int i) { - return i == 0 ? Relation.EQUAL : i > 0 ? Relation.GREATER : Relation.SMALLER; - } - - /** - * Gets a Relation from a difference: If d is 0, EQUAL is returned, if d is greater than 0, GREATER is returned, otherwise SMALLER. - * - * @param d - * @return d == 0 ? Relation.EQUAL : d > 0 ? Relation.GREATER : Relation.SMALLER - */ - public static Relation get(final double d) { - return d == 0 ? Relation.EQUAL : d > 0 ? Relation.GREATER : Relation.SMALLER; - } - - /** - * Test whether this relation is fulfilled if another is, i.e. if the parameter relation fulfils X rel Y, then this relation fulfils X rel Y as - * well. - * - * @param other - * @return Whether this relation is part of the given relation, e.g. GREATER_OR_EQUAL.is(EQUAL) returns true. - */ - public boolean is(final Relation other) { - if (other == this) - return true; - switch (this) { - case EQUAL: - return false; - case NOT_EQUAL: - return other == SMALLER || other == GREATER; - case GREATER: - return false; - case GREATER_OR_EQUAL: - return other == GREATER || other == EQUAL; - case SMALLER: - return false; - case SMALLER_OR_EQUAL: - return other == SMALLER || other == EQUAL; - } - assert false; - return false; - } - - /** - * Returns this relation's string representation, which is similar to "equal to" or "greater than". - */ - @Override - public String toString() { - switch (this) { - case EQUAL: - return "equal to"; - case NOT_EQUAL: - return "not equal to"; - case GREATER: - return "greater than"; - case GREATER_OR_EQUAL: - return "greater than or equal to"; - case SMALLER: - return "smaller than"; - case SMALLER_OR_EQUAL: - return "smaller than or equal to"; - } - assert false; - return ""; - } - - /** - * Gets the inverse of this relation, i.e if this relation fulfils X rel Y, then the returned relation fulfils !(X rel Y). - * - * @return !this - */ - public Relation getInverse() { - switch (this) { - case EQUAL: - return NOT_EQUAL; - case NOT_EQUAL: - return EQUAL; - case GREATER: - return SMALLER_OR_EQUAL; - case GREATER_OR_EQUAL: - return SMALLER; - case SMALLER: - return GREATER_OR_EQUAL; - case SMALLER_OR_EQUAL: - return GREATER; - } - assert false; - return NOT_EQUAL; - } - - /** - * Gets the relation which has switched arguments, i.e. if this relation fulfils X rel Y, then the returned relation fulfils Y rel X. - * - * @return siht - */ - public Relation getSwitched() { - switch (this) { - case EQUAL: - return EQUAL; - case NOT_EQUAL: - return NOT_EQUAL; - case GREATER: - return SMALLER; - case GREATER_OR_EQUAL: - return SMALLER_OR_EQUAL; - case SMALLER: - return GREATER; - case SMALLER_OR_EQUAL: - return GREATER_OR_EQUAL; - } - assert false; - return NOT_EQUAL; - } - - public boolean isEqualOrInverse() { - return this == Relation.EQUAL || this == Relation.NOT_EQUAL; - } - - public int getRelation() { - switch (this) { - case EQUAL: - case NOT_EQUAL: - return 0; - case GREATER: - case GREATER_OR_EQUAL: - return 1; - case SMALLER: - case SMALLER_OR_EQUAL: - return -1; - } - assert false; - return 0; - } - } - - /** - * holds information about a comparator. - * - * @param see {@link Comparator} - * @param dito - */ - @Deprecated - public static class ComparatorInfo { - - public Class c1; - public Class c2; - public Comparator c; - - public ComparatorInfo(final Class c1, final Class c2, final Comparator c) { - this.c1 = c1; - this.c2 = c2; - this.c = c; - } - - public Class getType(final boolean first) { - return first ? c1 : c2; - } - - } - - Comparator equalsComparator = new Comparator() { - @Override - public Relation compare(final Object o1, final Object o2) { - return Relation.get(o1.equals(o2)); - } - - @Override - public boolean supportsOrdering() { - return false; - } - }; - - /** - * Compares the given objects which may not be null. Returning GREATER/SMALLER means that the first parameter is greater/smaller. - * - * @param o1 Non-null object - * @param o2 Non-null object - * @return the relation of the objects. Should neither return GREATER_OR_EQUAL nor SMALLER_OR_EQUAL. - */ - public Relation compare(T1 o1, T2 o2); - - /** - * @return whether this comparator supports ordering of elements or not. - */ - public boolean supportsOrdering(); - -} diff --git a/src/main/java/ch/njol/skript/classes/Converter.java b/src/main/java/ch/njol/skript/classes/Converter.java deleted file mode 100644 index f9aefe2d8f2..00000000000 --- a/src/main/java/ch/njol/skript/classes/Converter.java +++ /dev/null @@ -1,173 +0,0 @@ -package ch.njol.skript.classes; - -import ch.njol.skript.lang.Debuggable; -import ch.njol.skript.registrations.Classes; -import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; -import org.skriptlang.skript.lang.converter.Converters; - -import java.util.Arrays; -import java.util.stream.Collectors; - -/** - * Converts data from type to another. - * - * @param The accepted type of objects to convert from - * @param The type to convert to - * @see Converters#registerConverter(Class, Class, Converter) - * @deprecated Use {@link org.skriptlang.skript.lang.converter.Converter} - */ -@Deprecated -public interface Converter { - - /** - * Disallow other converters from being chained to this. - */ - public final static int NO_LEFT_CHAINING = 1; - - /** - * Disallow chaining this with other converters. - */ - public final static int NO_RIGHT_CHAINING = 2; - - /** - * Disallow all chaining. - */ - public final static int NO_CHAINING = NO_LEFT_CHAINING | NO_RIGHT_CHAINING; - - public final static int NO_COMMAND_ARGUMENTS = 4; - - /** - * holds information about a converter - * - * @author Peter Güttinger - * @param same as in {@link Converter} - * @param dito - */ - public final static class ConverterInfo implements Debuggable { - - public final Class from; - public final Class to; - public final Converter converter; - public final int options; - - /** - * Chain of types this converter will go through from right to left. - * For normal converters, contains from at 0 and to at 1. For chained - * converters, chains of first and second converter are concatenated - * together. - */ - private final Class[] chain; - - public ConverterInfo(Class from, Class to, Converter converter, int options) { - this.from = from; - this.to = to; - this.converter = converter; - this.options = options; - this.chain = new Class[] {from, to}; - } - - @SuppressWarnings("unchecked") - public ConverterInfo(ConverterInfo first, ConverterInfo second, Converter converter, int options) { - this.from = (Class) first.from; - this.to = (Class) second.to; - this.converter = converter; - this.options = options; - this.chain = new Class[first.chain.length + second.chain.length]; - System.arraycopy(first.chain, 0, chain, 0, first.chain.length); - System.arraycopy(second.chain, 0, chain, first.chain.length, second.chain.length); - } - - @Override - public String toString(@Nullable Event event, boolean debug) { - if (debug) { - String str = Arrays.stream(chain).map(c -> Classes.getExactClassName(c)).collect(Collectors.joining(" -> ")); - assert str != null; - return str; - } - return Classes.getExactClassName(from) + " to " + Classes.getExactClassName(to); - } - - } - - /** - * Converts an object from the given to the desired type. - * - * @param f The object to convert. - * @return the converted object - */ - @Nullable - public T convert(F f); - - public final static class ConverterUtils { - - public static Converter createInstanceofConverter(final ConverterInfo conv) { - return createInstanceofConverter(conv.from, conv.converter); - } - - public static Converter createInstanceofConverter(final Class from, final Converter conv) { - return new Converter() { - @SuppressWarnings("unchecked") - @Override - @Nullable - public T convert(final Object o) { - if (!from.isInstance(o)) - return null; - return conv.convert((F) o); - } - }; - } - - /** - * Wraps a converter in a filter that will only accept conversion - * results of given type. All other results are replaced with nulls. - * @param conv Converter to wrap. - * @param to Accepted return type of the converter. - * @return The wrapped converter. - */ - public static Converter createInstanceofConverter(final Converter conv, final Class to) { - return new Converter() { - @SuppressWarnings("unchecked") - @Override - @Nullable - public T convert(final F f) { - final Object o = conv.convert(f); - if (to.isInstance(o)) - return (T) o; - return null; - } - }; - } - - public static Converter createDoubleInstanceofConverter(final ConverterInfo conv, final Class to) { - return createDoubleInstanceofConverter(conv.from, conv.converter, to); - } - - /** - * Wraps a converter. When values given to the wrapper converter are - * not of accepted type, it will not be called; instead, a null is - * returned. When it returns a value that is not of accepted type, the - * wrapped converter will return null instead. - * @param from Accepted type of input. - * @param conv Converter to wrap. - * @param to Accepted type of output. - * @return A wrapped converter. - */ - public static Converter createDoubleInstanceofConverter(final Class from, final Converter conv, final Class to) { - return new Converter() { - @SuppressWarnings("unchecked") - @Override - @Nullable - public T convert(final Object o) { - if (!from.isInstance(o)) - return null; - final Object o2 = conv.convert((F) o); - if (to.isInstance(o2)) - return (T) o2; - return null; - } - }; - } - - } -} diff --git a/src/main/java/ch/njol/skript/classes/InverseComparator.java b/src/main/java/ch/njol/skript/classes/InverseComparator.java deleted file mode 100644 index a8ae1d2dba8..00000000000 --- a/src/main/java/ch/njol/skript/classes/InverseComparator.java +++ /dev/null @@ -1,31 +0,0 @@ -package ch.njol.skript.classes; - -/** - * @author Peter Güttinger - * @deprecated This class is no longer exposed in newer versions. It should not be used or referenced. - */ -@Deprecated -public class InverseComparator implements Comparator { - - private final Comparator comp; - - public InverseComparator(final Comparator c) { - comp = c; - } - - @Override - public Relation compare(final T1 o1, final T2 o2) { - return comp.compare(o2, o1).getSwitched(); - } - - @Override - public boolean supportsOrdering() { - return comp.supportsOrdering(); - } - - @Override - public String toString() { - return "InverseComparator(" + comp + ")"; - } - -} diff --git a/src/main/java/ch/njol/skript/classes/NumberArithmetic.java b/src/main/java/ch/njol/skript/classes/NumberArithmetic.java deleted file mode 100644 index cc5e487f7a1..00000000000 --- a/src/main/java/ch/njol/skript/classes/NumberArithmetic.java +++ /dev/null @@ -1,57 +0,0 @@ -package ch.njol.skript.classes; - -/** - * @author Peter Güttinger - */ -@Deprecated -public class NumberArithmetic implements Arithmetic { - - @Override - public Number difference(final Number first, final Number second) { - double result = Math.abs(first.doubleValue() - second.doubleValue()); - if (result == (long) result) - return (long) result; - return result; - } - - @Override - public Number add(final Number value, final Number difference) { - double result = value.doubleValue() + difference.doubleValue(); - if (result == (long) result) - return (long) result; - return result; - } - - @Override - public Number subtract(final Number value, final Number difference) { - double result = value.doubleValue() - difference.doubleValue(); - if (result == (long) result) - return (long) result; - return result; - } - - @Override - public Number multiply(Number value, Number multiplier) { - double result = value.doubleValue() * multiplier.doubleValue(); - if (result == (long) result) - return (long) result; - return result; - } - - @Override - public Number divide(Number value, Number divider) { - double result = value.doubleValue() / divider.doubleValue(); - if (result == (long) result) - return (long) result; - return result; - } - - @Override - public Number power(Number value, Number exponent) { - double result = Math.pow(value.doubleValue(), exponent.doubleValue()); - if (result == (long) result) - return (long) result; - return result; - } - -} diff --git a/src/main/java/ch/njol/skript/classes/SerializableChanger.java b/src/main/java/ch/njol/skript/classes/SerializableChanger.java deleted file mode 100644 index e2967a6de81..00000000000 --- a/src/main/java/ch/njol/skript/classes/SerializableChanger.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.njol.skript.classes; - -/** - * @author Peter Güttinger - */ -@Deprecated -public interface SerializableChanger extends Changer {} diff --git a/src/main/java/ch/njol/skript/classes/SerializableChecker.java b/src/main/java/ch/njol/skript/classes/SerializableChecker.java index 58420e2e59e..ce5e8a66c8f 100644 --- a/src/main/java/ch/njol/skript/classes/SerializableChecker.java +++ b/src/main/java/ch/njol/skript/classes/SerializableChecker.java @@ -5,9 +5,9 @@ import java.util.function.Predicate; /** - * @author Peter Güttinger + * @deprecated use {@link Predicate} */ -@Deprecated @FunctionalInterface -@ApiStatus.ScheduledForRemoval +@Deprecated(forRemoval = true) +@SuppressWarnings("removal") public interface SerializableChecker extends ch.njol.util.Checker, Predicate {} diff --git a/src/main/java/ch/njol/skript/classes/SerializableGetter.java b/src/main/java/ch/njol/skript/classes/SerializableGetter.java deleted file mode 100644 index f73f6be2251..00000000000 --- a/src/main/java/ch/njol/skript/classes/SerializableGetter.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.njol.skript.classes; - -import ch.njol.skript.util.Getter; - -@Deprecated(forRemoval = true) -@SuppressWarnings("removal") -public abstract class SerializableGetter extends Getter {} diff --git a/src/main/java/ch/njol/skript/classes/VectorArithmethic.java b/src/main/java/ch/njol/skript/classes/VectorArithmethic.java deleted file mode 100644 index a4d7db28b4e..00000000000 --- a/src/main/java/ch/njol/skript/classes/VectorArithmethic.java +++ /dev/null @@ -1,40 +0,0 @@ -package ch.njol.skript.classes; - -import org.bukkit.util.Vector; - -/** - * @author bi0qaw - */ -@Deprecated -public class VectorArithmethic implements Arithmetic { - - @Override - public Vector difference(final Vector first, final Vector second) { - return new Vector(Math.abs(first.getX() - second.getX()), Math.abs(first.getY() - second.getY()), Math.abs(first.getZ() - second.getZ())); - } - - @Override - public Vector add(final Vector value, final Vector difference) { - return new Vector().add(value).add(difference); - } - - @Override - public Vector subtract(Vector value, Vector difference) { - return new Vector().add(value).subtract(difference); - } - - @Override - public Vector multiply(Vector value, Vector multiplier) { - return value.clone().multiply(multiplier); - } - - @Override - public Vector divide(Vector value, Vector divider) { - return value.clone().divide(divider); - } - - @Override - public Vector power(Vector value, Vector exponent) { - return new Vector(Math.pow(value.getX(), exponent.getX()), Math.pow(value.getY(), exponent.getY()), Math.pow(value.getZ(), exponent.getZ())); - } -} diff --git a/src/main/java/ch/njol/skript/command/Commands.java b/src/main/java/ch/njol/skript/command/Commands.java index ec4c4f6595d..01534038dd0 100644 --- a/src/main/java/ch/njol/skript/command/Commands.java +++ b/src/main/java/ch/njol/skript/command/Commands.java @@ -186,8 +186,7 @@ static boolean handleEffectCommand(CommandSender sender, String command) { log.printLog(); if (!effectCommand.isCancelled()) { sender.sendMessage(ChatColor.GRAY + "executing '" + SkriptColor.replaceColorChar(command) + "'"); - // TODO: remove logPlayerCommands for 2.8.0 - if ((SkriptConfig.logEffectCommands.value() || SkriptConfig.logPlayerCommands.value()) && !(sender instanceof ConsoleCommandSender)) + if (SkriptConfig.logEffectCommands.value() && !(sender instanceof ConsoleCommandSender)) Skript.info(sender.getName() + " issued effect command: " + SkriptColor.replaceColorChar(command)); TriggerItem.walk(effect, effectCommand); Variables.removeLocals(effectCommand); diff --git a/src/main/java/ch/njol/skript/conditions/CondCompare.java b/src/main/java/ch/njol/skript/conditions/CondCompare.java index 58aa9501e62..cea7a493ba3 100644 --- a/src/main/java/ch/njol/skript/conditions/CondCompare.java +++ b/src/main/java/ch/njol/skript/conditions/CondCompare.java @@ -217,7 +217,6 @@ private boolean init(String expr) { comparator = Comparators.getComparator(first.getReturnType(), secondReturnType); } } - } return comparator != null; diff --git a/src/main/java/ch/njol/skript/conditions/CondIsDivisibleBy.java b/src/main/java/ch/njol/skript/conditions/CondIsDivisibleBy.java index 42131fb7069..036520c5c7b 100644 --- a/src/main/java/ch/njol/skript/conditions/CondIsDivisibleBy.java +++ b/src/main/java/ch/njol/skript/conditions/CondIsDivisibleBy.java @@ -8,7 +8,6 @@ import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Checker; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; diff --git a/src/main/java/ch/njol/skript/conditions/CondIsOfType.java b/src/main/java/ch/njol/skript/conditions/CondIsOfType.java index dbc1b163ce8..47baed7a481 100644 --- a/src/main/java/ch/njol/skript/conditions/CondIsOfType.java +++ b/src/main/java/ch/njol/skript/conditions/CondIsOfType.java @@ -1,12 +1,6 @@ package ch.njol.skript.conditions; -import org.bukkit.entity.Entity; -import org.bukkit.event.Event; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.aliases.ItemType; -import org.skriptlang.skript.lang.comparator.Relation; import ch.njol.skript.classes.data.DefaultComparators; import ch.njol.skript.conditions.base.PropertyCondition; import ch.njol.skript.conditions.base.PropertyCondition.PropertyType; @@ -19,20 +13,26 @@ import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; +import org.bukkit.entity.Entity; +import org.bukkit.event.Event; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; +import org.skriptlang.skript.lang.comparator.Relation; import java.util.function.Predicate; + @Name("Is of Type") @Description("Checks whether an item or an entity is of the given type. This is mostly useful for variables," + - " as you can use the general 'is' condition otherwise (e.g. 'victim is a creeper').") + " as you can use the general 'is' condition otherwise (e.g. 'victim is a creeper').") @Examples({"tool is of type {selected type}", - "victim is of type {villager type}"}) + "victim is of type {villager type}"}) @Since("1.4") public class CondIsOfType extends Condition { static { PropertyCondition.register(CondIsOfType.class, "of type[s] %itemtypes/entitydatas%", "itemstacks/entities"); } - + @SuppressWarnings("NotNullFieldNotInitialized") private Expression what; @SuppressWarnings("NotNullFieldNotInitialized") @@ -48,27 +48,27 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye } @Override - public boolean check(final Event e) { - return what.check(e, - (Predicate) o1 -> types.check(e, - (Predicate) o2 -> { - if (o2 instanceof ItemType && o1 instanceof ItemType) { - return ((ItemType) o2).isSupertypeOf((ItemType) o1); - } else if (o2 instanceof EntityData && o1 instanceof Entity) { - return ((EntityData) o2).isInstance((Entity) o1); - } else if (o2 instanceof ItemType && o1 instanceof Entity) { - return Relation.EQUAL.isImpliedBy(DefaultComparators.entityItemComparator.compare(EntityData.fromEntity((Entity) o1), (ItemType) o2)); - } else { - return false; - } - }), - isNegated()); + public boolean check(Event event) { + return what.check(event, + (Predicate) o1 -> types.check(event, + (Predicate) o2 -> { + if (o2 instanceof ItemType && o1 instanceof ItemStack) { + return ((ItemType) o2).isSupertypeOf(new ItemType((ItemStack) o1)); + } else if (o2 instanceof EntityData && o1 instanceof Entity) { + return ((EntityData) o2).isInstance((Entity) o1); + } else if (o2 instanceof ItemType && o1 instanceof Entity) { + return Relation.EQUAL.isImpliedBy(DefaultComparators.entityItemComparator.compare(EntityData.fromEntity((Entity) o1), (ItemType) o2)); + } else { + return false; + } + }), + isNegated()); } @Override public String toString(@Nullable Event event, boolean debug) { return PropertyCondition.toString(this, PropertyType.BE, event, debug, what, - "of " + (types.isSingle() ? "type " : "types ") + types.toString(event, debug)); + "of " + (types.isSingle() ? "type " : "types ") + types.toString(event, debug)); } } diff --git a/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java b/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java index dadc7f71d47..1711fcfb812 100644 --- a/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java +++ b/src/main/java/ch/njol/skript/conditions/base/PropertyCondition.java @@ -1,14 +1,16 @@ package ch.njol.skript.conditions.base; -import org.bukkit.event.Event; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.SkriptAPIException; import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.util.Kleenean; +import org.bukkit.event.Event; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Predicate; import org.jetbrains.annotations.ApiStatus; import org.skriptlang.skript.registration.SyntaxInfo; import org.skriptlang.skript.registration.SyntaxRegistry; @@ -39,7 +41,7 @@ * {@link PropertyCondition#register(Class, String, String)}, be aware that there can only be two patterns - * the first one needs to be a non-negated one and a negated one. */ -public abstract class PropertyCondition extends Condition implements ch.njol.util.Checker, Predicate { +public abstract class PropertyCondition extends Condition implements Predicate { /** * A priority for {@link PropertyCondition}s. @@ -179,8 +181,8 @@ public static String[] getPatterns(PropertyType propertyType, String property, S private Expression expr; @Override - @SuppressWarnings("unchecked") public boolean init(Expression[] expressions, int matchedPattern, Kleenean isDelayed, ParseResult parseResult) { + //noinspection unchecked expr = (Expression) expressions[0]; setNegated(matchedPattern == 1); return true; @@ -195,7 +197,7 @@ public final boolean check(Event event) { @Override public final boolean test(T value) { - return this.check(value); + return check(value); } protected abstract String getPropertyName(); @@ -239,4 +241,19 @@ public static String toString(Condition condition, PropertyType propertyType, @N } } + @Override + public @NotNull Predicate and(@NotNull Predicate other) { + throw new UnsupportedOperationException("Combining property conditions is undefined behaviour"); + } + + @Override + public @NotNull Predicate negate() { + throw new UnsupportedOperationException("Negating property conditions without setNegated is undefined behaviour"); + } + + @Override + public @NotNull Predicate or(@NotNull Predicate other) { + throw new UnsupportedOperationException("Combining property conditions is undefined behaviour"); + } + } diff --git a/src/main/java/ch/njol/skript/config/Option.java b/src/main/java/ch/njol/skript/config/Option.java index def15007e27..e918f715394 100644 --- a/src/main/java/ch/njol/skript/config/Option.java +++ b/src/main/java/ch/njol/skript/config/Option.java @@ -11,10 +11,8 @@ import org.skriptlang.skript.lang.converter.Converter; import java.util.Locale; +import java.util.function.Consumer; -/** - * @author Peter Güttinger - */ public class Option { public final String key; @@ -36,13 +34,7 @@ public Option(final String key, final T defaultValue) { @SuppressWarnings("unchecked") final Class c = (Class) defaultValue.getClass(); if (c == String.class) { - parser = new Converter() { - @SuppressWarnings("unchecked") - @Override - public T convert(final String s) { - return (T) s; - } - }; + parser = (Converter) s -> (T) s; } else { final ClassInfo ci = Classes.getExactClassInfo(c); final Parser p; @@ -105,7 +97,7 @@ public final T value() { public final T defaultValue() { return defaultValue; } - + public final boolean isOptional() { return optional; } diff --git a/src/main/java/ch/njol/skript/config/validate/EntryValidator.java b/src/main/java/ch/njol/skript/config/validate/EntryValidator.java index c1595bf2d19..56b005906a6 100644 --- a/src/main/java/ch/njol/skript/config/validate/EntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/EntryValidator.java @@ -9,9 +9,6 @@ import java.util.function.Consumer; -/** - * @author Peter Güttinger - */ public class EntryValidator implements NodeValidator { @Nullable @@ -21,12 +18,12 @@ public EntryValidator() { setter = null; } - public EntryValidator(final Consumer setter) { + public EntryValidator(Consumer setter) { this.setter = setter; } @Override - public boolean validate(final Node node) { + public boolean validate(Node node) { if (!(node instanceof EntryNode)) { notAnEntryError(node); return false; @@ -36,11 +33,11 @@ public boolean validate(final Node node) { return true; } - public static void notAnEntryError(final Node node) { + public static void notAnEntryError(Node node) { notAnEntryError(node, node.getConfig().getSeparator()); } - public static void notAnEntryError(final Node node, String separator) { + public static void notAnEntryError(Node node, String separator) { SkriptLogger.setNode(node); Skript.error("'" + node.getKey() + "' is not an entry (like 'name " + separator + " value')"); } diff --git a/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java b/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java index 26015cd898f..a6d68981752 100644 --- a/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/EnumEntryValidator.java @@ -9,9 +9,7 @@ import ch.njol.skript.config.EntryNode; import ch.njol.skript.config.Node; -/** - * @author Peter Güttinger - */ +@Deprecated(forRemoval = true) public class EnumEntryValidator> extends EntryValidator { private final Class enumType; diff --git a/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java b/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java index c6b84711fbe..b941a1d22a3 100644 --- a/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/ParsedEntryValidator.java @@ -7,15 +7,12 @@ import java.util.function.Consumer; -/** - * @author Peter Güttinger - */ public class ParsedEntryValidator extends EntryValidator { private final Parser parser; private final Consumer setter; - public ParsedEntryValidator(final Parser parser, final Consumer setter) { + public ParsedEntryValidator(Parser parser, Consumer setter) { assert parser != null; assert setter != null; this.parser = parser; @@ -23,10 +20,10 @@ public ParsedEntryValidator(final Parser parser, final Consumer } @Override - public boolean validate(final Node node) { + public boolean validate(Node node) { if (!super.validate(node)) return false; - final T t = parser.parse(((EntryNode) node).getValue(), ParseContext.CONFIG); + T t = parser.parse(((EntryNode) node).getValue(), ParseContext.CONFIG); if (t == null) return false; setter.accept(t); diff --git a/src/main/java/ch/njol/skript/config/validate/SectionValidator.java b/src/main/java/ch/njol/skript/config/validate/SectionValidator.java index 916f932dc74..909ec29f55e 100644 --- a/src/main/java/ch/njol/skript/config/validate/SectionValidator.java +++ b/src/main/java/ch/njol/skript/config/validate/SectionValidator.java @@ -12,9 +12,6 @@ import ch.njol.skript.config.SectionNode; import ch.njol.skript.log.SkriptLogger; -/** - * @author Peter Güttinger - */ public class SectionValidator implements NodeValidator { private final static class NodeInfo { diff --git a/src/main/java/ch/njol/skript/doc/Documentation.java b/src/main/java/ch/njol/skript/doc/Documentation.java index 49d90a1f265..3f444971b4d 100644 --- a/src/main/java/ch/njol/skript/doc/Documentation.java +++ b/src/main/java/ch/njol/skript/doc/Documentation.java @@ -246,40 +246,37 @@ protected static String cleanPatterns(String patterns, boolean escapeHTML) { assert cleanedPatterns != null; final String s = StringUtils.replaceAll(cleanedPatterns, "(?() { - @Override - public String apply(final Matcher m) { - String s = m.group(1); - if (s.startsWith("-")) - s = s.substring(1); - String flag = ""; - if (s.startsWith("*") || s.startsWith("~")) { - flag = s.substring(0, 1); - s = s.substring(1); - } - final int a = s.indexOf("@"); - if (a != -1) - s = s.substring(0, a); - final StringBuilder b = new StringBuilder("%"); - b.append(flag); - boolean first = true; - for (final String c : s.split("/")) { - assert c != null; - if (!first) - b.append("/"); - first = false; - final NonNullPair p = Utils.getEnglishPlural(c); - final ClassInfo ci = Classes.getClassInfoNoError(p.getFirst()); - if (ci != null && ci.hasDocs()) { // equals method throws null error when doc name is null - b.append("").append(ci.getName().toString(p.getSecond())).append(""); - } else { - b.append(c); - if (ci != null && ci.hasDocs()) - Skript.warning("Used class " + p.getFirst() + " has no docName/name defined"); - } + m -> { + String s1 = m.group(1); + if (s1.startsWith("-")) + s1 = s1.substring(1); + String flag = ""; + if (s1.startsWith("*") || s1.startsWith("~")) { + flag = s1.substring(0, 1); + s1 = s1.substring(1); + } + final int a = s1.indexOf("@"); + if (a != -1) + s1 = s1.substring(0, a); + final StringBuilder b = new StringBuilder("%"); + b.append(flag); + boolean first = true; + for (final String c : s1.split("/")) { + assert c != null; + if (!first) + b.append("/"); + first = false; + final NonNullPair p = Utils.getEnglishPlural(c); + final ClassInfo ci = Classes.getClassInfoNoError(p.getFirst()); + if (ci != null && ci.hasDocs()) { // equals method throws null error when doc name is null + b.append("").append(ci.getName().toString(p.getSecond())).append(""); + } else { + b.append(c); + if (ci != null && ci.hasDocs()) + Skript.warning("Used class " + p.getFirst() + " has no docName/name defined"); } - return "" + b.append("%").toString(); } + return b.append("%").toString(); }); assert s != null : patterns; return s; diff --git a/src/main/java/ch/njol/skript/effects/EffLog.java b/src/main/java/ch/njol/skript/effects/EffLog.java index c528a09df50..0d4f0eb2908 100644 --- a/src/main/java/ch/njol/skript/effects/EffLog.java +++ b/src/main/java/ch/njol/skript/effects/EffLog.java @@ -44,20 +44,17 @@ public class EffLog extends Effect { static { Skript.registerEffect(EffLog.class, "log %strings% [(to|in) [file[s]] %-strings%] [with [the|a] severity [of] (1:warning|2:severe)]"); } - + private static final File logsFolder = new File(Skript.getInstance().getDataFolder(), "logs"); - + final static HashMap writers = new HashMap<>(); static { - Skript.closeOnDisable(new Closeable() { - @Override - public void close() { - for (PrintWriter pw : writers.values()) - pw.close(); - } + Skript.closeOnDisable(() -> { + for (PrintWriter pw : writers.values()) + pw.close(); }); } - + @SuppressWarnings("null") private Expression messages; @Nullable @@ -83,7 +80,7 @@ public boolean init(Expression[] exprs, int matchedPattern, Kleenean isDelaye } return true; } - + @SuppressWarnings("resource") @Override protected void execute(Event event) { diff --git a/src/main/java/ch/njol/skript/entity/EndermanData.java b/src/main/java/ch/njol/skript/entity/EndermanData.java index 15cd38aff65..3fb1685dec4 100644 --- a/src/main/java/ch/njol/skript/entity/EndermanData.java +++ b/src/main/java/ch/njol/skript/entity/EndermanData.java @@ -1,16 +1,5 @@ package ch.njol.skript.entity; -import java.util.Arrays; -import java.util.function.Predicate; - -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Enderman; -import org.bukkit.inventory.ItemStack; -import org.bukkit.material.MaterialData; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.aliases.ItemType; import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptParser.ParseResult; @@ -18,6 +7,15 @@ import ch.njol.skript.localization.ArgsMessage; import ch.njol.skript.registrations.Classes; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.block.data.BlockData; +import org.bukkit.entity.Enderman; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.Nullable; + +import java.util.Arrays; +import java.util.function.Predicate; @SuppressWarnings("deprecation") public class EndermanData extends EntityData { @@ -72,13 +70,9 @@ public void set(final Enderman entity) { @Override public boolean match(final Enderman entity) { - return hand == null || SimpleExpression.check(hand, new Predicate() { - @SuppressWarnings("null") - @Override - public boolean test(final @Nullable ItemType t) { - // TODO {Block/Material}Data -> Material conversion is not 100% accurate, needs a better solution - return t != null && t.isOfType(entity.getCarriedBlock().getMaterial()); - } + return hand == null || SimpleExpression.check(hand, type -> { + // TODO {Block/Material}Data -> Material conversion is not 100% accurate, needs a better solution + return type != null && type.isOfType(entity.getCarriedBlock().getMaterial()); }, false, false); } diff --git a/src/main/java/ch/njol/skript/entity/EntityData.java b/src/main/java/ch/njol/skript/entity/EntityData.java index 89a1476c957..793a9d9091a 100644 --- a/src/main/java/ch/njol/skript/entity/EntityData.java +++ b/src/main/java/ch/njol/skript/entity/EntityData.java @@ -186,7 +186,9 @@ public static void onRegistrationStop() { }); } - private final static class EntityDataInfo> extends SyntaxElementInfo implements LanguageChangeListener { + private final static class EntityDataInfo> extends SyntaxElementInfo + implements LanguageChangeListener { + final String codeName; final String[] codeNames; final int defaultName; diff --git a/src/main/java/ch/njol/skript/events/EvtClick.java b/src/main/java/ch/njol/skript/events/EvtClick.java index ab4a0159255..ceca1cc5534 100644 --- a/src/main/java/ch/njol/skript/events/EvtClick.java +++ b/src/main/java/ch/njol/skript/events/EvtClick.java @@ -8,7 +8,6 @@ import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; -import ch.njol.util.Predicate; import ch.njol.util.coll.CollectionUtils; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; @@ -27,6 +26,8 @@ import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.comparator.Relation; +import java.util.function.Predicate; + public class EvtClick extends SkriptEvent { /** @@ -46,17 +47,17 @@ public class EvtClick extends SkriptEvent { Skript.registerEvent("Click", EvtClick.class, eventTypes, "[(" + RIGHT + ":right|" + LEFT + ":left)(| |-)][mouse(| |-)]click[ing] [on %-entitydata/itemtype/blockdata%] [(with|using|holding) %-itemtype%]", "[(" + RIGHT + ":right|" + LEFT + ":left)(| |-)][mouse(| |-)]click[ing] (with|using|holding) %itemtype% on %entitydata/itemtype/blockdata%") - .description("Called when a user clicks on a block, an entity or air with or without an item in their hand.", - "Please note that rightclick events with an empty hand while not looking at a block are not sent to the server, so there's no way to detect them.", - "Also note that a leftclick on an entity is an attack and thus not covered by the 'click' event, but the 'damage' event.") - .examples("on click:", - "on rightclick holding a fishing rod:", - "on leftclick on a stone or obsidian:", - "on rightclick on a creeper:", - "on click with a sword:", - "on click on chest[facing=north]:", - "on click on campfire[lit=true]:") - .since("1.0, INSERT VERSION (blockdata)"); + .description("Called when a user clicks on a block, an entity or air with or without an item in their hand.", + "Please note that rightclick events with an empty hand while not looking at a block are not sent to the server, so there's no way to detect them.", + "Also note that a leftclick on an entity is an attack and thus not covered by the 'click' event, but the 'damage' event.") + .examples("on click:", + "on rightclick holding a fishing rod:", + "on leftclick on a stone or obsidian:", + "on rightclick on a creeper:", + "on click with a sword:", + "on click on chest[facing=north]:", + "on click on campfire[lit=true]:") + .since("1.0, INSERT VERSION (blockdata)"); } /** @@ -91,10 +92,10 @@ public boolean init(Literal[] args, int matchedPattern, ParseResult parseResu } else if (click == ANY) { if (Vehicle.class.isAssignableFrom(entitydata.getSingle().getType())) { Skript.error("A leftclick on a vehicle entity is an attack and thus not covered by the 'click' event, but the 'vehicle damage' event. " + - "Change this event to a rightclick to fix this warning message."); + "Change this event to a rightclick to fix this warning message."); } else { Skript.error("A leftclick on an entity is an attack and thus not covered by the 'click' event, but the 'damage' event. " + - "Change this event to a rightclick to fix this warning message."); + "Change this event to a rightclick to fix this warning message."); } } } diff --git a/src/main/java/ch/njol/skript/events/EvtGameMode.java b/src/main/java/ch/njol/skript/events/EvtGameMode.java index 8c9174043ad..d776fa0be79 100644 --- a/src/main/java/ch/njol/skript/events/EvtGameMode.java +++ b/src/main/java/ch/njol/skript/events/EvtGameMode.java @@ -37,12 +37,7 @@ public boolean init(final Literal[] args, final int matchedPattern, final Par @Override public boolean check(final Event e) { if (mode != null) { - return mode.check(e, new Predicate() { - @Override - public boolean test(final GameMode m) { - return ((PlayerGameModeChangeEvent) e).getNewGameMode().equals(m); - } - }); + return mode.check(e, m -> ((PlayerGameModeChangeEvent) e).getNewGameMode().equals(m)); } return true; } diff --git a/src/main/java/ch/njol/skript/events/EvtWeatherChange.java b/src/main/java/ch/njol/skript/events/EvtWeatherChange.java index 497aecc8870..e01ac20c1c3 100644 --- a/src/main/java/ch/njol/skript/events/EvtWeatherChange.java +++ b/src/main/java/ch/njol/skript/events/EvtWeatherChange.java @@ -1,16 +1,15 @@ package ch.njol.skript.events; -import org.bukkit.event.Event; -import org.bukkit.event.weather.ThunderChangeEvent; -import org.bukkit.event.weather.WeatherChangeEvent; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.lang.Literal; import ch.njol.skript.lang.SkriptEvent; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.util.WeatherType; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.event.weather.ThunderChangeEvent; +import org.bukkit.event.weather.WeatherChangeEvent; +import org.jetbrains.annotations.Nullable; import java.util.function.Predicate; @@ -44,12 +43,7 @@ public boolean check(final Event e) { return false; final boolean rain = e instanceof WeatherChangeEvent ? ((WeatherChangeEvent) e).toWeatherState() : ((ThunderChangeEvent) e).getWorld().hasStorm(); final boolean thunder = e instanceof ThunderChangeEvent ? ((ThunderChangeEvent) e).toThunderState() : ((WeatherChangeEvent) e).getWorld().isThundering(); - return types.check(e, new Predicate() { - @Override - public boolean test(final WeatherType t) { - return t.isWeather(rain, thunder); - } - }); + return types.check(e, t -> t.isWeather(rain, thunder)); } @Override diff --git a/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java b/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java index a80607e812f..185ef328743 100644 --- a/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java +++ b/src/main/java/ch/njol/skript/events/bukkit/PreScriptLoadEvent.java @@ -1,5 +1,6 @@ package ch.njol.skript.events.bukkit; +import ch.njol.skript.ScriptLoader; import ch.njol.skript.config.Config; import com.google.common.base.Preconditions; import org.bukkit.Bukkit; @@ -13,14 +14,14 @@ * Please do not use bukkit api before checking {@link Bukkit#isPrimaryThread()} * @deprecated Use {@link ScriptLoader.ScriptPreInitEvent}. */ -@Deprecated +@Deprecated(forRemoval = true) public class PreScriptLoadEvent extends Event { private final List scripts; public PreScriptLoadEvent(List scripts) { super(!Bukkit.isPrimaryThread()); - Preconditions.checkNotNull(scripts); + Preconditions.checkNotNull(scripts); this.scripts = scripts; } diff --git a/src/main/java/ch/njol/skript/expressions/ExprDifference.java b/src/main/java/ch/njol/skript/expressions/ExprDifference.java index 99e55690122..6a652b83a26 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprDifference.java +++ b/src/main/java/ch/njol/skript/expressions/ExprDifference.java @@ -1,8 +1,6 @@ package ch.njol.skript.expressions; import ch.njol.skript.Skript; -import ch.njol.skript.classes.Arithmetic; -import ch.njol.skript.classes.ClassInfo; import ch.njol.skript.conditions.CondCompare; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -12,7 +10,6 @@ import ch.njol.skript.lang.ExpressionType; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; -import ch.njol.skript.registrations.Classes; import ch.njol.skript.util.LiteralUtils; import ch.njol.skript.util.Utils; import ch.njol.util.Kleenean; diff --git a/src/main/java/ch/njol/skript/expressions/ExprNamed.java b/src/main/java/ch/njol/skript/expressions/ExprNamed.java index e5b9d8126e8..a3a43aaa777 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprNamed.java +++ b/src/main/java/ch/njol/skript/expressions/ExprNamed.java @@ -2,7 +2,6 @@ import ch.njol.skript.Skript; import ch.njol.skript.aliases.ItemType; -import ch.njol.skript.classes.Converter; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; diff --git a/src/main/java/ch/njol/skript/expressions/ExprTarget.java b/src/main/java/ch/njol/skript/expressions/ExprTarget.java index 6f320192891..bb4a806dc62 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprTarget.java +++ b/src/main/java/ch/njol/skript/expressions/ExprTarget.java @@ -152,20 +152,6 @@ public String toString(@Nullable Event event, boolean debug) { return "target" + (type == null ? "" : "ed " + type) + (getExpr().isDefault() ? "" : " of " + getExpr().toString(event, debug)); } - /** - * Gets an entity's target. - * - * @param origin The entity to get the target of. - * @param type The exact EntityData to find. Can be null for any entity. - * @return The entity's target. - * @deprecated Use {@link #getTarget(LivingEntity, EntityData, double)} to include raysize. - */ - @Deprecated - @ScheduledForRemoval - public static T getTarget(LivingEntity origin, @Nullable EntityData type) { - return getTarget(origin, type, 0.0D); - } - /** * Gets an entity's target entity. * diff --git a/src/main/java/ch/njol/skript/expressions/ExprTool.java b/src/main/java/ch/njol/skript/expressions/ExprTool.java index 12a3aa7d32b..39b1eecee24 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprTool.java +++ b/src/main/java/ch/njol/skript/expressions/ExprTool.java @@ -1,7 +1,6 @@ package ch.njol.skript.expressions; import ch.njol.skript.Skript; -import ch.njol.skript.classes.Converter; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorAngleBetween.java b/src/main/java/ch/njol/skript/expressions/ExprVectorAngleBetween.java index c23630d00a1..126260c1abf 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorAngleBetween.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorAngleBetween.java @@ -1,9 +1,5 @@ package ch.njol.skript.expressions; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -14,8 +10,10 @@ import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; -import ch.njol.util.VectorMath; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.Nullable; @Name("Vectors - Angle Between") @Description("Gets the angle between two vectors.") @@ -23,6 +21,8 @@ @Since("2.2-dev28") public class ExprVectorAngleBetween extends SimpleExpression { + private static final float RAD_TO_DEG = (float) (180 / Math.PI); + static { Skript.registerExpression(ExprVectorAngleBetween.class, Number.class, ExpressionType.COMBINED, "[the] angle between [[the] vectors] %vector% and %vector%"); @@ -46,7 +46,7 @@ protected Number[] get(Event event) { Vector second = this.second.getSingle(event); if (first == null || second == null) return null; - return CollectionUtils.array(first.angle(second) * (float) VectorMath.RAD_TO_DEG); + return CollectionUtils.array(first.angle(second) * RAD_TO_DEG); } @Override diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java index b8b9b84ab6c..3f2a3822aff 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorCylindrical.java @@ -13,7 +13,6 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @Name("Vectors - Cylindrical Shape") @@ -53,7 +52,7 @@ protected Vector[] get(Event event) { Number height = this.height.getSingle(event); if (radius == null || yaw == null || height == null) return null; - return CollectionUtils.array(fromCylindricalCoordinates(radius.doubleValue(), fromSkriptYaw(yaw.floatValue()), height.doubleValue())); + return CollectionUtils.array(fromCylindricalCoordinates(radius.doubleValue(), ExprYawPitch.fromSkriptYaw(yaw.floatValue()), height.doubleValue())); } @Override @@ -72,8 +71,6 @@ public String toString(@Nullable Event event, boolean debug) { yaw.toString(event, debug) + " and height " + height.toString(event, debug); } - // TODO Mark as private next version after VectorMath deletion - @ApiStatus.Internal public static Vector fromCylindricalCoordinates(double radius, double phi, double height) { double r = Math.abs(radius); double p = phi * DEG_TO_RAD; @@ -82,10 +79,4 @@ public static Vector fromCylindricalCoordinates(double radius, double phi, doubl return new Vector(x, height, z); } - private static float fromSkriptYaw(float yaw) { - return yaw > 270 - ? yaw - 270 - : yaw + 90; - } - } diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java index a0892371c1d..6c94b56e858 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorFromYawAndPitch.java @@ -13,9 +13,10 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; +import static ch.njol.skript.expressions.ExprYawPitch.fromYawAndPitch; + @Name("Vectors - Vector from Pitch and Yaw") @Description("Creates a vector from a yaw and pitch value.") @Examples("set {_v} to vector from yaw 45 and pitch 45") @@ -47,8 +48,8 @@ protected Vector[] get(Event event) { Number skriptPitch = pitch.getSingle(event); if (skriptYaw == null || skriptPitch == null) return null; - float yaw = fromSkriptYaw(wrapAngleDeg(skriptYaw.floatValue())); - float pitch = fromSkriptPitch(wrapAngleDeg(skriptPitch.floatValue())); + float yaw = ExprYawPitch.fromSkriptYaw(wrapAngleDeg(skriptYaw.floatValue())); + float pitch = ExprYawPitch.fromSkriptPitch(wrapAngleDeg(skriptPitch.floatValue())); return CollectionUtils.array(fromYawAndPitch(yaw, pitch)); } @@ -67,18 +68,6 @@ public String toString(@Nullable Event event, boolean debug) { return "vector from yaw " + yaw.toString(event, debug) + " and pitch " + pitch.toString(event, debug); } - private static Vector fromYawAndPitch(float yaw, float pitch) { - double y = Math.sin(pitch * DEG_TO_RAD); - double div = Math.cos(pitch * DEG_TO_RAD); - double x = Math.cos(yaw * DEG_TO_RAD); - double z = Math.sin(yaw * DEG_TO_RAD); - x *= div; - z *= div; - return new Vector(x,y,z); - } - - // TODO Mark as private next version after VectorMath deletion - @ApiStatus.Internal public static float wrapAngleDeg(float angle) { angle %= 360f; if (angle <= -180) { @@ -90,18 +79,4 @@ public static float wrapAngleDeg(float angle) { } } - // TODO Mark as private next version after VectorMath deletion - @ApiStatus.Internal - public static float fromSkriptYaw(float yaw) { - return yaw > 270 - ? yaw - 270 - : yaw + 90; - } - - // TODO Mark as private next version after VectorMath deletion - @ApiStatus.Internal - public static float fromSkriptPitch(float pitch) { - return -pitch; - } - } diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorLength.java b/src/main/java/ch/njol/skript/expressions/ExprVectorLength.java index f16cb3b060a..6311d02579f 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorLength.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorLength.java @@ -7,7 +7,6 @@ import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.SimplePropertyExpression; import ch.njol.skript.lang.Expression; -import ch.njol.util.VectorMath; import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; @@ -58,7 +57,7 @@ public void change(Event event, Object @Nullable [] delta, ChangeMode mode) { final double finalDeltaLength = deltaLength; final double finalDeltaLengthSquared = deltaLength * deltaLength; changeFunction = vector -> { - if (VectorMath.isZero(vector) || (finalDeltaLength < 0 && vector.lengthSquared() < finalDeltaLengthSquared)) { + if (vector.isZero() || (finalDeltaLength < 0 && vector.lengthSquared() < finalDeltaLengthSquared)) { vector.zero(); } else { double newLength = finalDeltaLength + vector.length(); @@ -72,7 +71,7 @@ public void change(Event event, Object @Nullable [] delta, ChangeMode mode) { case SET: final double finalDeltaLength1 = deltaLength; changeFunction = vector -> { - if (finalDeltaLength1 < 0 || VectorMath.isZero(vector)) { + if (finalDeltaLength1 < 0 || vector.isZero()) { vector.zero(); } else { if (!vector.isNormalized()) diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorNormalize.java b/src/main/java/ch/njol/skript/expressions/ExprVectorNormalize.java index 27bf04842ed..a320b92ddae 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorNormalize.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorNormalize.java @@ -1,10 +1,5 @@ package ch.njol.skript.expressions; -import ch.njol.util.VectorMath; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; -import org.jetbrains.annotations.Nullable; - import ch.njol.skript.Skript; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; @@ -16,6 +11,9 @@ import ch.njol.skript.lang.util.SimpleExpression; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; +import org.bukkit.event.Event; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.Nullable; @Name("Vectors - Normalized") @Description("Returns the same vector but with length 1.") @@ -46,7 +44,7 @@ protected Vector[] get(Event event) { if (vector == null) return null; vector = vector.clone(); - if (!VectorMath.isZero(vector) && !vector.isNormalized()) + if (!vector.isZero() && !vector.isNormalized()) vector.normalize(); return CollectionUtils.array(vector); } diff --git a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java index e624663e00a..877b1c0bd64 100644 --- a/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java +++ b/src/main/java/ch/njol/skript/expressions/ExprVectorSpherical.java @@ -13,7 +13,6 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.bukkit.util.Vector; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; @Name("Vectors - Spherical Shape") @@ -53,7 +52,8 @@ protected Vector[] get(Event event) { Number pitch = this.pitch.getSingle(event); if (radius == null || yaw == null || pitch == null) return null; - return CollectionUtils.array(fromSphericalCoordinates(radius.doubleValue(), fromSkriptYaw(yaw.floatValue()), pitch.floatValue() + 90)); + return CollectionUtils.array(fromSphericalCoordinates(radius.doubleValue(), + ExprYawPitch.fromSkriptYaw(yaw.floatValue()), pitch.floatValue() + 90)); } @Override @@ -72,8 +72,6 @@ public String toString(@Nullable Event event, boolean debug) { " and pitch" + pitch.toString(event, debug); } - // TODO Mark as private next version after VectorMath deletion - @ApiStatus.Internal public static Vector fromSphericalCoordinates(double radius, double theta, double phi) { double r = Math.abs(radius); double t = theta * DEG_TO_RAD; @@ -85,10 +83,4 @@ public static Vector fromSphericalCoordinates(double radius, double theta, doubl return new Vector(x, y, z); } - private static float fromSkriptYaw(float yaw) { - return yaw > 270 - ? yaw - 270 - : yaw + 90; - } - } diff --git a/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java b/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java index e501127cfc0..4625fb37726 100644 --- a/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java +++ b/src/main/java/ch/njol/skript/expressions/arithmetic/ArithmeticChain.java @@ -1,20 +1,19 @@ package ch.njol.skript.expressions.arithmetic; -import java.util.List; -import java.util.function.Function; -import java.util.function.Predicate; - -import org.bukkit.event.Event; - import ch.njol.skript.lang.Expression; import ch.njol.skript.util.Utils; +import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import org.skriptlang.skript.lang.arithmetic.Arithmetics; import org.skriptlang.skript.lang.arithmetic.Operation; import org.skriptlang.skript.lang.arithmetic.OperationInfo; import org.skriptlang.skript.lang.arithmetic.Operator; -import org.skriptlang.skript.lang.arithmetic.Arithmetics; import org.skriptlang.skript.lang.converter.Converters; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + /** * Represents a chain of arithmetic operations between two operands. * diff --git a/src/main/java/ch/njol/skript/expressions/base/PropertyExpression.java b/src/main/java/ch/njol/skript/expressions/base/PropertyExpression.java index 29a569a4c65..e331044076e 100644 --- a/src/main/java/ch/njol/skript/expressions/base/PropertyExpression.java +++ b/src/main/java/ch/njol/skript/expressions/base/PropertyExpression.java @@ -195,11 +195,10 @@ public final T[] getAll(Event event) { * @return An array containing the converted values * @throws ArrayStoreException if the converter returned invalid values */ - @SuppressWarnings("deprecation") // for backwards compatibility - protected T[] get(final F[] source, final ch.njol.skript.classes.Converter converter) { + protected T[] get(final F[] source, Converter converter) { assert source != null; assert converter != null; - return ch.njol.skript.registrations.Converters.convertUnsafe(source, getReturnType(), converter); + return Converters.convertUnsafe(source, getReturnType(), converter); } @Override diff --git a/src/main/java/ch/njol/skript/expressions/base/SimplePropertyExpression.java b/src/main/java/ch/njol/skript/expressions/base/SimplePropertyExpression.java index dbbf968f9df..2523ec573af 100644 --- a/src/main/java/ch/njol/skript/expressions/base/SimplePropertyExpression.java +++ b/src/main/java/ch/njol/skript/expressions/base/SimplePropertyExpression.java @@ -1,12 +1,12 @@ package ch.njol.skript.expressions.base; -import ch.njol.skript.classes.Converter; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.util.LiteralUtils; import ch.njol.util.Kleenean; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; +import org.skriptlang.skript.lang.converter.Converter; /** * A base class for property expressions that requires only few overridden methods @@ -14,7 +14,6 @@ * @see PropertyExpression * @see PropertyExpression#register(Class, Class, String, String) */ -@SuppressWarnings("deprecation") // for backwards compatibility public abstract class SimplePropertyExpression extends PropertyExpression implements Converter { @Override diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java index 5eefd224aa6..79fef6b1330 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondCanBuild.java @@ -1,11 +1,7 @@ package ch.njol.skript.hooks.regions.conditions; import ch.njol.skript.Skript; -import ch.njol.skript.doc.Description; -import ch.njol.skript.doc.Examples; -import ch.njol.skript.doc.Name; -import ch.njol.skript.doc.RequiredPlugins; -import ch.njol.skript.doc.Since; +import ch.njol.skript.doc.*; import ch.njol.skript.hooks.regions.RegionsPlugin; import ch.njol.skript.lang.Condition; import ch.njol.skript.lang.Expression; @@ -19,9 +15,6 @@ import java.util.function.Predicate; -/** - * @author Peter Güttinger - */ @Name("Can Build") @Description({ "Tests whether a player is allowed to build at a certain location.", @@ -29,12 +22,12 @@ }) @Examples({ "command /setblock <material>:", - "\tdescription: set the block at your crosshair to a different type", - "\ttrigger:", - "\t\tplayer cannot build at the targeted block:", - "\t\t\tmessage \"You do not have permission to change blocks there!\"", - "\t\t\tstop", - "\t\tset the targeted block to argument" + "\tdescription: set the block at your crosshair to a different type", + "\ttrigger:", + "\t\tplayer cannot build at the targeted block:", + "\t\t\tmessage \"You do not have permission to change blocks there!\"", + "\t\t\tstop", + "\t\tset the targeted block to argument" }) @Since("2.0") @RequiredPlugins("Supported regions plugin") @@ -60,18 +53,10 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final } @Override - public boolean check(final Event e) { - return players.check(e, new Predicate() { - @Override - public boolean test(final Player p) { - return locations.check(e, new Predicate() { - @Override - public boolean test(final Location l) { - return RegionsPlugin.canBuild(p, l); - } - }, isNegated()); - } - }); + public boolean check(Event event) { + return players.check(event, + player -> locations.check(event, + location -> RegionsPlugin.canBuild(player, location), isNegated())); } @Override diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java index e6711cd7fe7..17c2c5843b6 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondIsMember.java @@ -56,18 +56,10 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final } @Override - public boolean check(final Event e) { - return players.check(e, new Predicate() { - @Override - public boolean test(final OfflinePlayer p) { - return regions.check(e, new Predicate() { - @Override - public boolean test(final Region r) { - return owner ? r.isOwner(p) : r.isMember(p); - } - }, isNegated()); - } - }); + public boolean check(Event event) { + return players.check(event, + player -> regions.check(event, + region -> owner ? region.isOwner(player) : region.isMember(player), isNegated())); } @Override diff --git a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java index 55828245e66..66230a7ee6f 100644 --- a/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java +++ b/src/main/java/ch/njol/skript/hooks/regions/conditions/CondRegionContains.java @@ -18,9 +18,6 @@ import java.util.function.Predicate; -/** - * @author Peter Güttinger - */ @Name("Region Contains") @Description({ "Checks whether a location is contained in a particular region.", @@ -30,12 +27,13 @@ "player is in the region {regions::3}", "", "on region enter:", - "\tregion contains {flags.%world%.red}", - "\tmessage \"The red flag is near!\"" + "\tregion contains {flags.%world%.red}", + "\tmessage \"The red flag is near!\"" }) @Since("2.1") @RequiredPlugins("Supported regions plugin") public class CondRegionContains extends Condition { + static { Skript.registerCondition(CondRegionContains.class, "[[the] region] %regions% contain[s] %directions% %locations%", "%locations% (is|are) ([contained] in|part of) [[the] region] %regions%", @@ -62,18 +60,9 @@ public boolean init(final Expression[] exprs, final int matchedPattern, final } @Override - public boolean check(final Event e) { - return regions.check(e, new Predicate() { - @Override - public boolean test(final Region r) { - return locs.check(e, new Predicate() { - @Override - public boolean test(final Location l) { - return r.contains(l); - } - }, isNegated()); - } - }); + public boolean check(Event event) { + return regions.check(event, + region -> locs.check(event, region::contains, isNegated())); } @Override diff --git a/src/main/java/ch/njol/skript/lang/Expression.java b/src/main/java/ch/njol/skript/lang/Expression.java index e286e95c879..720006261f3 100644 --- a/src/main/java/ch/njol/skript/lang/Expression.java +++ b/src/main/java/ch/njol/skript/lang/Expression.java @@ -17,15 +17,9 @@ import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.converter.Converter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Spliterators; -import java.util.function.Predicate; +import java.util.*; import java.util.function.Function; +import java.util.function.Predicate; import java.util.stream.Stream; import java.util.stream.StreamSupport; @@ -71,7 +65,7 @@ default Optional getOptionalSingle(Event event) { * The returned array must not contain any null values. *

* Do not use this in conditions, use {@link #check(Event, Predicate, boolean)} instead. - * + * * @param event The event * @return An array of values of this expression which must neither be null nor contain nulls, and which must not be an internal array. */ @@ -92,7 +86,7 @@ default Optional getOptionalSingle(Event event) { * @param event The event * @return A non-null stream of this expression's non-null values */ - default Stream<@NotNull ? extends T> stream(Event event) { + default Stream stream(Event event) { Iterator iterator = iterator(event); if (iterator == null) { return Stream.empty(); diff --git a/src/main/java/ch/njol/skript/lang/ExpressionList.java b/src/main/java/ch/njol/skript/lang/ExpressionList.java index a6c715a2155..584de92e82b 100644 --- a/src/main/java/ch/njol/skript/lang/ExpressionList.java +++ b/src/main/java/ch/njol/skript/lang/ExpressionList.java @@ -9,7 +9,6 @@ import ch.njol.util.coll.CollectionUtils; import org.bukkit.event.Event; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; import java.lang.reflect.Array; import java.util.*; diff --git a/src/main/java/ch/njol/skript/lang/Variable.java b/src/main/java/ch/njol/skript/lang/Variable.java index 95fb0f6c59b..3fe427c9bda 100644 --- a/src/main/java/ch/njol/skript/lang/Variable.java +++ b/src/main/java/ch/njol/skript/lang/Variable.java @@ -50,6 +50,12 @@ import org.skriptlang.skript.lang.script.Script; import org.skriptlang.skript.lang.script.ScriptWarning; +import java.lang.reflect.Array; +import java.util.*; +import java.util.Map.Entry; +import java.util.function.Function; +import java.util.function.Predicate; + public class Variable implements Expression, KeyReceiverExpression, KeyProviderExpression { private final static String SINGLE_SEPARATOR_CHAR = ":"; @@ -191,9 +197,9 @@ else if (character == '%') ParserInstance parser = ParserInstance.get(); Script currentScript = parser.isActive() ? parser.getCurrentScript() : null; if (currentScript != null - && !SkriptConfig.disableVariableStartingWithExpressionWarnings.value() - && !currentScript.suppressesWarning(ScriptWarning.VARIABLE_STARTS_WITH_EXPRESSION) - && (isLocal ? name.substring(LOCAL_VARIABLE_TOKEN.length()) : name).startsWith("%")) { + && !SkriptConfig.disableVariableStartingWithExpressionWarnings.value() + && !currentScript.suppressesWarning(ScriptWarning.VARIABLE_STARTS_WITH_EXPRESSION) + && (isLocal ? name.substring(LOCAL_VARIABLE_TOKEN.length()) : name).startsWith("%")) { Skript.warning("Starting a variable's name with an expression is discouraged ({" + name + "}). " + "You could prefix it with the script's name: " + "{" + StringUtils.substring(currentScript.getConfig().getFileName(), 0, -3) + SEPARATOR + name + "}"); diff --git a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java index e76ff438747..2a3b332813d 100644 --- a/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java +++ b/src/main/java/ch/njol/skript/lang/util/ConvertedExpression.java @@ -15,12 +15,8 @@ import org.skriptlang.skript.lang.converter.ConverterInfo; import org.skriptlang.skript.lang.converter.Converters; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; +import java.util.*; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.function.Predicate; diff --git a/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java b/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java index 94175bf1557..556ffbde7ba 100644 --- a/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java +++ b/src/main/java/ch/njol/skript/lang/util/SimpleExpression.java @@ -22,6 +22,7 @@ import java.lang.reflect.Array; import java.util.Arrays; import java.util.Iterator; +import java.util.List; import java.util.function.Predicate; /** @@ -136,7 +137,7 @@ public final boolean check(Event event, Predicate checker, boolean ne } // TODO return a kleenean (UNKNOWN if 'values' is null or empty) - public static boolean check(@Nullable T[] values, Predicate checker, boolean invert, boolean and) { + public static boolean check(T @Nullable [] values, Predicate checker, boolean invert, boolean and) { if (values == null) return invert; boolean hasElement = false; @@ -279,7 +280,7 @@ protected final boolean setTime(int time, Expression mustbeDefaultVar, Class< } if (mustbeDefaultVar == null) { Skript.exception(new SkriptAPIException("Default expression was null. If the default expression can be null, don't be using" + - " 'SimpleExpression#setTime(int, Expression, Class...)' instead use the setTime without an expression if null.")); + " 'SimpleExpression#setTime(int, Expression, Class...)' instead use the setTime without an expression if null.")); return false; } if (!mustbeDefaultVar.isDefault()) diff --git a/src/main/java/ch/njol/skript/localization/Language.java b/src/main/java/ch/njol/skript/localization/Language.java index f3a68f9b6c4..aa61d532ea5 100644 --- a/src/main/java/ch/njol/skript/localization/Language.java +++ b/src/main/java/ch/njol/skript/localization/Language.java @@ -235,7 +235,7 @@ public static void loadDefault(SkriptAddon addon) { } public static boolean load(String name) { - name = "" + name.toLowerCase(Locale.ENGLISH); + name = name.toLowerCase(Locale.ENGLISH); localizedLanguage = new HashMap<>(); boolean exists = load(Skript.instance(), name, true); diff --git a/src/main/java/ch/njol/skript/localization/LanguageChangeListener.java b/src/main/java/ch/njol/skript/localization/LanguageChangeListener.java index 429a4230e06..5dcb854eeef 100644 --- a/src/main/java/ch/njol/skript/localization/LanguageChangeListener.java +++ b/src/main/java/ch/njol/skript/localization/LanguageChangeListener.java @@ -1,5 +1,6 @@ package ch.njol.skript.localization; +@FunctionalInterface public interface LanguageChangeListener { void onLanguageChange(); diff --git a/src/main/java/ch/njol/skript/registrations/Comparators.java b/src/main/java/ch/njol/skript/registrations/Comparators.java index ea29257da48..e69de29bb2d 100644 --- a/src/main/java/ch/njol/skript/registrations/Comparators.java +++ b/src/main/java/ch/njol/skript/registrations/Comparators.java @@ -1,102 +0,0 @@ -package ch.njol.skript.registrations; - -import ch.njol.skript.classes.Comparator; -import ch.njol.skript.classes.Comparator.Relation; -import org.jetbrains.annotations.Nullable; - -/** - * @deprecated Use {@link org.skriptlang.skript.lang.comparator.Comparators} - */ -@Deprecated -public class Comparators { - - private Comparators() {} - - /** - * Registers a {@link Comparator}. - * - * @param t1 - * @param t2 - * @param c - * @throws IllegalArgumentException if any given class is equal to Object.class - */ - public static void registerComparator(final Class t1, final Class t2, final Comparator c) { - org.skriptlang.skript.lang.comparator.Comparators.registerComparator(t1, t2, new org.skriptlang.skript.lang.comparator.Comparator() { - @Override - public org.skriptlang.skript.lang.comparator.Relation compare(T1 o1, T2 o2) { - return getFromOld(c.compare(o1, o2)); - } - - @Override - public boolean supportsOrdering() { - return c.supportsOrdering(); - } - }); - } - - public static Relation compare(final @Nullable Object o1, final @Nullable Object o2) { - return getFromNew(org.skriptlang.skript.lang.comparator.Comparators.compare(o1, o2)); - } - - public static java.util.Comparator getJavaComparator() { - return (o1, o2) -> compare(o1, o2).getRelation(); - } - - @Nullable - public static Comparator getComparator(final Class f, final Class s) { - org.skriptlang.skript.lang.comparator.Comparator newComp = - org.skriptlang.skript.lang.comparator.Comparators.getComparator(f, s); - if (newComp == null) - return null; - return new Comparator() { - @Override - public Relation compare(F f, S s) { - return getFromNew(newComp.compare(f, s)); - } - - @Override - public boolean supportsOrdering() { - return newComp.supportsOrdering(); - } - }; - } - - private static Relation getFromNew(org.skriptlang.skript.lang.comparator.Relation newRelation) { - switch (newRelation) { - case EQUAL: - return Relation.EQUAL; - case NOT_EQUAL: - return Relation.NOT_EQUAL; - case SMALLER: - return Relation.SMALLER; - case SMALLER_OR_EQUAL: - return Relation.SMALLER_OR_EQUAL; - case GREATER: - return Relation.GREATER; - case GREATER_OR_EQUAL: - return Relation.GREATER_OR_EQUAL; - default: - throw new IllegalArgumentException("Unexpected value: " + newRelation); - } - } - - private static org.skriptlang.skript.lang.comparator.Relation getFromOld(Relation oldRelation) { - switch (oldRelation) { - case EQUAL: - return org.skriptlang.skript.lang.comparator.Relation.EQUAL; - case NOT_EQUAL: - return org.skriptlang.skript.lang.comparator.Relation.NOT_EQUAL; - case SMALLER: - return org.skriptlang.skript.lang.comparator.Relation.SMALLER; - case SMALLER_OR_EQUAL: - return org.skriptlang.skript.lang.comparator.Relation.SMALLER_OR_EQUAL; - case GREATER: - return org.skriptlang.skript.lang.comparator.Relation.GREATER; - case GREATER_OR_EQUAL: - return org.skriptlang.skript.lang.comparator.Relation.GREATER_OR_EQUAL; - default: - throw new IllegalArgumentException("Unexpected value: " + oldRelation); - } - } - -} diff --git a/src/main/java/ch/njol/skript/registrations/Converters.java b/src/main/java/ch/njol/skript/registrations/Converters.java deleted file mode 100644 index 0858ef29e09..00000000000 --- a/src/main/java/ch/njol/skript/registrations/Converters.java +++ /dev/null @@ -1,192 +0,0 @@ -package ch.njol.skript.registrations; - -import ch.njol.skript.classes.Converter; -import ch.njol.skript.classes.Converter.ConverterInfo; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.stream.Collectors; - -/** - * Contains all registered converters and allows operating with them. - * @deprecated Use {@link org.skriptlang.skript.lang.converter.Converters} - */ -@Deprecated -public abstract class Converters { - - private Converters() {} - - @SuppressWarnings("unchecked") - public static List> getConverters() { - return org.skriptlang.skript.lang.converter.Converters.getConverterInfos().stream() - .map(unknownInfo -> { - org.skriptlang.skript.lang.converter.ConverterInfo info = (org.skriptlang.skript.lang.converter.ConverterInfo) unknownInfo; - return new ConverterInfo<>(info.getFrom(), info.getTo(), info.getConverter()::convert, info.getFlags()); - }) - .collect(Collectors.toList()); - } - - /** - * Registers a converter. - * - * @param from Type that the converter converts from. - * @param to Type that the converter converts to. - * @param converter Actual converter. - */ - public static void registerConverter(Class from, Class to, Converter converter) { - registerConverter(from, to, converter, 0); - } - - public static void registerConverter(Class from, Class to, Converter converter, int options) { - org.skriptlang.skript.lang.converter.Converters.registerConverter(from, to, converter::convert, options); - } - - // REMIND how to manage overriding of converters? - shouldn't actually matter - public static void createMissingConverters() { - org.skriptlang.skript.lang.converter.Converters.createChainedConverters(); - } - - /** - * Converts the given value to the desired type. If you want to convert multiple values of the same type you should use {@link #getConverter(Class, Class)} to get a - * converter to convert the values. - * - * @param o - * @param to - * @return The converted value or null if no converter exists or the converter returned null for the given value. - */ - @Nullable - public static T convert(final @Nullable F o, final Class to) { - return org.skriptlang.skript.lang.converter.Converters.convert(o, to); - } - - /** - * Converts an object into one of the given types. - *

- * This method does not convert the object if it is already an instance of any of the given classes. - * - * @param o - * @param to - * @return The converted object - */ - @Nullable - public static T convert(final @Nullable F o, final Class[] to) { - return org.skriptlang.skript.lang.converter.Converters.convert(o, to); - } - - /** - * Converts all entries in the given array to the desired type, using {@link #convert(Object, Class)} to convert every single value. If you want to convert an array of values - * of a known type, consider using {@link #convert(Object[], Class, Converter)} for much better performance. - * - * @param o - * @param to - * @return A T[] array without null elements - */ - @Nullable - public static T[] convertArray(final @Nullable Object[] o, final Class to) { - T[] converted = org.skriptlang.skript.lang.converter.Converters.convert(o, to); - if (converted.length == 0) // no longer nullable with new converter classes - return null; - return converted; - } - - /** - * Converts multiple objects into any of the given classes. - * - * @param o - * @param to - * @param superType The component type of the returned array - * @return The converted array - */ - public static T[] convertArray(final @Nullable Object[] o, final Class[] to, final Class superType) { - return org.skriptlang.skript.lang.converter.Converters.convert(o, to, superType); - } - - /** - * Strictly converts an array to a non-null array of the specified class. - * Uses registered {@link ch.njol.skript.registrations.Converters} to convert. - * - * @param original The array to convert - * @param to What to convert {@code original} to - * @return {@code original} converted to an array of {@code to} - * @throws ClassCastException if one of {@code original}'s - * elements cannot be converted to a {@code to} - */ - public static T[] convertStrictly(Object[] original, Class to) throws ClassCastException { - return org.skriptlang.skript.lang.converter.Converters.convertStrictly(original, to); - } - - /** - * Strictly converts an object to the specified class - * - * @param original The object to convert - * @param to What to convert {@code original} to - * @return {@code original} converted to a {@code to} - * @throws ClassCastException if {@code original} could not be converted to a {@code to} - */ - public static T convertStrictly(Object original, Class to) throws ClassCastException { - return org.skriptlang.skript.lang.converter.Converters.convertStrictly(original, to); - } - - /** - * Tests whether a converter between the given classes exists. - * - * @param from - * @param to - * @return Whether a converter exists - */ - public static boolean converterExists(final Class from, final Class to) { - return org.skriptlang.skript.lang.converter.Converters.converterExists(from, to); - } - - public static boolean converterExists(final Class from, final Class... to) { - return org.skriptlang.skript.lang.converter.Converters.converterExists(from, to); - } - - /** - * Gets a converter - * - * @param from - * @param to - * @return the converter or null if none exist - */ - @Nullable - public static Converter getConverter(final Class from, final Class to) { - org.skriptlang.skript.lang.converter.Converter converter = - org.skriptlang.skript.lang.converter.Converters.getConverter(from, to); - if (converter == null) - return null; - return (Converter) converter::convert; - } - - /** - * Gets a converter that has been registered before. - * - * @param from - * @param to - * @return The converter info or null if no converters were found. - */ - @Nullable - public static ConverterInfo getConverterInfo(Class from, Class to) { - org.skriptlang.skript.lang.converter.ConverterInfo info = - org.skriptlang.skript.lang.converter.Converters.getConverterInfo(from, to); - if (info == null) - return null; - return new ConverterInfo<>(info.getFrom(), info.getTo(), info.getConverter()::convert, info.getFlags()); - } - - /** - * @param from - * @param to - * @param conv - * @return The converted array - * @throws ArrayStoreException if the given class is not a superclass of all objects returned by the converter - */ - public static T[] convertUnsafe(final F[] from, final Class to, final Converter conv) { - return org.skriptlang.skript.lang.converter.Converters.convertUnsafe(from, to, conv::convert); - } - - public static T[] convert(final F[] from, final Class to, final Converter conv) { - return org.skriptlang.skript.lang.converter.Converters.convert(from, to, conv::convert); - } - -} diff --git a/src/main/java/ch/njol/skript/util/FileUtils.java b/src/main/java/ch/njol/skript/util/FileUtils.java index 2e9b7bd8e48..a5ff0d1cbcd 100644 --- a/src/main/java/ch/njol/skript/util/FileUtils.java +++ b/src/main/java/ch/njol/skript/util/FileUtils.java @@ -1,5 +1,7 @@ package ch.njol.skript.util; +import org.skriptlang.skript.lang.converter.Converter; + import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -12,9 +14,6 @@ import java.util.Collection; import java.util.Comparator; -import org.skriptlang.skript.lang.converter.Converter; - - /** * @author Peter Güttinger */ @@ -77,10 +76,12 @@ public static File backup(final File f) throws IOException { public static File move(final File from, final File to, final boolean replace) throws IOException { if (!replace && to.exists()) throw new IOException("Can't rename " + from.getName() + " to " + to.getName() + ": The target file already exists"); - if (replace) + + if (replace) { Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); - else + } else { Files.move(from.toPath(), to.toPath(), StandardCopyOption.ATOMIC_MOVE); + } return to; } @@ -90,7 +91,7 @@ public static void copy(final File from, final File to) throws IOException { /** * @param directory - * @param renamer Renames files. Return null to leave a file as-is. + * @param renamer Renames files. Return null to leave a file as-is. * @return A collection of all changed files (with their new names) * @throws IOException If renaming one of the files caused an IOException. Some files might have been renamed already. */ @@ -117,7 +118,7 @@ public static Collection renameAll(final File directory, final Converter the type which holds the value */ @Deprecated(forRemoval = true) -public abstract class Getter implements ch.njol.skript.classes.Converter, Converter { +public abstract class Getter implements Converter { /** * Gets a value from the given object. diff --git a/src/main/java/ch/njol/skript/util/PotionEffectUtils.java b/src/main/java/ch/njol/skript/util/PotionEffectUtils.java index 0886074d448..8d3495bb129 100644 --- a/src/main/java/ch/njol/skript/util/PotionEffectUtils.java +++ b/src/main/java/ch/njol/skript/util/PotionEffectUtils.java @@ -19,7 +19,6 @@ import ch.njol.skript.Skript; import ch.njol.skript.aliases.ItemType; import ch.njol.skript.localization.Language; -import ch.njol.skript.localization.LanguageChangeListener; @SuppressWarnings({"deprecation", "removal"}) public abstract class PotionEffectUtils { @@ -44,21 +43,18 @@ private static int getMaxPotionId() { } static { - Language.addListener(new LanguageChangeListener() { - @Override - public void onLanguageChange() { - types.clear(); - for (final PotionEffectType t : PotionEffectType.values()) { - if (t == null) - continue; - String name = t.getName(); - if (name.startsWith("minecraft:")) // seems to be the case for experimental entries... - name = name.substring(10); // trim off namespace - final String[] ls = Language.getList("potions." + name); - names[t.getId()] = ls[0]; - for (final String l : ls) { - types.put(l.toLowerCase(Locale.ENGLISH), t); - } + Language.addListener(() -> { + types.clear(); + for (final PotionEffectType t : PotionEffectType.values()) { + if (t == null) + continue; + String name = t.getName(); + if (name.startsWith("minecraft:")) // seems to be the case for experimental entries... + name = name.substring(10); // trim off namespace + final String[] ls = Language.getList("potions." + name); + names[t.getId()] = ls[0]; + for (final String l : ls) { + types.put(l.toLowerCase(Locale.ENGLISH), t); } } }); diff --git a/src/main/java/ch/njol/skript/util/Slot.java b/src/main/java/ch/njol/skript/util/Slot.java deleted file mode 100644 index 3249972efa6..00000000000 --- a/src/main/java/ch/njol/skript/util/Slot.java +++ /dev/null @@ -1,10 +0,0 @@ -package ch.njol.skript.util; - -/** - * Preserved for addon compatibility for a limited amount of time. - * Please, do use {@link ch.njol.skript.util.slot.Slot} instead! - * @deprecated Slot stuff got its own package. - */ -@Deprecated -public abstract class Slot extends ch.njol.skript.util.slot.Slot { -} diff --git a/src/main/java/ch/njol/skript/util/StructureType.java b/src/main/java/ch/njol/skript/util/StructureType.java index 74df73a7bb2..f15182c7892 100644 --- a/src/main/java/ch/njol/skript/util/StructureType.java +++ b/src/main/java/ch/njol/skript/util/StructureType.java @@ -12,7 +12,6 @@ import org.jetbrains.annotations.Nullable; import ch.njol.skript.localization.Language; -import ch.njol.skript.localization.LanguageChangeListener; import ch.njol.skript.localization.Noun; import ch.njol.util.coll.CollectionUtils; @@ -82,12 +81,7 @@ public boolean is(final TreeType type) { final static Map parseMap = new HashMap<>(); static { - Language.addListener(new LanguageChangeListener() { - @Override - public void onLanguageChange() { - parseMap.clear(); - } - }); + Language.addListener(parseMap::clear); } @Nullable diff --git a/src/main/java/ch/njol/skript/util/Task.java b/src/main/java/ch/njol/skript/util/Task.java index 9de544a1994..068b1cc758d 100644 --- a/src/main/java/ch/njol/skript/util/Task.java +++ b/src/main/java/ch/njol/skript/util/Task.java @@ -15,6 +15,7 @@ /** * @author Peter Güttinger */ +@SuppressWarnings("removal") public abstract class Task implements Runnable, Closeable { private final Plugin plugin; diff --git a/src/main/java/ch/njol/skript/util/Utils.java b/src/main/java/ch/njol/skript/util/Utils.java index 7cf915961bf..6a2db700ae3 100644 --- a/src/main/java/ch/njol/skript/util/Utils.java +++ b/src/main/java/ch/njol/skript/util/Utils.java @@ -1,45 +1,37 @@ package ch.njol.skript.util; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; - -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.plugin.messaging.Messenger; -import org.bukkit.plugin.messaging.PluginMessageListener; - -import com.google.common.collect.Iterables; -import com.google.common.io.ByteArrayDataInput; -import com.google.common.io.ByteArrayDataOutput; -import com.google.common.io.ByteStreams; - import ch.njol.skript.Skript; import ch.njol.skript.effects.EffTeleport; import ch.njol.skript.localization.Language; -import ch.njol.skript.localization.LanguageChangeListener; import ch.njol.skript.registrations.Classes; import ch.njol.util.NonNullPair; import ch.njol.util.Pair; import ch.njol.util.StringUtils; import ch.njol.util.coll.CollectionUtils; -import ch.njol.util.coll.iterator.EnumerationIterable; +import com.google.common.collect.Iterables; +import com.google.common.io.ByteArrayDataInput; +import com.google.common.io.ByteArrayDataOutput; +import com.google.common.io.ByteStreams; import net.md_5.bungee.api.ChatColor; -import org.jetbrains.annotations.Nullable; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.plugin.messaging.Messenger; +import org.bukkit.plugin.messaging.PluginMessageListener; import org.jetbrains.annotations.NotNull; -import org.skriptlang.skript.util.ClassLoader; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.*; +import java.util.concurrent.CompletableFuture; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; /** * Utility class. @@ -203,7 +195,7 @@ public static Pair getAmount(String s) { @Deprecated public static Class[] getClasses(Plugin plugin, String basePackage, String... subPackages) throws IOException { List> classes = new ArrayList<>(); - ClassLoader loader = ClassLoader.builder() + org.skriptlang.skript.util.ClassLoader loader = org.skriptlang.skript.util.ClassLoader.builder() .basePackage(basePackage) .addSubPackages(subPackages) .deep(true) @@ -480,8 +472,10 @@ public static CompletableFuture sendPluginMessage(Player pla * this completable future will complete exceptionally if the player is null. * @throws IllegalStateException when there are no players online */ - public static CompletableFuture sendPluginMessage(String channel, - Predicate messageVerifier, String... data) throws IllegalStateException { + public static CompletableFuture sendPluginMessage( + String channel, + Predicate messageVerifier, String... data + ) throws IllegalStateException { Player firstPlayer = Iterables.getFirst(Bukkit.getOnlinePlayers(), null); if (firstPlayer == null) throw new IllegalStateException("There are no players online"); @@ -498,7 +492,7 @@ public static CompletableFuture sendPluginMessage(String cha * .exceptionally(ex -> { * Skript.warning("Failed to get servers because there are no players online"); * return null; - * }); + * }); * * * @param player the player to send the plugin message through @@ -508,8 +502,10 @@ public static CompletableFuture sendPluginMessage(String cha * @return a completable future for the message of the responding plugin message, if there is one. * this completable future will complete exceptionally if the player is null. */ - public static CompletableFuture sendPluginMessage(Player player, String channel, - Predicate messageVerifier, String... data) { + public static CompletableFuture sendPluginMessage( + Player player, String channel, + Predicate messageVerifier, String... data + ) { CompletableFuture completableFuture = new CompletableFuture<>(); Skript skript = Skript.getInstance(); @@ -520,7 +516,7 @@ public static CompletableFuture sendPluginMessage(Player pla PluginMessageListener listener = (sendingChannel, sendingPlayer, message) -> { ByteArrayDataInput input = ByteStreams.newDataInput(message); if (channel.equals(sendingChannel) && sendingPlayer == player && !completableFuture.isDone() - && !completableFuture.isCancelled() && messageVerifier.test(input)) { + && !completableFuture.isCancelled() && messageVerifier.test(input)) { completableFuture.complete(input); } }; @@ -549,17 +545,14 @@ public static CompletableFuture sendPluginMessage(Player pla final static Map englishChat = new HashMap<>(); static { - Language.addListener(new LanguageChangeListener() { - @Override - public void onLanguageChange() { - final boolean english = englishChat.isEmpty(); - chat.clear(); - for (final ChatColor style : styles) { - for (final String s : Language.getList("chat styles." + style.name())) { - chat.put(s.toLowerCase(Locale.ENGLISH), style.toString()); - if (english) - englishChat.put(s.toLowerCase(Locale.ENGLISH), style.toString()); - } + Language.addListener(() -> { + final boolean english = englishChat.isEmpty(); + chat.clear(); + for (final ChatColor style : styles) { + for (final String s : Language.getList("chat styles." + style.name())) { + chat.put(s.toLowerCase(Locale.ENGLISH), style.toString()); + if (english) + englishChat.put(s.toLowerCase(Locale.ENGLISH), style.toString()); } } }); diff --git a/src/main/java/ch/njol/skript/util/chat/ChatMessages.java b/src/main/java/ch/njol/skript/util/chat/ChatMessages.java index b8bcd5d4ed9..bb4280bec30 100644 --- a/src/main/java/ch/njol/skript/util/chat/ChatMessages.java +++ b/src/main/java/ch/njol/skript/util/chat/ChatMessages.java @@ -68,31 +68,13 @@ public class ChatMessages { */ public static void registerListeners() { // When language changes or server is loaded loop through all chatcodes - Language.addListener(new LanguageChangeListener() { - - @Override - public void onLanguageChange() { - codes.clear(); - - Skript.debug("Parsing message style lang files"); - for (SkriptChatCode code : SkriptChatCode.values()) { - assert code != null; - registerChatCode(code); - } - - // Re-register any missing addon chat codes - for (ChatCode code : addonCodes) { - assert code != null; - registerChatCode(code); - } - - // Add formatting chars - addColorChar('k', SkriptChatCode.obfuscated); - addColorChar('l', SkriptChatCode.bold); - addColorChar('m', SkriptChatCode.strikethrough); - addColorChar('n', SkriptChatCode.underlined); - addColorChar('o', SkriptChatCode.italic); - addColorChar('r', SkriptChatCode.reset); + Language.addListener(() -> { + codes.clear(); + + Skript.debug("Parsing message style lang files"); + for (SkriptChatCode code : SkriptChatCode.values()) { + assert code != null; + registerChatCode(code); } }); } diff --git a/src/main/java/ch/njol/skript/variables/SQLStorage.java b/src/main/java/ch/njol/skript/variables/SQLStorage.java index 08b83f8d0d2..e0ab25c3ee8 100644 --- a/src/main/java/ch/njol/skript/variables/SQLStorage.java +++ b/src/main/java/ch/njol/skript/variables/SQLStorage.java @@ -4,7 +4,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.util.Map.Entry; import java.util.UUID; import java.util.concurrent.Callable; @@ -138,7 +137,7 @@ protected boolean load_i(SectionNode n) { return false; try { - final boolean hasOldTable = db.isTable(OLD_TABLE_NAME); + final boolean hasOldTable = false; final boolean hadNewTable = db.isTable(getTableName()); if (getFormattedCreateQuery() == null){ @@ -160,15 +159,6 @@ protected boolean load_i(SectionNode n) { // old // Table name support was added after the verison that used the legacy database format - if (hasOldTable && !tableName.equals("variables")) { - final ResultSet r1 = db.query("SELECT " + SELECT_ORDER + " FROM " + OLD_TABLE_NAME); - assert r1 != null; - try { - oldLoadVariables(r1, hadNewTable); - } finally { - r1.close(); - } - } // new final ResultSet r2 = db.query("SELECT " + SELECT_ORDER + " FROM " + getTableName()); @@ -180,51 +170,6 @@ protected boolean load_i(SectionNode n) { } // store old variables in new table and delete the old table - if (hasOldTable) { - if (!hadNewTable) { - Skript.info("[2.1] Updating the database '" + getUserConfigurationName() + "' to the new format..."); - try { - Variables.getReadLock().lock(); - for (final Entry v : Variables.getVariablesHashMap().entrySet()) { - if (accept(v.getKey())) {// only one database was possible, so only checking this database is correct - @SuppressWarnings("null") - final SerializedVariable var = Variables.serialize(v.getKey(), v.getValue()); - final SerializedVariable.Value d = var.value; - save(var.name, d == null ? null : d.type, d == null ? null : d.data); - } - } - Skript.info("Updated and transferred " + Variables.getVariablesHashMap().size() + " variables to the new table."); - } finally { - Variables.getReadLock().unlock(); - } - } - db.query("DELETE FROM " + OLD_TABLE_NAME + " WHERE value IS NULL"); - db.query("DELETE FROM old USING " + OLD_TABLE_NAME + " AS old, " + getTableName() + " AS new WHERE old.name = new.name"); - final ResultSet r = db.query("SELECT * FROM " + OLD_TABLE_NAME + " LIMIT 1"); - try { - if (r.next()) {// i.e. the old table is not empty - Skript.error("Could not successfully convert & transfer all variables to the new table in the database '" + getUserConfigurationName() + "'. " - + "Variables that could not be transferred are left in the old table and Skript will reattempt to transfer them whenever it starts until the old table is empty or is manually deleted. " - + "Please note that variables recreated by scripts will count as converted and will be removed from the old table on the next restart."); - } else { - boolean error = false; - try { - disconnect(); // prevents SQLITE_LOCKED error - connect(); - db.query("DROP TABLE " + OLD_TABLE_NAME); - } catch (final SQLException e) { - Skript.error("There was an error deleting the old variables table from the database '" + getUserConfigurationName() + "', please delete it yourself: " + e.getLocalizedMessage()); - error = true; - } - if (!error) - Skript.info("Successfully deleted the old variables table from the database '" + getUserConfigurationName() + "'."); - if (!hadNewTable) - Skript.info("Database '" + getUserConfigurationName() + "' successfully updated."); - } - } finally { - r.close(); - } - } } catch (final SQLException e) { sqlException(e); return false; @@ -633,132 +578,6 @@ public SQLException call() throws Exception { // final static LinkedList oldSyncDeserializing = new LinkedList(); - @Deprecated - private void oldLoadVariables(final ResultSet r, final boolean hadNewTable) throws SQLException { -// synchronized (oldSyncDeserializing) { - - final VariablesStorage temp = new VariablesStorage(getUserConfigurationName() + " old variables table") { - @Override - protected boolean save(final String name, @Nullable final String type, @Nullable final byte[] value) { - assert type == null : name + "; " + type; - return true; - } - - @Override - boolean accept(@Nullable final String var) { - assert false; - return false; - } - - @Override - protected boolean requiresFile() { - assert false; - return false; - } - - @Override - protected boolean load_i(final SectionNode n) { - assert false; - return false; - } - - @Override - protected File getFile(final String file) { - assert false; - return new File(file); - } - - @Override - protected void disconnect() { - assert false; - } - - @Override - protected boolean connect() { - assert false; - return false; - } - - @Override - protected void allLoaded() { - assert false; - } - }; - - final SQLException e = Task.callSync(new Callable() { - @SuppressWarnings("null") - @Override - @Nullable - public SQLException call() throws Exception { - try { - while (r.next()) { - int i = 1; - final String name = r.getString(i++); - if (name == null) { - Skript.error("Variable with NULL name found in the database, ignoring it"); - continue; - } - final String type = r.getString(i++); - final String value = r.getString(i++); - lastRowID = r.getLong(i++); - if (type == null || value == null) { - Variables.variableLoaded(name, null, hadNewTable ? temp : SQLStorage.this); - } else { - final ClassInfo c = Classes.getClassInfoNoError(type); - Serializer s; - if (c == null || (s = c.getSerializer()) == null) { - Skript.error("Cannot load the variable {" + name + "} from the database, because the type '" + type + "' cannot be recognised or not stored in variables"); - continue; - } -// if (s.mustSyncDeserialization()) { -// oldSyncDeserializing.add(new OldVariableInfo(name, value, c)); -// } else { - final Object d = s.deserialize(value); - if (d == null) { - Skript.error("Cannot load the variable {" + name + "} from the database, because '" + value + "' cannot be parsed as a " + type); - continue; - } - Variables.variableLoaded(name, d, SQLStorage.this); -// } - } - } - } catch (final SQLException e) { - return e; - } - return null; - } - }); - if (e != null) - throw e; - -// if (!oldSyncDeserializing.isEmpty()) { -// Task.callSync(new Callable() { -// @Override -// @Nullable -// public Void call() throws Exception { -// synchronized (oldSyncDeserializing) { -// for (final OldVariableInfo o : oldSyncDeserializing) { -// final Serializer s = o.ci.getSerializer(); -// if (s == null) { -// assert false : o.ci; -// continue; -// } -// final Object d = s.deserialize(o.value); -// if (d == null) { -// Skript.error("Cannot load the variable {" + o.name + "} from the database, because '" + o.value + "' cannot be parsed as a " + o.ci.getCodeName()); -// continue; -// } -// Variables.variableLoaded(o.name, d, DatabaseStorage.this); -// } -// oldSyncDeserializing.clear(); -// return null; -// } -// } -// }); -// } -// } - } - void sqlException(final SQLException e) { Skript.error("database error: " + e.getLocalizedMessage()); if (Skript.testing()) diff --git a/src/main/java/ch/njol/skript/variables/VariablesStorage.java b/src/main/java/ch/njol/skript/variables/VariablesStorage.java index 27e5560ecb4..10c4bf99d01 100644 --- a/src/main/java/ch/njol/skript/variables/VariablesStorage.java +++ b/src/main/java/ch/njol/skript/variables/VariablesStorage.java @@ -32,7 +32,7 @@ * @see DatabaseStorage */ // FIXME ! large databases (>25 MB) cause the server to be unresponsive instead of loading slowly -@SuppressWarnings("SuspiciousIndentAfterControlStatement") +@SuppressWarnings({"SuspiciousIndentAfterControlStatement", "removal"}) public abstract class VariablesStorage implements Closeable { /** diff --git a/src/main/java/ch/njol/util/Callback.java b/src/main/java/ch/njol/util/Callback.java index 64bdbf0d19b..bc3b5488308 100644 --- a/src/main/java/ch/njol/util/Callback.java +++ b/src/main/java/ch/njol/util/Callback.java @@ -5,9 +5,11 @@ import java.util.function.Function; -@Deprecated +/** + * @deprecated use {@link Function} + */ +@Deprecated(forRemoval = true) @FunctionalInterface -@ApiStatus.ScheduledForRemoval public interface Callback extends Function { @Nullable diff --git a/src/main/java/ch/njol/util/CaseInsensitiveString.java b/src/main/java/ch/njol/util/CaseInsensitiveString.java index bc4562eb9e2..ccf421c2096 100644 --- a/src/main/java/ch/njol/util/CaseInsensitiveString.java +++ b/src/main/java/ch/njol/util/CaseInsensitiveString.java @@ -7,15 +7,10 @@ import javax.annotation.Nullable; - - /** - * A string which is compared ignoring it's case. - * - * @author Peter Güttinger + * @deprecated use {@link java.lang.String#equalsIgnoreCase(String)} */ -@Deprecated -@ApiStatus.ScheduledForRemoval +@Deprecated(forRemoval = true) public class CaseInsensitiveString implements Serializable, Comparable, CharSequence { private static final long serialVersionUID = 1205018864604639962L; diff --git a/src/main/java/ch/njol/util/Checker.java b/src/main/java/ch/njol/util/Checker.java index a4ba070f4e0..8f98a7a08b7 100644 --- a/src/main/java/ch/njol/util/Checker.java +++ b/src/main/java/ch/njol/util/Checker.java @@ -1,12 +1,12 @@ package ch.njol.util; -import org.jetbrains.annotations.ApiStatus; - import java.util.function.Predicate; -@Deprecated +/** + * @deprecated use {@link Predicate} + */ +@Deprecated(forRemoval = true) @FunctionalInterface -@ApiStatus.ScheduledForRemoval public interface Checker extends Predicate { boolean check(T o); diff --git a/src/main/java/ch/njol/util/Closeable.java b/src/main/java/ch/njol/util/Closeable.java index 75ed886ac20..b4fa7c18ee7 100644 --- a/src/main/java/ch/njol/util/Closeable.java +++ b/src/main/java/ch/njol/util/Closeable.java @@ -4,7 +4,9 @@ * Like {@link java.io.Closeable}, but not used for resources, thus it neither throws checked exceptions nor causes resource leak warnings. * * This is an auto-closeable resource and so may be used within a try-with-resources section for automatic disposal. + * @deprecated use {@link java.io.Closeable} */ +@Deprecated(forRemoval = true) public interface Closeable extends AutoCloseable { /** diff --git a/src/main/java/ch/njol/util/LoggerFilter.java b/src/main/java/ch/njol/util/LoggerFilter.java index 6f15d88af34..6ef542de9f0 100644 --- a/src/main/java/ch/njol/util/LoggerFilter.java +++ b/src/main/java/ch/njol/util/LoggerFilter.java @@ -8,18 +8,19 @@ import org.jetbrains.annotations.Nullable; +@SuppressWarnings("removal") public final class LoggerFilter implements Filter, Closeable { private final Logger l; private final Collection filters = new ArrayList<>(5); @Nullable private final Filter oldFilter; - + public LoggerFilter(final Logger l) { this.l = l; oldFilter = l.getFilter(); l.setFilter(this); } - + @Override public boolean isLoggable(final @Nullable LogRecord record) { if (oldFilter != null && !oldFilter.isLoggable(record)) @@ -29,15 +30,15 @@ public boolean isLoggable(final @Nullable LogRecord record) { return false; return true; } - + public final void addFilter(final Filter f) { filters.add(f); } - + public final boolean removeFilter(final Filter f) { return filters.remove(f); } - + @Override public void close() { l.setFilter(oldFilter); diff --git a/src/main/java/ch/njol/util/Math2.java b/src/main/java/ch/njol/util/Math2.java index 40073193d86..6029be12027 100644 --- a/src/main/java/ch/njol/util/Math2.java +++ b/src/main/java/ch/njol/util/Math2.java @@ -163,91 +163,4 @@ public static long multiplyClamped(long x, long y) { return result; } - @Deprecated - @ScheduledForRemoval - public static int floorI(double value) { - return (int) Math.floor(value + Skript.EPSILON); - } - - @Deprecated - @ScheduledForRemoval - public static int ceilI(double value) { - return (int) Math.ceil(value - Skript.EPSILON); - } - - // Change signature to return int instead of removing. - @Deprecated - @ScheduledForRemoval - public static long floor(float value) { - return (long) Math.floor(value + Skript.EPSILON); - } - - @Deprecated - @ScheduledForRemoval - public static int min(int a, int b, int c) { - return Math.min(a, Math.min(b, c)); - } - - @Deprecated - @ScheduledForRemoval - public static int min(int... numbers) { - if (numbers.length == 0) - return 0; - - return Arrays.stream(numbers) - .min() - .getAsInt(); - } - - @Deprecated - @ScheduledForRemoval - public static int max(int a, int b, int c) { - return Math.max(a, Math.max(b, c)); - } - - @Deprecated - @ScheduledForRemoval - public static int max(int... numbers) { - if (numbers.length == 0) - return 0; - - return Arrays.stream(numbers) - .max() - .getAsInt(); - } - - @Deprecated - @ScheduledForRemoval - public static double min(double a, double b, double c) { - return Math.min(a, Math.min(b, c)); - } - - @Deprecated - @ScheduledForRemoval - public static double min(double... numbers) { - if (numbers.length == 0) - return Double.NaN; - - return Arrays.stream(numbers) - .min() - .getAsDouble(); - } - - @Deprecated - @ScheduledForRemoval - public static double max(double a, double b, double c) { - return Math.max(a, Math.max(b, c)); - } - - @Deprecated - @ScheduledForRemoval - public static double max(double... numbers) { - if (numbers.length == 0) - return Double.NaN; - - return Arrays.stream(numbers) - .max() - .getAsDouble(); - } - } diff --git a/src/main/java/ch/njol/util/NonNullPair.java b/src/main/java/ch/njol/util/NonNullPair.java index 39fba1de6b1..d11807b2427 100644 --- a/src/main/java/ch/njol/util/NonNullPair.java +++ b/src/main/java/ch/njol/util/NonNullPair.java @@ -1,8 +1,9 @@ package ch.njol.util; /** - * @author Peter Güttinger + * @deprecated Use a use-case specific record. */ +@Deprecated public class NonNullPair extends Pair { private static final long serialVersionUID = 820250942098905541L; diff --git a/src/main/java/ch/njol/util/NullableChecker.java b/src/main/java/ch/njol/util/NullableChecker.java index 0707c3bb10f..9f34909f6d1 100644 --- a/src/main/java/ch/njol/util/NullableChecker.java +++ b/src/main/java/ch/njol/util/NullableChecker.java @@ -2,18 +2,20 @@ import org.jetbrains.annotations.Nullable; +import java.util.Objects; import java.util.function.Predicate; +@SuppressWarnings("removal") public interface NullableChecker extends ch.njol.util.Checker, Predicate { @Override boolean check(@Nullable T o); - public static final NullableChecker nullChecker = new NullableChecker() { - @Override - public boolean check(final @Nullable Object o) { - return o != null; - } - }; + @Override + default boolean test(@Nullable T t) { + return this.check(t); + } + + NullableChecker nullChecker = Objects::nonNull; } diff --git a/src/main/java/ch/njol/util/Pair.java b/src/main/java/ch/njol/util/Pair.java index 25bb2cc0b83..01e5453db3f 100644 --- a/src/main/java/ch/njol/util/Pair.java +++ b/src/main/java/ch/njol/util/Pair.java @@ -9,6 +9,12 @@ import java.util.Map.Entry; import java.util.Objects; +import org.jetbrains.annotations.Nullable; + +/** + * @deprecated Use a use-case specific record. + */ +@Deprecated public class Pair implements Entry, Cloneable, Serializable { @Serial private static final long serialVersionUID = 8296563685697678334L; diff --git a/src/main/java/ch/njol/util/Predicate.java b/src/main/java/ch/njol/util/Predicate.java index f5e80de8c81..e18627fd134 100644 --- a/src/main/java/ch/njol/util/Predicate.java +++ b/src/main/java/ch/njol/util/Predicate.java @@ -5,12 +5,10 @@ import javax.annotation.Nullable; /** - * @author Peter G�ttinger - * + * @deprecated use {@link java.util.function.Predicate} */ -@Deprecated +@Deprecated(forRemoval = true) @FunctionalInterface -@ApiStatus.ScheduledForRemoval public interface Predicate extends java.util.function.Predicate { boolean test(@Nullable T paramT); } diff --git a/src/main/java/ch/njol/util/Setter.java b/src/main/java/ch/njol/util/Setter.java index 4b285941068..246c57f1af5 100644 --- a/src/main/java/ch/njol/util/Setter.java +++ b/src/main/java/ch/njol/util/Setter.java @@ -1,12 +1,12 @@ package ch.njol.util; -import org.jetbrains.annotations.ApiStatus; - import java.util.function.Consumer; -@Deprecated +/** + * @deprecated use {@link Consumer} + */ +@Deprecated(forRemoval = true) @FunctionalInterface -@ApiStatus.ScheduledForRemoval public interface Setter extends Consumer { void set(T t); diff --git a/src/main/java/ch/njol/util/StringUtils.java b/src/main/java/ch/njol/util/StringUtils.java index 6a48d73b635..aa277b454a3 100644 --- a/src/main/java/ch/njol/util/StringUtils.java +++ b/src/main/java/ch/njol/util/StringUtils.java @@ -1,26 +1,23 @@ package ch.njol.util; +import org.jetbrains.annotations.Nullable; + import java.util.Iterator; import java.util.Locale; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.jetbrains.annotations.Nullable; - -/** - * @author Peter Güttinger - */ public abstract class StringUtils { - + public static void checkIndices(final String s, final int start, final int end) { if (start < 0 || end > s.length()) throw new StringIndexOutOfBoundsException("invalid start/end indices " + start + "," + end + " for string \"" + s + "\" (length " + s.length() + ")"); } - + /** * Appends the english order suffix to the given number. - * + * * @param i the number * @return 1st, 2nd, 3rd, 4th, etc. */ @@ -35,14 +32,14 @@ public static String fancyOrderNumber(int i) { return i + "rd"; return i + "th"; } - + /** * Performs regex replacing using a callback. - * - * @param string the String in which should be searched & replaced - * @param regex the Regex to match + * + * @param string the String in which should be searched & replaced + * @param regex the Regex to match * @param callback the callback will be run for every match of the regex in the string, and should return the replacement string for the given match. - * If the callback returns null for any given match this function will immediately terminate and return null. + * If the callback returns null for any given match this function will immediately terminate and return null. * @return */ @SuppressWarnings("null") @@ -50,14 +47,14 @@ public static String fancyOrderNumber(int i) { public static String replaceAll(final CharSequence string, final String regex, final Function callback) { return replaceAll(string, Pattern.compile(regex), callback); } - + /** * Performs regex replacing using a callback. - * - * @param string the String in which should be searched & replaced - * @param regex the Regex to match + * + * @param string the String in which should be searched & replaced + * @param regex the Regex to match * @param callback the callback will be run for every match of the regex in the string, and should return the replacement string for the given match. - * If the callback returns null for any given match this function will immediately terminate and return null. + * If the callback returns null for any given match this function will immediately terminate and return null. * @return */ @Nullable @@ -73,15 +70,15 @@ public static String replaceAll(final CharSequence string, final Pattern regex, m.appendTail(sb); return sb.toString(); } - + public static int count(final String s, final char c) { return count(s, c, 0, s.length()); } - + public static int count(final String s, final char c, final int start) { return count(s, c, start, s.length()); } - + public static int count(final String s, final char c, final int start, final int end) { checkIndices(s, start, end); int r = 0; @@ -91,7 +88,7 @@ public static int count(final String s, final char c, final int start, final int } return r; } - + public static boolean contains(final String s, final char c, final int start, final int end) { checkIndices(s, start, end); for (int i = start; i < end; i++) { @@ -100,11 +97,11 @@ public static boolean contains(final String s, final char c, final int start, fi } return false; } - + /** * Gets a rounded english (##.##) representation of a number - * - * @param d The number to be turned into a string + * + * @param d The number to be turned into a string * @param accuracy Maximum number of digits after the period * @return */ @@ -120,7 +117,7 @@ public static String toString(final double d, final int accuracy) { c--; return "" + s.substring(0, c + 1); } - + public static String firstToUpper(final String s) { if (s.isEmpty()) return s; @@ -128,10 +125,10 @@ public static String firstToUpper(final String s) { return s; return Character.toUpperCase(s.charAt(0)) + s.substring(1); } - + /** * Equal to {@link String#substring(int, int)}, but allows negative indices that are counted from the end of the string. - * + * * @param s * @param start * @param end @@ -146,10 +143,10 @@ public static String substring(final String s, int start, int end) { throw new IllegalArgumentException("invalid indices"); return "" + s.substring(start, end); } - + /** * Capitalises the first character of the string and all characters that follow periods, exclamation and question marks. - * + * * @param string * @return */ @@ -167,7 +164,7 @@ public static String fixCapitalization(final String string) { } return new String(s); } - + private static int indexOf(final char[] s, final int start, final char... cs) { for (int i = start; i < s.length; i++) { for (final char c : cs) @@ -176,10 +173,10 @@ private static int indexOf(final char[] s, final int start, final char... cs) { } return -1; } - + /** * Shorthand for {@link #numberAt(CharSequence, int, boolean) numberAt}(s, index, true) - * + * * @param s * @param index * @return @@ -187,10 +184,10 @@ private static int indexOf(final char[] s, final int start, final char... cs) { public static double numberAfter(final CharSequence s, final int index) { return numberAt(s, index, true); } - + /** * Shorthand for {@link #numberAt(CharSequence, int, boolean) numberAt}(s, index, false) - * + * * @param s * @param index * @return @@ -198,15 +195,15 @@ public static double numberAfter(final CharSequence s, final int index) { public static double numberBefore(final CharSequence s, final int index) { return numberAt(s, index, false); } - + /** * Finds a positive number in the given CharSequence, starting at the given index, and searching in the given direction. *

* The number has to start exactly at the given index (ignoring whitespace), and will only count if the other end of the number is either at an end of the string or padded by * whitespace. - * - * @param s The ChatSequence to search the number in - * @param index The index to start searching at (inclusive) + * + * @param s The ChatSequence to search the number in + * @param index The index to start searching at (inclusive) * @param forward Whether to search forwards or backwards * @return The number found or -1 if no matching number was found */ @@ -250,11 +247,11 @@ public static double numberAt(final CharSequence s, final int index, final boole return -1; return Double.parseDouble(s.subSequence(Math.min(d1, d2), Math.max(d1, d2) + 1).toString()); } - + public static boolean startsWithIgnoreCase(final String string, final String start) { return startsWithIgnoreCase(string, start, 0); } - + public static boolean startsWithIgnoreCase(final String string, final String start, final int offset) { assert string != null; assert start != null; @@ -262,7 +259,7 @@ public static boolean startsWithIgnoreCase(final String string, final String sta return false; return string.substring(offset, start.length()).equalsIgnoreCase(start); } - + public static boolean endsWithIgnoreCase(final String string, final String end) { assert string != null; assert end != null; @@ -270,7 +267,7 @@ public static boolean endsWithIgnoreCase(final String string, final String end) return false; return string.substring(string.length() - end.length()).equalsIgnoreCase(end); } - + public static String multiply(final @Nullable String s, final int amount) { assert amount >= 0 : amount; if (s == null) @@ -285,7 +282,7 @@ public static String multiply(final @Nullable String s, final int amount) { System.arraycopy(input, 0, multiplied, i * input.length, input.length); return new String(multiplied); } - + public static String multiply(final char c, final int amount) { if (amount == 0) return ""; @@ -294,19 +291,19 @@ public static String multiply(final char c, final int amount) { multiplied[i] = c; return new String(multiplied); } - + public static String join(final @Nullable Object[] strings) { if (strings == null) return ""; return join(strings, "", 0, strings.length); } - + public static String join(final @Nullable Object[] strings, final String delimiter) { if (strings == null) return ""; return join(strings, delimiter, 0, strings.length); } - + public static String join(final @Nullable Object[] strings, final String delimiter, final int start, final int end) { if (strings == null) return ""; @@ -320,13 +317,13 @@ public static String join(final @Nullable Object[] strings, final String delimit } return "" + b; } - + public static String join(final @Nullable Iterable strings) { if (strings == null) return ""; return join(strings.iterator(), ""); } - + public static String join(@Nullable Iterable strings, String delimiter) { if (strings == null) return ""; @@ -362,10 +359,10 @@ public static String join(@Nullable Iterable strings, String delimiter, Strin return ""; return join(strings.iterator(), delimiter, lastDelimiter); } - + /** * Scans the string starting at start for digits. - * + * * @param s * @param start Index of the first digit * @return The index after the last digit or start if there are no digits at the given index @@ -376,10 +373,10 @@ public static int findLastDigit(final String s, final int start) { end++; return end; } - + /** * Searches for whether a String contains any of the characters of another string. - * + * * @param s * @param chars * @return @@ -391,23 +388,23 @@ public static boolean containsAny(final String s, final String chars) { } return false; } - + public static boolean equals(final String s1, final String s2, final boolean caseSensitive) { return caseSensitive ? s1.equals(s2) : s1.equalsIgnoreCase(s2); } - + public static boolean contains(final String haystack, final String needle, final boolean caseSensitive) { if (caseSensitive) return haystack.contains(needle); return haystack.toLowerCase().contains(needle.toLowerCase()); } - + public static String replace(final String haystack, final String needle, final String replacement, final boolean caseSensitive) { if (caseSensitive) return "" + haystack.replace(needle, replacement); return "" + haystack.replaceAll("(?ui)" + Pattern.quote(needle), Matcher.quoteReplacement(replacement)); } - + public static String replaceFirst(final String haystack, final String needle, final String replacement, final boolean caseSensitive) { if (caseSensitive) return "" + haystack.replaceFirst(needle, replacement); @@ -419,11 +416,11 @@ public static byte[] hexStringToByteArray(String s) { byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) - + Character.digit(s.charAt(i+1), 16)); + + Character.digit(s.charAt(i + 1), 16)); } return data; } - + public static int indexOfOutsideGroup(String string, char find, char groupOpen, char groupClose, int i) { int group = 0; for (; i < string.length(); i++) { @@ -440,5 +437,5 @@ public static int indexOfOutsideGroup(String string, char find, char groupOpen, } return -1; } - + } diff --git a/src/main/java/ch/njol/util/Validate.java b/src/main/java/ch/njol/util/Validate.java index 293796a533a..e87478dd94e 100644 --- a/src/main/java/ch/njol/util/Validate.java +++ b/src/main/java/ch/njol/util/Validate.java @@ -1,11 +1,13 @@ package ch.njol.util; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.Nullable; import java.util.Collection; -@Deprecated -@ApiStatus.ScheduledForRemoval + +/** + * use {@link com.google.common.base.Preconditions} + */ +@Deprecated(forRemoval = true) public final class Validate { private Validate() {} diff --git a/src/main/java/ch/njol/util/coll/BidiHashMap.java b/src/main/java/ch/njol/util/coll/BidiHashMap.java index 78c16cd0e87..3beb65301db 100644 --- a/src/main/java/ch/njol/util/coll/BidiHashMap.java +++ b/src/main/java/ch/njol/util/coll/BidiHashMap.java @@ -8,64 +8,66 @@ import org.jetbrains.annotations.Nullable; /** - * @author Peter Güttinger + * @deprecated Use {@link com.google.common.collect.BiMap} */ +@Deprecated(forRemoval = true) +@SuppressWarnings("removal") public class BidiHashMap extends HashMap implements BidiMap { - + private static final long serialVersionUID = -9011678701069901061L; - + private final BidiHashMap other; - + private BidiHashMap(final BidiHashMap other) { this.other = other; } - + public BidiHashMap() { other = new BidiHashMap<>(this); } - + public BidiHashMap(final Map values) { other = new BidiHashMap<>(this); putAll(values); } - + @Override public BidiHashMap getReverseView() { return other; } - + @SuppressWarnings("null") @Override @Nullable public T1 getKey(final T2 value) { return other.get(value); } - + @SuppressWarnings("null") @Override @Nullable public T2 getValue(final @Nullable T1 key) { return get(key); } - + @Nullable private T2 putDirect(final @Nullable T1 key, final @Nullable T2 value) { return super.put(key, value); } - + @Override @Nullable public T2 put(final @Nullable T1 key, final @Nullable T2 value) { if (key == null || value == null) throw new NullPointerException("Can't store null in a BidiHashMap"); - + removeDirect(key); other.removeDirect(value); final T2 oldValue = putDirect(key, value); other.putDirect(value, key); return oldValue; } - + @SuppressWarnings("null") @Override public void putAll(final Map m) { @@ -73,12 +75,12 @@ public void putAll(final Map m) { put(e.getKey(), e.getValue()); } } - + @Nullable private T2 removeDirect(final @Nullable Object key) { return super.remove(key); } - + @Override @Nullable public T2 remove(final @Nullable Object key) { @@ -87,50 +89,50 @@ public T2 remove(final @Nullable Object key) { other.removeDirect(oldValue); return oldValue; } - + private void clearDirect() { super.clear(); } - + @Override public void clear() { this.clearDirect(); other.clearDirect(); } - + @Override public boolean containsValue(final @Nullable Object value) { return other.containsKey(value); } - + // TODO check how changes to the sets affect the map - + @SuppressWarnings("null") @Override public Set> entrySet() { return Collections.unmodifiableSet(super.entrySet()); } - + @SuppressWarnings("null") @Override public Set keySet() { return Collections.unmodifiableSet(super.keySet()); } - + @Override public Set values() { return valueSet(); } - + @SuppressWarnings("null") @Override public Set valueSet() { return Collections.unmodifiableSet(other.keySet()); } - + @Override public BidiHashMap clone() { return new BidiHashMap(this); } - + } diff --git a/src/main/java/ch/njol/util/coll/BidiMap.java b/src/main/java/ch/njol/util/coll/BidiMap.java index 129fa9b23da..2ace5935495 100644 --- a/src/main/java/ch/njol/util/coll/BidiMap.java +++ b/src/main/java/ch/njol/util/coll/BidiMap.java @@ -4,8 +4,9 @@ import java.util.Set; /** - * @author Peter Güttinger + * @deprecated Use {@link com.google.common.collect.BiMap} */ +@Deprecated(forRemoval = true) public interface BidiMap extends Map { public BidiMap getReverseView(); diff --git a/src/main/java/ch/njol/util/coll/CyclicList.java b/src/main/java/ch/njol/util/coll/CyclicList.java index 556db77c53a..8725def4edf 100644 --- a/src/main/java/ch/njol/util/coll/CyclicList.java +++ b/src/main/java/ch/njol/util/coll/CyclicList.java @@ -11,8 +11,9 @@ /** * A list with fixed size that overrides the oldest elements when new elements are added and no more space is available. * - * @author Peter Güttinger + * @deprecated unused */ +@Deprecated(forRemoval = true) public final class CyclicList extends AbstractList { private final Object[] items; diff --git a/src/main/java/ch/njol/util/coll/ReversedListView.java b/src/main/java/ch/njol/util/coll/ReversedListView.java index 89fb5943fde..b833ab74403 100644 --- a/src/main/java/ch/njol/util/coll/ReversedListView.java +++ b/src/main/java/ch/njol/util/coll/ReversedListView.java @@ -11,8 +11,9 @@ import ch.njol.util.coll.iterator.ReversedListIterator; /** - * @author Peter Güttinger + * @deprecated unused */ +@Deprecated(forRemoval = true) public class ReversedListView implements List { private final List list; diff --git a/src/main/java/ch/njol/util/coll/iterator/CombinedIterator.java b/src/main/java/ch/njol/util/coll/iterator/CombinedIterator.java index b58e564c501..1a2cfdabc6f 100644 --- a/src/main/java/ch/njol/util/coll/iterator/CombinedIterator.java +++ b/src/main/java/ch/njol/util/coll/iterator/CombinedIterator.java @@ -10,8 +10,9 @@ *

* Elements are removable from this iterator if the source iterables support element removal, unless removal is blocked on creation. * - * @author Peter Güttinger + * @deprecated use {@link com.google.common.collect.Iterators#concat(Iterator[])} */ +@Deprecated public class CombinedIterator implements Iterator { private final Iterator> iterators; diff --git a/src/main/java/ch/njol/util/coll/iterator/ImprovedIterator.java b/src/main/java/ch/njol/util/coll/iterator/ImprovedIterator.java index 9fe640faffd..0a6ef00e2bf 100644 --- a/src/main/java/ch/njol/util/coll/iterator/ImprovedIterator.java +++ b/src/main/java/ch/njol/util/coll/iterator/ImprovedIterator.java @@ -4,6 +4,10 @@ import org.jetbrains.annotations.Nullable; +/** + * @deprecated use {@link Iterator} + */ +@Deprecated public class ImprovedIterator implements Iterator { private final Iterator iter; diff --git a/src/main/java/ch/njol/util/coll/iterator/ReversedListIterator.java b/src/main/java/ch/njol/util/coll/iterator/ReversedListIterator.java index 4327bd9ee26..37f82d722c8 100644 --- a/src/main/java/ch/njol/util/coll/iterator/ReversedListIterator.java +++ b/src/main/java/ch/njol/util/coll/iterator/ReversedListIterator.java @@ -6,8 +6,9 @@ import org.jetbrains.annotations.Nullable; /** - * @author Peter Güttinger + * @deprecated unused */ +@Deprecated public class ReversedListIterator implements ListIterator { private final ListIterator iter; diff --git a/src/main/java/ch/njol/yggdrasil/util/JREFieldHandler.java b/src/main/java/ch/njol/yggdrasil/util/JREFieldHandler.java deleted file mode 100644 index 042c864cf70..00000000000 --- a/src/main/java/ch/njol/yggdrasil/util/JREFieldHandler.java +++ /dev/null @@ -1,98 +0,0 @@ -package ch.njol.yggdrasil.util; - -import ch.njol.yggdrasil.FieldHandler; -import ch.njol.yggdrasil.Fields.FieldContext; -import ch.njol.yggdrasil.YggdrasilException; - -import java.io.StreamCorruptedException; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - -/** - * Handles common JRE-related incompatible field types. - * This handler is not added by default and is merely a utility. - */ -@Deprecated -public class JREFieldHandler implements FieldHandler { - - @Override - public boolean excessiveField(Object object, FieldContext field) { - return false; - } - - @Override - public boolean missingField(Object object, Field field) { - return false; - } - - /** - * Converts collection types and non-primitive arrays - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public boolean incompatibleField(Object object, Field field, FieldContext context) throws StreamCorruptedException { - Object value = context.getObject(); - if (value instanceof Object[]) - value = Collections.singletonList(value); - if (value instanceof Collection) { - Collection collection = (Collection) value; - try { - if (Collection.class.isAssignableFrom(field.getType())) { - Collection c = (Collection) field.get(object); - if (c != null) { - c.clear(); - c.addAll(collection); - return true; - } - } else if (Object[].class.isAssignableFrom(field.getType())) { - Object[] array = (Object[]) field.get(object); - if (array != null) { - if (array.length < collection.size()) - return false; - Class ct = array.getClass().getComponentType(); - for (Object iterated : collection) { - if (!ct.isInstance(iterated)) - return false; - } - } else { - array = (Object[]) Array.newInstance(field.getType().getComponentType(), collection.size()); - field.set(object, array); - } - int length = array.length; - int i = 0; - for (Object iterated : collection) - array[i++] = iterated; - while (i < length) - array[i++] = null; - } - } catch ( - IllegalArgumentException | NullPointerException | IllegalStateException | - ClassCastException | UnsupportedOperationException | IllegalAccessException e - ) { - throw new YggdrasilException(e); - } - } else if (value instanceof Map) { - if (!Map.class.isAssignableFrom(field.getType())) - return false; - try { - Map m = (Map) field.get(object); - if (m != null) { - m.clear(); - m.putAll((Map) value); - return true; - } - } catch ( - IllegalArgumentException | IllegalAccessException | UnsupportedOperationException | - ClassCastException | NullPointerException e - ) { - throw new YggdrasilException(e); - } - } - - return false; - } - -} diff --git a/src/main/java/ch/njol/yggdrasil/util/package-info.java b/src/main/java/ch/njol/yggdrasil/util/package-info.java deleted file mode 100644 index b031f9cbe4a..00000000000 --- a/src/main/java/ch/njol/yggdrasil/util/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file is part of Skript. - * - * Skript is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Skript is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Skript. If not, see . - * - * Copyright Peter Güttinger, SkriptLang team and contributors - */ -/** - * @author Peter Güttinger - */ -package ch.njol.yggdrasil.util; - - diff --git a/src/main/java/org/skriptlang/skript/lang/converter/Converters.java b/src/main/java/org/skriptlang/skript/lang/converter/Converters.java index 1efeb559676..b1cc798ed20 100644 --- a/src/main/java/org/skriptlang/skript/lang/converter/Converters.java +++ b/src/main/java/org/skriptlang/skript/lang/converter/Converters.java @@ -7,12 +7,7 @@ import org.jetbrains.annotations.Unmodifiable; import java.lang.reflect.Array; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * Converters are used to provide Skript with specific instructions for converting an object to a different type. diff --git a/src/main/java/org/skriptlang/skript/lang/structure/Structure.java b/src/main/java/org/skriptlang/skript/lang/structure/Structure.java index 145d99ecad1..893d408578e 100644 --- a/src/main/java/org/skriptlang/skript/lang/structure/Structure.java +++ b/src/main/java/org/skriptlang/skript/lang/structure/Structure.java @@ -17,7 +17,6 @@ import ch.njol.util.Kleenean; import ch.njol.util.coll.iterator.CheckedIterator; import ch.njol.util.coll.iterator.ConsumingIterator; -import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.skriptlang.skript.lang.entry.EntryContainer; @@ -78,8 +77,7 @@ public int compareTo(@NotNull Structure.Priority o) { * If the EntryContainer is needed outside of {@link #init(Literal[], int, ParseResult, EntryContainer)}, * the Structure should keep a reference to it. */ - @Deprecated - @ApiStatus.ScheduledForRemoval + @Deprecated(forRemoval = true) public final EntryContainer getEntryContainer() { if (entryContainer == null) throw new IllegalStateException("This Structure hasn't been initialized!");