1 package net.mograsim.logic.model.snippets;
3 import java.util.Collections;
4 import java.util.HashMap;
7 import net.mograsim.logic.model.serializing.ReflectionHelper;
9 public class CodeSnippetSupplier<C, S>
11 private final Map<String, String> standardSnippetIDClassNames = new HashMap<>();
12 private final Map<String, String> standardSnippetIDClassNamesUnmodifiable = Collections.unmodifiableMap(standardSnippetIDClassNames);
13 private final Map<String, SnippetDefinintion<C, ?, S>> snippetSuppliersForClassNames = new HashMap<>();
14 private final SnippetDefinintion<C, ?, S> defaultSnippetSupplier;
16 public CodeSnippetSupplier(SnippetDefinintion<C, ?, S> defaultSnippetSupplier)
18 this.defaultSnippetSupplier = defaultSnippetSupplier;
21 public void addStandardSnippetID(String standardSnippetID, String associatedSnippetID)
23 if (!associatedSnippetID.startsWith("class:"))
24 throw new IllegalArgumentException("Unrecognized snippet ID format: " + associatedSnippetID);
25 standardSnippetIDClassNames.put(standardSnippetID, associatedSnippetID);
28 public Map<String, String> getStandardSnippetIDs()
30 return standardSnippetIDClassNamesUnmodifiable;
33 public void setSnippetSupplier(String id, SnippetDefinintion<C, ?, S> snippetSupplier)
35 snippetSuppliersForClassNames.put(id, snippetSupplier);
39 public SnippetDefinintion<C, ?, S> getSnippetSupplier(String id)
43 String resolvedID = resolveID(id);
44 if (resolvedID != null)
46 String snippetClassName = resolvedID.substring(6);
47 tryLoadSnippetClass(snippetClassName);
48 SnippetDefinintion<C, ?, S> snippetSupplier = snippetSuppliersForClassNames.get(snippetClassName);
49 if (snippetSupplier != null)
50 return snippetSupplier;
52 System.err.println("Couldn't load snippet " + id + "; using default");
54 if (defaultSnippetSupplier == null)
55 throw new IllegalArgumentException("No default snippet set");
56 return defaultSnippetSupplier;
59 public String resolveID(String id)
61 if (id.startsWith("class:"))
63 return standardSnippetIDClassNames.get(id);
68 private static void tryLoadSnippetClass(String snippetClassName)
70 ReflectionHelper.tryInvokeStaticInitializer(snippetClassName, "Error getting snippet class: %s: %s\n");