2424package org .incendo .cloud .minecraft .modded .internal ;
2525
2626import io .leangen .geantyref .TypeToken ;
27+ import java .util .Iterator ;
2728import java .util .Map ;
29+ import java .util .ServiceLoader ;
2830import java .util .concurrent .CompletableFuture ;
2931import net .kyori .adventure .util .Services ;
3032import net .minecraft .commands .CommandSigningContext ;
4042import org .incendo .cloud .minecraft .signed .SignedString ;
4143import org .incendo .cloud .minecraft .signed .SignedStringMapper ;
4244import org .incendo .cloud .parser .ArgumentParseResult ;
45+ import org .jetbrains .annotations .NotNull ;
4346
4447@ API (status = API .Status .INTERNAL )
4548public 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