1 package net.mograsim.logic.model.snippets;
3 import java.util.Collections;
4 import java.util.HashMap;
8 public class CodeSnippetSupplier<C, S>
10 private final Map<String, String> standardSnippetIDClassNames = new HashMap<>();
11 private final Set<String> standardSnippetIDSetUnmodifiable = Collections.unmodifiableSet(standardSnippetIDClassNames.keySet());
12 private final Map<String, SnippetDefinintion<C, ?, S>> snippetSuppliersForClassNames = new HashMap<>();
13 private final SnippetDefinintion<C, ?, S> defaultSnippetSupplier;
15 public CodeSnippetSupplier(SnippetDefinintion<C, ?, S> defaultSnippetSupplier)
17 this.defaultSnippetSupplier = defaultSnippetSupplier;
20 public void addStandardSnippetID(String standardSnippetID, String associatedSnippetClassName)
22 standardSnippetIDClassNames.put(standardSnippetID, associatedSnippetClassName);
25 public Set<String> getStandardSnippetIDs()
27 return standardSnippetIDSetUnmodifiable;
30 public void setSnippetSupplier(String id, SnippetDefinintion<C, ?, S> snippetSupplier)
32 snippetSuppliersForClassNames.put(id, snippetSupplier);
36 public SnippetDefinintion<C, ?, S> getSnippetSupplier(String id)
40 String snippetClassName;
41 if (id.startsWith("class:"))
42 snippetClassName = id.substring(6);
44 snippetClassName = standardSnippetIDClassNames.get(id);
45 if (snippetClassName != null)
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;
61 private static void tryLoadSnippetClass(String snippetClassName)
63 tryInvokeStaticInitializer(snippetClassName, "Error getting snippet class: %s: %s\n");
66 public static void tryInvokeStaticInitializer(String className, String errorMessageFormat)
70 Class.forName(className, true, CodeSnippetSupplier.class.getClassLoader());
72 catch (ClassNotFoundException e)
74 System.err.printf(errorMessageFormat, className, "ClassNotFoundException thrown: " + e.getMessage());