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 associatedSnippetClassName)
21 standardSnippetIDClassNames.put(standardSnippetID, associatedSnippetClassName);
24 public Map<String, String> getStandardSnippetIDs()
26 return standardSnippetIDClassNamesUnmodifiable;
29 public void setSnippetSupplier(String id, SnippetDefinintion<C, ?, S> snippetSupplier)
31 snippetSuppliersForClassNames.put(id, snippetSupplier);
35 public SnippetDefinintion<C, ?, S> getSnippetSupplier(String id)
39 String snippetClassName;
40 if (id.startsWith("class:"))
41 snippetClassName = id.substring(6);
43 snippetClassName = standardSnippetIDClassNames.get(id);
44 if (snippetClassName != null)
46 tryLoadSnippetClass(snippetClassName);
47 SnippetDefinintion<C, ?, S> snippetSupplier = snippetSuppliersForClassNames.get(snippetClassName);
48 if (snippetSupplier != null)
49 return snippetSupplier;
51 System.err.println("Couldn't load snippet " + id + "; using default");
53 if (defaultSnippetSupplier == null)
54 throw new IllegalArgumentException("No default snippet set");
55 return defaultSnippetSupplier;
60 private static void tryLoadSnippetClass(String snippetClassName)
62 tryInvokeStaticInitializer(snippetClassName, "Error getting snippet class: %s: %s\n");
65 public static void tryInvokeStaticInitializer(String className, String errorMessageFormat)
69 Class.forName(className, true, CodeSnippetSupplier.class.getClassLoader());
71 catch (ClassNotFoundException e)
73 System.err.printf(errorMessageFormat, className, "ClassNotFoundException thrown: " + e.getMessage());