refactor: Tackle a few Semgrep and ErrorProne violations (#1520)

* refactor: Tackle a few Semgrep and ErrorProne violations

* Address comments
This commit is contained in:
Alex 2022-01-07 12:45:53 +01:00 committed by GitHub
parent f27959e49a
commit 64442a8051
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 55 additions and 400 deletions

View File

@ -804,7 +804,6 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
// Pre-gen all the chunks
for (BlockVector2 chunk : region.getChunks()) {
try {
//noinspection unchecked
chunkLoadings.add(
((CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>)
getChunkFutureMainThreadMethod.invoke(chunkManager, chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true))
@ -924,7 +923,7 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
* @throws IllegalArgumentException on error
*/
private ListBinaryTag toNativeList(net.minecraft.nbt.ListTag foreign) throws SecurityException, IllegalArgumentException {
ListBinaryTag.Builder values = ListBinaryTag.builder();
ListBinaryTag.Builder<BinaryTag> values = ListBinaryTag.builder();
for (net.minecraft.nbt.Tag tag : foreign) {
values.add(toNativeBinary(tag));
@ -964,9 +963,8 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
return new net.minecraft.nbt.IntArrayTag(((IntArrayBinaryTag) foreign).value());
} else if (foreign instanceof LongArrayBinaryTag) {
return new net.minecraft.nbt.LongArrayTag(((LongArrayBinaryTag) foreign).value());
} else if (foreign instanceof ListBinaryTag) {
} else if (foreign instanceof ListBinaryTag foreignList) {
net.minecraft.nbt.ListTag tag = new net.minecraft.nbt.ListTag();
ListBinaryTag foreignList = (ListBinaryTag) foreign;
for (BinaryTag t : foreignList) {
tag.add(fromNativeBinary(t));
}

View File

@ -413,6 +413,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
}
@Override
@SuppressWarnings("rawtypes")
public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) {
forceLoadSections = false;
copy = createCopy ? new PaperweightGetBlocks_Copy(serverLevel) : null;

View File

@ -799,7 +799,6 @@ public final class PaperweightAdapter implements BukkitImplAdapter<net.minecraft
// Pre-gen all the chunks
for (BlockVector2 chunk : region.getChunks()) {
try {
//noinspection unchecked
chunkLoadings.add(
((CompletableFuture<Either<ChunkAccess, ChunkHolder.ChunkLoadingFailure>>)
getChunkFutureMainThreadMethod.invoke(chunkManager, chunk.getX(), chunk.getZ(), ChunkStatus.FEATURES, true))

View File

@ -394,6 +394,7 @@ public class PaperweightGetBlocks extends CharGetBlocks implements BukkitGetBloc
}
@Override
@SuppressWarnings("rawtypes")
public synchronized <T extends Future<T>> T call(IChunkSet set, Runnable finalizer) {
forceLoadSections = false;
copy = createCopy ? new PaperweightGetBlocks_Copy(serverLevel) : null;

View File

@ -247,6 +247,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
}
}
@SuppressWarnings("deprecation")
public static void sendChunk(ServerLevel nmsWorld, int chunkX, int chunkZ, boolean lighting) {
ChunkHolder chunkHolder = getPlayerChunk(nmsWorld, chunkX, chunkZ);
if (chunkHolder == null) {
@ -279,8 +280,7 @@ public final class PaperweightPlatformAdapter extends NMSAdapter {
false // last false is to not bother with x-ray
);
} else {
// deprecated on paper
//noinspection deprecation
// deprecated on paper - deprecation suppressed
packet = new ClientboundLevelChunkWithLightPacket(
levelChunk,
nmsWorld.getChunkSource().getLightEngine(),

View File

@ -9,12 +9,13 @@ import it.unimi.dsi.fastutil.longs.LongSet;
/**
* Class to prevent the above/below being removed from shaded/relocated dependencies via minimization
*/
@SuppressWarnings("unused")
final class DoNotMiniseThese {
private final Long2ObjectLinkedOpenHashMap a = null;
private final Long2ObjectLinkedOpenHashMap<?> a = null;
private final LongArraySet b = null;
private final LongIterator c = null;
private final LongSet d = null;
private final Int2ObjectMap e = null;
private final Int2ObjectMap<?> e = null;
}

View File

@ -1,128 +0,0 @@
package com.fastasyncworldedit.core.configuration;
import org.yaml.snakeyaml.nodes.Tag;
import java.util.HashMap;
import java.util.Map;
/**
* Provides additional runtime information necessary to create a custom Java
* instance.
*/
public final class TypeDescription {
private final Class<? extends Object> type;
private Tag tag;
private final Map<String, Class<? extends Object>> listProperties;
private final Map<String, Class<? extends Object>> keyProperties;
private final Map<String, Class<? extends Object>> valueProperties;
public TypeDescription(Class<? extends Object> clazz, Tag tag) {
this.type = clazz;
this.tag = tag;
listProperties = new HashMap<>();
keyProperties = new HashMap<>();
valueProperties = new HashMap<>();
}
public TypeDescription(Class<? extends Object> clazz, String tag) {
this(clazz, new Tag(tag));
}
public TypeDescription(Class<? extends Object> clazz) {
this(clazz, (Tag) null);
}
/**
* Get tag which shall be used to load or dump the type (class).
*
* @return tag to be used. It may be a tag for Language-Independent Types
* (http://www.yaml.org/type/)
*/
public Tag getTag() {
return tag;
}
/**
* Set tag to be used to load or dump the type (class).
*
* @param tag local or global tag
*/
public void setTag(Tag tag) {
this.tag = tag;
}
public void setTag(String tag) {
setTag(new Tag(tag));
}
/**
* Get the represented type (class).
*
* @return type (class) to be described.
*/
public Class<? extends Object> getType() {
return type;
}
/**
* Specify that the property is a type-safe {@code List}.
*
* @param property name of the JavaBean property
* @param type class of List values
*/
public void putListPropertyType(String property, Class<? extends Object> type) {
listProperties.put(property, type);
}
/**
* Get class of List values for provided JavaBean property.
*
* @param property property name
* @return class of List values
*/
public Class<? extends Object> getListPropertyType(String property) {
return listProperties.get(property);
}
/**
* Specify that the property is a type-safe {@code Map}.
*
* @param property property name of this JavaBean
* @param key class of keys in Map
* @param value class of values in Map
*/
public void putMapPropertyType(
String property, Class<? extends Object> key,
Class<? extends Object> value
) {
keyProperties.put(property, key);
valueProperties.put(property, value);
}
/**
* Get keys type info for this JavaBean.
*
* @param property property name of this JavaBean
* @return class of keys in the Map
*/
public Class<? extends Object> getMapKeyType(String property) {
return keyProperties.get(property);
}
/**
* Get values type info for this JavaBean.
*
* @param property property name of this JavaBean
* @return class of values in the Map
*/
public Class<? extends Object> getMapValueType(String property) {
return valueProperties.get(property);
}
@Override
public String toString() {
return "TypeDescription for " + getType() + " (tag='" + getTag() + "')";
}
}

View File

@ -336,13 +336,13 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
}
@Override
@SuppressWarnings("ResultOfMethodCallIgnored")
public void close() {
try {
if (byteBuffer != null) {
byteBuffer.force();
fileChannel.close();
braf.close();
//noinspection ResultOfMethodCallIgnored
file.setWritable(true);
closeDirectBuffer(byteBuffer);
byteBuffer = null;
@ -494,10 +494,9 @@ public class DiskOptimizedClipboard extends LinearClipboard implements Closeable
@Override
public List<? extends Entity> getEntities(Region region) {
return new ArrayList<>(entities
return entities
.stream()
.filter(e -> region.contains(e.getLocation().toBlockPoint()))
.collect(Collectors.toList()));
.filter(e -> region.contains(e.getLocation().toBlockPoint())).collect(Collectors.toList());
}
@Override

View File

@ -8,8 +8,6 @@ public class NBTException extends RuntimeException {
/**
* Faster exception throwing if you don't fill the stacktrace.
*
* @return
*/
@Override
public Throwable fillInStackTrace() {

View File

@ -2,6 +2,7 @@ package com.fastasyncworldedit.core.jnbt.streamer;
import java.io.IOException;
@SuppressWarnings("unchecked")
public interface ValueReader<T> extends StreamReader<T> {
void apply(int index, T value) throws IOException;

View File

@ -1,51 +0,0 @@
package com.fastasyncworldedit.core.math.heightmap;
public class AverageHeightMapFilter {
private int[] inData;
private int[] buffer;
private final int width;
private final int height;
private final int minY;
private final int maxY;
public AverageHeightMapFilter(int[] inData, int width, int height, int minY, int maxY) {
this.inData = inData;
this.width = width;
this.height = height;
this.minY = minY;
this.maxY = maxY;
this.buffer = new int[inData.length];
}
public int[] filter(int iterations) {
for (int j = 0; j < iterations; j++) {
int a = -width;
int b = width;
int c = 1;
int d = -1;
for (int i = 0; i < inData.length; i++, a++, b++, c++, d++) {
int height = inData[i];
if (height < minY || height > maxY) {
buffer[i] = height;
continue;
}
int average = (2 + get(a, height) + get(b, height) + get(c, height) + get(d, height)) >> 2;
buffer[i] = average;
}
int[] tmp = inData;
inData = buffer;
buffer = tmp;
}
return inData;
}
private int get(int index, int def) {
int val = inData[Math.max(0, Math.min(inData.length - 1, index))];
if (val < minY || val > maxY) {
return def;
}
return val;
}
}

View File

@ -69,13 +69,13 @@ public class PropertyKeySet implements Set<PropertyKey> {
return toArray(new Object[0]);
}
@SuppressWarnings("unchecked")
@Nonnull
@Override
public <T> T[] toArray(@Nonnull T[] a) {
T[] array = Arrays.copyOf(a, this.bits.cardinality());
Iterator<PropertyKey> iter = iterator();
for (int i = 0; i < array.length && iter.hasNext(); i++) {
//noinspection unchecked
array[i] = (T) iter.next();
}
return array;

View File

@ -1,149 +0,0 @@
package com.fastasyncworldedit.core.util;
import java.awt.Color;
import java.lang.reflect.Field;
import java.util.Locale;
public class ColorUtil {
private static final int PARSE_COMPONENT = 0; // percent, or clamped to [0,255] => [0,1]
private static final int PARSE_PERCENT = 1; // clamped to [0,100]% => [0,1]
private static final int PARSE_ANGLE = 2; // clamped to [0,360]
private static final int PARSE_ALPHA = 3; // clamped to [0f,1f]
private static float parseComponent(String color, int off, int end, int type) {
color = color.substring(off, end).trim();
if (color.endsWith("%")) {
if (type > PARSE_PERCENT) {
throw new IllegalArgumentException("Invalid color specification");
}
type = PARSE_PERCENT;
color = color.substring(0, color.length() - 1).trim();
} else if (type == PARSE_PERCENT) {
throw new IllegalArgumentException("Invalid color specification");
}
float c = type == PARSE_COMPONENT
? Integer.parseInt(color)
: Float.parseFloat(color);
switch (type) {
case PARSE_ALPHA:
return c < 0f ? 0f : Math.min(c, 1f);
case PARSE_PERCENT:
return c <= 0f ? 0f : c >= 100f ? 1f : c / 100f;
case PARSE_COMPONENT:
return c <= 0f ? 0f : c >= 255f ? 1f : c / 255f;
case PARSE_ANGLE:
return c < 0f
? c % 360f + 360f
: c > 360f
? c % 360f
: c;
}
throw new IllegalArgumentException("Invalid color specification");
}
private static Color parseRGBColor(String color, int roff) {
try {
int rend = color.indexOf(',', roff);
int gend = rend < 0 ? -1 : color.indexOf(',', rend + 1);
int bend = gend < 0 ? -1 : color.indexOf(gend + 1);
float r = parseComponent(color, roff, rend, PARSE_COMPONENT);
float g = parseComponent(color, rend + 1, gend, PARSE_COMPONENT);
float b = parseComponent(color, gend + 1, bend, PARSE_COMPONENT);
return new Color(r, g, b);
} catch (NumberFormatException ignored) {
}
throw new IllegalArgumentException("Invalid color specification");
}
private static Color parseHSLColor(String color, int hoff) {
try {
int hend = color.indexOf(',', hoff);
int send = hend < 0 ? -1 : color.indexOf(',', hend + 1);
int lend = send < 0 ? -1 : color.indexOf(send + 1);
float h = parseComponent(color, hoff, hend, PARSE_ANGLE);
float s = parseComponent(color, hend + 1, send, PARSE_PERCENT);
float l = parseComponent(color, send + 1, lend, PARSE_PERCENT);
return Color.getHSBColor(h, s, l);
} catch (NumberFormatException ignored) {
}
throw new IllegalArgumentException("Invalid color specification");
}
public static Color parseColor(String colorString) {
if (colorString == null) {
throw new NullPointerException(
"The color components or name must be specified");
}
if (colorString.isEmpty()) {
throw new IllegalArgumentException("Invalid color specification");
}
String color = colorString.toLowerCase(Locale.ROOT);
if (color.startsWith("#")) {
color = color.substring(1);
} else if (color.startsWith("0x")) {
color = color.substring(2);
} else if (color.startsWith("rgb")) {
if (color.startsWith("(", 3)) {
return parseRGBColor(color, 4);
} else if (color.startsWith("a(", 3)) {
return parseRGBColor(color, 5);
}
} else if (color.startsWith("hsl")) {
if (color.startsWith("(", 3)) {
return parseHSLColor(color, 4);
} else if (color.startsWith("a(", 3)) {
return parseHSLColor(color, 5);
}
} else {
Color col = null;
try {
Field field = Color.class.getField(color.toLowerCase(Locale.ROOT));
col = (Color) field.get(null);
} catch (Throwable ignored) {
}
if (col != null) {
return col;
}
}
int len = color.length();
try {
int r;
int g;
int b;
if (len == 3) {
r = Integer.parseInt(color.substring(0, 1), 16);
g = Integer.parseInt(color.substring(1, 2), 16);
b = Integer.parseInt(color.substring(2, 3), 16);
return new Color(r / 15f, g / 15f, b / 15f);
} else if (len == 4) {
r = Integer.parseInt(color.substring(0, 1), 16);
g = Integer.parseInt(color.substring(1, 2), 16);
b = Integer.parseInt(color.substring(2, 3), 16);
return new Color(r / 15f, g / 15f, b / 15f);
} else if (len == 6) {
r = Integer.parseInt(color.substring(0, 2), 16);
g = Integer.parseInt(color.substring(2, 4), 16);
b = Integer.parseInt(color.substring(4, 6), 16);
return new Color(r, g, b);
} else if (len == 8) {
r = Integer.parseInt(color.substring(0, 2), 16);
g = Integer.parseInt(color.substring(2, 4), 16);
b = Integer.parseInt(color.substring(4, 6), 16);
return new Color(r, g, b);
}
} catch (NumberFormatException ignored) {
}
throw new IllegalArgumentException("Invalid color specification");
}
}

View File

@ -75,7 +75,7 @@ public class MathMan {
}
public static float clamp(float check, float min, float max) {
return check > max ? max : (Math.max(check, min));
return check > max ? max : Math.max(check, min);
}
public static double hypot(final double... pars) {

View File

@ -71,11 +71,11 @@ public class StringMan {
long b = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
return b < 1024L ? bytes + " B"
: b <= 0xfffccccccccccccL >> 40 ? String.format("%.1f KiB", bytes / 0x1p10)
: b <= 0xfffccccccccccccL >> 30 ? String.format("%.1f MiB", bytes / 0x1p20)
: b <= 0xfffccccccccccccL >> 20 ? String.format("%.1f GiB", bytes / 0x1p30)
: b <= 0xfffccccccccccccL >> 10 ? String.format("%.1f TiB", bytes / 0x1p40)
: b <= 0xfffccccccccccccL ? String.format("%.1f PiB", (bytes >> 10) / 0x1p40)
: String.format("%.1f EiB", (bytes >> 20) / 0x1p40);
: b <= 0xfffccccccccccccL >> 30 ? String.format("%.1f MiB", bytes / 0x1p20)
: b <= 0xfffccccccccccccL >> 20 ? String.format("%.1f GiB", bytes / 0x1p30)
: b <= 0xfffccccccccccccL >> 10 ? String.format("%.1f TiB", bytes / 0x1p40)
: b <= 0xfffccccccccccccL ? String.format("%.1f PiB", (bytes >> 10) / 0x1p40)
: String.format("%.1f EiB", (bytes >> 20) / 0x1p40);
}
public static String prettyFormat(double d) {
@ -93,43 +93,28 @@ public class StringMan {
}
public static boolean isBracketForwards(char c) {
switch (c) {
case '[':
case '(':
case '{':
case '<':
return true;
default:
return false;
}
return switch (c) {
case '[', '(', '{', '<' -> true;
default -> false;
};
}
public static char getMatchingBracket(char c) {
switch (c) {
case '[':
return ']';
case '(':
return ')';
case '{':
return '}';
case '<':
return '>';
case ']':
return '[';
case ')':
return '(';
case '}':
return '{';
case '>':
return '<';
default:
return c;
}
return switch (c) {
case '[' -> ']';
case '(' -> ')';
case '{' -> '}';
case '<' -> '>';
case ']' -> '[';
case ')' -> '(';
case '}' -> '{';
case '>' -> '<';
default -> c;
};
}
public static int parseInt(CharSequence string) {
int val = 0;
boolean neg = false;
int numIndex = 1;
int len = string.length();
for (int i = len - 1; i >= 0; i--) {
@ -377,13 +362,13 @@ public class StringMan {
char bj = item.charAt(j++);
if (sequentail) {
switch (bj) {
case ':':
case '_':
case ':', '_' -> {
sequentail = false;
if (bj == ai) {
break outer;
}
continue;
}
}
continue;
}
@ -531,13 +516,13 @@ public class StringMan {
}
public static boolean isEqual(String a, String b) {
return a == b || a != null && b != null && a.length() == b.length()
return a.equals(b) || a != null && b != null && a.length() == b.length()
&& a.hashCode() == b.hashCode()
&& a.equals(b);
}
public static boolean isEqualIgnoreCase(String a, String b) {
return a == b ||
return a.equals(b) ||
a != null && b != null && a.length() == b.length() && a.equalsIgnoreCase(b);
}

View File

@ -9,6 +9,7 @@ import java.util.Collections;
import java.util.Map;
import java.util.Set;
@SuppressWarnings("unchecked")
public interface IAdaptedMap<K, V, K2, V2> extends Map<K, V> {
Map<K2, V2> getParent();

View File

@ -12,9 +12,9 @@ public class YieldIterable<T> implements Iterable<T>, Consumer<T>, Closeable {
private static final Object END_MARKER = new Object();
private final LinkedBlockingQueue<T> queue;
private Future future;
private Future<?> future;
public YieldIterable(@Nullable Future task) {
public YieldIterable(@Nullable Future<?> task) {
this.queue = new LinkedBlockingQueue<>();
this.future = task;
}
@ -23,13 +23,13 @@ public class YieldIterable<T> implements Iterable<T>, Consumer<T>, Closeable {
this(null);
}
public void setFuture(Future future) {
public void setFuture(Future<?> future) {
this.future = future;
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
return new Iterator<>() {
private boolean interrupted;
private T buffer;

View File

@ -27,10 +27,9 @@ public final class ReflectionUtil {
}
//FAWE start
@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
if (from instanceof Class) {
return getField((Class) from, null, name);
return getField((Class<?>) from, null, name);
} else {
return getField(from.getClass(), from, name);
}
@ -38,7 +37,7 @@ public final class ReflectionUtil {
//FAWE end
@SuppressWarnings("unchecked")
public static <T> T getField(Class checkClass, Object from, String name) {
public static <T> T getField(Class<?> checkClass, Object from, String name) {
do {
try {
Field field = checkClass.getDeclaredField(name);

View File

@ -6,7 +6,9 @@ import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Link {
Class clazz() default Link.class;
//FAWE start - address rawtypes
Class<?> clazz() default Link.class;
//FAWE end
String value();

View File

@ -192,8 +192,8 @@ public class TargetBlock {
*
* @return Block
*/
@SuppressWarnings("StatementWithEmptyBody")
public Location getTargetBlock() {
//noinspection StatementWithEmptyBody
while (getNextBlock() != null && !stopMask.test(targetPos)) {
}
return getCurrentBlock();
@ -205,8 +205,8 @@ public class TargetBlock {
*
* @return Block
*/
@SuppressWarnings("StatementWithEmptyBody")
public Location getSolidTargetBlock() {
//noinspection StatementWithEmptyBody
while (getNextBlock() != null && !solidMask.test(targetPos)) {
}
return getCurrentBlock();

View File

@ -21,6 +21,7 @@ package com.sk89q.worldedit.util.logging;
import javax.annotation.Nullable;
import java.io.UnsupportedEncodingException;
import java.util.Objects;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Level;
@ -131,11 +132,7 @@ public class DynamicStreamHandler extends StreamHandler {
Formatter formatter = this.formatter;
if (handler != null) {
return handler.getFormatter();
} else if (formatter != null) {
return formatter;
} else {
return new SimpleFormatter();
}
} else return Objects.requireNonNullElseGet(formatter, SimpleFormatter::new);
}
@Override

View File

@ -340,6 +340,7 @@ public class BlockState implements BlockStateHolder<BlockState>, Pattern {
//FAWE end
@Override
@SuppressWarnings("RedundantCast")
public Map<Property<?>, Object> getStates() {
//FAWE end
BlockType type = this.getBlockType();
@ -348,7 +349,7 @@ public class BlockState implements BlockStateHolder<BlockState>, Pattern {
type.getPropertiesSet(),
(Function<Property<?>, Object>) this::getState
);
//noinspection RedundantCast - This is required for compilation, etc.
//This is required for compilation, etc.
return Collections.unmodifiableMap((Map<Property<?>, Object>) map);
//FAWE end
}