Java org.springframework.ui.velocity.VelocityEngineUtils 代码实例

・20 分钟阅读

以下是展示如何使用org.springframework.ui.velocity.VelocityEngineUtils的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


private EmailServiceTokenModel sendVerificationEmail(final EmailServiceTokenModel emailVerificationModel, final String emailSubject,
                                                     final String velocityModel, final Map<String, String> resources) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_RELATED, "UTF-8");
            messageHelper.setTo(emailVerificationModel.getEmailAddress());
            messageHelper.setFrom(emailFromAddress);
            messageHelper.setReplyTo(emailReplyToAddress);
            messageHelper.setSubject(emailSubject);
            Map model = new HashMap();
            model.put("model", emailVerificationModel);
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, velocityModel, model);
            messageHelper.setText(new String(text.getBytes(), "UTF-8"), true);
                  for(String resourceIdentifier: resources.keySet()) {
               addInlineResource(messageHelper, resources.get(resourceIdentifier), resourceIdentifier);
            }
        }
    };
    LOG.debug("Sending {} token to : {}",emailVerificationModel.getTokenType().toString(), emailVerificationModel.getEmailAddress());
    this.mailSender.send(preparator);
    return emailVerificationModel;
}
 

实例 2


@Test
@Ignore(value = "Too Mails from Hudson / Jenkins")
public void sendMail() throws InterruptedException {
    this.gpMailSpringSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setSubject("Notification");
            message.setTo("[email protected]");
            String text = VelocityEngineUtils.mergeTemplateIntoString(
                    gpSpringVelocityEngine, "template/"
                    + "geoPlatformMailSupport.html.vm",
                    "UTF-8", null);
            message.setText(text, Boolean.TRUE);
            message.setFrom(gpMailSpringDetail.getFrom(),
                    gpMailSpringDetail.getFromName());
            message.setReplyTo(gpMailSpringDetail.getReplayTo(),
                    gpMailSpringDetail.getReplayToName());
        }
    });
}
 

实例 3


/**
    * Send a simple message based on a Velocity template.
    * @param msg the message to populate
    * @param templateName the Velocity template to use (relative to classpath)
    * @param model a map containing key/value pairs
    */
   @SuppressWarnings("unchecked")
public void sendMessage(SimpleMailMessage msg, String templateName, Map model) {
       String result = null;
       try {
           result =
               VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                                                           templateName, model);
       } catch (VelocityException e) {
           e.printStackTrace();
           log.error(e.getMessage());
       }
       msg.setText(result);
       send(msg);
   }
 

实例 4


/**
 * Send a simple message based on a Velocity template.
 * @param msg the message to populate
 * @param templateName the Velocity template to use (relative to classpath)
 * @param model a map containing key/value pairs
 */
public void sendMessage(SimpleMailMessage msg, String templateName, Map model) {
    String result = null;
    try {
        result =
            VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                                                        templateName, model);
    } catch (VelocityException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
    msg.setText(result);
    send(msg);
}
 

实例 5


/**
    * Send a simple message based on a Velocity template.
    * 
    * @param msg
    *                the message to populate
    * @param templateName
    *                the Velocity template to use (relative to classpath)
    * @param model
    *                a map containing key/value pairs
    */
   @SuppressWarnings("unchecked")
   public void sendMessage(SimpleMailMessage msg, String templateName,
    Map model) {
String result = null;
try {
    result = VelocityEngineUtils.mergeTemplateIntoString(
            velocityEngine, templateName, model);
} catch (VelocityException e) {
    log.error(e.getMessage());
}
msg.setText(result);
send(msg);
   }
 

实例 6


public void setModel(Map model) throws VelocityException {
  String result = null;
  result = VelocityEngineUtils.mergeTemplateIntoString(
                  getVelocityConfigurer().getVelocityEngine(),
                  getTemplate(), model);
   this.setText(result);
}
 

实例 7


/**
 * Send a simple message based on a Velocity template.
 * @param msg the message to populate
 * @param templateName the Velocity template to use (relative to classpath)
 * @param model a map containing key/value pairs
 */
@SuppressWarnings("unchecked")
public void sendMessage(SimpleMailMessage msg, String templateName, Map model) {
    String result = null;
    try {
        result =
            VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                                                        templateName, "UTF-8", model);
    } catch (VelocityException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
    msg.setText(result);
    send(msg);
}
 

实例 8


public void sendConfirmationLink(Account account) {
        String baseUrl = appSrv.getProperty(AppService.URL);
        String confirmlink = baseUrl + "/confirm?id=" + account.getUuid();
        String subject = msg.getMessage("signup.register", null, Utils.getDefaultLocale());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(ACCOUNT, account);
        model.put(LINK, confirmlink);
        model.put(APPLICATION, appSrv.getProperty(AppService.URL));
        String message = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                        "email/" + Utils.getDefaultLocale() + "/register.vm", "UTF-8", model);
        mailer.sendMail(MailMail.REGISTER, account.getEmail(), subject, message, resourceSrv.getBasicResourceMap());
}
 

实例 9


@Override
public void run(String... args) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("time", new Date());
        model.put("message", this.message);
        System.out.println(VelocityEngineUtils.mergeTemplateIntoString(this.engine,
                        "welcome.vm", "UTF-8", model));
}
 

实例 10


/**
    * Send a simple message based on a Velocity template.
    * 
    * @param msg
    *                the message to populate
    * @param templateName
    *                the Velocity template to use (relative to classpath)
    * @param model
    *                a map containing key/value pairs
    */
   @SuppressWarnings("unchecked")
   public void sendMessage(SimpleMailMessage msg, String templateName,
    Map model) {
String result = null;
try {
    result = VelocityEngineUtils.mergeTemplateIntoString(
            velocityEngine, templateName, model);
} catch (VelocityException e) {
    log.error(e.getMessage());
}
msg.setText(result);
send(msg);
   }
 

实例 11


/**
 * Creates a welcome mail with a unique identifier to verify the email
 * address.
 * 
 * @param event
 *            Event to handle.
 */
@EventHandler
public final void handle(final UserCreatedEvent event) {
        if (LOG.isDebugEnabled()) {
                LOG.debug("SEND user created mail to " + event.getEmail() + " [securityToken='"
                        + event.getSecurityToken() + "']");
        }
        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(final MimeMessage mimeMessage) throws Exception {
                        final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                        message.setTo(event.getEmail().toString());
                        message.setFrom(mailProperties.getProperty("sender"));
                        final Map<String, String> varMap = new HashMap<String, String>();
                        varMap.put("email", event.getEmail().toString());
                        varMap.put("userName", event.getUserName().toString());
                        varMap.put("securityToken", event.getSecurityToken().toString());
                        final String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                                "user-created-mail.vm", varMap);
                        message.setText(text, true);
                }
        };
        this.mailSender.send(preparator);
}
 

实例 12


private MailMessage composeMailMessage(final MailMessageTemplate mailMessageTemplate, final User respondent,
        final String surveyLinkToken) {
    Map<String, Object> model = new HashMap<>();
    model.put("lastname", StringUtils.defaultIfBlank(respondent.getSurname(), ""));
    model.put("firstname", StringUtils.defaultIfBlank(respondent.getGivenNames(), ""));
    model.put("gender", respondent.getGender());
    model.put("link", "http://localhost:8080/questionaires-ui/token=" + surveyLinkToken);
    Language preferredLanguage = respondent.getPreferredLanguage();
    StringBuilder templateLocation = new StringBuilder().append(mailMessageTemplate.getId());
    if (preferredLanguage != null) {
        templateLocation.append("/");
        templateLocation.append(preferredLanguage);
    }
    VelocityEngine velocityEngine = velocityFactory.getObject();
    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, templateLocation.toString(), "UTF-8",
            model);
    MailMessageTemplateLanguageSettings languageSettings = mailMessageTemplate.getLanguageSettings();
    if (preferredLanguage != null && !preferredLanguage.equals(mailMessageTemplate.getLanguage())) {
        MailMessageTemplateTranslation preferedTranslation = mailMessageTemplate.getTranslations().get(
                preferredLanguage);
        if (preferedTranslation != null) {
            languageSettings = preferedTranslation.getLanguageSettings();
        }
    }
    MailMessage mailMessage = MailMessage.with().subject(languageSettings.getSubject()).to(respondent.getEmail())
            .replyTo(mailMessageTemplate.getReplyTo()).from(mailMessageTemplate.getFromAddress()).text(body)
            .build();
    return mailMessage;
}
 

实例 13


public boolean sendLmsMail(String[] emailList, String subject, String velocityTemplate, Map model,String fromOrgName){
        try{
                 log.info("***LmsMailer: sendLmsMail()--> Start -->");
                 Properties prop = new Properties();
prop.put("mail.smtp.starttls.enable", "true"); // added this line
             prop.put("mail.host", mailSenderHost.getHost());
                 prop.put("mail.smtp.auth", value.getString("mail.smtp.auth"));
                 prop.put("mail.smtp.port", value.getString("mail.port"));
                 if(!value.getString("mail.socket").equals("No")){
                         prop.put("mail.smtp.socketFactory.class", value.getString("mail.socket"));
                 }
                 log.info("Port-->"+value.getString("mail.port"));
                 log.info("Socket-->"+value.getString("mail.socket"));
                 java.util.Date currDate = new java.util.Date();
                 javax.mail.Session session1 = javax.mail.Session.getDefaultInstance(prop, null);
                 log.info("***LmsMailer: sendLmsMail()--> Session 1-->"+session1);
                        Message msg = new MimeMessage(session1);
                        String fromEmail = templateMessage.getFrom();
                        String aliasEmailName =fromOrgName;
                        log.info("***LmsMailer: sendLmsMail()--> Alais Name -->"+aliasEmailName);
                    InternetAddress fromAddr = new InternetAddress(fromEmail,aliasEmailName);
                    log.info("***LmsMailer: sendLmsMail()--> From Address -->"+fromAddr);
                        msg.setFrom(fromAddr);
                        msg.setSubject(subject);        
                        msg.setSentDate(currDate);
                        InternetAddress[] toAddress = new InternetAddress[emailList.length];
                        log.info("***LmsMailer: sendLmsMail()--> Email List Loop Start");
                        log.info("***LmsMailer: sendLmsMail()--> Email List Length --> "+emailList.length);
                        for (int i = 0; i < emailList.length; i++)
                                {
                                        toAddress[i] = new InternetAddress(emailList[i]);
                                        log.info("***LmsMailer: sendLmsMail()--> toAddress --> " + toAddress[i]);
                                }
                        log.info("***LmsMailer: sendLmsMail()--> Email List Loop End");
                        msg.addRecipients(Message.RecipientType.TO, toAddress);
                        log.info("***LmsMailer: sendLmsMail()--> Recipient Type -->"+Message.RecipientType.TO);
                        String mailTemplate = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,velocityTemplate, model);
                    msg.setContent(mailTemplate,"text/html");
                    //javax.mail.Session session2 = javax.mail.Session.getDefaultInstance(prop, null);
                    //log.info("***LmsMailer: sendMail()--> Session 2-->"+session2);
                    //Transport tr = session2.getTransport("smtp");
                        Transport tr = session1.getTransport("smtp");
                        log.info("***LmsMailer: sendLmsMail()--> Transport -->"+tr);
                        if(value.getString("mail.smtp.auth").equals("true")){
                                tr.connect(mailSenderHost.getHost(), templateMessage.getFrom(),mailSenderHost.getPassword());
                                log.info("***LmsMailer: sendLmsMail()--> Transport Authentication -->"+tr);
                        }else{
                                tr.connect();
                                log.info("***LmsMailer: sendLmsMail()--> Transport without Authentication -->"+tr);
                        }
                        log.info("***LmsMailer: sendLmsMail()--> Message -->"+msg);
                        msg.saveChanges();
                        log.info("***LmsMailer: sendLmsMail()--> Message Save Changes -->"+msg);
                        log.info("***LmsMailer: sendLmsMail())--> Transport Before Send Message -->"+tr);
                        tr.sendMessage(msg, msg.getAllRecipients());
                        log.info("***LmsMailer: sendLmsMail()--> Transport After Send Message -->"+tr);
                        log.info("***LmsMailer: sendLmsMail()--> Mail sent successfully");
                        log.info("***LmsMailer: sendLmsMail()--> Transport Before Close");
                        tr.close();
                        log.info("***LmsMailer: sendLmsMail()--> Transport Close");
                        return true;
        }catch(MailException me){
                log.info("***LmsMailer: sendLmsMail()--> MailException:"+me);
                return false;
        }catch(SendFailedException sfe) {
                log.info("***LmsMailer: sendLmsMail()--> SendFailedException:"+sfe);
           return false;
        }catch(AddressException ae){
                log.info("***LmsMailer: sendLmsMail()--> AddressException:"+ae);
                return false;
       }catch(Exception e){
                log.info("***LmsMailer: sendLmsMail()--> Exception:"+e);
                return false;
        }
}
 
讨论
淘淘あ西西 profile image