TemplateUtils.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.udapsoft.modular.web.template;
  2. import java.io.OutputStream;
  3. import java.io.OutputStreamWriter;
  4. import java.io.Writer;
  5. import java.util.Map;
  6. import org.springframework.core.io.Resource;
  7. import org.springframework.util.StringUtils;
  8. import com.udapsoft.modular.core.context.ApplicationContextAwareImpl;
  9. import freemarker.cache.ClassTemplateLoader;
  10. import freemarker.cache.FileTemplateLoader;
  11. import freemarker.template.Configuration;
  12. import freemarker.template.Template;
  13. public class TemplateUtils {
  14. private static final String DEFAULT_ENCODING = "UTF-8";
  15. public static void generate(String templatePath, Class<?> loaderClass,
  16. Map model, OutputStream out) {
  17. try {
  18. generate(templatePath, loaderClass, model, new OutputStreamWriter(
  19. out));
  20. } catch (Exception e) {
  21. throw new TemplateGenerateException(e);
  22. }
  23. }
  24. public static void generate(String templatePath, Class loaderClass,
  25. Map model, Writer out) {
  26. if (!StringUtils.hasText(templatePath)) {
  27. throw new IllegalArgumentException("템플릿의 클래스 경로가 필요합니다. - "
  28. + templatePath);
  29. }
  30. if (model == null) {
  31. throw new IllegalArgumentException("템플릿을 생성하기 위해서는 모델이 필요합니다.");
  32. }
  33. if (out == null) {
  34. throw new IllegalArgumentException("템플릿을 생성할 스트림이 필요합니다.");
  35. }
  36. String PATH = "/";
  37. try {
  38. Configuration cfg = new Configuration();
  39. cfg.setDefaultEncoding("UTF-8");
  40. cfg.setNumberFormat("0.######");
  41. int idx = templatePath.lastIndexOf("/");
  42. String prefix = templatePath.substring(0, idx);
  43. String templateFile = templatePath.substring(idx + 1);
  44. Template template = null;
  45. if ((templatePath.startsWith("file:"))
  46. || (templatePath.startsWith("url:"))
  47. || (templatePath.startsWith("classpath:"))) {
  48. Resource resource = ApplicationContextAwareImpl.getApplicationContext().getResource(prefix);
  49. FileTemplateLoader ftl = new FileTemplateLoader(
  50. resource.getFile());
  51. cfg.setTemplateLoader(ftl);
  52. template = cfg.getTemplate(templateFile);
  53. } else {
  54. Class<?> lc = null;
  55. if (templatePath.startsWith("/")) {
  56. lc = loaderClass == null ? TemplateUtils.class
  57. : loaderClass;
  58. } else {
  59. if (loaderClass == null) {
  60. throw new IllegalArgumentException(
  61. "템플릿의 클래스 경로가 상대경로일 경우에는 loaderClass가 필요합니다.");
  62. }
  63. lc = loaderClass;
  64. }
  65. ClassTemplateLoader ctl = new ClassTemplateLoader(lc, prefix);
  66. cfg.setTemplateLoader(ctl);
  67. template = cfg.getTemplate(templateFile);
  68. }
  69. template.process(model, out);
  70. } catch (Exception e) {
  71. throw new TemplateGenerateException(e);
  72. }
  73. }
  74. }