<commit_before>package com.almende.dialog.adapter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;

import com.almende.dialog.accounts.AdapterConfig;
import com.almende.dialog.agent.AdapterAgent;
import com.almende.dialog.agent.tools.TextMessage;
import com.almende.dialog.state.StringStore;
import com.almende.dialog.util.ServerUtils;
import com.almende.util.TypeUtil;


public class MailServlet extends TextServlet implements Runnable, MessageChangedListener, MessageCountListener, ConnectionListener, StoreListener {

    public static final String SENDING_PROTOCOL_KEY = "SENDING_PROTOCOL";
    public static final String SENDING_HOST_KEY = "SENDING_HOST";
    public static final String SENDING_PORT_KEY = "SENDING_PORT";
    public static final String RECEIVING_PROTOCOL_KEY = "RECEIVING_PROTOCOL";
    public static final String RECEIVING_HOST_KEY = "RECEIVING_HOST";
    
    public static final String GMAIL_SENDING_PORT = "465";
    public static final String GMAIL_SENDING_HOST = "smtp.gmail.com";
    public static final String GMAIL_SENDING_PROTOCOL = "smtps";
    public static final String GMAIL_RECEIVING_HOST = "imap.gmail.com";
    public static final String GMAIL_RECEIVING_PROTOCOL = "imaps";
    public static final String CC_ADDRESS_LIST_KEY = "cc_email";
    public static final String BCC_ADDRESS_LIST_KEY = "bcc_email";
	private static final long serialVersionUID = 6892283600126803780L;
	private static final String servletPath = "/_ah/mail/";
	
	public void doErrorPost(HttpServletRequest req, HttpServletResponse res) {}
	
	private AdapterConfig adapterConfig = null;
	public MailServlet()
	{
	    
	}
	
	public MailServlet( AdapterConfig adapterConfig )
    {
	    this.adapterConfig = adapterConfig;
    }
	
	@Override
	protected TextMessage receiveMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		Properties props = new Properties();
		javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, null);
		
		MimeMessage message = new MimeMessage(mailSession, req.getInputStream());
		
		String uri = req.getRequestURI();
		String recipient = uri.substring(servletPath.length());
		
		/*Address[] recipients = message.getAllRecipients();
		Address recipient=null;
		if (recipients.length>0){
			recipient = recipients[0];
		}*/ 
		return receiveMessage( message, recipient );
	}

    /**
     * method separated from the original
     * @link{MailServlet#receiveMessage(HttpServletRequest,
     * HttpServletResponse)} so that it can be tested without any data mock-ups.
     * @since 3/09/2013
     */
    private TextMessage receiveMessage( MimeMessage message, String recipient ) throws Exception
    {
        TextMessage msg = new TextMessage();
        msg.setSubject( "RE: " + message.getSubject() );
        if ( recipient != null && !recipient.equals( "" ) )
        {
            msg.setLocalAddress( recipient.toString() );
        }
        else
        {
            Address[] recipients = message.getAllRecipients();
            if ( recipients.length > 0 )
            {
                InternetAddress recip = (InternetAddress) recipients[0];
                msg.setLocalAddress( recip.getAddress() );
            }
            else
                throw new Exception( "MailServlet: Can't determine local address! (Dev)" );
        }

        Address[] senders = message.getFrom();
        if ( senders != null && senders.length > 0 )
        {
            InternetAddress sender = (InternetAddress) senders[0];
            msg.setAddress( sender.getAddress() );
            msg.setRecipientName( sender.getPersonal() );
        }

        Multipart mp = null;
        if ( message.getContent() instanceof Multipart )
        {
            mp = (Multipart) message.getContent();
        }
        else
        {
            mp = new MimeMultipart();
            mp.addBodyPart( new MimeBodyPart( new InternetHeaders(), message.getContent().toString().getBytes() ) );
        }
        if ( mp.getCount() > 0 )
        {
            msg.setBody( mp.getBodyPart( 0 ).getContent().toString() );
            log.info( "Receive mail: " + msg.getBody() );
        }
        return msg;
    }

    @Deprecated
    /**
     * @Deprecated use broadcastMessage instead
     */
    @Override
    protected int sendMessage( String message, String subject, String from, String fromName, String to, String toName,
        Map<String, Object> extras, AdapterConfig config ) throws Exception
    {
        HashMap<String, String> addressNameMap = new HashMap<>( 1 );
        addressNameMap.put( to, toName );
        return broadcastMessage( message, subject, from, fromName, addressNameMap, extras, config );
    }
	
    @Override
    protected int broadcastMessage( String message, String subject, String from, String senderName,
        Map<String, String> addressNameMap, Map<String, Object> extras, AdapterConfig config ) throws Exception
    {
        final String sendingHost = adapterConfig.getProperties().get( SENDING_HOST_KEY ) != null ? adapterConfig
            .getProperties().get( SENDING_HOST_KEY ).toString() : GMAIL_SENDING_HOST;
        final String sendingPort = adapterConfig.getProperties().get( SENDING_PORT_KEY ) != null ? adapterConfig
            .getProperties().get( SENDING_PORT_KEY ).toString() : GMAIL_SENDING_PORT;
        final String sendingProtocol = adapterConfig.getProperties().get( SENDING_PROTOCOL_KEY ) != null ? adapterConfig
            .getProperties().get( SENDING_PROTOCOL_KEY ).toString() : GMAIL_SENDING_PROTOCOL;
        final String username = config.getXsiUser();
        final String password = config.getXsi<PASSWORD>();
        Properties props = new Properties();
        props.put( "mail.smtp.host", sendingHost );
        props.put( "mail.smtp.port", sendingPort );
        props.put( "mail.smtp.user", username );
        props.put( "mail.smtp.password", password );
        props.put( "mail.smtp.auth", "true" );
        Session session = Session.getDefaultInstance( props );
        Message simpleMessage = new MimeMessage( session );
        try
        {
            log.info( String.format(
                "sending email from: %s senderName: %s to: %s with params: host: %s port: %s user: %s ", from,
                senderName, ServerUtils.serialize( addressNameMap ), sendingHost, sendingPort, username ) );<commit_msg>fix: rookie mistake with email adapter :)<commit_after>package com.almende.dialog.adapter;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.event.MessageChangedEvent;
import javax.mail.event.MessageChangedListener;
import javax.mail.event.MessageCountEvent;
import javax.mail.event.MessageCountListener;
import javax.mail.event.StoreEvent;
import javax.mail.event.StoreListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.InternetHeaders;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.joda.time.DateTime;

import com.almende.dialog.accounts.AdapterConfig;
import com.almende.dialog.agent.AdapterAgent;
import com.almende.dialog.agent.tools.TextMessage;
import com.almende.dialog.state.StringStore;
import com.almende.dialog.util.ServerUtils;
import com.almende.util.TypeUtil;


public class MailServlet extends TextServlet implements Runnable, MessageChangedListener, MessageCountListener, ConnectionListener, StoreListener {

    public static final String SENDING_PROTOCOL_KEY = "SENDING_PROTOCOL";
    public static final String SENDING_HOST_KEY = "SENDING_HOST";
    public static final String SENDING_PORT_KEY = "SENDING_PORT";
    public static final String RECEIVING_PROTOCOL_KEY = "RECEIVING_PROTOCOL";
    public static final String RECEIVING_HOST_KEY = "RECEIVING_HOST";
    
    public static final String GMAIL_SENDING_PORT = "465";
    public static final String GMAIL_SENDING_HOST = "smtp.gmail.com";
    public static final String GMAIL_SENDING_PROTOCOL = "smtps";
    public static final String GMAIL_RECEIVING_HOST = "imap.gmail.com";
    public static final String GMAIL_RECEIVING_PROTOCOL = "imaps";
    public static final String CC_ADDRESS_LIST_KEY = "cc_email";
    public static final String BCC_ADDRESS_LIST_KEY = "bcc_email";
	private static final long serialVersionUID = 6892283600126803780L;
	private static final String servletPath = "/_ah/mail/";
	
	public void doErrorPost(HttpServletRequest req, HttpServletResponse res) {}
	
	private AdapterConfig adapterConfig = null;
	public MailServlet()
	{
	    
	}
	
	public MailServlet( AdapterConfig adapterConfig )
    {
	    this.adapterConfig = adapterConfig;
    }
	
	@Override
	protected TextMessage receiveMessage(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		Properties props = new Properties();
		javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, null);
		
		MimeMessage message = new MimeMessage(mailSession, req.getInputStream());
		
		String uri = req.getRequestURI();
		String recipient = uri.substring(servletPath.length());
		
		/*Address[] recipients = message.getAllRecipients();
		Address recipient=null;
		if (recipients.length>0){
			recipient = recipients[0];
		}*/ 
		return receiveMessage( message, recipient );
	}

    /**
     * method separated from the original
     * @link{MailServlet#receiveMessage(HttpServletRequest,
     * HttpServletResponse)} so that it can be tested without any data mock-ups.
     * @since 3/09/2013
     */
    private TextMessage receiveMessage( MimeMessage message, String recipient ) throws Exception
    {
        TextMessage msg = new TextMessage();
        msg.setSubject( "RE: " + message.getSubject() );
        if ( recipient != null && !recipient.equals( "" ) )
        {
            msg.setLocalAddress( recipient.toString() );
        }
        else
        {
            Address[] recipients = message.getAllRecipients();
            if ( recipients.length > 0 )
            {
                InternetAddress recip = (InternetAddress) recipients[0];
                msg.setLocalAddress( recip.getAddress() );
            }
            else
                throw new Exception( "MailServlet: Can't determine local address! (Dev)" );
        }

        Address[] senders = message.getFrom();
        if ( senders != null && senders.length > 0 )
        {
            InternetAddress sender = (InternetAddress) senders[0];
            msg.setAddress( sender.getAddress() );
            msg.setRecipientName( sender.getPersonal() );
        }

        Multipart mp = null;
        if ( message.getContent() instanceof Multipart )
        {
            mp = (Multipart) message.getContent();
        }
        else
        {
            mp = new MimeMultipart();
            mp.addBodyPart( new MimeBodyPart( new InternetHeaders(), message.getContent().toString().getBytes() ) );
        }
        if ( mp.getCount() > 0 )
        {
            msg.setBody( mp.getBodyPart( 0 ).getContent().toString() );
            log.info( "Receive mail: " + msg.getBody() );
        }
        return msg;
    }

    @Deprecated
    /**
     * @Deprecated use broadcastMessage instead
     */
    @Override
    protected int sendMessage( String message, String subject, String from, String fromName, String to, String toName,
        Map<String, Object> extras, AdapterConfig config ) throws Exception
    {
        HashMap<String, String> addressNameMap = new HashMap<>( 1 );
        addressNameMap.put( to, toName );
        return broadcastMessage( message, subject, from, fromName, addressNameMap, extras, config );
    }
	
    @Override
    protected int broadcastMessage( String message, String subject, String from, String senderName,
        Map<String, String> addressNameMap, Map<String, Object> extras, AdapterConfig config ) throws Exception
    {
        final String sendingHost = config.getProperties().get( SENDING_HOST_KEY ) != null ? config.getProperties()
            .get( SENDING_HOST_KEY ).toString() : GMAIL_SENDING_HOST;
        final String sendingPort = config.getProperties().get( SENDING_PORT_KEY ) != null ? config.getProperties()
            .get( SENDING_PORT_KEY ).toString() : GMAIL_SENDING_PORT;
        final String sendingProtocol = config.getProperties().get( SENDING_PROTOCOL_KEY ) != null ? config
            .getProperties().get( SENDING_PROTOCOL_KEY ).toString() : GMAIL_SENDING_PROTOCOL;
        final String username = config.getXsiUser();
        final String password = config.getXsi<PASSWORD>();
        Properties props = new Properties();
        props.put( "mail.smtp.host", sendingHost );
        props.put( "mail.smtp.port", sendingPort );
        props.put( "mail.smtp.user", username );
        props.put( "mail.smtp.password", password );
        props.put( "mail.smtp.auth", "true" );
        Session session = Session.getDefaultInstance( props );
        Message simpleMessage = new MimeMessage( session );
        try
        {
            log.info( String.format(
                "sending email from: %s senderName: %s to: %s with params: host: %s port: %s user: %s ", from,
                senderName, ServerUtils.serialize( addressNameMap ), sendingHost, sendingPort, username ) );
{'fraction_non_alphanumeric': 0.09959486833220797, 'fraction_numerical': 0.0051316677920324105, 'mean_word_length': 3.3193350831146105, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2144943', 'n_tokens_mistral': 4248, 'n_tokens_neox': 4081, 'n_words': 1014}