1 package net.mograsim.logic.model.snippets;
3 import java.util.HashMap;
6 public class CodeSnippetSupplier<C, S>
8 private final Map<String, String> standardSnippetIDClassNames = new HashMap<>();
9 private final Map<String, SnippetDefinintion<C, ?, S>> snippetSuppliersForClassNames = new HashMap<>();
10 private final SnippetDefinintion<C, ?, S> defaultSnippetSupplier;
12 public CodeSnippetSupplier(SnippetDefinintion<C, ?, S> defaultSnippetSupplier)
14 this.defaultSnippetSupplier = defaultSnippetSupplier;
17 public void addStandardSnippetID(String standardSnippetID, String associatedSnippetClassName)
19 standardSnippetIDClassNames.put(standardSnippetID, associatedSnippetClassName);
22 public void setSnippetSupplier(String id, SnippetDefinintion<C, ?, S> snippetSupplier)
24 snippetSuppliersForClassNames.put(id, snippetSupplier);
28 public SnippetDefinintion<C, ?, S> getSnippetSupplier(String id)
32 String snippetClassName;
33 if (id.startsWith("class:"))
34 snippetClassName = id.substring(6);
36 snippetClassName = standardSnippetIDClassNames.get(id);
37 if (snippetClassName != null)
39 tryLoadSnippetClass(snippetClassName);
40 SnippetDefinintion<C, ?, S> snippetSupplier = snippetSuppliersForClassNames.get(snippetClassName);
41 if (snippetSupplier != null)
42 return snippetSupplier;
44 System.err.println("Couldn't load snippet " + id + "; using default");
46 if (defaultSnippetSupplier == null)
47 throw new IllegalArgumentException("No default snippet set");
48 return defaultSnippetSupplier;
53 private static void tryLoadSnippetClass(String snippetClassName)
55 tryInvokeStaticInitializer(snippetClassName, "Error getting snippet class: %s: %s\n");
58 public static void tryInvokeStaticInitializer(String className, String errorMessageFormat)
62 Class.forName(className, true, CodeSnippetSupplier.class.getClassLoader());
64 catch (ClassNotFoundException e)
66 System.err.printf(errorMessageFormat, className, "ClassNotFoundException thrown: " + e.getMessage());