1 package spoon.reflect.factory; 2 3 import java.io.Serializable ; 4 import java.util.Map ; 5 import java.util.TreeMap ; 6 7 import spoon.reflect.Factory; 8 import spoon.reflect.declaration.CtClass; 9 import spoon.reflect.declaration.CtElement; 10 import spoon.reflect.declaration.CtSimpleType; 11 import spoon.reflect.declaration.CtType; 12 import spoon.reflect.reference.CtReference; 13 import spoon.reflect.reference.CtTypeReference; 14 import spoon.reflect.visitor.CtScanner; 15 import spoon.template.Template; 16 import spoon.template.TemplateException; 17 18 21 public class TemplateFactory extends SubFactory implements Serializable { 22 23 private static final long serialVersionUID = 1L; 24 25 31 public TemplateFactory(Factory factory) { 32 super(factory); 33 } 34 35 private Map <String , CtClass<?>> templates = new TreeMap <String , CtClass<?>>(); 36 37 43 public void add(CtClass<?> template) { 44 if (templates.containsKey(template.getQualifiedName())) 45 templates.remove(template.getQualifiedName()); 46 templates.put(template.getQualifiedName(), template); 47 new CtScanner() { 48 public void enter(CtElement e) { 49 e.setFactory(factory); 50 super.enter(e); 51 } 52 53 @Override 54 protected void enterReference(CtReference e) { 55 e.setFactory(factory); 56 super.enterReference(e); 57 } 58 }.scan(template); 59 } 60 61 66 public Map <String , CtClass<?>> getAll() { 67 return templates; 68 } 69 70 77 public <T> CtClass<T> get(Class <T> templateClass) { 78 return get(templateClass.getName()); 79 } 80 81 88 @SuppressWarnings ("unchecked") 89 public <T> CtClass<T> get(String templateName) { 90 if (!templates.containsKey(templateName)) 91 throw new TemplateException("Unable to load template \"" 92 + templateName + "\". Check your template source path"); 93 return (CtClass<T>) templates.get(templateName); 94 } 95 96 100 @SuppressWarnings ("unchecked") 101 public void parseTypes() { 102 for (CtSimpleType<?> t : factory.Type().getAll()) { 103 if (t instanceof CtClass) { 104 for (CtSimpleType nested : ((CtType<?>) t).getNestedTypes()) { 105 if (nested instanceof CtClass) 106 scanType((CtClass<? extends Template>) nested); 107 } 108 scanType((CtClass<? extends Template>) t); 109 } 110 } 111 } 112 113 private void scanType(CtClass<? extends Template> t) { 114 if (factory.Type().createReference(Template.class).isAssignableFrom( 115 t.getReference())) { 116 add(t); 117 } 118 } 119 120 129 public boolean isTemplate(CtTypeReference<?> candidate) { 130 return templates.containsKey(candidate.getQualifiedName()); 131 } 132 } | Popular Tags |