Skip to content

Instantly share code, notes, and snippets.

@stephen-maina
Last active November 21, 2022 19:51
Show Gist options
  • Save stephen-maina/246e543f5a5414094d92 to your computer and use it in GitHub Desktop.
Save stephen-maina/246e543f5a5414094d92 to your computer and use it in GitHub Desktop.
Basic Email activities using javamail and saving of files on a cloud storage facility eg. AWS
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.security.PermitAll;
import javax.mail.FetchProfile;
import javax.mail.FetchProfile.Item;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.UIDFolder;
import javax.mail.internet.ContentType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.ParseException;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.StreamingOutput;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.poi.util.IOUtils;
import org.atmosphere.cpr.AtmosphereFramework;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceFactory;
import org.atmosphere.cpr.BroadcasterFactory;
import org.atmosphere.util.ServletContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.CreateBucketRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.api.Account;
import com.api.MyDataSource;
import com.api.SecurityCheck;
import com.api.json.JSONArray;
import com.api.json.JSONObject;
import com.api.services.album.document.Document;
import com.api.utils.Utils;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPMessage;
@Path("resources/email")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED,
MediaType.MULTIPART_FORM_DATA })
public class Email {
private static Utils utils = new Utils();
private static Account acc = null;
private final Logger log = LoggerFactory.getLogger(Email.class);
private long[] messageDeletes;
// private static HashMap<StreamingOutput, String> attach = null;
private static int count = 0;
private static int closeBrackets = 0;
private static int levelIndex = 0;
private static String attachmentName = null;
private static boolean rfc822 = false;
// @Context
// ContainerRequestContext requestContext;
// String uuid=requestContext
// .getHeaderString("X-Atmosphere-tracking-id:");
ServletContext servletContext = ServletContextFactory.getDefault()
.getServletContext();
AtmosphereFramework framework = (AtmosphereFramework) servletContext
.getAttribute("AtmosphereServlet");
BroadcasterFactory broadcasterFactory = framework.getBroadcasterFactory();
AtmosphereResourceFactory atmosphereResourceFactory = framework
.atmosphereFactory();
@PermitAll
@POST
@Path("send")
@SecurityCheck
public Response sendEmail(@Context SecurityContext sc,
@FormParam("json") String json) {
// TODO deal with multiple uploads
acc = (Account) sc.getUserPrincipal();
String subject = null;
String emailMessage = null;
String recipientEmail = null;
String bccEmail = null;
String from = null;
String ccEmail = null;
JSONArray attachments = null;
String userEmail = null;
boolean attachment = false;
// System.out.println("uuid: "
// + (String) requestContext
// .getHeaderString("X-Atmosphere-tracking-id:"));
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("subject")) {
subject = object.getString("subject");
}
if (object.keySet().contains("user_email")) {
userEmail = object.getString("user_email");
}
if (object.keySet().contains("message")) {
emailMessage = object.getString("message");
}
if (object.keySet().contains("recipient")) {
recipientEmail = object.getString("recipient");
}
if (object.keySet().contains("bcc_email")) {
bccEmail = object.getString("bcc_email");
}
if (object.keySet().contains("from")) {
from = object.getString("from");
}
if (object.keySet().contains("cc_email")) {
ccEmail = object.getString("cc_email");
}
if (object.keySet().contains("attachment")) {
attachment = object.getBoolean("attachment");
}
if (object.keySet().contains("file")) {
attachments = object.getJSONArray("file");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
// System.out.println("part: " + part);
return sendEmail(subject, emailMessage, recipientEmail, bccEmail,
ccEmail, from, attachment, attachments, userEmail);
}
public Response sendEmail(String subject, String emailMessage,
String recipientEmail, String bccEmail, String ccEmail,
String from, boolean attachment, JSONArray attachments,
String userEmail) {
Folder sent = null;
Store store = null;
File tempFile = null;
try {
String host = utils.getEmailHost(acc.getAccountId(),
acc.getSchoolId(), from);
String password = utils.getEmailAccountsPassword(
acc.getAccountId(), acc.getSchoolId(), from);
String fromName = utils.getEmailUserName(acc.getAccountId(),
acc.getSchoolId(), from);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// deals with bounced messages
props.put("mail.smtp.from", userEmail);
Session session = Session.getInstance(props,
new DefaultAuthenticator(userEmail, password));
store = getStore(host, userEmail, password);
store.connect();
Folder[] folders = store.getDefaultFolder().list("*");
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("sent")) {
sent = fold;
}
}
if (sent == null) {
sent = (Folder) store.getFolder("Sent");
if (!sent.exists()) {
sent.create(Folder.HOLDS_MESSAGES);
}
}
sent.open(Folder.READ_WRITE);
System.out.println("folder: " + sent);
Message message = new MimeMessage(session);
if (recipientEmail != null && !recipientEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(recipientEmail, false));
}
if (ccEmail != null && !ccEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(ccEmail, false));
}
if (bccEmail != null && !bccEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(bccEmail, false));
}
message.setFrom(new InternetAddress(from, fromName));
if (subject != null && !subject.isEmpty()) {
message.setSubject(subject);
}
MimeBodyPart summaryBodyPart = new MimeBodyPart();
summaryBodyPart.setText(emailMessage);
summaryBodyPart.setContent(emailMessage, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(summaryBodyPart);
AmazonS3 s3Client = new AmazonS3Client(
new ProfileCredentialsProvider());
if (attachments != null && attachments.length() != 0) {
for (int index = 0; index < attachments.length(); index++) {
String fileName = attachments.getJSONObject(index)
.getString("file_name");
String albumId = attachments.getJSONObject(index)
.getString("album_id");
String key = fileName.replace(
"http://s3.amazonaws.com/schoolmart-document/", "");
// String key=fileName.replace("s3.amazonaws.com/", "");
S3Object object = s3Client.getObject(new GetObjectRequest(
"schoolmart-document", key));
InputStream objectData = object.getObjectContent();
// Process the objectData stream.
tempFile = File.createTempFile(
"schoolmart-email" + acc.getAccountId() + "-",
".tmp");
// tempFile.createNewFile();
tempFile.deleteOnExit();
try (OutputStream outpuStream = new FileOutputStream(
tempFile)) {
IOUtils.copy(objectData, outpuStream);
}
// TODO: SAVE FILE HERE
// if you want media type for validation, it's
// field.getMediaType()
System.out.println("file: " + tempFile + "\n exists: "
+ tempFile.exists());
if (attachment && tempFile.exists()) {
System.out.println("attahcment");
summaryBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(tempFile);
summaryBodyPart.setDataHandler(new DataHandler(source));
summaryBodyPart.setFileName(key.replace(albumId + "/"
+ acc.getAccountId() + "/", ""));
multipart.addBodyPart(summaryBodyPart);
}
if (objectData != null) {
objectData.close();
}
}
}
message.setContent(multipart);
Transport.send(message);
message.setFlag(Flag.SEEN, true);
sent.appendMessages(new Message[] { message });
return Response.ok("{\"message\":{\"sent\":\"true\"}}")
.cacheControl(utils.cacheControl()).build();
// append to sent folder
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
tempFile = null;
acc = null;
if (sent != null) {
sent.close(false);
sent = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String error = utils.createErrorResponse(Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong lease try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":{\"sent\":\"false\"},\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
}
private Store getStore(String host, String userEmail, String password)
throws NoSuchProviderException {
Properties props = new Properties();
System.out.println("password: " + password);
// server setting
props.put("mail.imap.host", host);
props.put("mail.imap.port", "993");
props.put("mail.imap.partialfetch", "false");
// SSL setting
props.setProperty("mail.imap.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.port", String.valueOf("993"));
Session session = Session.getInstance(props, new DefaultAuthenticator(
userEmail, password));
return session.getStore("imap");
}
@PermitAll
@POST
@Path("draft")
@SecurityCheck
public Response draftEmail(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String subject = null;
String emailMessage = null;
String recipientEmail = null;
String bccEmail = null;
String from = null;
JSONArray attachments = null;
String ccEmail = null;
String userEmail = null;
boolean attachment = false;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("subject")) {
subject = object.getString("subject");
}
if (object.keySet().contains("user_email")) {
userEmail = object.getString("user_email");
}
if (object.keySet().contains("message")) {
emailMessage = object.getString("message");
}
if (object.keySet().contains("recipient")) {
recipientEmail = object.getString("recipient");
}
if (object.keySet().contains("bcc_email")) {
bccEmail = object.getString("bcc");
}
if (object.keySet().contains("from")) {
from = object.getString("from");
}
if (object.keySet().contains("cc_email")) {
ccEmail = object.getString("cc_email");
}
if (object.keySet().contains("attachment")) {
attachment = object.getBoolean("attachment");
}
if (object.keySet().contains("file")) {
attachments = object.getJSONArray("file");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return draftEmail(subject, emailMessage, recipientEmail, bccEmail,
ccEmail, from, attachment, attachments, userEmail);
}
public Response draftEmail(String subject, String emailMessage,
String recipientEmail, String bccEmail, String ccEmail,
String from, boolean attachment, JSONArray attachments,
String userEmail) {
Folder draft = null;
Store store = null;
File tempFile = null;
try {
String host = utils.getEmailHost(acc.getAccountId(),
acc.getSchoolId(), from);
String password = utils.getEmailAccountsPassword(
acc.getAccountId(), acc.getSchoolId(), from);
String fromName = utils.getEmailUserName(acc.getAccountId(),
acc.getSchoolId(), from);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
String rec;
String bcc;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// deals with bounced messages
props.put("mail.smtp.from", userEmail);
Session session = Session.getInstance(props,
new DefaultAuthenticator(userEmail, password));
store = getStore(host, userEmail, password);
store.connect();
Folder[] folders = store.getDefaultFolder().list("*");
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("drafts")) {
draft = fold;
}
}
if (draft == null) {
draft = (Folder) store.getFolder("Drafts");
if (!draft.exists()) {
draft.create(Folder.HOLDS_MESSAGES);
}
}
System.out.println("draft: " + draft);
draft.open(Folder.READ_WRITE);
// if (draft == null) {
// String error = utils.createErrorResponse(Status.NOT_FOUND,
// "Please create a draft folder");
// return Response
// .status(Status.NOT_FOUND)
// .entity("{\"message\":{\"draft\":\"false\"},\"error\" : {"
// + error + " }}")
// .cacheControl(utils.cacheControl()).build();
// }
Message message = new MimeMessage(session);
if (recipientEmail != null && !recipientEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(recipientEmail, false));
}
if (ccEmail != null && !ccEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(ccEmail, false));
//
}
if (bccEmail != null && !bccEmail.isEmpty()) {
message.setRecipients(RecipientType.CC,
InternetAddress.parse(bccEmail, false));
//
}
message.setFrom(new InternetAddress(from, fromName));
if (subject != null && !subject.isEmpty()) {
message.setSubject(subject);
}
MimeBodyPart summaryBodyPart = new MimeBodyPart();
summaryBodyPart.setText(emailMessage);
summaryBodyPart.setContent(emailMessage, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(summaryBodyPart);
AmazonS3 s3Client = new AmazonS3Client(
new ProfileCredentialsProvider());
if (attachments != null && attachments.length() != 0) {
for (int index = 0; index < attachments.length(); index++) {
String fileName = attachments.getJSONObject(index)
.getString("file_name");
String albumId = attachments.getJSONObject(index)
.getString("album_id");
String key = fileName.replace(
"http://s3.amazonaws.com/schoolmart-document/", "");
// String key=fileName.replace("s3.amazonaws.com/", "");
S3Object object = s3Client.getObject(new GetObjectRequest(
"schoolmart-document", key));
InputStream objectData = object.getObjectContent();
// Process the objectData stream.
tempFile = File.createTempFile(
"schoolmart-email" + acc.getAccountId() + "-",
".tmp");
// tempFile.createNewFile();
tempFile.deleteOnExit();
try (OutputStream outpuStream = new FileOutputStream(
tempFile)) {
IOUtils.copy(objectData, outpuStream);
}
// TODO: SAVE FILE HERE
// if you want media type for validation, it's
// field.getMediaType()
System.out.println("file: " + tempFile + "\n exists: "
+ tempFile.exists());
if (attachment && tempFile.exists()) {
System.out.println("attahcment");
summaryBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(tempFile);
summaryBodyPart.setDataHandler(new DataHandler(source));
summaryBodyPart.setFileName(key.replace(albumId + "/"
+ acc.getAccountId() + "/", ""));
multipart.addBodyPart(summaryBodyPart);
}
if (objectData != null) {
objectData.close();
}
}
}
message.setContent(multipart);
message.setFlag(Flag.SEEN, true);
draft.appendMessages(new Message[] { message });
return Response.ok("{\"message\":{\"draft\":\"true\"}}")
.cacheControl(utils.cacheControl()).build();
// append to sent folder
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
acc = null;
tempFile = null;
if (draft != null) {
draft.close(false);
draft = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String error = utils.createErrorResponse(Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong lease try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":{\"sent\":\"false\"},\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
}
@PermitAll
@GET
@Path("search")
@SecurityCheck
public Response searchEmail(@Context SecurityContext sc,
@QueryParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String userName = null;
String folderName = null;
String subject = null;
String from = null;
boolean or = false;
boolean today = false;
try {
JSONObject object = new JSONObject(json);
folderName = object.getString("folder_name");
if (object.keySet().contains("subject")) {
subject = object.getString("subject");
}
if (object.keySet().contains("or")) {
or = object.getBoolean("or");
}
if (object.keySet().contains("today")) {
today = object.getBoolean("today");
}
if (object.keySet().contains("from")) {
from = object.getString("from");
}
userName = object.getString("user_name");
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return searchEmail(userName, folderName, subject, from, or, today);
}
/**
* Searches for e-mail messages containing the specified keyword in Subject
* field.
*
* @param host
* @param userName
* @param password
* @param keyword
*/
public Response searchEmail(String userName, String folderName,
String subject, String from, boolean or, boolean today) {
String host = utils.getEmailHost(acc.getAccountId(), acc.getSchoolId(),
userName);
String password = utils.getEmailAccountsPassword(acc.getAccountId(),
acc.getSchoolId(), userName);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl()).build();
}
String response = "{\"message\":[";
Folder folder = null;
Store store = null;
UIDFolder uf = null;
try {
// connects to the message store
store = getStore(host, userName, password);
store.connect();
// opens the inbox folder
if (!store.getFolder(folderName).exists()) {
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such folder: " + folderName + "");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}")
.cacheControl(utils.cacheControl()).build();
}
folder = store.getFolder(folderName);
System.out.println("folder: " + folder);
folder.open(Folder.READ_ONLY);
uf = (UIDFolder) folder;
SearchTerm term = null;
if (subject != null)
term = new SubjectTerm(subject);
if (from != null) {
FromStringTerm fromTerm = new FromStringTerm(from);
if (term != null) {
if (or)
term = new OrTerm(term, fromTerm);
else
term = new AndTerm(term, fromTerm);
} else
term = fromTerm;
}
if (today) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.AM_PM, Calendar.AM);
ReceivedDateTerm startDateTerm = new ReceivedDateTerm(
ComparisonTerm.GE, c.getTime());
c.add(Calendar.DATE, 1); // next day
ReceivedDateTerm endDateTerm = new ReceivedDateTerm(
ComparisonTerm.LT, c.getTime());
SearchTerm dateTerm = new AndTerm(startDateTerm, endDateTerm);
if (term != null) {
if (or)
term = new OrTerm(term, dateTerm);
else
term = new AndTerm(term, dateTerm);
} else
term = dateTerm;
}
Message[] foundMessages = folder.search(term);
System.out.println("FOUND " + foundMessages.length + " MESSAGES");
if (foundMessages.length == 0) // no match
if (foundMessages.length == 0) {
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\":[{}],\"error\":{"
+ utils.createErrorResponse(
Status.NOT_FOUND,
"There are no email messages with the given criteria")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
// Use a suitable FetchProfile
FetchProfile prof = new FetchProfile();
prof.add(Item.FLAGS);
prof.add(Item.ENVELOPE);
prof.add(Item.CONTENT_INFO);
folder.fetch(foundMessages, prof);
// TODO search
// SearchTerm addressTerm = new AddressTerm(new InternetAddress(
// keyword)) {p;
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// @Override
// public boolean match(Message message) {
//
// return false;
// }
// };
// performs search through the folder
for (int i = 0; i < foundMessages.length; i++) {
IMAPMessage messages = (IMAPMessage) foundMessages[i];
String userFlags = "{\"user\":";
if (messages.isSet(Flag.USER)) {
userFlags += "[";
String[] userFlagsArray = messages.getFlags()
.getUserFlags();
for (String flag : userFlagsArray) {
userFlags += "{\"" + flag + "\":\"true\"},";
}
int last = userFlags.lastIndexOf(",");
userFlags = new StringBuilder(userFlags).replace(last,
last + 1, "").toString()
+ " ]}";
} else {
userFlags += "\"false\"}";
}
String disposition = "\"disposition\":";
if (messages.getDisposition() != null) {
if (messages.getDisposition().contains(Part.INLINE)) {
disposition += "{\"inline\":\"true\","
+ "\"attachment\":\"false\"}";
}
if (messages.getDisposition().contains(Part.ATTACHMENT)) {
disposition += "{\"inline\":\""
+ messages.getDisposition().contains(
Part.INLINE)
+ "\","
+ "\"attachment\":\""
+ messages.getDisposition().contains(
Part.ATTACHMENT) + "\"}";
}
} else {
disposition += "{\"attachment\":\""
+ hasBodyAttachment(messages) + "\"}";
}
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
response += "{\"uid\":\""
+ uf.getUID(messages)
+ "\",\"date\":{\"sent\":\""
+ utils.getTime(messages.getSentDate())
+ "\",\"recieved\":\""
+ utils.getTime(messages.getReceivedDate())
+ "\"},"
+ "\"from\":"
+ gson.toJson(InternetAddress.toString(messages
.getFrom())) + ",\"subject\":"
+ gson.toJson(messages.getSubject()) + "" + ","
+ disposition + ",\"flags\":{\"deleted\":\""
+ messages.isSet(Flags.Flag.DELETED) + "\","
+ "\"answered\":\""
+ messages.isSet(Flags.Flag.ANSWERED) + "\","
+ "\"draft\":\"" + messages.isSet(Flags.Flag.DRAFT)
+ "\"," + "\"flagged\":\""
+ messages.isSet(Flags.Flag.FLAGGED) + "\","
+ "\"seen\":\"" + messages.isSet(Flags.Flag.SEEN)
+ "\",\"custom\":" + "" + userFlags + "}},";
}
int last = response.lastIndexOf(",");
return Response
.ok(new StringBuilder(response).replace(last, last + 1, "")
.toString() + " ]}")
.cacheControl(utils.cacheControl()).build();
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":[{}],\"error\":{"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"No provider found") + "}}")
.cacheControl(utils.cacheControl()).build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":[{}],\"error\":{"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store")
+ "}}").cacheControl(utils.cacheControl()).build();
} catch (Exception ex) {
System.out
.println("It seems something went wrong please try again");
ex.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":[{}],\"error\":{"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store")
+ "}}").cacheControl(utils.cacheControl()).build();
} finally {
try {
acc = null;
if (folder != null) {
folder.close(false);
folder = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\":[{}],\"error\":{"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong pleasetry again")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
}
}
@PermitAll
@GET
@Path("folder")
@SecurityCheck
public Response getFolderEmail(@Context SecurityContext sc,
@QueryParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String userName = null;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("user_email")) {
userName = object.getString("user_email");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
AtmosphereResource resource = atmosphereResourceFactory
.find(Utils.userAcc.get(acc.getAccountId()));
System.out.println("resource: " + resource);
System.out.println("uuid: " + Utils.userAcc.get(acc.getAccountId()));
return getFolderEmail(userName);
}
/**
* gets email messages field.
*
* @param host
* @param userName
* @param password
*/
public Response getFolderEmail(String userName) {
String host = utils.getEmailHost(acc.getAccountId(), acc.getSchoolId(),
userName);
String password = utils.getEmailAccountsPassword(acc.getAccountId(),
acc.getSchoolId(), userName);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl()).build();
}
// server setting
Folder folderInbox = null;
Store store = null;
String response = "";
try {
// connects to the message store
store = getStore(host, userName, password);
store.connect();
// opens the inbox folder
Folder[] folders = store.getDefaultFolder().list("*");
response += "{\"seperator\":\""
+ store.getDefaultFolder().getSeparator()
+ "\",\"folder\":[";
int index = 0;
for (Folder folder : folders) {
IMAPFolder imapFolder = (IMAPFolder) folder;
response += "{\"full name\":\"" + folder.getFullName() + "\","
+ "\"url\":\"" + folder.getURLName() + "\","
+ "\"name\":\"" + folder.getName() + "\",\"parent\":\""
+ imapFolder.getParent().getURLName()
+ "\",\"parent name\":\""
+ imapFolder.getParent().getName() + "\","
+ "\"unread message\":\""
+ folder.getUnreadMessageCount() + "\","
+ "\"total messages\":\"" + folder.getMessageCount()
+ "\"},";
// for (String attribute : imapFolder.getAttributes()) {
// response += "{\"attributes\":\"" + attribute + "\"},";
// }
index++;
}
int last = response.lastIndexOf(",");
return Response
.ok(new StringBuilder(response).replace(last, last + 1, "")
.toString() + " ]}")
.cacheControl(utils.cacheControl()).build();
// disconnect
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such provider");
return Response.status(Status.NOT_FOUND)
.entity("{\"folder\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"folder\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
} catch (Exception e) {
e.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong please try again");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"folder\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
} finally {
try {
acc = null;
if (folderInbox != null) {
folderInbox.close(false);
folderInbox = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@PermitAll
@DELETE
@Path("email")
@SecurityCheck
public Response deleteFolder(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String folderName = null;
String userName = null;
JSONArray message = null;
boolean expunge = false;
System.out.println("json: " + json);
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("user_email")) {
userName = object.getString("user_email");
}
if (object.keySet().contains("message_delete")) {
message = object.getJSONArray("message_delete");
messageDeletes = new long[message.length()];
System.out.println("json message_delete: " + message);
for (int index = 0; index < message.length(); index++) {
messageDeletes[index] = message.getJSONObject(index)
.getLong("message_id");
}
}
if (object.keySet().contains("folder_name")) {
folderName = object.getString("folder_name");
}
if (object.keySet().contains("expunge")) {
expunge = object.getBoolean("expunge");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return deleteEmail(userName, folderName, messageDeletes, expunge);
}
public Response deleteEmail(String userName, String folderName,
long[] messageDelete, boolean expunge) {
String host = utils.getEmailHost(acc.getAccountId(), acc.getSchoolId(),
userName);
String password = utils.getEmailAccountsPassword(acc.getAccountId(),
acc.getSchoolId(), userName);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl()).build();
}
IMAPFolder folders = null;
Store store = null;
String response = "{\"message\":[";
try {
// connects to the message store
store = getStore(host, userName, password);
store.connect();
// opens the inbox folder
// TODO delete based on uid
if (!store.getFolder(folderName).exists()) {
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such folder: " + folderName + "");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}")
.cacheControl(utils.cacheControl()).build();
}
folders = (IMAPFolder) store.getFolder(folderName);
folders.open(Folder.READ_WRITE);
for (long messageNumber : messageDelete) {
folders.getMessageByUID(messageNumber).setFlag(Flag.DELETED,
true);
response += "{\"message number\":\"" + messageNumber
+ "\",\"deleted\":\"true\"},";
}
int last = response.lastIndexOf(",");
return Response
.ok(new StringBuilder(response).replace(last, last + 1, "")
.toString() + " ]}")
.cacheControl(utils.cacheControl()).build();
// disconnect
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such provider");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (Exception e) {
e.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong please try again");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} finally {
try {
acc = null;
if (folders != null) {
if (expunge) {
folders.close(true);
} else {
folders.close(false);
}
folders = null;
}
if (store != null) {
store.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@PermitAll
@POST
@Path("reply")
@SecurityCheck
public Response replyEmail(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String emailMessage = null;
String userEmail = null;
boolean attachment = false;
boolean quote = false;
boolean replyAll = false;
long messageNumber = 0;
JSONArray attachments = null;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("user_email")) {
userEmail = object.getString("user_email");
}
if (object.keySet().contains("message")) {
emailMessage = object.getString("message");
}
if (object.keySet().contains("message_number")) {
messageNumber = object.getLong("message_number");
}
if (object.keySet().contains("attachment")) {
attachment = object.getBoolean("attachment");
}
if (object.keySet().contains("quote")) {
quote = object.getBoolean("quote");
}
if (object.keySet().contains("reply_all")) {
replyAll = object.getBoolean("reply_all");
}
if (object.keySet().contains("file")) {
attachments = object.getJSONArray("file");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return replyEmail(emailMessage, attachment, attachments, userEmail,
messageNumber, quote, replyAll);
}
public Response replyEmail(String emailMessage, boolean attachment,
JSONArray attachments, String userEmail, long messageNumber,
boolean quote, boolean replyAll) {
Folder sent = null;
Message originalMessage = null;
Store store = null;
IMAPFolder folder = null;
File tempFile = null;
try {
String host = utils.getEmailHost(acc.getAccountId(),
acc.getSchoolId(), userEmail);
String password = utils.getEmailAccountsPassword(
acc.getAccountId(), acc.getSchoolId(), userEmail);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// deals with bounced messages
props.put("mail.smtp.from", userEmail);
Session session = Session.getInstance(props,
new DefaultAuthenticator(userEmail, password));
store = getStore(host, userEmail, password);
store.connect();
Folder[] folders = store.getDefaultFolder().list("*");
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("sent")) {
sent = fold;
}
}
if (sent == null) {
sent = (Folder) store.getFolder("Sent");
if (!sent.exists()) {
sent.create(Folder.HOLDS_MESSAGES);
}
}
sent.open(Folder.READ_WRITE);
System.out.println("folder: " + sent);
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("inbox")) {
folder = (IMAPFolder) fold;
}
}
folder.open(Folder.READ_WRITE);
System.out.println("folder: " + folder);
originalMessage = folder.getMessageByUID(messageNumber);
// Date sentDate=originalMessage.getSentDate();
// String from=InternetAddress.toString(originalMessage.getFrom());
// String
// replyTo=InternetAddress.toString(originalMessage.getReplyTo());
String to = InternetAddress.toString(originalMessage
.getRecipients(RecipientType.TO));
// String subject=originalMessage.getSubject();
Message replyMessage = new MimeMessage(session);
replyMessage = (MimeMessage) originalMessage.reply(replyAll);
if (!replyAll) {
replyMessage.setFrom(new InternetAddress(to));
replyMessage.setReplyTo(originalMessage.getReplyTo());
}
Multipart multipart = new MimeMultipart();
MimeBodyPart summaryBodyPart = new MimeBodyPart();
// quoted message
summaryBodyPart.setContent(originalMessage, "message/rfc822");
multipart.addBodyPart(summaryBodyPart);
// reply message
summaryBodyPart = new MimeBodyPart();
summaryBodyPart.setText(emailMessage);
summaryBodyPart.setContent(emailMessage, "text/html");
multipart.addBodyPart(summaryBodyPart);
// attachment
AmazonS3 s3Client = new AmazonS3Client(
new ProfileCredentialsProvider());
if (attachments != null && attachments.length() != 0) {
for (int index = 0; index < attachments.length(); index++) {
String fileName = attachments.getJSONObject(index)
.getString("file_name");
String albumId = attachments.getJSONObject(index)
.getString("album_id");
String key = fileName.replace(
"http://s3.amazonaws.com/schoolmart-document/", "");
// String key=fileName.replace("s3.amazonaws.com/", "");
S3Object object = s3Client.getObject(new GetObjectRequest(
"schoolmart-document", key));
InputStream objectData = object.getObjectContent();
// Process the objectData stream.
tempFile = File.createTempFile(
"schoolmart-email" + acc.getAccountId() + "-",
".tmp");
// tempFile.createNewFile();
tempFile.deleteOnExit();
try (OutputStream outpuStream = new FileOutputStream(
tempFile)) {
IOUtils.copy(objectData, outpuStream);
}
// TODO: SAVE FILE HERE
// if you want media type for validation, it's
// field.getMediaType()
System.out.println("file: " + tempFile + "\n exists: "
+ tempFile.exists());
if (attachment && tempFile.exists()) {
System.out.println("attahcment");
summaryBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(tempFile);
summaryBodyPart.setDataHandler(new DataHandler(source));
summaryBodyPart.setFileName(key.replace(albumId + "/"
+ acc.getAccountId() + "/", ""));
multipart.addBodyPart(summaryBodyPart);
}
if (objectData != null) {
objectData.close();
}
tempFile = null;
}
}
replyMessage.setContent(multipart);
// replyMessage.saveChanges();
System.out.println("propert: " + props.toString() + "\n mess: "
+ replyMessage.toString());
// Transport.send(replyMessage);
String protocol = "smtp";
Transport t = session.getTransport(protocol);
t.connect(userEmail, password);
t.sendMessage(replyMessage, replyMessage.getAllRecipients());
replyMessage.setFlag(Flag.SEEN, true);
sent.appendMessages(new Message[] { replyMessage });
return Response.status(Status.OK)
.entity("{\"message\": \"reply\":\"true\"}")
.cacheControl(utils.cacheControl()).build();
// append to sent folder
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such provider");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (Exception e) {
e.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems that something went wrong please try again");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} finally {
try {
acc = null;
tempFile = null;
if (sent != null) {
sent.close(false);
sent = null;
}
if (folder != null) {
folder.close(false);
folder = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@PermitAll
@POST
@Path("foward")
@SecurityCheck
public Response forwardEmail(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String userEmail = null;
long messageNumber = 0;
String recipientEmail = null;
String bccEmail = null;
String ccEmail = null;
String from = null;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("user_email")) {
userEmail = object.getString("user_email");
}
if (object.keySet().contains("message_number")) {
messageNumber = object.getLong("message_number");
}
if (object.keySet().contains("recipient")) {
recipientEmail = object.getString("recipient");
}
if (object.keySet().contains("bcc")) {
bccEmail = object.getString("bcc");
}
if (object.keySet().contains("from")) {
from = object.getString("from");
}
if (object.keySet().contains("cc")) {
ccEmail = object.getString("cc_email");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return forwardEmail(userEmail, messageNumber, recipientEmail, bccEmail,
ccEmail);
}
public Response forwardEmail(String userEmail, long messageNumber,
String recipientEmail, String bccEmail, String ccEmail) {
Folder sent = null;
Message originalMessage = null;
IMAPFolder folder = null;
Store store = null;
try {
String fromName = utils.getEmailUserName(acc.getAccountId(),
acc.getSchoolId(), userEmail);
String host = utils.getEmailHost(acc.getAccountId(),
acc.getSchoolId(), userEmail);
String password = utils.getEmailAccountsPassword(
acc.getAccountId(), acc.getSchoolId(), userEmail);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// deals with bounced messages
props.put("mail.smtp.from", userEmail);
Session session = Session.getInstance(props,
new DefaultAuthenticator(userEmail, password));
store = getStore(host, userEmail, password);
store.connect();
Folder[] folders = store.getDefaultFolder().list("*");
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("sent")) {
sent = fold;
}
}
if (sent == null) {
sent = (Folder) store.getFolder("Sent");
if (!sent.exists()) {
sent.create(Folder.HOLDS_MESSAGES);
}
}
sent.open(Folder.READ_WRITE);
for (Folder fold : folders) {
if (fold.getName().equalsIgnoreCase("inbox")) {
folder = (IMAPFolder) fold;
}
}
folder.open(Folder.READ_WRITE);
originalMessage = folder.getMessageByUID(messageNumber);
// Date sentDate=originalMessage.getSentDate();
String from = InternetAddress.toString(originalMessage.getFrom());
// String
// replyTo=InternetAddress.toString(originalMessage.getReplyTo());
String to = InternetAddress.toString(originalMessage
.getRecipients(RecipientType.TO));
String subject = originalMessage.getSubject();
Message forwardMessage = new MimeMessage(session);
forwardMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(from));
forwardMessage.setSubject("FWD: " + subject);
forwardMessage.setFrom(new InternetAddress(to));
if (recipientEmail != null && !recipientEmail.isEmpty()) {
forwardMessage.setRecipients(RecipientType.CC,
InternetAddress.parse(recipientEmail, false));
}
if (ccEmail != null && !ccEmail.isEmpty()) {
forwardMessage.setRecipients(RecipientType.CC,
InternetAddress.parse(ccEmail, false));
//
}
if (bccEmail != null && !bccEmail.isEmpty()) {
forwardMessage.setRecipients(RecipientType.CC,
InternetAddress.parse(bccEmail, false));
//
}
forwardMessage.setFrom(new InternetAddress(from, fromName));
if (subject != null && !subject.isEmpty()) {
forwardMessage.setSubject(subject);
}
Multipart multipart = new MimeMultipart();
MimeBodyPart summaryBodyPart = new MimeBodyPart();
// quoted message
summaryBodyPart.setContent(originalMessage, "message/rfc822");
multipart.addBodyPart(summaryBodyPart);
forwardMessage.setContent(multipart);
// forwardMessage.saveChanges();
String protocol = "smtp";
Transport t = session.getTransport(protocol);
t.connect(userEmail, password);
t.sendMessage(forwardMessage, forwardMessage.getAllRecipients());
forwardMessage.setFlag(Flag.SEEN, true);
sent.appendMessages(new Message[] { forwardMessage });
return Response.status(Status.OK)
.entity("{\"message\": \"foward\":\"true\"}")
.cacheControl(utils.cacheControl()).build();
// append to sent folder
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such provider");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} catch (Exception e) {
e.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems that something went wrong please try again");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"reply\":\"false\",\"error\" : {"
+ error + " }}").cacheControl(utils.cacheControl())
.build();
} finally {
try {
acc = null;
if (sent != null) {
sent.close(false);
sent = null;
}
if (folder != null) {
folder.close(false);
folder = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@PermitAll
@GET
@Path("messages")
@SecurityCheck
public Response getMessages(@Context SecurityContext sc,
@QueryParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String userName = null;
String folderName = null;
Integer offset = null;
int batch = 50;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("offset")) {
offset = object.getInt("offset");
}
if (object.keySet().contains("batch")) {
batch = object.getInt("batch");
}
if (object.keySet().contains("user_email")) {
userName = object.getString("user_email");
}
if (object.keySet().contains("folder_name")) {
folderName = object.getString("folder_name");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return getMessages(userName, folderName, offset, batch);
}
private Response getMessages(String userName, String folderName,
Integer offset, int batch) {
String host = utils.getEmailHost(acc.getAccountId(), acc.getSchoolId(),
userName);
String password = utils.getEmailAccountsPassword(acc.getAccountId(),
acc.getSchoolId(), userName);
if (offset != null && offset < 1) {
return Response
.status(Status.BAD_REQUEST)
.entity("{\"error\":\""
+ utils.createErrorResponse(Status.BAD_REQUEST,
"invalid offset value") + "\"}").build();
}
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl()).build();
}
String response = "{\"message\":[";
Folder folder = null;
UIDFolder uf = null;
Store store = null;
Message[] messagesArray = null;
try {
// connects to the message store
store = getStore(host, userName, password);
store.connect();
// opens the inbox folder
if (!store.getFolder(folderName).exists()) {
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such folder: " + folderName + "");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}")
.cacheControl(utils.cacheControl()).build();
}
folder = store.getFolder(folderName);
folder.open(Folder.READ_ONLY);
uf = (UIDFolder) folder;
int lastMessage = folder.getMessageCount();
System.out.println("message: " + lastMessage);
if (batch > lastMessage) {
batch = lastMessage;
}
if (offset == null) {
messagesArray = folder.getMessages((lastMessage - batch) + 1,
lastMessage);
} else {
messagesArray = folder.getMessages(offset, offset + batch);
}
FetchProfile prof = new FetchProfile();
prof.add(Item.FLAGS);
prof.add(Item.ENVELOPE);
prof.add(Item.CONTENT_INFO);
folder.fetch(messagesArray, prof);
for (int i = messagesArray.length - 1; i > 0; i--) {
IMAPMessage messages = (IMAPMessage) messagesArray[i];
String userFlags = "{\"user\":";
if (messages.isSet(Flag.USER)) {
userFlags += "[";
String[] userFlagsArray = messages.getFlags()
.getUserFlags();
for (String flag : userFlagsArray) {
userFlags += "{\"" + flag + "\":\"true\"},";
}
int last = userFlags.lastIndexOf(",");
userFlags = new StringBuilder(userFlags).replace(last,
last + 1, "").toString()
+ " ]}";
} else {
userFlags += "\"false\"}";
}
String disposition = "\"disposition\":";
if (messages.getDisposition() != null) {
if (messages.getDisposition().contains(Part.INLINE)) {
disposition += "{\"inline\":\"true\","
+ "\"attachment\":\"false\"}";
}
if (messages.getDisposition().contains(Part.ATTACHMENT)) {
disposition += "{\"inline\":\""
+ messages.getDisposition().contains(
Part.INLINE)
+ "\","
+ "\"attachment\":\""
+ messages.getDisposition().contains(
Part.ATTACHMENT) + "\"}";
}
} else {
disposition += "{\"attachment\":\""
+ hasBodyAttachment(messages) + "\"}";
}
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
response += "{\"uid\":\""
+ uf.getUID(messages)
+ "\",\"date\":{\"sent\":\""
+ utils.getTime(messages.getSentDate())
+ "\",\"recieved\":\""
+ utils.getTime(messages.getReceivedDate())
+ "\"},"
+ "\"from\":"
+ gson.toJson(InternetAddress.toString(messages
.getFrom())) + ",\"subject\":"
+ gson.toJson(messages.getSubject()) + "" + ","
+ disposition + ",\"flags\":{\"deleted\":\""
+ messages.isSet(Flags.Flag.DELETED) + "\","
+ "\"answered\":\""
+ messages.isSet(Flags.Flag.ANSWERED) + "\","
+ "\"draft\":\"" + messages.isSet(Flags.Flag.DRAFT)
+ "\"," + "\"flagged\":\""
+ messages.isSet(Flags.Flag.FLAGGED) + "\","
+ "\"seen\":\"" + messages.isSet(Flags.Flag.SEEN)
+ "\",\"custom\":" + "" + userFlags + "}},";
}
if (lastMessage != 0) {
int last = response.lastIndexOf(",");
return Response
.ok(new StringBuilder(response).replace(last, last + 1,
"").toString()
+ " ],\"total messages\":\""
+ lastMessage
+ "\"}").cacheControl(utils.cacheControl())
.build();
} else {
return Response
.ok(response + " ],\"total messages\":\"" + lastMessage
+ "\"}").cacheControl(utils.cacheControl())
.build();
}
// disconnect
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
} catch (Exception ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
} finally {
try {
acc = null;
if (folder != null) {
folder.close(false);
folder = null;
}
if (store != null) {
store.close();
store = null;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String error = utils.createErrorResponse(Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong please try again");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
}
@PermitAll
@GET
@Path("message/specific/{messageNumber}")
@SecurityCheck
public Response getSpecificMessage(@Context SecurityContext sc,
@QueryParam("json") String json,
@PathParam("messageNumber") String messageNumber) {
acc = (Account) sc.getUserPrincipal();
String userName = null;
String folderName = null;
boolean showStructure = false;
boolean saveAttachments = false;
try {
JSONObject object = new JSONObject(json);
if (object.keySet().contains("user_email")) {
userName = object.getString("user_email");
}
if (object.keySet().contains("folder_name")) {
folderName = object.getString("folder_name");
}
if (object.keySet().contains("attachment_name")) {
attachmentName = object.getString("attachment_name");
}
if (object.keySet().contains("structure")) {
showStructure = object.getBoolean("structure");
}
if (object.keySet().contains("save")) {
saveAttachments = object.getBoolean("save");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return getSpecificMessage(userName, folderName, showStructure,
messageNumber, saveAttachments)
;
}
private Response getSpecificMessage(String userName, String folderName,
boolean showStructure, String messageNumber, boolean saveAttachments) {
String host = utils.getEmailHost(acc.getAccountId(), acc.getSchoolId(),
userName);
String password = utils.getEmailAccountsPassword(acc.getAccountId(),
acc.getSchoolId(), userName);
if (host == null || password == null) {
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"Please fill out the email configuration ")
+ "}}").cacheControl(utils.cacheControl()).build();
}
String response = "";
IMAPFolder folder = null;
Store store = null;
IMAPMessage message = null;
UIDFolder uf = null;
try {
// connects to the message store
store = getStore(host, userName, password);
store.connect();
// opens the inbox folder
if (!store.getFolder(folderName).exists()) {
String error = utils.createErrorResponse(Status.NOT_FOUND,
"There is no such folder: " + folderName + "");
return Response
.status(Status.NOT_FOUND)
.entity("{\"message\": [{ }],\"deleted\":\"false\",\"error\" : {"
+ error + " }}")
.cacheControl(utils.cacheControl()).build();
}
folder = (IMAPFolder) store.getFolder(folderName);
uf = (UIDFolder) folder;
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
int lastMessage = folder.getMessageCount();
if (lastMessage <= 0) {
String error = utils.createErrorResponse(
Status.EXPECTATION_FAILED,
"You do not have any messages to read from");
return Response
.status(Status.EXPECTATION_FAILED)
.entity("{\"message\": [{ }],\"error\" : {" + error
+ " }}").cacheControl(utils.cacheControl())
.build();
}
message = (IMAPMessage) folder.getMessageByUID(Long
.parseLong(messageNumber));
String userFlags = "{\"user\":";
if (message.isSet(Flag.USER)) {
userFlags += "[";
String[] userFlagsArray = message.getFlags().getUserFlags();
for (String flag : userFlagsArray) {
userFlags += "{\"" + flag + "\":\"true\"},";
}
int last = userFlags.lastIndexOf(",");
userFlags = new StringBuilder(userFlags).replace(last,
last + 1, "").toString()
+ " ]}";
} else {
userFlags += "\"false\"}";
}
String disposition = "\"disposition\":";
if (message.getDisposition() != null) {
if (message.getDisposition().contains(Part.INLINE)) {
disposition += "{\"inline\":\"true\","
+ "\"attachment\":\"false\"}";
}
if (message.getDisposition().contains(Part.ATTACHMENT)) {
disposition += "{\"inline\":\""
+ message.getDisposition().contains(Part.INLINE)
+ "\","
+ "\"attachment\":\""
+ message.getDisposition()
.contains(Part.ATTACHMENT) + "\"}";
}
} else {
String contentType = message.getContentType();
System.out.println("type: " + contentType);
if (contentType.contains("multipart")) {
if (message.getFileName() != null) {
disposition += "{\"attachment\":\""
+ hasBodyAttachment(message) + "\"}";
} else {
disposition += "{}";
}
} else {
disposition += "{}";
}
}
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
response += "{\"meta\":{\"uid\":\"" + uf.getUID(message)
+ "\",\"date\":{\"sent\":\"" + message.getSentDate()
+ "\",\"recieved\":\"" + message.getReceivedDate() + "\"},"
+ "\"from\":"
+ gson.toJson(InternetAddress.toString(message.getFrom()))
+ ",\"subject\":\"" + message.getSubject() + "\"" + ","
+ disposition + ",\"flags\":{\"deleted\":\""
+ message.isSet(Flags.Flag.DELETED) + "\","
+ "\"answered\":\"" + message.isSet(Flags.Flag.ANSWERED)
+ "\"," + "\"draft\":\"" + message.isSet(Flags.Flag.DRAFT)
+ "\"," + "\"flagged\":\""
+ message.isSet(Flags.Flag.FLAGGED) + "\"," + "\"seen\":\""
+ message.isSet(Flags.Flag.SEEN) + "\",\"custom\":" + ""
+ userFlags + "}},";
ResponseBuilder res = null;
response = dumpPart(message, showStructure, saveAttachments, 0, 1,
response);
int last = response.lastIndexOf(",");
response = new StringBuilder(response).replace(last, last + 1, "}")
+ "}";
String close = "";
for (int index = 0; index < closeBrackets - 1; index++) {
close += "}";
}
res = Response.ok(response + close).cacheControl(
utils.cacheControl());
return res.build();
// disconnect
} catch (NoSuchProviderException ex) {
System.out.println("No provider.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR, "No provider.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store.");
ex.printStackTrace();
String error = utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Could not connect to the message store.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl()).build();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (folder != null) {
folder.close(false);
folder = null;
}
if (store != null) {
store.close();
store = null;
}
levelIndex = 0;
count = 0;
attachmentName = null;
rfc822 = false;
closeBrackets = 0;
acc = null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String error = utils.createErrorResponse(Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong please try again");
ResponseBuilder res = Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"message\": [{ }],\"error\" : {" + error + " }}")
.cacheControl(utils.cacheControl())
.cacheControl(utils.cacheControl());
return res.build();
}
public static String dumpPart(Part p, boolean showStructure,
boolean saveAttachments, int level, int attNum, String response)
throws Exception {
if (levelIndex == 0 && level != 0) {
response += "{\"message\":{";
} else if (level == 0 && levelIndex == 0) {
response += "\"message container\":";
} else {
response += "\"message\":{";
}
System.out.println("rfc822: " + rfc822);
System.out.println("closeBrackets: " + closeBrackets);
Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting()
.create();
/**
* Dump input stream ..
*
* InputStream is = p.getInputStream(); // If "is" is not already
* buffered, wrap a BufferedInputStream // around it. if (!(is
* instanceof BufferedInputStream)) is = new BufferedInputStream(is);
* int c; while ((c = is.read()) != -1) System.out.write(c);
**/
String ct = p.getContentType();
try {
System.out.println("CONTENT-TYPE: "
+ (new ContentType(ct)).toString());
System.out.println("response: " + response);
} catch (ParseException pex) {
System.out.println("BAD CONTENT-TYPE: " + ct);
}
String filename = p.getFileName();
if (filename != null)
System.out.println("FILENAME: " + filename);
/*
* Using isMimeType to determine the content type avoids fetching the
* actual content data until we need it.
*/
if (p.isMimeType("text/plain")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
response += Utils.pr(
"\"content\":\"string\",\"format\":"
+ gson.toJson((String) p.getContentType())
+ ",\"value\":"
+ gson.toJson((String) p.getContent()) + ",",
showStructure, level);
} else if (p.isMimeType("text/html")) {
System.out.println("This is plain text");
System.out.println("---------------------------");
response += Utils.pr(
"\"content\":\"string\",\"format\":"
+ gson.toJson((String) p.getContentType())
+ ",\"value\":"
+ gson.toJson((String) p.getContent()) + ",",
showStructure, level);
} else if (p.isMimeType("multipart/*")) {
System.out.println("This is a Multipart");
System.out.println("---------------------------");
Multipart mp = (Multipart) p.getContent();
level++;
count = mp.getCount();
System.out.println("count: " + count);
for (; levelIndex < count; levelIndex++)
response = dumpPart(mp.getBodyPart(levelIndex), showStructure,
saveAttachments, level, attNum, response);
System.out.println("response: " + response);
// int last = response.lastIndexOf(",");
// response = new StringBuilder(response).replace(last, last + 1,
// "")
// + "],";
level--;
} else if (p.isMimeType("message/rfc822")) {
// nested message
level++;
// for (; levelIndex < count; levelIndex++)
rfc822 = true;
response = dumpPart((Part) p.getContent(), showStructure,
saveAttachments, level, attNum, response);
// int last = response.lastIndexOf(",");
// response = new StringBuilder(response).replace(last, last + 1,
// "")
// + "],";
level--;
} else {
if (!showStructure && !saveAttachments) {
/*
* If we actually want to see the data, and it's not a MIME type
* we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
// string
System.out.println((String) o);
response += Utils.pr("\"content\":\"string\",\"format\":"
+ gson.toJson(p.getContentType()) + ",\"value\":"
+ gson.toJson(o) + ",", showStructure, level);
} else if (o instanceof InputStream) {
// inputstream
// InputStream is = (InputStream) o;
// if (!(is instanceof BufferedInputStream))
// is = new BufferedInputStream(is);
// int c;
// while ((c = is.read()) != -1)
// System.out.write(c);
if (p.getContentType().contains("image/jpeg")) {
response += Utils.pr(
"\"content\":\"image\",\"format\":"
+ gson.toJson(p.getContentType())
+ ",\"file name\":" + ""
+ gson.toJson(p.getFileName()) + ",",
showStructure, level);
} else if (p.isMimeType("image/")) {
response += Utils.pr(
"\"content\":\"image\",\"format\":"
+ gson.toJson(p.getContentType())
+ ",\"file name\":" + ""
+ gson.toJson(p.getFileName()) + ",",
showStructure, level);
} else {
response += Utils.pr(
"\"content\":\"unknown\",\"format\":"
+ gson.toJson(p.getContentType())
+ ",\"file name\":" + "\""
+ p.getFileName() + "\",",
showStructure, level);
}
} else {
// unknown type
// System.out.println(o.toString());
response += Utils.pr(
"\"content\":\"unknown\",\"format\":\"unknown\",",
showStructure, level);
}
} else {
// just a separator
System.out.println("---------------------------");
}
}
/*
* If we're saving attachments, write out anything that looks like an
* attachment into an appropriately named file. Don't overwrite existing
* files to prevent mistakes.
*/
if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
String disp = p.getDisposition();
// many mailers don't include a Content-Disposition
if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
if (filename == null)
filename = "Attachment" + attNum++;
System.out.println("Saving attachment to file " + filename);
// File f=null;
try {
File f = new File(filename);
if (f.exists())
// XXX - could try a series of names
throw new IOException("file exists");
((MimeBodyPart) p).saveFile(f);
StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream output)
throws IOException, WebApplicationException {
BufferedOutputStream bus = new BufferedOutputStream(
output);
FileInputStream fileStream = new FileInputStream(f);
byte[] buffer2 = IOUtils.toByteArray(fileStream);
bus.write(buffer2);
}
};
TransferManager tx = new TransferManager(
new PropertiesCredentials(
Document.class
.getResourceAsStream("/com/api/AwsCredentials.properties")));
AmazonS3 s3Conn = new AmazonS3Client(
new PropertiesCredentials(
Document.class
.getResourceAsStream("/com/api/AwsCredentials.properties")));
String key = acc.getAccountId() + "/" + filename;
java.util.List<Bucket> buckets = s3Conn.listBuckets();
if (!buckets.contains("schoolmart-email")) {
CreateBucketRequest createBucket = new CreateBucketRequest(
"schoolmart-email")
.withCannedAcl(CannedAccessControlList.PublicRead);
s3Conn.createBucket(createBucket);
}
Upload documentUpload = tx.upload(new PutObjectRequest(
"schoolmart-email", key, f)
.withCannedAcl(CannedAccessControlList.PublicRead));
tx.shutdownNow();
if (!documentUpload.isDone()) {
response += Utils
.pr("\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems an error occured while uploading your documents, please try again.")
+ " ,", showStructure, level);
} else {
response += Utils.pr("\"file\" : {\"link\":\""
+ "http://s3.amazonaws.com/schoolmart-email/"
+ key + "\"," + "\"name\":\"" + filename
+ "\"},", showStructure, level);
}
} catch (IOException ex) {
System.out.println("Failed to save attachment: " + ex);
response += Utils
.pr("\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems an error occured while uploading your documents, please try again.")
+ " ,", showStructure, level);
} finally {
}
System.out.println("---------------------------");
}
}
closeBrackets++;
return response;
}
@PermitAll
@GET
@SecurityCheck
public Response getSpecificEmailAccount(@Context SecurityContext sc,
@QueryParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
int offset;
int batch;
boolean ascending;
boolean getAll;
try {
JSONObject object = new JSONObject(json);
if (object.getString("get_all").isEmpty()
|| object.getString("get_all") == null) {
getAll = false;
} else {
getAll = object.getBoolean("get_all");
}
if (object.getString("offset").isEmpty()
|| object.getString("offset") == null) {
offset = 0;
} else {
offset = object.getInt("offset");
}
if (object.getString("batch").isEmpty()
|| object.getString("batch") == null) {
batch = 15;
} else {
batch = object.getInt("batch");
}
if (object.getString("ascending").isEmpty()
|| object.getString("ascending") == null) {
ascending = true;
} else {
ascending = object.getBoolean("ascending");
}
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return getEmailAccounts(ascending, offset, batch, getAll,
acc.getAccountId());
}
@PermitAll
@Path("account")
@POST
@SecurityCheck
public Response addEmailAccount(@Context SecurityContext sc,
@FormParam("json") final String json) {
acc = (Account) sc.getUserPrincipal();
String password = null;
String email = null;
String host = null;
String name = null;
try {
JSONObject object = new JSONObject(json);
password = object.getString("password");
email = object.getString("email");
host = object.getString("host");
name = object.getString("name");
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}").cacheControl(utils.cacheControl()).build();
}
if (email.isEmpty() || email == null) {
return Response
.status(Status.BAD_REQUEST)
.entity("{"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"missing source email ") + "}")
.cacheControl(utils.cacheControl()).build();
}
if (password.isEmpty() || password == null) {
return Response
.status(Status.BAD_REQUEST)
.entity("{"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"missing target password ") + "}")
.cacheControl(utils.cacheControl()).build();
}
String encryptedPassword = null;
javax.sql.DataSource ds = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
encryptedPassword = utils.encrypt(password, acc.getAccountId()
+ acc.getSchoolId(), 65536, 128);
ds = MyDataSource.INSTANCE.getDataSource(acc.getSchoolId());
conn = ds.getConnection();
if (conn != null) {
String now = String.valueOf(System.nanoTime());
stmt = conn.prepareStatement("INSERT INTO `"
+ acc.getSchoolId()
+ "`.`email_config` VALUES (?,?,?,?,?) ");
stmt.setString(1, acc.getAccountId());
stmt.setString(2, email);
stmt.setString(3, encryptedPassword);
stmt.setString(4, host);
stmt.setString(5, name);
if (stmt.executeUpdate() == 1) {
return Response
.ok("{\"email\" : {\"email\" : \"" + now
+ "\", \"email\" : \"" + email
+ "\" ,\"creator\" : \""
+ acc.getAccountId() + "\"} }")
.cacheControl(utils.cacheControl()).build();
} else {
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to create tag synonym please try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"email\": { },\"error\" : {" + error
+ "}}").cacheControl(utils.cacheControl())
.build();
}
} else {
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to create tag synonym please try again.");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"email\": { },\"error\" : {" + error + "}}")
.cacheControl(utils.cacheControl()).build();
}
} catch (SQLIntegrityConstraintViolationException me) {
me.printStackTrace();
log.error(Status.CONFLICT + " Server error");
HashMap<String, String> response = new HashMap<String, String>();
response.put("status", "false");
String error = utils
.createErrorResponse(Status.CONFLICT,
"DUPLICATE ENTRY: There seems to be an email with the given credentials");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"email\": { },\"error\" : {" + error + "}}")
.cacheControl(utils.cacheControl()).build();
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to create tag synonym please try again.");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"email\": { },\"error\" : {" + error + "}}")
.cacheControl(utils.cacheControl()).build();
} finally {
try {
acc = null;
if (stmt != null)
stmt.close();
stmt = null;
if (conn != null)
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
log.error(e.getMessage());
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to create email please try again.");
return Response.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"email\": { },\"error\" : {" + error + "}}")
.cacheControl(utils.cacheControl()).build();
}
}
}
private Response getEmailAccounts(boolean ascending, int offset, int batch,
boolean getAll, String userId) {
javax.sql.DataSource ds = null;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = null;
String response = "{\"email\" : [";
try {
ds = MyDataSource.INSTANCE.getDataSource(acc.getSchoolId());
conn = ds.getConnection();
if (conn != null) {
if (getAll) {
if (ascending) {
sql = "SELECT * from `"
+ acc.getSchoolId()
+ "`.`email_config` WHERE user_id=? ORDER BY email ASC ";
} else {
sql = "SELECT * from `"
+ acc.getSchoolId()
+ "`.`email_config` WHERE user_id=? ORDER BY email DESC ";
}
stmt = conn.prepareStatement(sql);
stmt.setString(1, userId);
} else {
if (ascending) {
sql = "SELECT * from `"
+ acc.getSchoolId()
+ "`.`email_config` WHERE user_id=? ORDER BY email ASC LIMIT ?,?";
} else {
sql = "SELECT * from `"
+ acc.getSchoolId()
+ "`.`email_config` WHERE user_id=? ORDER BY email DESC LIMIT ?,?";
}
stmt = conn.prepareStatement(sql);
stmt.setString(1, userId);
stmt.setInt(2, offset);
stmt.setInt(3, batch);
}
rs = stmt.executeQuery();
if (rs.isBeforeFirst()) {
while (rs.next()) {
response += "{\"account\" : \"" + rs.getString("email")
+ "\" ," + "\"host\" : \""
+ rs.getString("host") + "\" ,\"user id\" : \""
+ rs.getString("user_id") + "\",\"name\":\""
+ rs.getString("name") + "\"},";
}
} else {
return Response
.status(Status.NOT_FOUND)
.entity(response
+ "{}],\"error\" : {"
+ utils.createErrorResponse(
Status.NOT_FOUND,
"there are no emails created")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
int last = response.lastIndexOf(",");
return Response
.ok(new StringBuilder(response).replace(last, last + 1,
"").toString()
+ " ]}").cacheControl(utils.cacheControl())
.build();
} else {
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ " {}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops it seems something went wrong while retrieving the emails")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
} catch (Exception e) {
log.error(e.getMessage());
e.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ " {}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops it seems something went wrong while retrieving the emails")
+ "}}").cacheControl(utils.cacheControl()).build();
} finally {
try {
acc = null;
if (rs != null)
rs.close();
rs = null;
if (stmt != null)
stmt.close();
stmt = null;
if (conn != null)
conn.close();
conn = null;
} catch (SQLException e) {
log.error(e.getMessage());
e.printStackTrace();
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ " {}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops it seems something went wrong while retrieving the emails")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
}
}
@PermitAll
@PUT
@Path("account")
@SecurityCheck
public Response editEmailAccount(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String email = null;
String userId = null;
String host = null;
String password = null;
String name = null;
try {
JSONObject object = new JSONObject(json);
userId = object.getString("user_id");
email = object.getString("email");
host = object.getString("host");
password = object.getString("password");
name = object.getString("name");
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return editEmailAccount(userId, email, host, password, name);
}
private Response editEmailAccount(String userId, String email, String host,
String password, String name) {
javax.sql.DataSource ds = null;
PreparedStatement stmt = null;
Connection conn = null;
try {
ds = MyDataSource.INSTANCE.getDataSource(acc.getSchoolId());
conn = ds.getConnection();
if (conn != null) {
stmt = conn
.prepareStatement("UPDATE `"
+ acc.getSchoolId()
+ "`.`email_config` SET host=?,password=?,name=? WHERE user_id=? AND email=? ");
stmt.setString(1, host);
stmt.setString(2, utils.encrypt(password, acc.getSchoolId()
+ acc.getAccountId(), 65536, 128));
stmt.setString(3, name);
stmt.setString(4, userId);
stmt.setString(5, email);
if (stmt.executeUpdate() == 1) {
return Response.ok(
"{\"user id\" : \"" + userId
+ "\", \"account\" : \"" + email
+ "\",\"host\" : \"" + host
+ "\",\"name\":\"" + name
+ "\",\"edited\" : \"true\" } ").build();
} else {
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to edit email please try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"user id\" : \""
+ userId
+ "\", \"account\" : \""
+ email
+ "\",\"host\" : \""
+ host
+ "\",\"name\":\""
+ name
+ "\",\"edited\" : \"false\" ,\"error\" : {"
+ error + " }}").build();
}
} else {
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to edit email please try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"user id\" : \"" + userId
+ "\", \"account\" : \"" + email
+ "\",\"host\" : \"" + host + "\",\"name\":\""
+ name
+ "\",\"edited\" : \"false\" ,\"error\" : {"
+ error + " }}").build();
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to edit email please try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"user id\" : \"" + userId
+ "\", \"account\" : \"" + email
+ "\",\"host\" : \"" + host + "\",\"name\":\""
+ name + "\",\"edited\" : \"false\" ,\"error\" : {"
+ error + " }}").build();
} finally {
try {
acc = null;
if (stmt != null)
stmt.close();
stmt = null;
if (conn != null)
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
log.error(e.getMessage());
String error = utils
.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Server error: Oops something went wrong while trying to edit email please try again.");
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity("{\"user id\" : \"" + userId
+ "\", \"account\" : \"" + email
+ "\",\"host\" : \"" + host + "\",\"name\":\""
+ name
+ "\",\"edited\" : \"false\" ,\"error\" : {"
+ error + " }}").build();
}
}
}
@PermitAll
@DELETE
@Path("account")
@SecurityCheck
public Response deleteEmailAccount(@Context SecurityContext sc,
@FormParam("json") String json) {
acc = (Account) sc.getUserPrincipal();
String email = null;
String userId = null;
try {
JSONObject object = new JSONObject(json);
userId = object.getString("user_id");
email = object.getString("email");
} catch (Exception e) {
e.printStackTrace();
log.error("Invalid JSON STRING" + e.getMessage());
return Response
.status(Status.BAD_REQUEST)
.entity("{\"email\": [{ }],\"error\" : {"
+ utils.createErrorResponse(Status.BAD_REQUEST,
"Invalid JSON string. " + e.getMessage())
+ "}}").cacheControl(utils.cacheControl()).build();
}
return deleteEmailAccount(userId, email);
}
private Response deleteEmailAccount(String userId, String email) {
javax.sql.DataSource ds = null;
PreparedStatement stmt = null;
Connection conn = null;
String response = "{\"email account\" : [";
try {
ds = MyDataSource.INSTANCE.getDataSource(acc.getSchoolId());
conn = ds.getConnection();
if (conn != null) {
stmt = conn
.prepareStatement("DELETE FROM `"
+ acc.getSchoolId()
+ "`.`email_config` WHERE user_id=? AND email=? ORDER BY email ");
stmt.setString(1, userId);
stmt.setString(2, email);
if (stmt.executeUpdate() == 1) {
return Response
.ok(response + "{\"email\" : \"" + email
+ "\", \"deleted\" : \"true\"}" + " ]}")
.cacheControl(utils.cacheControl()).build();
} else {
return Response
.status(Status.NOT_FOUND)
.entity(response
+ "{\"email\" : \""
+ email
+ "\", \"deleted\" : \"false\"}],\"error\" : {"
+ utils.createErrorResponse(
Status.NOT_FOUND,
"There seems to be no email account existing with such criteria")
+ "}}").cacheControl(utils.cacheControl())
.build();
}
} else {
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ "{\"email\" : \""
+ email
+ "\", \"deleted\" : \"false\"}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong while trying to delete the temail account"
+ " please try again .") + "}}")
.cacheControl(utils.cacheControl()).build();
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ "{\"email\" : \""
+ email
+ "\", \"deleted\" : \"false\"}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong while trying to delete the email account"
+ " please try again .") + "}}")
.cacheControl(utils.cacheControl()).build();
} finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
log.error(e.getMessage());
return Response
.status(Status.INTERNAL_SERVER_ERROR)
.entity(response
+ "{\"email\" : \""
+ email
+ "\", \"deleted\" : \"false\"}],\"error\" : {"
+ utils.createErrorResponse(
Status.INTERNAL_SERVER_ERROR,
"Oops it seems something went wrong while trying to delete the email account"
+ " please try again .") + "}}")
.cacheControl(utils.cacheControl()).build();
}
}
}
private boolean hasBodyAttachment(MimeMessage msg) throws IOException,
MessagingException {
if(msg.getContent() instanceof String){
return false;
}
MimeMultipart mp = (MimeMultipart) msg.getContent();
int k = 0;
int number_2 = mp.getCount();
System.out.println(number_2);
for (; k < number_2; k++) {
MimeBodyPart mbp = (MimeBodyPart) mp.getBodyPart(k);
if (!mbp.isMimeType("multipart/*")) {
continue;
}
return hasAttachment(mbp);
}
return false;
}
private boolean hasAttachment(MimeBodyPart mes) throws IOException,
MessagingException {
MimeMultipart mp_nest = (MimeMultipart) mes.getContent();
int flag = mp_nest.getCount();
int m;
for (m = 0; m < flag; m++) {
MimeBodyPart mbp_nest = (MimeBodyPart) mp_nest.getBodyPart(m);
return hasAttachment(mbp_nest);
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment