1 package net.mograsim.logic.model.snippets;
3 import java.util.Collections;
4 import java.util.HashMap;
7 public class CodeSnippetSupplier<C, S>
9 private final Map<String, String> standardSnippetIDClassNames = new HashMap<>();
10 private final Map<String, String> standardSnippetIDClassNamesUnmodifiable = Collections.unmodifiableMap(standardSnippetIDClassNames);
11 private final Map<String, SnippetDefinintion<C, ?, S>> snippetSuppliersForClassNames = new HashMap<>();
12 private final SnippetDefinintion<C, ?, S> defaultSnippetSupplier;
14 public CodeSnippetSupplier(SnippetDefinintion<C, ?, S> defaultSnippetSupplier)
16 this.defaultSnippetSupplier = defaultSnippetSupplier;
19 public void addStandardSnippetID(String standardSnippetID, String associatedSnippetID)
21 if (!associatedSnippetID.startsWith("class:"))
22 throw new IllegalArgumentException("Unrecognized snippet ID format: " + associatedSnippetID);
23 standardSnippetIDClassNames.put(standardSnippetID, associatedSnippetID);
26 public Map<String, String> getStandardSnippetIDs()
28 return standardSnippetIDClassNamesUnmodifiable;
31 public void setSnippetSupplier(String id, SnippetDefinintion<C, ?, S> snippetSupplier)
33 snippetSuppliersForClassNames.put(id, snippetSupplier);
37 public SnippetDefinintion<C, ?, S> getSnippetSupplier(String id)
41 String resolvedID = resolveID(id);
42 if (resolvedID != null)
44 String snippetClassName = resolvedID.substring(6);
45 tryLoadSnippetClass(snippetClassName);
46 SnippetDefinintion<C, ?, S> snippetSupplier = snippetSuppliersForClassNames.get(snippetClassName);
47 if (snippetSupplier != null)
48 return snippetSupplier;
50 System.err.println("Couldn't load snippet " + id + "; using default");
52 if (defaultSnippetSupplier == null)
53 throw new IllegalArgumentException("No default snippet set");
54 return defaultSnippetSupplier;
57 public String resolveID(String id)
59 if (id.startsWith("class:"))
61 return standardSnippetIDClassNames.get(id);
66 private static void tryLoadSnippetClass(String snippetClassName)
68 tryInvokeStaticInitializer(snippetClassName, "Error getting snippet class: %s: %s\n");
71 public static void tryInvokeStaticInitializer(String className, String errorMessageFormat)
75 Class.forName(className, true, CodeSnippetSupplier.class.getClassLoader());
77 catch (ClassNotFoundException e)
79 System.err.printf(errorMessageFormat, className, "ClassNotFoundException thrown: " + e.getMessage());