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:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * We can assume that the recipients of this message are all going to the
 * same mail server. We will now rely on the JNDI to do DNS MX record lookup
 * and try to deliver to the multiple mail servers. If it fails, it should
 * throw an exception./* w ww .  j a  v  a 2 s . co  m*/
 * 
 * Creation date: (2/24/00 11:25:00 PM)
 * 
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param session
 *            javax.mail.Session
 * @return boolean Whether the delivery was successful and the message can
 *         be deleted
 */
private boolean deliver(QuedItem qi, Session session) {
    MailAddress rcpt = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)");
        }
        MailImpl mail = (MailImpl) qi.getMail();
        MimeMessage message = mail.getMessage();
        // Create an array of the recipients as InternetAddress objects
        Collection recipients = mail.getRecipients();
        InternetAddress addr[] = new InternetAddress[recipients.size()];
        int j = 0;
        // funky ass look because you can't getElementAt() in a Collection

        for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
            MailAddress currentRcpt = (MailAddress) i.next();
            addr[j] = currentRcpt.toInternetAddress();
        }
        if (addr.length <= 0) {
            if (log.isDebugEnabled()) {
                log.debug("No recipients specified... returning");
            }
            return true;
        }
        // Figure out which servers to try to send to. This collection
        // will hold all the possible target servers
        Collection targetServers = null;
        Iterator it = recipients.iterator();
        while (it.hasNext()) {
            rcpt = (MailAddress) recipients.iterator().next();
            if (!qi.recepientHasBeenHandled(rcpt)) {
                break;
            }
        }
        // theoretically it is possible to not hav eone that hasn't been
        // handled
        // however that's only if something has gone really wrong.
        if (rcpt != null) {
            String host = rcpt.getHost();
            // Lookup the possible targets
            try {
                // targetServers = MXLookup.urlsForHost(host); // farking
                // unreliable jndi bs
                targetServers = getMXRecordsForHost(host);
            } catch (Exception e) {
                log.error(e);
            }
            if (targetServers == null || targetServers.size() == 0) {
                log.warn("No mail server found for: " + host);
                StringBuffer exceptionBuffer = new StringBuffer(128)
                        .append("I found no MX record entries for the hostname ").append(host)
                        .append(".  I cannot determine where to send this message.");
                return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true);
            } else if (log.isTraceEnabled()) {
                log.trace(targetServers.size() + " servers found for " + host);
            }
            MessagingException lastError = null;
            Iterator i = targetServers.iterator();
            while (i.hasNext()) {
                try {
                    URLName outgoingMailServer = (URLName) i.next();
                    StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ")
                            .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString())
                            .append(" to addresses ").append(Arrays.asList(addr));
                    if (log.isDebugEnabled()) {
                        log.debug(logMessageBuffer.toString());
                    }
                    ;
                    // URLName urlname = new URLName("smtp://"
                    // + outgoingMailServer);
                    Properties props = session.getProperties();
                    if (mail.getSender() == null) {
                        props.put("mail.smtp.from", "<>");
                    } else {
                        String sender = mail.getSender().toString();
                        props.put("mail.smtp.from", sender);
                    }
                    // Many of these properties are only in later JavaMail
                    // versions
                    // "mail.smtp.ehlo" //default true
                    // "mail.smtp.auth" //default false
                    // "mail.smtp.dsn.ret" //default to nothing... appended
                    // as
                    // RET= after MAIL FROM line.
                    // "mail.smtp.dsn.notify" //default to
                    // nothing...appended as
                    // NOTIFY= after RCPT TO line.
                    Transport transport = null;
                    try {
                        transport = session.getTransport(outgoingMailServer);
                        try {
                            transport.connect();
                        } catch (MessagingException me) {
                            log.error(me);
                            // Any error on connect should cause the mailet
                            // to
                            // attempt
                            // to connect to the next SMTP server associated
                            // with this MX record,
                            // assuming the number of retries hasn't been
                            // exceeded.
                            if (failMessage(qi, rcpt, me, false)) {
                                return true;
                            } else {
                                continue;
                            }
                        }
                        transport.sendMessage(message, addr);
                        // log.debug("message sent to " +addr);
                        /*TODO: catch failures that should result 
                         * in failure with no retries
                         } catch (SendFailedException sfe){
                           qi.failForRecipient(que, );
                           */
                    } finally {
                        if (transport != null) {
                            transport.close();
                            transport = null;
                        }
                    }
                    logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName())
                            .append(") sent successfully to ").append(outgoingMailServer);
                    log.debug(logMessageBuffer.toString());
                    qi.succeededForRecipient(que, rcpt);
                    return true;
                } catch (MessagingException me) {
                    log.error(me);
                    // MessagingException are horribly difficult to figure
                    // out
                    // what actually happened.
                    StringBuffer exceptionBuffer = new StringBuffer(256)
                            .append("Exception delivering message (").append(mail.getName()).append(") - ")
                            .append(me.getMessage());
                    log.warn(exceptionBuffer.toString());
                    if ((me.getNextException() != null)
                            && (me.getNextException() instanceof java.io.IOException)) {
                        // This is more than likely a temporary failure
                        // If it's an IO exception with no nested exception,
                        // it's probably
                        // some socket or weird I/O related problem.
                        lastError = me;
                        continue;
                    }
                    // This was not a connection or I/O error particular to
                    // one
                    // SMTP server of an MX set. Instead, it is almost
                    // certainly
                    // a protocol level error. In this case we assume that
                    // this
                    // is an error we'd encounter with any of the SMTP
                    // servers
                    // associated with this MX record, and we pass the
                    // exception
                    // to the code in the outer block that determines its
                    // severity.
                    throw me;
                } // end catch
            } // end while
              // If we encountered an exception while looping through,
              // throw the last MessagingException we caught. We only
              // do this if we were unable to send the message to any
              // server. If sending eventually succeeded, we exit
              // deliver() though the return at the end of the try
              // block.
            if (lastError != null) {
                throw lastError;
            }
        } // END if (rcpt != null)
        else {
            log.error("unable to find recipient that handn't already been handled");
        }
    } catch (SendFailedException sfe) {
        log.error(sfe);
        boolean deleteMessage = false;
        Collection recipients = qi.getMail().getRecipients();
        // Would like to log all the types of email addresses
        if (log.isDebugEnabled()) {
            log.debug("Recipients: " + recipients);
        }
        /*
         * The rest of the recipients failed for one reason or another.
         * 
         * SendFailedException actually handles this for us. For example, if
         * you send a message that has multiple invalid addresses, you'll
         * get a top-level SendFailedException that that has the valid,
         * valid-unsent, and invalid address lists, with all of the server
         * response messages will be contained within the nested exceptions.
         * [Note: the content of the nested exceptions is implementation
         * dependent.]
         * 
         * sfe.getInvalidAddresses() should be considered permanent.
         * sfe.getValidUnsentAddresses() should be considered temporary.
         * 
         * JavaMail v1.3 properly populates those collections based upon the
         * 4xx and 5xx response codes.
         * 
         */
        if (sfe.getInvalidAddresses() != null) {
            Address[] address = sfe.getInvalidAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse invalid address: " + pe.getMessage());
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Invalid recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, true);
            }
        }
        if (sfe.getValidUnsentAddresses() != null) {
            Address[] address = sfe.getValidUnsentAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse unsent address: " + pe.getMessage());
                        }
                        pe.printStackTrace();
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unsent recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, false);
            }
        }
        return deleteMessage;
    } catch (MessagingException ex) {
        log.error(ex);
        // We should do a better job checking this... if the failure is a
        // general
        // connect exception, this is less descriptive than more specific
        // SMTP command
        // failure... have to lookup and see what are the various Exception
        // possibilities
        // Unable to deliver message after numerous tries... fail
        // accordingly
        // We check whether this is a 5xx error message, which
        // indicates a permanent failure (like account doesn't exist
        // or mailbox is full or domain is setup wrong).
        // We fail permanently if this was a 5xx error
        return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0)));
    } catch (Throwable t) {
        log.error(t);
    }
    /*
     * If we get here, we've exhausted the loop of servers without sending
     * the message or throwing an exception. One case where this might
     * happen is if we get a MessagingException on each transport.connect(),
     * e.g., if there is only one server and we get a connect exception.
     * Return FALSE to keep run() from deleting the message.
     */
    return false;
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Send message.//from   w ww  . j  ava 2  s  . c o  m
 *
 * @param messageBody MIME message body
 * @throws IOException on error
 */
public void sendMessage(byte[] messageBody) throws IOException {
    try {
        sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:davmail.exchange.dav.DavExchangeSession.java

@Override
public void sendMessage(MimeMessage mimeMessage) throws IOException {
    try {//from   w  w w  .ja  v a  2s.c  om
        // need to create draft first
        String itemName = UUID.randomUUID().toString() + ".EML";
        HashMap<String, String> properties = new HashMap<String, String>();
        properties.put("draft", "9");
        String contentType = mimeMessage.getContentType();
        if (contentType != null && contentType.startsWith("text/plain")) {
            properties.put("messageFormat", "1");
        } else {
            properties.put("mailOverrideFormat",
                    String.valueOf(ENCODING_PREFERENCE | ENCODING_MIME | BODY_ENCODING_TEXT_AND_HTML));
            properties.put("messageFormat", "2");
        }
        createMessage(DRAFTS, itemName, properties, mimeMessage);
        MoveMethod method = new MoveMethod(URIUtil.encodePath(getFolderPath(DRAFTS + '/' + itemName)),
                URIUtil.encodePath(getFolderPath(SENDMSG)), false);
        // set header if saveInSent is disabled 
        if (!Settings.getBooleanProperty("davmail.smtpSaveInSent", true)) {
            method.setRequestHeader("Saveinsent", "f");
        }
        moveItem(method);
    } catch (MessagingException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *///from   w  ww.  j a  v a2  s.  c  om
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:com.krawler.hrms.hrmsHandler.java

public static void addRecruitersFunction(Session session, HttpServletRequest request)
        throws ServiceException, SessionException, HibernateException {
    //Status 0=pending,1=accepted,2=rejected,3=Not sent
    List tabledata = null;/*  w ww .j  ava  2s  .  com*/
    String hql = null;
    Recruiter pos = null;
    try {
        String[] recids = null;
        Company cmpid = (Company) session.get(Company.class, AuthHandler.getCompanyid(request));
        User u = (User) session.get(User.class, AuthHandler.getUserid(request));
        if (StringUtil.isNullOrEmpty(request.getParameter("delrec"))) {
            recids = request.getParameterValues("jobids");
            for (int i = 0; i < recids.length; i++) {
                hql = "from Recruiter where recruit.userID=? ";
                tabledata = HibernateUtil.executeQuery(session, hql, recids[i]);
                if (!tabledata.isEmpty()) {
                    pos = (Recruiter) tabledata.get(0);
                    pos.setDelflag(0);
                    session.update(pos);
                    //@@ProfileHandler.insertAuditLog(session, AuditAction.SET_AS_INTERVIEWER, "User  " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)) + " has set " + AuthHandler.getFullName(pos.getRecruit()) + " as interviewer",request);
                } else {
                    User md = (User) session.load(User.class, recids[i]);
                    String id = UUID.randomUUID().toString();
                    Recruiter contact = new Recruiter();
                    contact.setRid(id);
                    contact.setRecruit(md);
                    contact.setDelflag(0);
                    session.save(contact);
                    //@@ProfileHandler.insertAuditLog(session, AuditAction.SET_AS_INTERVIEWER, "User  " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)) + " has set " + AuthHandler.getFullName(contact.getRecruit()) + " as interviewer",request);
                }
            }
        } else {
            String[] delrecids = request.getParameterValues("appid");
            for (int i = 0; i < delrecids.length; i++) {
                String query = "from Recruiter where recruit.userID=?";
                tabledata = HibernateUtil.executeQuery(session, query, delrecids[i]);
                if (!tabledata.isEmpty()) {
                    pos = (Recruiter) tabledata.get(0);
                    pos.setDelflag(3);
                    //@@ProfileHandler.insertAuditLog(session, AuditAction.UNASSIGN_INTERVIEWER, "User  " + AuthHandler.getFullName(pos.getRecruit()) + " has been unassigned  as interviewer by " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)),request);
                    session.update(pos);
                }
            }
        }
        if (StringUtil.isNullOrEmpty(request.getParameter("delrec"))) {
            for (int i = 0; i < recids.length; i++) {
                User r = (User) session.get(User.class, recids[i]);
                Useraccount ua = (Useraccount) session.get(Useraccount.class, r.getUserID());
                String fullname = AuthHandler.getFullName(r);
                String uri = URLUtil.getPageURL(request, Links.loginpagewthFull, cmpid.getSubDomain())
                        + "jspfiles/Confirmation.jsp?c=" + cmpid.getCompanyID() + "&u=" + r.getUserID()
                        + "&acpt=";
                String pmsg = String.format(HrmsMsgs.interviewerSelectionpln, fullname);
                String htmlmsg = String.format(HrmsMsgs.interviewerSelectionHTML, fullname, uri + "1",
                        uri + "0", AuthHandler.getFullName(u), ua.getDesignationid().getValue(),
                        cmpid.getCompanyName());
                try {
                    SendMailHandler.postMail(new String[] { r.getEmailID() }, HrmsMsgs.interviewerSubject,
                            htmlmsg, pmsg, u.getEmailID());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (SessionExpiredException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (HibernateException ex) {
        throw ServiceException.FAILURE("Failure hrms.Handler", ex);
    }
}

From source file:com.krawler.hrms.hrmsHandler.java

public static void applyforjobexternal(Session session, HttpServletRequest request)
        throws ServiceException, SessionExpiredException, ParseException, JSONException {
    String status = "Pending";
    Date date1;/*from   w  w w . j a  v  a  2 s . c o m*/
    DateFormat formatter;
    String positions = "";
    Jobapplicant applicant = null;
    User user = null;
    String applicantid;
    try {
        formatter = new SimpleDateFormat("MM/dd/yyyy");
        date1 = (Date) formatter.parse(request.getParameter("applydt"));
        Allapplications allapl = null;
        if (StringUtil.isNullOrEmpty(request.getParameter("apcntid"))) {
            applicantid = AuthHandler.getUserid(request);
        } else {
            applicantid = request.getParameter("apcntid");
        }
        if (Integer.parseInt(request.getParameter("employeetype")) == 1) {
            user = (User) session.load(User.class, applicantid);
        } else {
            applicant = (Jobapplicant) session.load(Jobapplicant.class, applicantid);
        }
        Company cmp = (Company) session.load(Company.class, AuthHandler.getCompanyid(request));
        CompanyPreferences cmpPref = (CompanyPreferences) session.load(CompanyPreferences.class,
                cmp.getCompanyID());
        String[] ids = request.getParameterValues("posid");
        for (int i = 0; i < ids.length; i++) {
            Positionmain position = (Positionmain) session.load(Positionmain.class, ids[i]);
            allapl = new Allapplications();
            allapl.setStatus(status);
            allapl.setApplydate(date1);
            if (Integer.parseInt(request.getParameter("employeetype")) == 1) {
                allapl.setEmployee(user);
                allapl.setEmployeetype(1);
            } else {
                allapl.setJobapplicant(applicant);
                allapl.setEmployeetype(0);
            }
            allapl.setPosition(position);
            allapl.setCompany(cmp);
            allapl.setDelflag(0);
            allapl.setApplicationflag(0);
            allapl.setRejectedbefore(0);
            session.save(allapl);
            positions += "" + position.getJobid() + ":" + position.getPosition().getValue() + ",";
            if (Integer.parseInt(request.getParameter("employeetype")) == 1) {
                //@@ProfileHandler.insertAuditLog(session, AuditAction.APPLY_FOR_JOB, "User  " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)) + " has applied for job position " + allapl.getPosition().getJobid(),request);
            } else {
                if (request.getSession().getAttribute("userid") != null) {
                    //@@ProfileHandler.insertAuditLog(session, AuditAction.APPLY_FOR_JOB, "User  " + AuthHandler.getFullName(session, AuthHandler.getUserid(request)) + " has applied external applicant " + allapl.getJobapplicant().getFirstname() + " " + allapl.getJobapplicant().getLastname() + " for job position " + allapl.getPosition().getJobid(),request);
                }
            }
        }
        if (!(Integer.parseInt(request.getParameter("employeetype")) == 1)) {
            String cmpname = cmp.getCompanyName();
            positions = positions.replace(positions.substring(positions.length() - 1), "");
            String pmsg = String.format(HrmsMsgs.jobPlnmsg,
                    (applicant.getFirstname() + " " + applicant.getLastname()), cmpname, cmpname);
            String htmlmsg = String.format(HrmsMsgs.jobHTMLmsg,
                    allapl.getPosition().getPosition().getValue() + "["
                            + (allapl.getPosition().getJobid() != null ? allapl.getPosition().getJobid() : "")
                            + "]",
                    cmpname, cmpname);
            String subject = String.format(HrmsMsgs.jobSubject,
                    (allapl.getPosition().getJobid() != null ? allapl.getPosition().getJobid() : ""),
                    allapl.getPosition().getPosition().getValue());
            try {
                SendMailHandler.postMail(new String[] { applicant.getEmail() }, subject, htmlmsg, pmsg,
                        cmp.getEmailID());
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    } catch (ParseException ex) {
        throw new JSONException("applyforjobexternal");
    } catch (SessionExpiredException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailMessage wrapMessage(Message msg, boolean populateContent, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    // Prepare subject
    String subject = msg.getSubject();
    if (!StringUtils.isBlank(subject)) {
        AntiSamy as = new AntiSamy();
        CleanResults cr = as.scan(subject, policy);
        subject = cr.getCleanHTML();//  www.  ja  va  2s  .  co  m
    }

    // Prepare content if requested
    EmailMessageContent msgContent = null; // default...
    if (populateContent) {
        // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
        try {
            msgContent = getMessageContent(msg.getContent(), msg.getContentType());
        } catch (MessagingException me) {
            // We are unable to read digitally-signed messages (perhaps
            // others?) in the API-standard way;  we have to use a work around.
            // See: http://www.oracle.com/technetwork/java/faq-135477.html#imapserverbug
            // Logging as DEBUG because this behavior is known & expected.
            log.debug("Difficulty reading a message (digitally signed?). Attempting workaround...");
            try {
                MimeMessage mm = (MimeMessage) msg;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                mm.writeTo(bos);
                bos.close();
                SharedByteArrayInputStream bis = new SharedByteArrayInputStream(bos.toByteArray());
                MimeMessage copy = new MimeMessage(session, bis);
                bis.close();
                msgContent = getMessageContent(copy.getContent(), copy.getContentType());
            } catch (Throwable t) {
                log.error("Failed to read message body", t);
                msgContent = new EmailMessageContent("UNABLE TO READ MESSAGE BODY: " + t.getMessage(), false);
            }
        }

        // Sanitize with AntiSamy
        String content = msgContent.getContentString();
        if (!StringUtils.isBlank(content)) {
            AntiSamy as = new AntiSamy();
            CleanResults cr = as.scan(content, policy);
            content = cr.getCleanHTML();
        }
        msgContent.setContentString(content);
    }

    int messageNumber = msg.getMessageNumber();

    // Prepare the UID if present
    String uid = null; // default
    if (msg.getFolder() instanceof UIDFolder) {
        uid = Long.toString(((UIDFolder) msg.getFolder()).getUID(msg));
    }

    Address[] addr = msg.getFrom();
    String sender = getFormattedAddresses(addr);
    Date sentDate = msg.getSentDate();

    boolean unread = !msg.isSet(Flag.SEEN);
    boolean answered = msg.isSet(Flag.ANSWERED);
    boolean deleted = msg.isSet(Flag.DELETED);
    // Defend against the dreaded: "Unable to load BODYSTRUCTURE"
    boolean multipart = false; // sensible default;
    String contentType = null; // sensible default
    try {
        multipart = msg.getContentType().toLowerCase().startsWith(CONTENT_TYPE_ATTACHMENTS_PATTERN);
        contentType = msg.getContentType();
    } catch (MessagingException me) {
        // Message was digitally signed and we are unable to read it;
        // logging as DEBUG because this issue is known/expected, and
        // because the user's experience is in no way affected (at this point)
        log.debug("Message content unavailable (digitally signed?);  "
                + "message will appear in the preview table correctly, " + "but the body will not be viewable");
        log.trace(me.getMessage(), me);
    }
    String to = getTo(msg);
    String cc = getCc(msg);
    String bcc = getBcc(msg);
    return new EmailMessage(messageNumber, uid, sender, subject, sentDate, unread, answered, deleted, multipart,
            contentType, msgContent, to, cc, bcc);
}

From source file:com.ephesoft.gxt.admin.server.BatchClassManagementServiceImpl.java

@Override
public Boolean verifyEmailConfig(final EmailConfigurationDTO emailConfigDTO) {
    Boolean isMailConfigCorrect = false;
    LOGGER.debug("Entering the Email config verification method");
    try {/*from ww  w  . ja  v a 2 s .  c  om*/
        String password = emailConfigDTO.getPassword();
        String mailPassword = EphesoftEncryptionUtil.getDecryptedPasswordString(password);
        // Create a store object with user credentials and server properties
        final Store mailStore = MailUtil.getMailStore(emailConfigDTO.getServerType(),
                emailConfigDTO.getServerName(), emailConfigDTO.getUserName(), mailPassword,
                emailConfigDTO.getPortNumber(), emailConfigDTO.getIsSSL());
        // Try to connect to the given folder in the store. If the return object is null, then error.
        if (null != mailStore
                && null != MailUtil.getFolderFromMailStore(mailStore, emailConfigDTO.getFolderName())) {
            isMailConfigCorrect = true;
        }
    } catch (MessagingException e) {
        LOGGER.error(EphesoftStringUtil.concatenate("Email configuration is incorrect.", e.getMessage()), e);
    }
    LOGGER.debug(EphesoftStringUtil.concatenate("Is Email config correct : \t", isMailConfigCorrect));
    return isMailConfigCorrect;
}

From source file:com.zimbra.cs.service.mail.ToXML.java

private static Element addPart(VisitPhase phase, Element parent, Element root, MPartInfo mpi,
        Set<MPartInfo> bodies, String prefix, int maxSize, boolean neuter, boolean excludeCalendarParts,
        String defaultCharset, boolean swallowContentExceptions, MsgContent wantContent)
        throws ServiceException {
    if (phase == VisitPhase.POSTVISIT) {
        return null;
    }/*w  ww . j a v a2  s. c o  m*/
    String ctype = StringUtil.stripControlCharacters(mpi.getContentType());

    if (excludeCalendarParts && MimeConstants.CT_TEXT_CALENDAR.equalsIgnoreCase(ctype)) {
        // A true calendar part has "method" parameter in the content type.  Otherwise it's just an attachment
        // that happens to be a .ics file.
        try {
            ContentType ct = new ContentType(mpi.getMimePart().getContentType());
            if (ct.getParameter("method") != null) {
                return null;
            }
        } catch (MessagingException e) {
        }
    }

    Element el = parent.addNonUniqueElement(MailConstants.E_MIMEPART);
    MimePart mp = mpi.getMimePart();

    String part = mpi.getPartName();
    part = prefix + (prefix.isEmpty() || part.isEmpty() ? "" : ".") + part;
    el.addAttribute(MailConstants.A_PART, part);

    String fname = Mime.getFilename(mp);
    if (MimeConstants.CT_XML_ZIMBRA_SHARE.equals(ctype)) {
        // the <shr> share info goes underneath the top-level <m>
        Element shr = root.addNonUniqueElement(MailConstants.E_SHARE_NOTIFICATION);
        try {
            addContent(shr, mpi, maxSize, defaultCharset);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing share XML", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing share XML", e);
            }
        }
    } else if (MimeConstants.CT_XML_ZIMBRA_DL_SUBSCRIPTION.equals(ctype)) {
        // the <dlSubs> dl subscription info goes underneath the top-level <m>
        Element dlSubs = root.addNonUniqueElement(MailConstants.E_DL_SUBSCRIPTION_NOTIFICATION);
        try {
            addContent(dlSubs, mpi, maxSize, defaultCharset);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing DL subscription", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing DL subscription", e);
            }
        }
    } else if (MimeConstants.CT_TEXT_ENRICHED.equals(ctype)) {
        // we'll be replacing text/enriched with text/html
        ctype = MimeConstants.CT_TEXT_HTML;
    } else if (fname != null && (MimeConstants.CT_APPLICATION_OCTET_STREAM.equals(ctype)
            || MimeConstants.CT_APPLICATION_TNEF.equals(ctype))) {
        String guess = MimeDetect.getMimeDetect().detect(fname);
        if (guess != null) {
            ctype = guess;
        }
    }
    el.addAttribute(MailConstants.A_CONTENT_TYPE, ctype);

    if (mpi.isMultipart()) {
        return el; // none of the below stuff is relevant for a multipart, so just return now...
    }

    // figure out attachment size
    try {
        el.addAttribute(MailConstants.A_SIZE, Mime.getSize(mp));
    } catch (Exception e) { // don't put out size if we get exception
        ZimbraLog.mailbox.warn("Unable to determine MIME part size: %s", e.getMessage());
    }

    // figure out attachment disposition
    try {
        String disp = mp.getHeader("Content-Disposition", null);
        if (disp != null) {
            ContentDisposition cdisp = new ContentDisposition(MimeUtility.decodeText(disp));
            el.addAttribute(MailConstants.A_CONTENT_DISPOSITION,
                    StringUtil.stripControlCharacters(cdisp.getDisposition()));
        }
    } catch (MessagingException e) {
    } catch (UnsupportedEncodingException e) {
    }

    // figure out attachment name
    try {
        if (fname == null && MimeConstants.CT_MESSAGE_RFC822.equals(ctype)) {
            // "filename" for attached messages is the Subject
            Object content = Mime.getMessageContent(mp);
            if (content instanceof MimeMessage) {
                fname = Mime.getSubject((MimeMessage) content);
            }
        }
        if (!Strings.isNullOrEmpty(fname)) {
            el.addAttribute(MailConstants.A_CONTENT_FILENAME, StringUtil.stripControlCharacters(fname));
        }
    } catch (MessagingException me) {
    } catch (IOException ioe) {
    }

    // figure out content-id (used in displaying attached images)
    String cid = mpi.getContentID();
    if (cid != null) {
        el.addAttribute(MailConstants.A_CONTENT_ID, StringUtil.stripControlCharacters(cid));
    }
    // figure out content-location (used in displaying attached images)
    try {
        String cl = mp.getHeader("Content-Location", null);
        if (cl != null) {
            el.addAttribute(MailConstants.A_CONTENT_LOCATION, StringUtil.stripControlCharacters(cl));
        }
    } catch (MessagingException e) {
    }

    // include the part's content if this is the displayable "memo part",
    // or if it was requested to include all parts
    if (bodies == null || bodies.contains(mpi)) {
        if (bodies != null) {
            el.addAttribute(MailConstants.A_BODY, true);
        }

        try {
            addContent(el, mpi, maxSize, neuter, defaultCharset, wantContent);
        } catch (IOException e) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing part content", e);
            } else {
                LOG.warn("error writing body part", e);
            }
        } catch (MessagingException me) {
            if (!swallowContentExceptions) {
                throw ServiceException.FAILURE("error serializing part content", me);
            }
        }
    }

    return el;
}