001package io.jstach.jstachio.spi; 002 003import static io.jstach.jstachio.spi.Templates.sneakyThrow; 004 005import java.io.IOException; 006import java.io.UncheckedIOException; 007 008import io.jstach.jstachio.JStachio; 009import io.jstach.jstachio.TemplateInfo; 010 011/** 012 * An abstract jstachio that just needs a {@link JStachioExtensions} container. 013 * <p> 014 * To extend just override {@link #extensions()}. 015 * 016 * @see JStachioExtensions 017 * @author agentgt 018 */ 019public abstract class AbstractJStachio implements JStachio, JStachioExtensions.Provider { 020 021 /** 022 * Do nothing constructor 023 */ 024 public AbstractJStachio() { 025 026 } 027 028 @Override 029 public void execute(Object model, Appendable appendable) throws IOException { 030 TemplateInfo template = template(model.getClass()); 031 extensions().getFilter().filter(template).process(model, appendable); 032 } 033 034 @Override 035 public StringBuilder execute(Object model, StringBuilder sb) { 036 try { 037 execute(model, (Appendable) sb); 038 return sb; 039 } 040 catch (IOException e) { 041 sneakyThrow(e); 042 throw new UncheckedIOException(e); 043 } 044 } 045 046 @Override 047 public String execute(Object model) { 048 return execute(model, new StringBuilder()).toString(); 049 } 050 051 @Override 052 public boolean supportsType(Class<?> modelType) { 053 return extensions().getTemplateFinder().supportsType(modelType); 054 } 055 056 protected TemplateInfo template(Class<?> modelType) { 057 try { 058 return extensions().getTemplateFinder().findTemplate(modelType); 059 } 060 catch (Exception e) { 061 sneakyThrow(e); 062 throw new RuntimeException(e); 063 } 064 } 065 066} 067 068class DefaultJStachio extends AbstractJStachio { 069 070 private final JStachioExtensions extensions; 071 072 public DefaultJStachio(JStachioExtensions extensions) { 073 super(); 074 this.extensions = extensions; 075 } 076 077 @Override 078 public JStachioExtensions extensions() { 079 return this.extensions; 080 } 081 082}