Skip to content

Commit 637fef3

Browse files
committed
Fix SignedStringFactory fallback behavior
1 parent 449759d commit 637fef3

1 file changed

Lines changed: 39 additions & 2 deletions

File tree

cloud-minecraft-modded-common/src/main/java/org/incendo/cloud/minecraft/modded/internal/ModdedSignedStringMapper.java

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
package org.incendo.cloud.minecraft.modded.internal;
2525

2626
import io.leangen.geantyref.TypeToken;
27+
import java.util.Iterator;
2728
import java.util.Map;
29+
import java.util.ServiceLoader;
2830
import java.util.concurrent.CompletableFuture;
2931
import net.kyori.adventure.util.Services;
3032
import net.minecraft.commands.CommandSigningContext;
@@ -40,6 +42,7 @@
4042
import org.incendo.cloud.minecraft.signed.SignedString;
4143
import org.incendo.cloud.minecraft.signed.SignedStringMapper;
4244
import org.incendo.cloud.parser.ArgumentParseResult;
45+
import org.jetbrains.annotations.NotNull;
4346

4447
@API(status = API.Status.INTERNAL)
4548
public final class ModdedSignedStringMapper implements SignedStringMapper {
@@ -49,8 +52,7 @@ public final class ModdedSignedStringMapper implements SignedStringMapper {
4952
* Creates a new mapper.
5053
*/
5154
public ModdedSignedStringMapper() {
52-
this.factory = Services.serviceWithFallback(SignedStringFactory.class)
53-
.orElseThrow(() -> new IllegalStateException("Could not locate " + SignedStringFactory.class));
55+
this.factory = serviceWithFallback(SignedStringFactory.class);
5456
}
5557

5658
@SuppressWarnings({"unchecked", "rawtypes"})
@@ -111,4 +113,39 @@ public SignedString create(final String str, final PlayerChatMessage signedMessa
111113
return SignedString.unsigned(str);
112114
}
113115
}
116+
117+
private static <P> P serviceWithFallback(final @NotNull Class<P> type) {
118+
final ServiceLoader<P> loader = ServiceLoader.load(type, type.getClassLoader());
119+
final Iterator<P> it = loader.iterator();
120+
Throwable cause = null;
121+
P firstFallback = null;
122+
123+
while (it.hasNext()) {
124+
final P instance;
125+
126+
try {
127+
instance = it.next();
128+
} catch (final Throwable t) {
129+
if (cause == null) {
130+
cause = t;
131+
} else {
132+
cause.addSuppressed(t);
133+
}
134+
continue;
135+
}
136+
137+
if (instance instanceof Services.Fallback) {
138+
if (firstFallback == null) {
139+
firstFallback = instance;
140+
}
141+
} else {
142+
return instance;
143+
}
144+
}
145+
146+
if (firstFallback != null) {
147+
return firstFallback;
148+
}
149+
throw new IllegalStateException("Could not locate " + type, cause);
150+
}
114151
}

0 commit comments

Comments
 (0)