예제 #1
0
 private String prepareHtmlContent(String name, String message) {
   // Prepare the evaluation context
   final Context ctx = new Context(new Locale("en"));
   ctx.setVariable("name", name);
   ctx.setVariable("message", message);
   return this.templateEngine.process("mailTemplate", ctx);
 }
예제 #2
0
  @Async
  @Override
  public void enviarMailCambioContraseña(String nombre, String email, String token, Locale locale) {
    try {
      final Context ctx = new Context(locale);
      ctx.setVariable("nombre", nombre);
      ctx.setVariable("token", token);
      ctx.setVariable("lenguaje", locale.getLanguage());

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
      message.setSubject(messageSource.getMessage("reset.email.titulo", null, locale));
      message.setFrom("*****@*****.**", "Cudú");
      message.setTo(email);

      final String htmlContent = templateEngine.process("resetpassword", ctx);
      message.setText(htmlContent, true);
      mailSender.send(mimeMessage);
    } catch (Exception e) {
      String correlationId = UUID.randomUUID().toString();
      Marker marker = MarkerFactory.getMarker("ENVIO_EMAIL");
      logger.error(
          marker, "Error enviando email. Token: " + token + ", CorrelationId: " + correlationId, e);
      eventPublisher.publishEvent(new EmailErrorApplicationEvent(email, correlationId));
    }
  }
  public void sendEmail(String email, String template, String subject, Map<String, Object> vars)
      throws RegistrationException {

    try {
      final Context ctx = new Context();
      if (vars != null) {
        for (String var : vars.keySet()) {
          ctx.setVariable(var, vars.get(var));
        }
      }

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
      message.setSubject(subject);
      message.setFrom(mailUser);
      message.setTo(email);

      // Create the HTML body using Thymeleaf
      final String htmlContent = this.templateEngine.process(template, ctx);
      message.setText(htmlContent, true);
      // Send mail
      mailSender.send(mimeMessage);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RegistrationException(e);
    }
  }
예제 #4
0
  public PasswordResetToken createPasswordResetToken(PasswordResetTokenCreateRequest request) {
    User user = userRepository.findByEmail(request.getEmail());
    if (user == null) {
      throw new EmailNotFoundException();
    }

    LocalDateTime now = LocalDateTime.now();
    PasswordResetToken passwordResetToken = new PasswordResetToken();
    passwordResetToken.setUser(user);
    passwordResetToken.setEmail(user.getEmail());
    passwordResetToken.setExpiredAt(now.plusHours(24));
    passwordResetToken.setCreatedAt(now);
    passwordResetToken.setCreatedBy(user.toString());
    passwordResetToken.setUpdatedAt(now);
    passwordResetToken.setUpdatedBy(user.toString());
    passwordResetToken = passwordResetTokenRepository.saveAndFlush(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/password-reset");
      builder.path("/{token}");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String resetLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", resetLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordResetSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-reset", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return passwordResetToken;
  }
예제 #5
0
  @CacheEvict(value = "users", allEntries = true)
  public List<UserInvitation> inviteUsers(
      UserInvitationCreateRequest form, BindingResult result, AuthorizedUser authorizedUser)
      throws MessagingException {
    String[] recipients = StringUtils.commaDelimitedListToStringArray(form.getInvitees());

    LocalDateTime now = LocalDateTime.now();

    List<UserInvitation> invitations = new ArrayList<>();
    for (String recipient : recipients) {
      UserInvitation invitation = new UserInvitation();
      invitation.setEmail(recipient);
      invitation.setMessage(form.getMessage());
      invitation.setExpiredAt(now.plusHours(72));
      invitation.setCreatedAt(now);
      invitation.setCreatedBy(authorizedUser.toString());
      invitation.setUpdatedAt(now);
      invitation.setUpdatedBy(authorizedUser.toString());
      invitation = userInvitationRepository.saveAndFlush(invitation);
      invitations.add(invitation);
    }

    Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
    for (UserInvitation invitation : invitations) {
      String websiteTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());
      String signupLink =
          ServletUriComponentsBuilder.fromCurrentContextPath()
              .path("/_admin/signup")
              .queryParam("token", invitation.getToken())
              .buildAndExpand()
              .toString();

      final Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("websiteTitle", websiteTitle);
      ctx.setVariable("authorizedUser", authorizedUser);
      ctx.setVariable("signupLink", signupLink);
      ctx.setVariable("invitation", invitation);

      final MimeMessage mimeMessage = mailSender.createMimeMessage();
      final MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "InvitationMessageTitle", LocaleContextHolder.getLocale()),
              authorizedUser.toString(),
              websiteTitle));
      message.setFrom(authorizedUser.getEmail());
      message.setTo(invitation.getEmail());

      final String htmlContent = templateEngine.process("user-invite", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    }

    return invitations;
  }
예제 #6
0
 @Async
 public void sendPasswordResetMail(User user, String baseUrl) {
   log.debug("Sending password reset e-mail to '{}'", user.getEmail());
   Locale locale = Locale.forLanguageTag(user.getLangKey());
   Context context = new Context(locale);
   context.setVariable("user", user);
   context.setVariable("baseUrl", baseUrl);
   String content = templateEngine.process("passwordResetEmail", context);
   String subject = messageSource.getMessage("email.reset.title", null, locale);
   sendEmail(user.getEmail(), subject, content, false, true);
 }
 @Async
 public void sendSocialRegistrationValidationEmail(User user, String provider) {
   log.debug("Sending social registration validation e-mail to '{}'", user.getEmail());
   Locale locale = Locale.forLanguageTag(user.getLangKey());
   Context context = new Context(locale);
   context.setVariable("user", user);
   context.setVariable("provider", WordUtils.capitalize(provider));
   String content = templateEngine.process("socialRegistrationValidationEmail", context);
   String subject = messageSource.getMessage("email.social.registration.title", null, locale);
   sendEmail(user.getEmail(), subject, content, false, true);
 }
예제 #8
0
  @CacheEvict(value = "users", allEntries = true)
  public User updatePassword(PasswordUpdateRequest request, PasswordResetToken passwordResetToken) {
    User user = userRepository.findByIdForUpdate(request.getUserId());
    if (user == null) {
      throw new IllegalArgumentException("The user does not exist");
    }
    PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
    user.setLoginPassword(passwordEncoder.encode(request.getPassword()));
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(passwordResetToken.getUser().toString());
    user = userRepository.saveAndFlush(user);

    passwordResetTokenRepository.delete(passwordResetToken);

    try {
      Blog blog = blogService.readBlogById(Blog.DEFAULT_ID);
      String blogTitle = blog.getTitle(LocaleContextHolder.getLocale().getLanguage());

      ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentContextPath();
      if (blog.isMultiLanguage()) {
        builder.path("/{language}");
      }
      builder.path("/login");

      Map<String, Object> urlVariables = new LinkedHashMap<>();
      urlVariables.put("language", request.getLanguage());
      urlVariables.put("token", passwordResetToken.getToken());
      String loginLink = builder.buildAndExpand(urlVariables).toString();

      Context ctx = new Context(LocaleContextHolder.getLocale());
      ctx.setVariable("passwordResetToken", passwordResetToken);
      ctx.setVariable("resetLink", loginLink);

      MimeMessage mimeMessage = mailSender.createMimeMessage();
      MimeMessageHelper message =
          new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
      message.setSubject(
          MessageFormat.format(
              messageSourceAccessor.getMessage(
                  "PasswordChangedSubject", LocaleContextHolder.getLocale()),
              blogTitle));
      message.setFrom(mailProperties.getProperties().get("mail.from"));
      message.setTo(passwordResetToken.getEmail());

      String htmlContent = templateEngine.process("password-changed", ctx);
      message.setText(htmlContent, true); // true = isHtml

      mailSender.send(mimeMessage);
    } catch (MessagingException e) {
      throw new ServiceException(e);
    }

    return user;
  }
 @Override
 public String generatePageHtml(ITestPage test) {
   TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
   templateResolver.setTemplateMode("HTML5");
   templateResolver.setCharacterEncoding("UTF-8");
   TemplateEngine templateEngine = new TemplateEngine();
   templateEngine.setTemplateResolver(templateResolver);
   Locale locale = LocaleUtils.toLocale("fr");
   final Context ctx = new Context(locale);
   ctx.setVariable("test", test);
   String htmlOutput = templateEngine.process("new_test_report_template.html", ctx);
   return htmlOutput;
 }
  protected void sendOrderStatusUpdateEmail(Order order) {
    try {

      // Prepare the evaluation context
      final Context ctx = new Context();
      ctx.setVariable("order", order);

      // Create the HTML body using Thymeleaf
      final String htmlContent = this.templateEngine.process("order-status-update-email", ctx);

      emailService.sendEmail(
          order.getCustomer().getEmail(), "QuilCartCart - Order Status Update", htmlContent);
    } catch (JCartException e) {
      logger.error(e);
    }
  }
예제 #11
0
  @Test
  public void testJavaScript() {
    TemplateEngine engine = createWisdomEngine();
    Context context = new Context();
    context.setVariable("test", "test");

    FakeRouter router = new FakeRouter();
    Controller controller = new FakeController();
    router.addController(controller);

    context.setVariable(Routes.ROUTES_VAR, new Routes(router, controller));

    String processed = engine.process("templates/javascript.thl.html", context);
    assertThat(processed).containsIgnoringCase("var t = 'test';");
    assertThat(processed).containsIgnoringCase("var url = '/';");
    assertThat(processed).containsIgnoringCase("$(document).ready(function () {");
  }
예제 #12
0
  /**
   * Renders the given template.
   *
   * <p>Variables from the session, flash and request parameters are added to the given parameters.
   *
   * @param template the template
   * @param controller the template asking for the rendering
   * @param router the router service
   * @param variables the template parameters
   * @return the rendered HTML page
   */
  public RenderableString process(
      Template template,
      Controller controller,
      Router router,
      Assets assets,
      Map<String, Object> variables) {
    Context ctx = new Context();
    // Add session
    final org.wisdom.api.http.Context http = org.wisdom.api.http.Context.CONTEXT.get();
    ctx.setVariables(http.session().getData());
    // Add flash
    ctx.setVariables(http.flash().getCurrentFlashCookieData());
    ctx.setVariables(http.flash().getOutgoingFlashCookieData());

    // Add parameter from request, flattened
    for (Map.Entry<String, List<String>> entry : http.parameters().entrySet()) {
      if (entry.getValue().size() == 1) {
        ctx.setVariable(entry.getKey(), entry.getValue().get(0));
      } else {
        ctx.setVariable(entry.getKey(), entry.getValue());
      }
    }

    // Add request scope
    for (Map.Entry<String, Object> entry : http.request().data().entrySet()) {
      ctx.setVariable(entry.getKey(), entry.getValue());
    }

    // Add variable.
    ctx.setVariables(variables);
    ctx.setVariable(Routes.ROUTES_VAR, new Routes(router, assets, controller));
    StringWriter writer = new StringWriter();
    try {
      this.process(template.fullName(), ctx, writer);
    } catch (TemplateProcessingException e) {
      // If we have a nested cause having a nested cause, heuristics say that it's the useful
      // message.
      // Rebuild an exception using this data.
      if (e.getCause() != null && e.getCause().getCause() != null) {
        throw new TemplateProcessingException(
            e.getCause().getCause().getMessage(),
            e.getTemplateName(),
            e.getLineNumber(),
            e.getCause().getCause());
      } else {
        throw e;
      }
    }
    return new RenderableString(writer, MimeTypes.HTML);
  }
예제 #13
0
  public void setResponse(Pair<ABSString, ABS.StdLib.List<ABSValue>> pair) throws Exception {
    TemplateResolver templateResolver = new TemplateResolver();
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setSuffix(".html");
    templateResolver.setResourceResolver(new ResourceResolver());

    TemplateEngine templateEngine = new TemplateEngine();
    templateEngine.setTemplateResolver(templateResolver);

    List_Cons<ABSValue> data;

    if (pair != null) {
      String view = DataTransformer.convertABSStringToJavaString((ABSString) pair.getArg(0));
      Context ctx = new Context();
      if (!(pair.getArg(1) instanceof List_Nil)) {
        data = (List_Cons<ABSValue>) pair.getArg(1);
        ArrayList<Object> dataModels = DataTransformer.convertABSListToJavaList(data);

        if (dataModels.size() > 1) {
          ctx.setVariable("dataList", dataModels);
        } else {
          ctx.setVariable("data", dataModels.get(0));
        }
      }
      ctx.setVariable("requestMethod", this.request.getMethod());
      ctx.setVariable("requestURI", this.request.getRequestURI());
      ctx.setVariable("requestContextPath", this.request.getContextPath());
      ctx.setVariable(
          "requestRoute", this.getRoute(request.getRequestURI(), request.getContextPath()));

      this.response = templateEngine.process(view, ctx);
    } else {
      this.response = "<h3>ERROR 404: PAGE NOT FOUND</h3>";
      this.response += "<span style='font-size:0.8em;'>ABS Server: " + new Date() + "</span><br />";
    }
  }