Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

In this page you can find the example usage for javax.mail MessagingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.cubusmail.server.services.MailboxService.java

public void markMessage(long[] messageIds, int flag) throws Exception {

    IMailbox mailbox = SessionManager.get().getMailbox();
    if (messageIds != null && messageIds.length > 0) {
        log.debug("marking " + messageIds.length + " messages...");

        try {/*from   w  ww .  ja  v  a 2s  . c om*/
            IMailFolder currentFolder = mailbox.getCurrentFolder();
            for (int i = 0; i < messageIds.length; i++) {
                Message msg = currentFolder.getMessageById(messageIds[i]);
                switch (flag) {
                case GWTMessageFlags.READ:
                    MessageUtils.setMessageFlag(msg, Flags.Flag.SEEN, true);
                    break;
                case GWTMessageFlags.UNREAD:
                    MessageUtils.setMessageFlag(msg, Flags.Flag.SEEN, false);
                    break;
                case GWTMessageFlags.DELETED:
                    MessageUtils.setMessageFlag(msg, Flags.Flag.DELETED, true);
                    break;
                case GWTMessageFlags.UNDELETED:
                    MessageUtils.setMessageFlag(msg, Flags.Flag.DELETED, false);
                    break;
                default:
                    throw new IllegalArgumentException("Unknown flag: " + flag);
                }
            }
            log.debug("...successful");
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            throw new GWTMessageException(e.getMessage());
        }
    }
}

From source file:com.stimulus.archiva.incoming.IAPRunnable.java

public void establishConnection(String protocol, String server, int port, String username, String password,
        Properties props) throws ArchivaException {
    logger.debug("establishConnection() protocol='" + protocol + "',server='" + server + "',port='" + port
            + "',username='" + username + "',password='********'}");
    Session session = Session.getInstance(props, null);
    if (System.getProperty("mailarchiva.mail.debug") != null)
        session.setDebug(true);/*from   ww w .j a va 2  s  . c om*/

    try {
        logger.debug("iap connect " + props);
        store = session.getStore(protocol);
    } catch (Throwable nspe) {
        logger.error("failed to retrieve iap store object:" + nspe, nspe);
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("mailbox connection properties " + props);
    }
    try {
        store.connect(server, port, username, password);
    } catch (AuthenticationFailedException e) {
        logger.error("cannot connect to mail server. authentication failed {" + props + "}");
        throw new ArchivaException("unable to connect to mail server. could not authenticate. {" + props + "}",
                e, logger);
    } catch (IllegalStateException ise) {
        throw new ArchivaException("attempt to connect mail server when it already connected. {" + props + "}",
                ise, logger);
    } catch (MessagingException me) {
        if (me.getMessage().contains("sun.security.validator.ValidatorException")) {
            throw new ArchivaException(
                    "failed to authenticate TLS certificate. You must install the mail server's certificate as per the administration guide.",
                    me, logger);
        } else if (connection.getConnectionMode() == MailboxConnections.ConnectionMode.FALLBACK
                && me.getMessage().contains("javax.net.ssl.SSLHandshakeException")) {
            logger.debug("cannot establish SSL handshake with mail server. falling back to insecure. {" + props
                    + "}");
            connection.setConnectionMode(MailboxConnections.ConnectionMode.INSECURE);
        } else
            throw new ArchivaException(
                    "failed to connect to mail server. " + me.getMessage() + ". {" + props + "}", me, logger);
    } catch (Throwable e) {
        throw new ArchivaException("unable to connect to mail server:" + e.getMessage(), e, logger);
    }
    try {
        inboxFolder = store.getDefaultFolder();
    } catch (Throwable e) {
        throw new ArchivaException("unable to get default folder. ", e, logger);
    }

    if (inboxFolder == null) {
        throw new ArchivaException("there was no default POP inbox folder found.", logger);
    }

    try {
        inboxFolder = inboxFolder.getFolder("INBOX");
        if (inboxFolder == null) {
            throw new ArchivaException("the inbox folder does not exist.", logger);
        }
    } catch (Throwable e) {
        throw new ArchivaException("unable to get INBOX folder. ", e, logger);
    }
    try {
        inboxFolder.open(Folder.READ_WRITE);
    } catch (Throwable e) {
        throw new ArchivaException("unable to open folder. ", e, logger);
    }
    return;
}

From source file:com.cubusmail.server.services.MailboxService.java

public void sendMessage(GWTMessage message) throws Exception {

    try {// w  w  w . j  ava2s . co m
        log.debug("sending message...");
        MessageHandler messageHandler = SessionManager.get().getCurrentComposeMessage();
        messageHandler.setGWTMessage(message);
        messageHandler.send();
        IMailbox mailbox = SessionManager.get().getMailbox();
        IMailFolder sentFolder = mailbox.getSentFolder();
        messageHandler.saveToFolder(sentFolder, false);
        log.debug("...successful");

        try {
            this.userAccountDao.saveRecipients(SessionManager.get().getUserAccount(),
                    messageHandler.getAllRecipients());
        } catch (Throwable e) {
            // catch all exceptions
            log.error(e.getMessage(), e);
        }
    } catch (AddressException e) {
        log.error(e.getMessage(), e);
        throw new GWTInvalidAddressException(e.getMessage(), e.getRef());
    } catch (SendFailedException e) {
        log.error(e.getMessage(), e);
        if ("Invalid Addresses".equals(e.getMessage())) {
            String address = "";
            try {
                address = MessageUtils.getMailAdressString(e.getInvalidAddresses(), AddressStringType.PERSONAL);
            } catch (MessagingException ex) {
                log.error(ex.getMessage(), ex);
            }
            throw new GWTInvalidAddressException(e.getMessage(), address);
        } else {
            throw new GWTMessageException(e.getMessage());
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    }
}

From source file:com.cubusmail.server.services.MailboxService.java

public GWTMessageList retrieveMessages(String folderId, int start, int pageSize, MessageListFields sortField,
        boolean ascending, MessageListFields[] searchFields, String[] searchValues) throws Exception {

    if (folderId != null) {
        IMailbox mailbox = SessionManager.get().getMailbox();
        UserAccount account = SessionManager.get().getUserAccount();
        log.debug("retrieving messages from " + folderId + " ...");

        try {/*from  ww  w  .j  ava2  s  .com*/
            IMailFolder currentFolder = mailbox.getMailFolderById(folderId);
            if (currentFolder == null) {
                mailbox.reloadFolder();
                currentFolder = mailbox.getMailFolderById(folderId);
            }
            mailbox.setCurrentFolder(currentFolder);

            Message[] msgs = currentFolder.retrieveMessages(sortField, ascending, searchFields, searchValues);

            if (msgs != null && msgs.length > 0) {
                int total_count = msgs.length;
                start = Math.min(total_count - 1, start == -1 ? 0 : start);
                pageSize = pageSize == -1 ? account.getPreferences().getPageCount() : pageSize;
                pageSize = Math.min(pageSize, total_count - start);

                Message[] pagedMessages = new Message[pageSize];
                int pagedIndex = 0;
                for (int msgIndex = start; msgIndex < start + pageSize; msgIndex++) {
                    pagedMessages[pagedIndex++] = msgs[msgIndex];
                }
                FetchProfile completeProfile = MessageUtils.createFetchProfile(true, null);
                currentFolder.fetch(pagedMessages, completeProfile);

                Preferences preferences = SessionManager.get().getPreferences();

                GWTMessageRecord[] messageStringArray = ConvertUtil.convertMessagesToStringArray(
                        getApplicationContext(), preferences, (IMAPFolder) currentFolder.getFolder(), pageSize,
                        pagedMessages);

                return new GWTMessageList(messageStringArray, msgs.length);
            }

            return null;
        } catch (MessagingException e) {
            log.error(e.getMessage(), e);
            throw new GWTMessageException(e.getMessage());
        }
    } else {
        return null;
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java

/** Handle Messaging exceptions in a consistent global manner */
protected static void handleMessagingException(MessagingException e, String context)
        throws ManifoldCFException, ServiceInterruption {
    Logging.connectors.error("Email: Error " + context + ": " + e.getMessage(), e);
    throw new ManifoldCFException("Error " + context + ": " + e.getMessage(), e);
}

From source file:org.kuali.coeus.propdev.impl.s2s.schedule.S2SPollingTask.java

/**
 * This method is the starting point of execution for the thread that is scheduled by the scheduler service
 * /*from w  w w .  ja v a2 s.c o m*/
 */
public void execute() {
    LOG.info("Executing polling schedule for status -" + statusMap.values() + ":" + stopPollInterval);
    Map<String, SubmissionData> pollingList = populatePollingList();
    int appListSize = pollingList.size();
    Iterator<SubmissionData> submissions = pollingList.values().iterator();
    HashMap<String, Vector<SubmissionData>> htMails = new LinkedHashMap<String, Vector<SubmissionData>>();
    Vector<SubmissionData> submList = new Vector<SubmissionData>();
    Timestamp[] lastNotiDateArr = new Timestamp[appListSize];
    while (submissions.hasNext()) {
        SubmissionData localSubInfo = submissions.next();
        S2sAppSubmission appSubmission = localSubInfo.getS2sAppSubmission();
        Timestamp oldLastNotiDate = appSubmission.getLastNotifiedDate();
        Timestamp today = new Timestamp(new Date().getTime());
        boolean updateFlag = false;
        boolean sendEmailFlag = false;
        boolean statusChanged = false;
        GetApplicationListResponse applicationListResponse = null;

        try {
            ProposalDevelopmentDocument pdDoc = getProposalDevelopmentDocument(
                    appSubmission.getProposalNumber());
            if (pdDoc != null) {
                applicationListResponse = s2sSubmissionService.fetchApplicationListResponse(pdDoc);
            }

            if (applicationListResponse.getApplicationInfo() == null
                    || applicationListResponse.getApplicationInfo().size() == 0) {
                statusChanged = s2sSubmissionService.checkForSubmissionStatusChange(pdDoc, appSubmission);
                if (statusChanged == false && appSubmission.getComments()
                        .equals(S2sAppSubmissionConstants.STATUS_NO_RESPONSE_FROM_GRANTS_GOV)) {
                    localSubInfo.setSortId(SORT_ID_F);
                    sendEmailFlag = true;
                }
            } else {
                ApplicationInfo ggApplication = applicationListResponse.getApplicationInfo().get(0);
                if (ggApplication != null) {
                    localSubInfo.setAcType('U');
                    statusChanged = !appSubmission.getStatus()
                            .equalsIgnoreCase(ggApplication.getGrantsGovApplicationStatus().value());
                    s2sSubmissionService.populateAppSubmission(pdDoc, appSubmission, ggApplication);
                }
            }
        } catch (S2sCommunicationException e) {
            LOG.error(e.getMessage(), e);
            appSubmission.setComments(e.getMessage());
            localSubInfo.setSortId(SORT_ID_F);
            sendEmailFlag = true;
        }

        String sortId = SORT_ID_Z;
        Timestamp lastNotifiedDate = appSubmission.getLastNotifiedDate();
        Timestamp statusChangedDate = appSubmission.getLastModifiedDate();
        Calendar lastNotifiedDateCal = Calendar.getInstance();
        if (lastNotifiedDate != null) {
            lastNotifiedDateCal.setTimeInMillis(lastNotifiedDate.getTime());
        }
        Calendar statusChangedDateCal = Calendar.getInstance();
        if (statusChangedDate != null) {
            statusChangedDateCal.setTimeInMillis(statusChangedDate.getTime());
        }
        Calendar recDateCal = Calendar.getInstance();
        recDateCal.setTimeInMillis(appSubmission.getReceivedDate().getTime());

        if (statusChanged) {
            if (appSubmission.getStatus()
                    .indexOf(S2sAppSubmissionConstants.STATUS_GRANTS_GOV_SUBMISSION_ERROR) != -1) {
                updateFlag = true;
                sendEmailFlag = true;
                sortId = SORT_ID_A;
            } else if (!lstStatus.contains(appSubmission.getStatus().trim().toUpperCase())) {
                updateFlag = false;
                sendEmailFlag = true;
                sortId = SORT_ID_B;
            } else {
                updateFlag = true;
                sendEmailFlag = true;
                sortId = SORT_ID_E;
            }
        } else {
            long lastModifiedTime = statusChangedDate == null ? appSubmission.getReceivedDate().getTime()
                    : statusChangedDate.getTime();
            long lastNotifiedTime = lastNotifiedDate == null ? lastModifiedTime : lastNotifiedDate.getTime();
            long mailDelta = today.getTime() - lastNotifiedTime;
            long delta = today.getTime() - lastModifiedTime;

            long stopPollDiff = ((Integer.parseInt(getStopPollInterval()) == 0 ? 4320L
                    : Integer.parseInt(getStopPollInterval())) - (delta / (60 * 60 * 1000)));
            if ((mailDelta / (1000 * 60)) >= (Integer.parseInt(getMailInterval()))) {
                if (localSubInfo.getSortId() == null) {
                    if (stopPollDiff <= 24) {
                        sortId = SORT_ID_C;
                    } else {
                        sortId = SORT_ID_D;
                        sortMsgKeyMap.put(SORT_ID_D, "Following submissions status has not been changed in "
                                + getMailInterval() + " minutes");
                    }
                }
                updateFlag = true;
                sendEmailFlag = true;
            }
        }
        if (sendEmailFlag) {
            Map<String, String> proposalMap = new HashMap<String, String>();
            proposalMap.put(KEY_PROPOSAL_NUMBER, appSubmission.getProposalNumber());
            DevelopmentProposal developmentProposal = (DevelopmentProposal) businessObjectService
                    .findByPrimaryKey(DevelopmentProposal.class, proposalMap);

            String dunsNum;
            if (developmentProposal.getApplicantOrganization().getOrganization().getDunsNumber() != null) {
                dunsNum = developmentProposal.getApplicantOrganization().getOrganization().getDunsNumber();
            } else {
                dunsNum = developmentProposal.getApplicantOrganization().getOrganizationId();
            }
            Vector<SubmissionData> mailGrpForDunNum = new Vector<SubmissionData>();
            mailGrpForDunNum.add(localSubInfo);
            htMails.put(dunsNum, mailGrpForDunNum);
            appSubmission.setLastNotifiedDate(today);
        }
        if (localSubInfo.getSortId() == null) {
            localSubInfo.setSortId(sortId);
        }
        if (updateFlag) {
            submList.addElement(localSubInfo);
            lastNotiDateArr[submList.size() - 1] = oldLastNotiDate;
        }

    }
    try {
        sendMail(htMails);
    } catch (InvalidAddressException ex) {
        LOG.error("Mail sending failed");
        LOG.error(ex.getMessage(), ex);
        int size = submList.size();
        for (int i = 0; i < size; i++) {
            SubmissionData localSubInfo = submList.elementAt(i);
            localSubInfo.getS2sAppSubmission().setLastNotifiedDate(lastNotiDateArr[i]);
        }
    } catch (MessagingException me) {
        LOG.error("Mail sending failed");
        LOG.error(me.getMessage(), me);
        int size = submList.size();
        for (int i = 0; i < size; i++) {
            SubmissionData localSubInfo = submList.elementAt(i);
            localSubInfo.getS2sAppSubmission().setLastNotifiedDate(lastNotiDateArr[i]);
        }
    }
    saveSubmissionDetails(submList);
}

From source file:org.webcurator.core.notification.InTrayManagerImpl.java

/**
 * Identifies if the User should be informed of the Notification via email.
 * If the User is to be notified by email, then the email will be sent to the users email address.
 * @param effectedUser the User effected by the Notification
 * @param notify the Notification to send
 *//*from ww  w  .  j a v a2 s. com*/
private void send(UserDTO effectedUser, Notification notify) {
    if (effectedUser.isNotificationsByEmail()) {
        //This user needs to be notified by email as well
        try {
            mailServer.sendHTML(convertNotificationToMail(notify, effectedUser.getEmail()));
        } catch (MessagingException e) {
            log.error(
                    "MailServer failure occurred during email of Notification with message " + e.getMessage());
        }
    }
}

From source file:MyServlet.UserController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  ww.j a va 2 s. com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response);
    String url = "/main.jsp";
    Object message;
    action = request.getServletPath();
    PrintWriter writer = response.getWriter();
    String formName = request.getParameter("formname");
    HttpSession session = request.getSession();
    writer.println("formName  :" + formName);
    System.out.println("Inside post user");
    if (formName.equals("create")) {
        String hosturl = request.getRequestURL().toString();
        String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length())
                + request.getContextPath() + "/";
        System.out.println("hosturl" + hosturl);
        System.out.println("baseURL" + baseURL);
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String cpass = request.getParameter("cpass");
        String token = request.getParameter("token");

        User user = new User();
        user.setName(name);
        user.setEmail(email);
        request.setAttribute("user", user);
        if (password.equals(cpass)) {
            if (userDB.getUser(email) == null) {
                if (token != null) {
                    int recomCoins;
                    User userRecom, newUser;
                    userRecom = UserDB.activateUser(token);
                    if (userRecom != null) {
                        newUser = UserDB.getUser(userRecom.getEmail());
                        recomCoins = newUser.getCoins();
                        newUser.setCoins(recomCoins + 2);
                        UserDB.update(newUser);
                        UserDB.deleteTemp(token);
                    }

                }
                UUID uId = UUID.randomUUID();
                System.out.println("UUID One: " + uId);
                //session.setAttribute("theUser", user);
                userPassword.put(email, password);
                userDB.tempUser(user, uId);
                /*
                userDB.addUser(user,password);
                userDB.addUser(user);*/
                String to = email;
                String from = email;
                String subject = "Activation Link";

                String body = baseURL + "user?action=activation&activationcode=" + uId;
                boolean bodyIsHTML = false;
                try {
                    MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML);
                    System.out.println("mail sent");
                    message = "Activation link sent to your email account";
                    request.setAttribute("message", message);
                    url = "/login.jsp";
                } catch (MessagingException e) {
                    String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage();
                    System.out.println(errorMessage);
                    request.setAttribute("errorMessage", errorMessage);
                    url = "/contact.jsp";
                }

            } else {
                message = "Email address already exist!!";
                request.setAttribute("message", message);
                url = "/signup.jsp";
            }

        } else {
            writer.println("Error");
            message = "Confirm Password doesnot match";
            request.setAttribute("message", message);
            url = "/signup.jsp";
        }

    } else if (formName.equals("login")) {

        User userLogin;
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        writer.println("inside login" + userPassword.get(email));
        userLogin = userDB.getUser(email);
        if (userLogin == null) {
            writer.println("no user");
            message = "Not found email address : " + email;
            request.setAttribute("message", message);
            url = "/login.jsp";

        } else {
            writer.println("inside else");
            try {
                String salt = UserDB.getSalt(email);
                if (salt != null) {
                    password = hashPassword(password + salt);
                    if (userDB.validateUser(email, password)) {
                        if (session.getAttribute("theUser") != null) {
                            session.invalidate();
                        }
                        session = request.getSession();
                        session.setAttribute("theUser", userLogin);

                        url = "/main.jsp";
                    } else {
                        message = "Password is incorrect!!";
                        request.setAttribute("message", message);
                        url = "/login.jsp";

                    }
                }
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    } else if (formName.equals("forgetpassword")) {
        String name = "name";
        String email = request.getParameter("email");
        System.out.println("email" + email);
        if (userDB.getUser(email) != null) {
            UUID uId = UUID.randomUUID();
            System.out.println("UUID One: " + uId);
            //session.setAttribute("theUser", user);
            String to = email;
            String from = email;
            String subject = "Password Reset Link";
            String hosturl = request.getRequestURL().toString();
            String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length())
                    + request.getContextPath() + "/";

            String body = baseURL + "user?action=resetpassword&token=" + uId;
            boolean bodyIsHTML = false;
            try {
                User user = new User();
                user.setName(name);
                user.setEmail(email);
                userDB.tempUser(user, uId);
                MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML);
                System.out.println("mail sent");
                message = "Please check your email account";
                request.setAttribute("message", message);
                url = "/login.jsp";
            } catch (MessagingException e) {
                String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage();
                System.out.println(errorMessage);
                request.setAttribute("errorMessage", errorMessage);
                url = "/contact.jsp";
            }
        }
    } else if (formName.equals("resetpassword")) {
        try {
            String currentTime = sdf.format(dt);
            String password = request.getParameter("password");
            String cpass = request.getParameter("cpass");
            String email = request.getParameter("email");
            String token = request.getParameter("token");
            String expiryTime = UserDB.getTime(token);
            Date date1 = sdf.parse(expiryTime);
            Date date2 = sdf.parse(currentTime);
            long differenceInMillis = date2.getTime() - date1.getTime();
            if (differenceInMillis < 3600000) {
                User user = new User();
                user.setEmail(email);
                if (password.equals(cpass)) {
                    try {
                        password = hashAndSalt(password);
                    } catch (NoSuchAlgorithmException ex) {
                        Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    UserDB.updatePassword(user, password, salt);
                    UserDB.deleteTempEmail(email);
                    url = "/login.jsp";
                } else {

                    request.setAttribute("user", user);
                    request.setAttribute("userResetToken", token);
                    url = "/resetpassword.jsp";
                }
            } else {
                message = "Token is expired!!";
                request.setAttribute("message", message);
                url = "/signup.jsp";
            }
            //url="/login.jsp";
        } catch (ParseException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    getServletContext().getRequestDispatcher(url).forward(request, response);
}

From source file:com.cubusmail.gwtui.server.services.MailboxService.java

public GWTMailFolder[] retrieveFolderTree() throws Exception {

    long millis = System.currentTimeMillis();

    IMailbox mailbox = SessionManager.get().getMailbox();
    try {/*  w  w w  .ja v  a2 s. c  o m*/
        mailbox.reloadFolder();
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
        throw new GWTMessageException(e.getMessage());
    }
    GWTMailFolder[] result = ConvertUtil.convert(mailbox.getMailFolderList());

    log.debug("Time for retrieveFolderTree(): " + (System.currentTimeMillis() - millis) + "ms");

    return result;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from  w  w w .  j  a v a 2  s  . c  o m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAsteriskSchemaPooledObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "schemaObj");
        }
    }

    ICFAsteriskSchema dbSchema = null;
    try {
        CFSecurityAuthorization auth = schemaObj.getAuthorization();
        if (auth != null) {
            response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");
            return;
        }

        dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();
        ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        String passwordHash = systemUser.getRequiredPasswordHash();
        if ((passwordHash == null) || (passwordHash.length() <= 0) || passwordHash.equals("bootstrap")) {
            response.sendRedirect("CFAsteriskSMWarSetSystemPasswordHtml");
        }

        ICFSecurityClusterObj resolvedCluster;
        ICFSecuritySysClusterObj sysCluster = schemaObj.getSysClusterTableObj().readSysClusterByIdIdx(1, false);
        if (sysCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "sysCluster");
        }
        resolvedCluster = sysCluster.getRequiredContainerCluster();
        if (resolvedCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName,
                    "resolvedCluster");
        }
        String clusterDomainName = resolvedCluster.getRequiredFullDomainName();
        String clusterDescription = resolvedCluster.getRequiredDescription();

        String loginId = (String) request.getParameter("LoginId");
        if ((loginId == null) || (loginId.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("You must specify a login id to reset.");
            out.println("<p style=\"text-align:center\">");
            out.println("Enter the login you'd like to request a password reset for.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok, Request Password Reset\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                            + clusterDescription + " Security Manager Login</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecuritySecUserObj authenticatingUser = schemaObj.getSecUserTableObj()
                .readSecUserByULoginIdx(loginId, true);
        if (authenticatingUser == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Login id not found.");
            out.println("<p style=\"text-align:center\">");
            out.println("Enter the login you'd like to request a password reset for.");
            out.println("<p>");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Login Id:</th><td><input type=\"text\" name=\"LoginId\"/></td></tr>");
            out.println(
                    "<tr><td colspan=\"2\" style=\"text-align:center\"><button type=\"submit\" name=\"Ok, Request Password Reset\"\">Ok</button></td></tr>");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                            + clusterDescription + " Security Manager Login</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        if (null != authenticatingUser.getOptionalPasswordResetUuid()) {

            sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">INFO</H2>");
            out.println("<p style=\"text-align:center\">");
            out.println("Password reset email resent.");
            out.println("<center>");
            out.println("<table style=\"width:60%\">");
            out.println(
                    "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                            + clusterDescription + " Security Manager Login</A></td></tr>");
            out.println("</table>");
            out.println("</center>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
        }

        ICFSecurityClusterObj systemCluster = schemaObj.getClusterTableObj()
                .readClusterByUDomainNameIdx("system");
        ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        auth = new CFSecurityAuthorization();
        auth.setSecCluster(systemCluster);
        auth.setSecTenant(systemTenant);
        auth.setSecSession(systemSession);
        schemaObj.setAuthorization(auth);

        ICFSecuritySecUserEditObj editAuthenticatingUser = authenticatingUser.beginEdit();
        editAuthenticatingUser.setOptionalPasswordResetUuid(UUID.randomUUID());
        editAuthenticatingUser.update();
        editAuthenticatingUser.endEdit();

        editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setOptionalFinish(Calendar.getInstance());
        editSystemSession.update();
        editSystemSession.endEdit();

        schemaObj.setAuthorization(null);

        schemaObj.commit();

        sendPasswordResetEMail(request, authenticatingUser, resolvedCluster);

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarRequestResetPasswordHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<H2 style=\"text-align:center\">INFO</H2>");
        out.println("<p style=\"text-align:center\">");
        out.println(
                "Password reset email sent.  Please use the links in the email to set a new password or to cancel the request.");
        out.println("<center>");
        out.println("<table style=\"width:60%\">");
        out.println(
                "<tr><td colSpan=\"2\" style=\"text-align:center\"><A HRef=\"CFAsteriskSMWarLoginHtml\">Back to "
                        + clusterDescription + " Security Manager Login</A></td></tr>");
        out.println("</table>");
        out.println("</center>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
    } catch (MessagingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught MessagingException -- " + e.getMessage(), e);
    } catch (NamingException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NamingException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}