Example usage for org.springframework.mail MailException getCause

List of usage examples for org.springframework.mail MailException getCause

Introduction

In this page you can find the example usage for org.springframework.mail MailException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.musicrecital.webapp.pages.PasswordHint.java

Object onActivate(EventContext ctx) {
    // ensure that the username has been set
    if (ctx == null || ctx.getCount() == 0) {
        logger.warn("Username not specified, notifying user that it's a required field.");
        alertManager.alert(Duration.TRANSIENT, Severity.ERROR,
                messages.format("errors.required", messages.get("user.username")));

        return Login.class;
    }/*  w  w  w.j a v  a 2s.  c  o  m*/

    // Expect username is the first item in the context
    int userIdx = 0;
    this.username = ctx.get(String.class, userIdx).trim();
    logger.debug("Processing Password Hint for username: " + username);

    // look up the user's information
    try {
        User user = userManager.getUserByUsername(username);

        StringBuilder msg = new StringBuilder();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        String subject = '[' + messages.get("webapp.name") + "] " + messages.get("user.passwordHint");

        emailService.send(user, subject, msg.toString(), RequestUtil.getAppURL(request), true);

        alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                messages.format("login.passwordHint.sent", username, user.getEmail()));
    } catch (UsernameNotFoundException e) {
        logger.warn(e.getMessage());
        // If exception is expected do not rethrow
        alertManager.error(messages.format("login.passwordHint.error", username));

    } catch (MailException me) {
        alertManager.error(me.getCause().getLocalizedMessage());
    }

    return Login.class;
}

From source file:ejportal.webapp.action.PasswordHintAction.java

/**
 * Execute sending the password hint via e-mail.
 * //from   w  ww . ja  v  a2  s .  c om
 * @return success if username works, input if not
 */
@Override
public String execute() {
    final List<Object> args = new ArrayList<Object>();

    // ensure that the username has been sent
    if (this.username == null) {
        this.log.warn("Username not specified, notifying user that it's a required field.");

        args.add(this.getText("user.username"));
        this.addActionError(this.getText("errors.requiredField", args));
        return Action.INPUT;
    }

    if (this.log.isDebugEnabled()) {
        this.log.debug("Processing Password Hint...");
    }

    // look up the user's information
    try {
        final User user = this.userManager.getUserByUsername(this.username);
        final String hint = user.getPasswordHint();

        if ((hint == null) || hint.trim().equals("")) {
            this.log.warn("User '" + this.username + "' found, but no password hint exists.");
            this.addActionError(this.getText("login.passwordHint.missing"));
            return Action.INPUT;
        }

        final StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(hint);
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(this.getRequest()));

        this.mailMessage.setTo(user.getEmail());
        final String subject = '[' + this.getText("webapp.name") + "] " + this.getText("user.passwordHint");
        this.mailMessage.setSubject(subject);
        this.mailMessage.setText(msg.toString());
        this.mailEngine.send(this.mailMessage);

        args.add(this.username);
        args.add(user.getEmail());

        this.saveMessage(this.getText("login.passwordHint.sent", args));
    } catch (final UsernameNotFoundException e) {
        this.log.warn(e.getMessage());
        args.add(this.username);
        this.addActionError(this.getText("login.passwordHint.error", args));
        this.getSession().setAttribute("errors", this.getActionErrors());
        return Action.INPUT;
    } catch (final MailException me) {
        this.addActionError(me.getCause().getLocalizedMessage());
        this.getSession().setAttribute("errors", this.getActionErrors());
        return Action.INPUT;
    }

    return Action.SUCCESS;
}

From source file:ch.wisv.areafiftylan.utils.mail.MailServiceImpl.java

@Override
public void sendMail(String recipientEmail, String recipientName, String subject, String messageString) {

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message;

    try {/*www .  j  a  v  a 2  s . co m*/
        message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setSubject("[Area FiftyLAN] " + subject);
        message.setFrom(sender);
        message.setTo(recipientEmail);

        // Create the HTML body using Thymeleaf
        String htmlContent = prepareHtmlContent(recipientName, messageString);
        message.setText(htmlContent, true); // true = isHtml

        // Send mail
        this.mailSender.send(mimeMessage);
    } catch (MessagingException e) {
        throw new MailPreparationException("Unable to prepare email", e.getCause());
    } catch (MailException m) {
        throw new MailSendException("Unable to send email", m.getCause());
    }

}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.PasswordHintController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {
    log.debug("entering 'handleRequest' method...");

    String username = request.getParameter("username");
    MessageSourceAccessor text = new MessageSourceAccessor(messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }// w  w  w .java  2s .  com

    log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        User user = userManager.getUserByUsername(username);

        StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        message.setTo(user.getEmail());
        String subject = '[' + text.getMessage("webapp.name") + "] " + text.getMessage("user.passwordHint");
        message.setSubject(subject);
        message.setText(msg.toString());
        mailEngine.send(message);

        saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (UsernameNotFoundException e) {
        log.warn(e.getMessage());
        saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (MailException me) {
        log.warn(me.getMessage());
        saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:alpha.portal.webapp.controller.PasswordHintController.java

/**
 * Handle request.//from   ww  w  .ja va2s.com
 * 
 * @param request
 *            the request
 * @return the model and view
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(final HttpServletRequest request) throws Exception {
    this.log.debug("entering 'handleRequest' method...");

    final String username = request.getParameter("username");
    final MessageSourceAccessor text = new MessageSourceAccessor(this.messageSource, request.getLocale());

    // ensure that the username has been sent
    if (username == null) {
        this.log.warn("Username not specified, notifying user that it's a required field.");
        request.setAttribute("error", text.getMessage("errors.required", text.getMessage("user.username")));
        return new ModelAndView("login");
    }

    this.log.debug("Processing Password Hint...");

    // look up the user's information
    try {
        final User user = this.userManager.getUserByUsername(username);

        final StringBuffer msg = new StringBuffer();
        msg.append("Your password hint is: ").append(user.getPasswordHint());
        msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(request));

        this.message.setTo(user.getEmail());
        final String subject = '[' + text.getMessage("webapp.name") + "] "
                + text.getMessage("user.passwordHint");
        this.message.setSubject(subject);
        this.message.setText(msg.toString());
        this.mailEngine.send(this.message);

        this.saveMessage(request,
                text.getMessage("login.passwordHint.sent", new Object[] { username, user.getEmail() }));
    } catch (final UsernameNotFoundException e) {
        this.log.warn(e.getMessage());
        this.saveError(request, text.getMessage("login.passwordHint.error", new Object[] { username }));
    } catch (final MailException me) {
        this.log.warn(me.getMessage());
        this.saveError(request, me.getCause().getLocalizedMessage());
    }

    return new ModelAndView(new RedirectView(request.getContextPath()));
}

From source file:org.openmrs.contrib.metadatarepository.webapp.controller.UserFormController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(User user, BindingResult errors, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            return getCancelView();
        } else {/*from   w w w .j  a  v a2  s. co  m*/
            return getSuccessView();
        }
    }

    if (validator != null) { // validator is null during testing
        validator.validate(user, errors);

        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return "userform";
        }
    }

    log.debug("entering 'onSubmit' method...");

    Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        getUserManager().removeUser(user.getId().toString());
        saveMessage(request, getText("user.deleted", user.getFullName(), locale));

        return getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE) || request.isUserInRole(Constants.USER_ROLE)) {
            String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (String roleName : userRoles) {
                    user.addRole(roleManager.getRole(roleName));
                }
            }
        }

        Integer originalVersion = user.getVersion();

        try {
            getUserManager().saveUser(user);
        } catch (AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
            log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            saveMessage(request, getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                saveMessage(request, getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                message.setSubject(getText("signup.email.subject", locale));

                try {
                    sendUserMessage(user, getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (MailException me) {
                    saveError(request, me.getCause().getLocalizedMessage());
                }

                return getSuccessView();
            } else {
                saveMessage(request, getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "userform";
}

From source file:ejportal.webapp.action.UserAction.java

/**
 * Save user.//from  www.j ava 2 s. c  om
 * 
 * @return success if everything worked, otherwise input
 * @throws Exception
 *             when setting "access denied" fails on response
 */
public String save() throws Exception {

    final Integer originalVersion = this.user.getVersion();

    final boolean isNew = ("".equals(this.getRequest().getParameter("user.version")));
    // only attempt to change roles if user is admin
    // for other users, prepare() method will handle populating
    // TODO hartkodiert
    if (this.getRequest().isUserInRole("ROLE_ADMIN")) {
        // if (getRequest().isUserInRole(Constants.ADMIN_ROLE)) {
        this.user.getRoles().clear(); // APF-788: Removing roles from user
        // doesn't work
        final String[] userRoles = this.getRequest().getParameterValues("userRoles");

        for (int i = 0; (userRoles != null) && (i < userRoles.length); i++) {
            final String roleName = userRoles[i];
            this.user.addRole(this.roleManager.getRole(roleName));
        }
    }

    try {
        this.userManager.saveUser(this.user);
    } catch (final AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor
        // userManagerSecurity
        this.log.warn(ade.getMessage());
        this.getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (final UserExistsException e) {
        final List<Object> args = new ArrayList<Object>();
        args.add(this.user.getUsername());
        args.add(this.user.getEmail());
        this.addActionError(this.getText("errors.existing.user", args));

        // reset the version # to what was passed in
        this.user.setVersion(originalVersion);
        // redisplay the unencrypted passwords
        this.user.setPassword(this.user.getConfirmPassword());
        return Action.INPUT;
    }

    if (!"list".equals(this.from)) {
        // add success messages
        this.saveMessage(this.getText("user.saved"));
        return "mainMenu";
    } else {
        // add success messages
        final List<Object> args = new ArrayList<Object>();
        args.add(this.user.getFullName());
        if (isNew) {
            this.saveMessage(this.getText("user.added", args));
            // Send an account information e-mail
            this.mailMessage.setSubject(this.getText("signup.email.subject"));
            try {
                this.sendUserMessage(this.user, this.getText("newuser.email.message", args),
                        RequestUtil.getAppURL(this.getRequest()));
            } catch (final MailException me) {
                this.addActionError(me.getCause().getLocalizedMessage());
            }
            return Action.SUCCESS;
        } else {
            this.saveMessage(this.getText("user.updated.byAdmin", args));
            return Action.INPUT;
        }
    }
}

From source file:org.musicrecital.webapp.pages.UserEdit.java

@Log
@DiscardAfter//w  w w  .  j a  va 2s  .  co m
Object onSuccess() throws UserExistsException, IOException {

    // Delete Button Clicked
    if (delete) {
        return onDelete();
    }

    // Only Admins can update roles for other users
    if (securityContext.isAdmin()) {
        if (selectedRoles != null && !selectedRoles.isEmpty()) {
            user.getRoles().clear();
            for (int i = 0; selectedRoles != null && i < selectedRoles.size(); i++) {
                String roleName = selectedRoles.get(i).getName();
                user.addRole(roleManager.getRole(roleName));
            }
        }
    }

    Integer originalVersion = user.getVersion();

    try {
        user = userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        logger.warn(ade.getMessage());
        return AccessDenied.class;
    } catch (UserExistsException e) {
        // TODO
        //form.recordError(form.getEmailField(), "User exits");
        alertManager.alert(Duration.TRANSIENT, Severity.ERROR,
                messages.format("errors.existing.user", user.getUsername(), user.getEmail()));

        user.setPassword(user.getConfirmPassword());
        user.setVersion(originalVersion);
        return null;
    }

    if (!"list".equalsIgnoreCase(from)) {
        // add success messages
        alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                messages.format("user.saved", user.getFullName()));
        return Home.class;
    } else {
        // add success messages
        if (originalVersion == null) {
            alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                    messages.format("user.added", user.getFullName()));

            try {
                String msg = messages.format("newuser.email.message", user.getFullName());
                String subject = messages.get("signup.email.subject");
                emailService.send(user, subject, msg, RequestUtil.getAppURL(request), false);
            } catch (MailException me) {
                alertManager.alert(Duration.TRANSIENT, Severity.ERROR, me.getCause().getLocalizedMessage());
            }
            return UserList.class;
        } else {
            alertManager.alert(Duration.TRANSIENT, Severity.INFO,
                    messages.format("user.updated.byAdmin", user.getFullName()));
        }
    }

    return this;
}

From source file:alpha.portal.webapp.controller.UserFormController.java

/**
 * On submit.//from  w w w. j  a  v a2  s .  com
 * 
 * @param user
 *            the user
 * @param errors
 *            the errors
 * @param request
 *            the request
 * @param response
 *            the response
 * @param model
 *            the model
 * @return the string
 * @throws Exception
 *             the exception
 */
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(final User user, final BindingResult errors, final HttpServletRequest request,
        final HttpServletResponse response, final Model model) throws Exception {
    if (request.getParameter("cancel") != null) {
        if (!StringUtils.equals(request.getParameter("from"), "list"))
            return this.getCancelView();
        else
            return this.getSuccessView();
    }

    if (this.validator != null) { // validator is null during testing
        this.validator.validate(user, errors);

        if (errors.hasErrors() && (request.getParameter("delete") == null)) {
            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }
    }

    this.log.debug("entering 'onSubmit' method...");

    final Locale locale = request.getLocale();

    if (request.getParameter("delete") != null) {
        this.getUserManager().removeUser(user.getId().toString());
        this.saveMessage(request, this.getText("user.deleted", user.getFullName(), locale));

        return this.getSuccessView();
    } else {

        // only attempt to change roles if user is admin for other users,
        // showForm() method will handle populating
        if (request.isUserInRole(Constants.ADMIN_ROLE)) {
            final String[] userRoles = request.getParameterValues("userRoles");

            if (userRoles != null) {
                user.getRoles().clear();
                for (final String roleName : userRoles) {
                    user.addRole(this.roleManager.getRole(roleName));
                }
            }
        }

        final Integer originalVersion = user.getVersion();

        try {
            this.getUserManager().saveUser(user);
        } catch (final AccessDeniedException ade) {
            // thrown by UserSecurityAdvice configured in aop:advisor
            // userManagerSecurity
            this.log.warn(ade.getMessage());
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (final UserExistsException e) {
            errors.rejectValue("username", "errors.existing.user",
                    new Object[] { user.getUsername(), user.getEmail() }, "duplicate user");

            // redisplay the unencrypted passwords
            user.setPassword(user.getConfirmPassword());
            // reset the version # to what was passed in
            user.setVersion(originalVersion);

            model.addAttribute("contributorRoles", this.contributorRoleManager.getAll());
            return "userform";
        }

        if (!StringUtils.equals(request.getParameter("from"), "list")) {
            this.saveMessage(request, this.getText("user.saved", user.getFullName(), locale));

            // return to main Menu
            return this.getCancelView();
        } else {
            if (StringUtils.isBlank(request.getParameter("version"))) {
                this.saveMessage(request, this.getText("user.added", user.getFullName(), locale));

                // Send an account information e-mail
                this.message.setSubject(this.getText("signup.email.subject", locale));

                try {
                    this.sendUserMessage(user,
                            this.getText("newuser.email.message", user.getFullName(), locale),
                            RequestUtil.getAppURL(request));
                } catch (final MailException me) {
                    this.saveError(request, me.getCause().getLocalizedMessage());
                }

                return this.getSuccessView();
            } else {
                this.saveMessage(request, this.getText("user.updated.byAdmin", user.getFullName(), locale));
            }
        }
    }

    return "redirect:/mainMenu";
}

From source file:com.virtusa.akura.common.controller.ForgotPasswordController.java

/**
 * This method handles the submit user email address request. User enters his/her email address into the
 * given field and click submit.//from   w  w w  .j  av  a2s  . c  o m
 * 
 * @param userLogin - the object to bind the user's email address.
 * @param bindingResult - bind errors to the binding results.
 * @param modMap - model to add attributes.
 * @param session - to get and set session attributes and parameters.
 * @return the view to be return after success or failure.
 * @throws AkuraAppException throws a detailed exception.
 */
@RequestMapping(value = SUBMIT_EMAIL_HTM, method = RequestMethod.POST)
public String submitEmail(@ModelAttribute(USER_LOGIN) UserLogin userLogin, BindingResult bindingResult,
        ModelMap modMap, HttpSession session) throws AkuraAppException {

    String error = null;
    String mailError = null;

    // Validate the email address.
    forgotUserNameValidator.validate(userLogin, bindingResult);

    // if there are errors then go back to the previous page and show the error message.
    if (bindingResult.hasErrors()) {
        return FORGOT_USERNAME;
    }

    // Get the User Login by email address.
    UserLogin user = userService.getAnyUserByEmail(userLogin.getEmail().trim());

    // If there is no user account with the given email address. UserLogin will be empty.
    if (user == null) {

        error = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.FORGOT_USERNAME_ERROR_EMAIL);
        bindingResult.addError(new ObjectError(ERROR, error));
        return FORGOT_USERNAME;

    } else {

        try {
            setMailProprties(user, PropertyReader.getPropertyValue(EMAIL_PROPERTIES, FORGOT_USERNAME_SUBJECT),
                    PropertyReader.getPropertyValue(EMAIL_PROPERTIES, FORGOT_USERANAME_TO_USER));

            // Add the message to Model to pass a value.
            modMap.addAttribute(MESSAGE, AkuraWebConstant.USERNAEM_SEND_SUCCESSFUL_MESSAGE);

        } catch (MailException e) {

            if (e instanceof MailAuthenticationException) {

                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR, e);

            } else if (e.getCause() instanceof MailSendException) {
                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
            }

            mailError = new ErrorMsgLoader().getErrorMessage(AkuraConstant.EMAIL_ERROR);
            LOG.error(AkuraConstant.EMAIL_ERROR, e);
        } catch (AkuraAppException e) {
            mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
            LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
        }

        if (mailError != null) {
            modMap.addAttribute(MAIL_ERRORS, mailError);
        }

    }
    userLogin.setEmail(null);
    return FORGOT_PASSWORD_SUCCESS_OR_ERROR;

}