Example usage for javax.mail.internet AddressException getMessage

List of usage examples for javax.mail.internet AddressException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails)
        throws UIException, JSONException {

    String token = createToken(csid);
    EmailData ed = spec.getEmailData();//from  w  w w .  java 2 s  .c  o m
    String[] recipients = new String[1];

    /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */
    String messagebase = ed.getPasswordResetMessage();
    String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam;
    String message = messagebase.replaceAll("\\{\\{link\\}\\}", link);
    String greeting = userdetails.getJSONObject("fields").getString("screenName");
    message = message.replaceAll("\\{\\{greeting\\}\\}", greeting);
    message = message.replaceAll("\\\\n", "\\\n");
    message = message.replaceAll("\\\\r", "\\\r");

    String SMTP_HOST_NAME = ed.getSMTPHost();
    String SMTP_PORT = ed.getSMTPPort();
    String subject = ed.getPasswordResetSubject();
    String from = ed.getFromAddress();
    if (ed.getToAddress().isEmpty()) {
        recipients[0] = emailparam;
    } else {
        recipients[0] = ed.getToAddress();
    }
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", ed.doSMTPAuth());
    props.put("mail.debug", ed.doSMTPDebug());
    props.put("mail.smtp.port", SMTP_PORT);

    Session session = Session.getDefaultInstance(props);
    // XXX fix to allow authpassword /username

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom;
    try {
        addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setText(message);

        Transport.send(msg);
    } catch (AddressException e) {
        throw new UIException("AddressException: " + e.getMessage());
    } catch (MessagingException e) {
        throw new UIException("MessagingException: " + e.getMessage());
    }

    return true;
}

From source file:ru.org.linux.user.RegisterController.java

@RequestMapping(value = "/register.jsp", method = RequestMethod.POST)
public ModelAndView doRegister(HttpServletRequest request, @Valid @ModelAttribute("form") RegisterRequest form,
        Errors errors, @RequestParam(required = false) String oldpass) throws Exception {
    HttpSession session = request.getSession();
    Template tmpl = Template.getTemplate(request);

    boolean changeMode = "change".equals(request.getParameter("mode"));

    String nick;//from   ww  w . j  a  va 2s.  c  om

    if (changeMode) {
        if (!tmpl.isSessionAuthorized()) {
            throw new AccessViolationException("Not authorized");
        }

        nick = tmpl.getNick();
    } else {
        nick = form.getNick();

        if (Strings.isNullOrEmpty(nick)) {
            errors.rejectValue("nick", null, "  nick");
        }

        if (nick != null && !StringUtil.checkLoginName(nick)) {
            errors.rejectValue("nick", null, " ? ?");
        }

        if (nick != null && nick.length() > User.MAX_NICK_LENGTH) {
            errors.rejectValue("nick", null, "?  ? ?");
        }
    }

    String password = Strings.emptyToNull(form.getPassword());

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(null, "   ? ? ");
    }

    InternetAddress mail = null;

    if (Strings.isNullOrEmpty(form.getEmail())) {
        errors.rejectValue("email", null, "?  e-mail");
    } else {
        try {
            mail = new InternetAddress(form.getEmail());
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    String url = null;

    if (!Strings.isNullOrEmpty(form.getUrl())) {
        url = URLUtil.fixURL(form.getUrl());
    }

    if (!changeMode) {
        if (Strings.isNullOrEmpty(password)) {
            errors.reject(null, "    ?");
        }
    }

    String name = Strings.emptyToNull(form.getName());

    if (name != null) {
        name = StringUtil.escapeHtml(name);
    }

    String town = null;

    if (!Strings.isNullOrEmpty(form.getTown())) {
        town = StringUtil.escapeHtml(form.getTown());
    }

    String info = null;

    if (!Strings.isNullOrEmpty(form.getInfo())) {
        info = StringUtil.escapeHtml(form.getInfo());
    }

    if (!changeMode && !errors.hasErrors()) {
        captcha.checkCaptcha(request, errors);

        if (session.getAttribute("register-visited") == null) {
            logger.info("Flood protection (not visited register.jsp) " + request.getRemoteAddr());
            errors.reject(null, "? ,   ");
        }
    }

    ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors);

    boolean emailChanged = false;

    if (changeMode) {
        User user = userDao.getUser(nick);

        if (!user.matchPassword(oldpass)) {
            errors.reject(null, "? ");
        }

        user.checkAnonymous();

        String newEmail = null;

        if (mail != null) {
            if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) {
                newEmail = null;
            } else {
                if (userDao.getByEmail(mail.getAddress()) != null) {
                    errors.rejectValue("email", null, " email  ???");
                }

                newEmail = mail.getAddress();

                emailChanged = true;
            }
        }

        if (!errors.hasErrors()) {
            userDao.updateUser(user, name, url, newEmail, town, password, info);

            if (emailChanged) {
                sendEmail(tmpl, user.getNick(), mail.getAddress(), false);
            }
        } else {
            return new ModelAndView("register-update");
        }
    } else {
        if (userDao.isUserExists(nick)) {
            errors.rejectValue("nick", null,
                    " " + nick + "  ??");
        }

        if (url != null && !URLUtil.isUrl(url)) {
            errors.rejectValue("url", null, "? URL");
        }

        if (mail != null && userDao.getByEmail(mail.getAddress()) != null) {
            errors.rejectValue("email", null,
                    " ?  e-mail  ?. "
                            + "?    ? , ??  ??? ?");
        }

        if (!errors.hasErrors()) {
            int userid = userDao.createUser(name, nick, password, url, mail, town, info);

            String logmessage = "?  " + nick + " (id="
                    + userid + ") " + LorHttpUtils.getRequestIP(request);
            logger.info(logmessage);

            sendEmail(tmpl, nick, mail.getAddress(), true);
        } else {
            return new ModelAndView("register");
        }
    }

    if (changeMode) {
        if (emailChanged) {
            String msg = " ?  ?.  ? ?   ? email.";

            return new ModelAndView("action-done", "message", msg);
        } else {
            return new ModelAndView(new RedirectView("/people/" + nick + "/profile"));
        }
    } else {
        return new ModelAndView("action-done", "message",
                " ?  ?.  ? ?  .");
    }
}

From source file:net.sourceforge.vulcan.mailer.EmailPlugin.java

private void sendMessages(BuildCompletedEvent event, final ProjectConfigDto projectConfig,
        final Map<Locale, List<String>> subscribers) {
    for (Map.Entry<Locale, List<String>> ent : subscribers.entrySet()) {
        try {//from w ww .  ja v a2  s  .  co m
            final URL sandboxURL = generateSandboxURL(projectConfig);
            final URL statusURL = generateStatusURL();
            URL trackerURL = null;

            if (StringUtils.isNotBlank(projectConfig.getBugtraqUrl())) {
                trackerURL = new URL(projectConfig.getBugtraqUrl());
            }

            final Document document = projectDomBuilder.createProjectDocument(event.getStatus(), ent.getKey());

            final String content = generateXhtml(document, sandboxURL, statusURL, trackerURL, ent.getKey());

            final MimeMessage message = messageAssembler.constructMessage(
                    StringUtils.join(ent.getValue().iterator(), ","), config, event.getStatus(), content);

            sendMessage(message);
        } catch (AddressException e) {
            eventHandler.reportEvent(new ErrorEvent(this, "errors.address.exception",
                    new Object[] { e.getRef(), e.getMessage() }, e));
        } catch (MessagingException e) {
            eventHandler.reportEvent(
                    new ErrorEvent(this, "errors.messaging.exception", new Object[] { e.getMessage() }, e));
        } catch (Exception e) {
            eventHandler
                    .reportEvent(new ErrorEvent(this, "errors.exception", new Object[] { e.getMessage() }, e));
        }
    }
}

From source file:fsi_admin.JSmtpConn.java

private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY,
        StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart,
        MimeMultipart multipart) {/*from w  w  w . ja v a  2  s  .  co m*/
    // Create a message with the specified information. 
    try {
        mmsg.setFrom(new InternetAddress(FROM));
        mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO));
        mmsg.setSubject(SUBJECT);
        messagebodypart.setContent(BODY, MIMETYPE);
        multipart.addBodyPart(messagebodypart);
        return true;
    } catch (AddressException e) {
        e.printStackTrace();
        msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage());
        return false;
    } catch (MessagingException e) {
        e.printStackTrace();
        msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage());
        return false;
    }
}

From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java

/**
 * ?????<code> InternetAddress </code>???
 *
 * @param addressList/*from  w  w  w . ja va  2s .com*/
 *            ???
 * @return <code> InternetAddress </code>??
 */
private InternetAddress[] getAddress(String[] addressList) {
    InternetAddress toAddress[] = null;
    Vector<InternetAddress> list = new Vector<InternetAddress>();
    if (addressList != null) {
        for (String address : addressList) {
            try {
                list.add(new InternetAddress(address));
            } catch (AddressException e) {
                m_log.info("getAddress() : " + e.getClass().getSimpleName() + ", " + address + ", "
                        + e.getMessage());
            }
        }
        if (list.size() > 0) {
            toAddress = new InternetAddress[list.size()];
            list.copyInto(toAddress);
        }
    }
    return toAddress;
}

From source file:hudson.tasks.MailSender.java

private MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener)
        throws MessagingException, UnsupportedEncodingException {
    MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    // TODO: I'd like to put the URL to the page in here,
    // but how do I obtain that?
    msg.addHeader("X-Jenkins-Job", build.getProject().getDisplayName());
    msg.addHeader("X-Jenkins-Result", build.getResult().toString());
    msg.setContent("", "text/plain");
    msg.setFrom(Mailer.StringToAddress(Mailer.descriptor().getAdminAddress(), charset));
    msg.setSentDate(new Date());

    String replyTo = Mailer.descriptor().getReplyToAddress();
    if (StringUtils.isNotBlank(replyTo)) {
        msg.setReplyTo(new Address[] { Mailer.StringToAddress(replyTo, charset) });
    }/*from  w  ww. ja  v  a  2  s.  c  o m*/

    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    String defaultSuffix = Mailer.descriptor().getDefaultSuffix();
    StringTokenizer tokens = new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        if (address.startsWith("upstream-individuals:")) {
            // people who made a change in the upstream
            String projectName = address.substring("upstream-individuals:".length());
            AbstractProject up = Jenkins.getInstance().getItem(projectName, build.getProject(),
                    AbstractProject.class);
            if (up == null) {
                listener.getLogger().println("No such project exist: " + projectName);
                continue;
            }
            includeCulpritsOf(up, build, listener, rcp);
        } else {
            // ordinary address

            // if not a valid address (i.e. no '@'), then try adding suffix
            if (!address.contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) {
                address += defaultSuffix;
            }

            try {
                rcp.add(Mailer.StringToAddress(address, charset));
            } catch (AddressException e) {
                // report bad address, but try to send to other addresses
                listener.getLogger().println("Unable to send to address: " + address);
                e.printStackTrace(listener.error(e.getMessage()));
            }
        }
    }

    for (AbstractProject project : includeUpstreamCommitters) {
        includeCulpritsOf(project, build, listener, rcp);
    }

    if (sendToIndividuals) {
        Set<User> culprits = build.getCulprits();

        if (debug)
            listener.getLogger()
                    .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)=="
                            + culprits.size());

        rcp.addAll(buildCulpritList(listener, culprits));
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));

    AbstractBuild<?, ?> pb = build.getPreviousBuild();
    if (pb != null) {
        MailMessageIdAction b = pb.getAction(MailMessageIdAction.class);
        if (b != null) {
            msg.setHeader("In-Reply-To", b.messageId);
            msg.setHeader("References", b.messageId);
        }
    }

    return msg;
}

From source file:nl.yenlo.transport.msews.EWSPollTableEntry.java

@Override
public boolean loadConfiguration(ParameterInclude paramIncl) throws AxisFault {

    if (paramIncl instanceof TransportInDescription) {
        // This is called when the transport is first initialized (at server start)...
        // We dont initialize the transport at this stage...
        return false;
    } else {//from w  w w  . j  av  a2s  . c o m

        String address = ParamUtils.getRequiredParam(paramIncl, EWSTransportConstants.MAIL_EWS_EMAILADDRESS);
        try {
            emailAddress = new InternetAddress(address);
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '"
                    + EWSTransportConstants.MAIL_EWS_EMAILADDRESS + "' parameter :: " + e.getMessage());
        }

        password = ParamUtils.getRequiredParam(paramIncl, EWSTransportConstants.MAIL_EWS_PASSWORD);

        try {
            String replyAddress = ParamUtils.getOptionalParam(paramIncl,
                    EWSTransportConstants.TRANSPORT_MAIL_REPLY_ADDRESS);
            if (replyAddress != null) {
                this.replyAddress = new InternetAddress(replyAddress);
            }
        } catch (AddressException e) {
            throw new AxisFault("Invalid email address specified by '"
                    + EWSTransportConstants.TRANSPORT_MAIL_REPLY_ADDRESS + "' parameter :: " + e.getMessage());
        }

        // Getting the attachment folder Default is the system tempora
        String attachmentFolder = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.MAIL_EWS_ATTACHMENT_FOLDER);
        if (attachmentFolder != null) {
            this.attachmentFolder = attachmentFolder;
        }

        // setting the transport.ews.extractType parameter if it exists in the optional parameter
        try {
            String extractType = ParamUtils.getOptionalParam(paramIncl,
                    EWSTransportConstants.MAIL_EWS_EXTRACT_TYPE);
            if (extractType != null) {
                this.extractType = this.extractType.valueOf(extractType.toUpperCase());
            }
        } catch (EnumConstantNotPresentException e) {
            throw new AxisFault("Invalid parameter ExtractType specified by '"
                    + EWSTransportConstants.MAIL_EWS_EXTRACT_TYPE + "' parameter :: " + e.getMessage());
        }

        String transportFolderNameValue = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.MAIL_EWS_FOLDER);
        try {
            if (transportFolderNameValue != null) {
                folder = getFolderId(transportFolderNameValue);

            }
        } catch (Exception e) {
            throw new EwsMailClientConfigException(
                    "The " + EWSTransportConstants.MAIL_EWS_FOLDER + " parameters is either not found or null",
                    e);
        }

        // EWS configuration
        password = ParamUtils.getRequiredParam(paramIncl, EWSTransportConstants.MAIL_EWS_PASSWORD);
        serviceUrl = ParamUtils.getRequiredParam(paramIncl, EWSTransportConstants.MAIL_EWS_URL);
        domain = ParamUtils.getRequiredParam(paramIncl, EWSTransportConstants.MAIL_EWS_DOMAIN);

        addPreserveHeaders(
                ParamUtils.getOptionalParam(paramIncl, EWSTransportConstants.TRANSPORT_MAIL_PRESERVE_HEADERS));
        addRemoveHeaders(
                ParamUtils.getOptionalParam(paramIncl, EWSTransportConstants.TRANSPORT_MAIL_REMOVE_HEADERS));

        try {
            String option = ParamUtils.getOptionalParam(paramIncl,
                    EWSTransportConstants.TRANSPORT_MAIL_ACTION_AFTER_PROCESS);
            if (option != null) {
                actionAfterProcess = ActionType.valueOf(option);
            }
        } catch (EnumConstantNotPresentException ecnpe) {
            log.error("The supplied " + EWSTransportConstants.TRANSPORT_MAIL_ACTION_AFTER_PROCESS
                    + " is not supported. Please use one of the following "
                    + StringUtils.join(ActionType.values()));
            throw ecnpe;
        }

        try {
            String option = ParamUtils.getOptionalParam(paramIncl,
                    EWSTransportConstants.TRANSPORT_MAIL_ACTION_AFTER_FAILURE);
            if (option != null) {
                actionAfterFailure = ActionType.valueOf(option);
            }
        } catch (EnumConstantNotPresentException ecnpe) {
            log.error("The supplied " + EWSTransportConstants.TRANSPORT_MAIL_ACTION_AFTER_FAILURE
                    + " is not supported. Please use one of the following "
                    + StringUtils.join(ActionType.values()));
            throw ecnpe;
        }

        moveAfterProcess = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.TRANSPORT_MAIL_MOVE_AFTER_PROCESS);
        moveAfterFailure = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.TRANSPORT_MAIL_MOVE_AFTER_FAILURE);

        String processInParallel = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.TRANSPORT_MAIL_PROCESS_IN_PARALLEL);
        if (processInParallel != null) {
            processingMailInParallel = Boolean.parseBoolean(processInParallel);
            if (log.isDebugEnabled() && processingMailInParallel) {
                log.debug("Parallel mail processing enabled for : " + address);
            }
        }

        String pollInParallel = ParamUtils.getOptionalParam(paramIncl,
                BaseConstants.TRANSPORT_POLL_IN_PARALLEL);
        if (pollInParallel != null) {
            setConcurrentPollingAllowed(Boolean.parseBoolean(pollInParallel));
            if (log.isDebugEnabled() && isConcurrentPollingAllowed()) {
                log.debug("Concurrent mail polling enabled for : " + address);
            }
        }

        String msgCountParamValue = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.MAIL_EWS_MAX_MSG_COUNT);
        // When msgCountParamValue not an integer then an exception will be thrown. Thats good! :)
        messageCount = msgCountParamValue == null ? messageCount : Integer.parseInt(msgCountParamValue);

        String optionalParam = ParamUtils.getOptionalParam(paramIncl,
                EWSTransportConstants.TRANSPORT_MAIL_EXTRACTTYPE);
        try {
            if (optionalParam != null) {
                extractType = ExtractType.valueOf(optionalParam);
            }
        } catch (EnumConstantNotPresentException ecnpe) {
            log.error("The supplied " + EWSTransportConstants.TRANSPORT_MAIL_EXTRACTTYPE
                    + " is not supported. Please use one of the following "
                    + StringUtils.join(ExtractType.values()));
            throw ecnpe;
        }

        optionalParam = ParamUtils.getOptionalParam(paramIncl, EWSTransportConstants.TRANSPORT_MAIL_DELETETYPE);
        try {
            if (optionalParam != null) {
                deleteActionType = DeleteActionType.valueOf(optionalParam);
            }
        } catch (EnumConstantNotPresentException ecnpe) {
            log.error("The supplied " + EWSTransportConstants.TRANSPORT_MAIL_DELETETYPE
                    + " is not supported. Please use one of the following "
                    + StringUtils.join(DeleteActionType.values()));
            throw ecnpe;
        }

    }
    return super.loadConfiguration(paramIncl);
}

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

public void saveMessageAsDraft(GWTMessage message) throws Exception {

    try {/*from  w  w  w. ja va  2s  .c  o  m*/
        log.debug("saving message to draft...");
        MessageHandler messageHandler = SessionManager.get().getCurrentComposeMessage();
        IMailbox mailbox = SessionManager.get().getMailbox();
        IMailFolder draftFolder = mailbox.getDraftFolder();
        messageHandler.setGWTMessage(message);
        messageHandler.saveToFolder(draftFolder, true);

        // if there is the original message to delete
        if (message.getId() > 0) {
            long[] deleteId = new long[] { message.getId() };
            deleteMessages(deleteId);
        }
        log.debug("...successful");
    } catch (AddressException e) {
        log.error(e.getMessage(), e);
        throw new GWTInvalidAddressException(e.getMessage(), e.getRef());
    } 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.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/wbmail")
public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) {
    model.clear();/*from   ww w .  j a v  a2s  . c o  m*/

    try {
        WBEmail email = new WBEmail();
        HttpSession session = req.getSession();
        String userName = session.getAttribute("userName").toString();
        String toAddress = req.getParameter("email");

        if (!WebUtil.isValidEmail(toAddress)) {
            throw new Exception("invalid email");

        }

        //TODO validate message contents
        email.setFromUser(userName);
        email.setToAddress(toAddress);

        WhiteBoard wb = getWhiteBoard(req);
        if (wb == null) {
            throw new Exception("Invalid White Board");
        }

        email.setWbKey(wb.getKey());
        email.setCreationTime(System.currentTimeMillis());

        Properties props = new Properties();
        Session mailsession = Session.getDefaultInstance(props, null);

        String emailError = null;
        try {
            MimeMessage msg = new MimeMessage(mailsession);
            msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            msg.setSubject("Please join the whiteboard session on " + req.getServerName());
            String msgBody = "To join " + userName
                    + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName()
                    + "/whiteboard/" + req.getParameter("wbId") + "</a>";
            msg.setText(msgBody, "UTF-8", "html");
            Transport.send(msg);

        } catch (AddressException e) {
            emailError = e.getMessage();
        } catch (MessagingException e) {
            emailError = e.getMessage();
        }

        if (emailError == null) {
            email.setStatus(WBEmail.STATUS_SENT);
        } else {
            email.setStatus(WBEmail.STATUS_ERROR);
        }

        getPM().makePersistent(email);

        if (email.getStatus() == WBEmail.STATUS_ERROR) {
            throw new Exception(emailError);
        }

        model.put("status", "ok");

    } catch (Exception e) {
        model.put("error", e.getMessage());
    }

    return doJSON(model);
}

From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java

/**
 * Creates MimeMessage with supplied values
 * /*from  w  w w.j  av a  2 s . c o  m*/
 * @param to - to email address
 * @param docType - String value for the attached document type
 * @param subject - Subject for the email
 * @param instructions - email body
 * @param content - content to be sent as attachment
 * @return MimeMessage instance
 */
public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content,
        String metadataXMl, String title, String indexBodyToken, String readmeToken) {
    final MimeMessage msg = mailSender.createMimeMessage();
    UUID uniqueID = UUID.randomUUID();
    tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID);
    try {
        msg.setFrom(new InternetAddress(getFrom()));
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // The readable part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(instructions);
        mbp1.setHeader("Content-Type", "text/plain");

        // The notification
        final MimeBodyPart mbp2 = new MimeBodyPart();

        final String contentType = "application/xml; charset=UTF-8";

        String extension;

        // HL7 messages should be a txt file, otherwise xml
        if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) {
            extension = TXT_EXT;
        } else {
            extension = XML_EXT;
        }

        final String fileName = docType + UUID.randomUUID() + extension;

        //            final DataSource ds = new AttachmentDS(fileName, content, contentType);
        //            mbp2.setDataHandler(new DataHandler(ds));

        /******** START NHIN COMPLIANCE CHANGES *****/

        boolean isTempZipFolderCreated = tempZipFolder.mkdirs();
        if (!isTempZipFolderCreated) {
            LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath());
        }

        String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM"));
        String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT"));

        indexFileString = StringUtils.replace(indexFileString, "@document_title@", title);
        indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString);

        readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken);
        FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString);

        // move template files & replace tokens
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false);
        //            FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false);

        // create sub-directories
        String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01";
        File nhinSubDirectory = new File(nhinSubDirectoryPath);
        boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs();
        if (!isNhinSubDirectoryCreated) {
            LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
            throw new ApplicationRuntimeException(
                    "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath());
        }
        FileOutputStream metadataStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/METADATA.XML"));
        metadataStream.write(metadataXMl.getBytes());
        metadataStream.flush();
        metadataStream.close();
        FileOutputStream documentStream = new FileOutputStream(
                new File(nhinSubDirectoryPath + "/DOCUMENT" + extension));
        documentStream.write(content.getBytes());
        documentStream.flush();
        documentStream.close();

        String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP";
        byte[] buffer = new byte[1024];
        //            FileOutputStream fos = new FileOutputStream(zipFile);
        //            ZipOutputStream zos = new ZipOutputStream(fos);

        List<String> fileList = generateFileList(tempZipFolder);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size());
        ZipOutputStream zos = new ZipOutputStream(bout);
        //            LOG.info("File List size: "+fileList.size());
        for (String file : fileList) {
            ZipEntry ze = new ZipEntry(file);
            zos.putNextEntry(ze);
            FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file);
            int len;
            while ((len = in.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }
            in.close();
        }
        zos.closeEntry();
        // remember close it
        zos.close();

        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        mbp2.setDataHandler(new DataHandler(source));
        mbp2.setFileName(docType + ".ZIP");

        /******** END NHIN COMPLIANCE CHANGES *****/

        //            mbp2.setFileName(fileName);
        //            mbp2.setHeader("Content-Type", contentType);

        final Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        //            FileUtils.deleteDirectory(tempZipFolder);
    } catch (AddressException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (MessagingException e) {
        LOG.error("Error creating email message!");
        throw new ApplicationRuntimeException("Error creating message!", e);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw new ApplicationRuntimeException(e.getMessage());
    } finally {
        //reset filelist contents
        fileList = new ArrayList<String>();
    }
    return msg;
}