Pages

2014년 2월 18일 화요일

[SPRING] Spring mvc에서 Quartz 적용하기 - (6)

- DAO에서 데이터를 조회할때, 파라메터를 넘겨주는 부분이 추가되었다.
001package kr.kangwoo.postman.service;
002 
003import java.io.File;
004import java.io.FileNotFoundException;
005import java.io.IOException;
006import java.io.StringReader;
007import java.io.StringWriter;
008import java.io.Writer;
009import java.util.ArrayList;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.List;
013import java.util.Map;
014import java.util.Set;
015 
016import kr.kangwoo.postman.core.MailException;
017import kr.kangwoo.postman.core.MailStatusCode;
018import kr.kangwoo.postman.core.MessageException;
019import kr.kangwoo.postman.domain.Mail;
020import kr.kangwoo.postman.domain.MailTemplate;
021import kr.kangwoo.postman.repository.MailTemplateDao;
022import kr.kangwoo.util.MessageUtils;
023import kr.kangwoo.util.StrTokenizer;
024import kr.kangwoo.util.StringUtils;
025 
026import org.xml.sax.InputSource;
027 
028import freemarker.cache.FileTemplateLoader;
029import freemarker.cache.MultiTemplateLoader;
030import freemarker.cache.TemplateLoader;
031import freemarker.template.Configuration;
032import freemarker.template.Template;
033import freemarker.template.TemplateException;
034 
035public class FreemarkerMailTemplateManager implements MailTemplateManager {
036 
037    private MailTemplateDao mailTemplateDao;
038     
039    private Map<String, MailTemplate> mailTemplateMap;
040    private Configuration configuration;
041     
042    public FreemarkerMailTemplateManager() {
043    }
044     
045    public void setMailTemplateDao(MailTemplateDao mailTemplateDao) {
046        this.mailTemplateDao = mailTemplateDao;
047    }
048     
049    public List<MailTemplate> getMailTemplateList() {
050        Map<String, Object> paramMap = new HashMap<String, Object>(2);
051        paramMap.put("useFlag""Y");
052        return mailTemplateDao.getList(paramMap);
053    }
054 
055    public void reload() {
056        try {
057            mailTemplateMap = new HashMap<String, MailTemplate>();
058            configuration = new Configuration();
059             
060            List<MailTemplate> templateList = getMailTemplateList();
061            if (templateList != null) {
062                List<TemplateLoader> loaderList = new ArrayList<TemplateLoader>();
063                Set<String> templateDirs = new HashSet<String>();
064                String dir = null;
065                for (MailTemplate mailTemplate : templateList) {
066                    dir = mailTemplate.getTemplateDir();
067                    if (StringUtils.isNotBlank(dir)) {
068                        mailTemplateMap.put(mailTemplate.getTemplateId(), mailTemplate);
069                        if (!templateDirs.contains(dir)) {
070                            // 중복 디렉토리 제거
071                            loaderList.add(new FileTemplateLoader(new File(dir)));
072                            templateDirs.add(dir);                     
073                        }
074                    else {
075                        throw new MessageException(MessageUtils.format("{0} 템플릿의 경로가 지정되어 있지 않습니다.", mailTemplate.getTemplateId()));
076                    }
077                }
078                TemplateLoader[] loaders = new TemplateLoader[loaderList.size()];
079                MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(loaderList.toArray(loaders));
080                configuration.setTemplateLoader(multiTemplateLoader);
081            }
082        catch (MessageException e) {
083            throw e;
084        catch (Exception e) {
085            throw new MessageException("메일 템플릿 정보를 가져오는 중 문제가 발생했습니다.", e);
086        }
087    }
088     
089    public String getSubject(Mail mail) throws MailException {
090        // TODO 제목도 파라메터를 가져올 수 있게 수정할것.
091        MailTemplate mailTemplate = mailTemplateMap.get(mail.getTemplateId());
092        if (mailTemplate == null) {
093            throw new MailException(MailStatusCode.TEMPLATE_INFO_NOT_FOUND, MessageUtils.format("메일템플릿 정보가 존재하지 않습니다. (TEMPLATE_ID={0})", mail.getTemplateId()));
094        }
095        return mailTemplate.getMailSubject();
096    }
097     
098    public String getContent(Mail mail) throws MailException {
099        MailTemplate mailTemplate = mailTemplateMap.get(mail.getTemplateId());
100        if (mailTemplate == null) {
101            throw new MailException(MailStatusCode.TEMPLATE_INFO_NOT_FOUND, MessageUtils.format("메일템플릿 정보가 존재하지 않습니다. (TEMPLATE_ID={0})", mail.getTemplateId()));
102        }
103        Template template;
104        try {
105            template = configuration.getTemplate(mailTemplate.getTemplateFilename());
106        catch (FileNotFoundException e) {
107            throw new MailException(MailStatusCode.TEMPLATE_FILE_NOT_FOUND, MessageUtils.format("템플릿 파일을 가져올 수 없습니다.(TEMPLATE_ID={0}, TEMPLATE_DIR={1}, TEMPLATE_FILE={2})", mailTemplate.getTemplateId(), mailTemplate.getTemplateDir(), mailTemplate.getTemplateFilename()));
108        catch (IOException e) {
109            throw new MailException(MailStatusCode.TEMPLATE_ERROR, MessageUtils.format("템플릿을 가져오는 중 에러가 발생했습니다.(TEMPLATE_ID={0}, TEMPLATE_DIR={1}, TEMPLATE_FILE={2})", mailTemplate.getTemplateId(), mailTemplate.getTemplateDir(), mailTemplate.getTemplateFilename()));
110        }
111         
112        Map<String, Object> root = new HashMap<String, Object>();
113        String dataModelType = mailTemplate.getDataModelType();
114        if ("X".equals(dataModelType)) {
115            // XML
116            InputSource input = new InputSource(new StringReader(mail.getCotentData()));
117            try {
118                root.put("doc", freemarker.ext.dom.NodeModel.parse(input));
119            catch (Exception e) {
120                throw new MailException(MailStatusCode.DATA_MODEL_ERROR, MessageUtils.format("데이터 모델을 분석하는중 에러가 발생했습니다. (MAIL_NO={0}, TEMPLATE_ID={1})", mail.getMailNo(), mail.getTemplateId()), e);
121            }
122        else if ("J".equals(dataModelType)) {
123            // TODO JSON 구현
124        else if ("P".equals(dataModelType)) {
125            // Parameter
126            StrTokenizer tokenizer = new StrTokenizer(mail.getCotentData(), "&");
127            String token = null;
128            while (tokenizer.hasMoreTokens()) {
129                token = tokenizer.nextToken();
130                root.put(StringUtils.substringBefore(token, "="), StringUtils.substringAfter(token, "="));
131            }
132        else {
133            throw new MailException(MailStatusCode.UNKOWN_DATA_MODEL_TYPE, MessageUtils.format("{0}은 사용할 수 없는 데이터 모델 타입(DATA_MODE_TYPE)입니다. ", dataModelType));
134        }
135        Writer out = new StringWriter();
136        try {
137            template.process(root, out);   
138        catch (IOException e) {
139            throw new MailException(MailStatusCode.BAD_CONTENT, MessageUtils.format("메일 본문 내용을 작성하는 중 에러가 발생했습니다. (MAIL_NO={0}, TEMPLATE_ID={1})", mail.getMailNo(), mail.getTemplateId()), e);
140        catch (TemplateException e) {
141            throw new MailException(MailStatusCode.BAD_CONTENT, MessageUtils.format("메일 본문 내용을 작성하는 중 에러가 발생했습니다. (MAIL_NO={0}, TEMPLATE_ID={1})", mail.getMailNo(), mail.getTemplateId()), e);
142        }
143        return out.toString();
144    }
145 
146}

댓글 없음:

댓글 쓰기