package com.casamind.adware.server.servlet.mail;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Logger;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import com.casamind.adware.server.domain.Company;
import com.casamind.adware.server.domain.Publisher;
import com.casamind.adware.server.domain.Slot;
import com.casamind.adware.server.proxy.DatastoreProxy;
import com.casamind.adware.shared.SlotStatus;
@SuppressWarnings("serial")
public class InboundMailHandler extends HttpServlet {
private static final Logger log = Logger.getLogger(InboundMailHandler.class.getName());
private Integer duration = 15;
private Integer price = 500;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = config.getServletContext();
duration = Integer.parseInt(context.getInitParameter("defaultSlotDurationInMinutes"));
price = Integer.parseInt(context.getInitParameter("defaultSlotPriceInCurrencyUnit"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session, request.getInputStream());
// Extract out the important fields from the Mime Message
String subject = message.getSubject();
String sender = message.getSender().toString();
String from = message.getFrom()[0].toString();
log.info("Got an email!");
log.info("Sender: " + sender);
log.info("From: " + from);
log.info("Subject: " + subject);
if (subject.contains("New Event: ") && from.contains("casamind.com") && sender.contains("@google.com")) {
Multipart multipart = (Multipart) message.getContent();
for (int i = 0, n = multipart.getCount(); i < n; i++) {
Part part = multipart.getBodyPart(i);
String disposition = part.getDisposition();
if (disposition != null && disposition.equals(Part.ATTACHMENT)) {
if (part.getFileName().equals("invite.ics")) {
log.info("Found an iCal attachement. Filename: " + part.getFileName());
CalendarBuilder builder = new CalendarBuilder();
Calendar calendar = builder.build(part.getInputStream());
Component event = calendar.getComponent(Component.VEVENT);
Property startDate = event.getProperty(Property.DTSTART);
Property endDate = event.getProperty(Property.DTEND);
Property attendee = null;
String login = null;
for (Iterator j = event.getProperties(Property.ATTENDEE).iterator(); j.hasNext();) {
Property att = (Property) j.next();
if (!att.getValue().contains("@casamind.com")) {
attendee = att;
login = attendee.getValue().replace("mailto:", "");
}
}
if (attendee != null) {
log.info("Extracted attendee: " + login);
SimpleDateFormat icalFormatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
SimpleDateFormat logFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z");
Company company = DatastoreProxy.getCompanyByLogin(login);
if (company != null) {
log.info("Found company: " + company.getLastname());
Slot slot = new Slot();
slot.setOwnerId(company.getId());
log.info("DTSTART :" + startDate.getValue());
Date parsedStartDate = icalFormatter.parse(startDate.getValue());
log.info("Parsed start date :" + logFormatter.format(parsedStartDate));
log.info("DTEND :" + endDate.getValue());
Date parsedEndDate = icalFormatter.parse(endDate.getValue());
log.info("Parsed end date :" + logFormatter.format(parsedEndDate));
slot.setStartDate(parsedStartDate);
slot.setEndDate(parsedEndDate);
slot.setStatus(SlotStatus.Ordered);
long slotInterval = parsedEndDate.getTime() - parsedStartDate.getTime();
log.info("Interval in miliseconds: " + slotInterval);
long slotDurationInMilisecondes = (long) duration * 60 * 1000;
log.info("Default slot duration in miliseconds: " + slotDurationInMilisecondes);
long nbSlots = slotInterval / slotDurationInMilisecondes;
log.info("Number of slots (Long): " + nbSlots);
slot.setNbSlots((int) nbSlots);
slot.setPrice(price);
Slot entity = DatastoreProxy.createSlot(slot);
log.info("Created new slot for company:" + company.getLastname());
log.info(entity.toString());
} else {
log.info("Did not find a company with login: " + login);
log.info("Trying to a find a publisher with login: " + login);
Publisher publisher = DatastoreProxy.getPublisherByLogin(login);
if (publisher != null) {
log.info("Found publisher with login: " + publisher.getFirstname() + " " + publisher.getLastname());
Slot slot = new Slot();
slot.setOwnerId(publisher.getId());
log.info("DTSTART :" + startDate.getValue());
Date parsedStartDate = icalFormatter.parse(startDate.getValue());
log.info("Parsed start date :" + logFormatter.format(parsedStartDate));
log.info("DTEND :" + endDate.getValue());
Date parsedEndDate = icalFormatter.parse(endDate.getValue());
log.info("Parsed end date :" + logFormatter.format(parsedEndDate));
slot.setStartDate(parsedStartDate);
slot.setEndDate(parsedEndDate);
slot.setStatus(SlotStatus.Ordered);
long slotInterval = parsedEndDate.getTime() - parsedStartDate.getTime();
log.info("Interval in miliseconds: " + slotInterval);
long slotDurationInMilisecondes = (long) duration * 60 * 1000;
log.info("Default slot duration in miliseconds: " + slotDurationInMilisecondes);
long nbSlots = slotInterval / slotDurationInMilisecondes;
log.info("Number of slots (Long): " + nbSlots);
slot.setNbSlots((int) nbSlots);
slot.setPrice(price);
Slot entity = DatastoreProxy.createSlot(slot);
log.info("Created new slot for publisher:" + publisher.getFirstname() + " " + publisher.getLastname());
log.info(entity.toString());
} else {
log.warning("Could not find publisher: " + login);
}
}
} else {
log.warning("Could not extract attendee!");
}
}
}
}
} else {
log.info("Did not know what to do with it. Here is the Body : ");
message.writeTo(System.out);
forward(message, "calendar@avicenaweb.appspotmail.com", "avicena@casamind.com");
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void forward(MimeMessage message, String from, String to) {
try {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
// Create the message to forward
Message forward = new MimeMessage(session);
// Fill in header
forward.setSubject("Fwd: " + message.getSubject());
forward.setFrom(new InternetAddress(from));
forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Create your new message part
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here you go with the original message:\n\n");
// Create a multi-part to combine the parts
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Create and fill part for the forwarded content
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(message.getDataHandler());
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
// Send message
Transport.send(forward);
log.info("Forwarded an email to " + to + ". Subject : " + forward.getSubject());
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}