use of javax.mail.util.ByteArrayDataSource in project ice by Netflix.
the class BasicWeeklyCostEmailService method constructEmail.
private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body) throws IOException, MessagingException {
if (index == 0 && !StringUtils.isEmpty(headerNote))
body.append(headerNote);
numberFormatter.setMaximumFractionDigits(1);
numberFormatter.setMinimumFractionDigits(1);
File file = createImage(appGroup);
if (file == null)
return null;
DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end);
body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link, appGroup.getDisplayName()));
body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
for (int i = 0; i <= accounts.size(); i++) {
int cols = i == accounts.size() ? 1 : regions.size();
String accName = i == accounts.size() ? "total" : accounts.get(i).name;
body.append(String.format("<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols)).append(accName).append("</td>");
}
body.append("</tr>");
body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
for (int i = 0; i < accounts.size(); i++) {
boolean first = true;
for (Region region : regions) {
body.append("<td style=\"font-weight: bold;padding: 4px;" + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name).append("</td>");
first = false;
}
}
body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");
Map<String, Double> costs = Maps.newHashMap();
Interval interval = new Interval(end.minusWeeks(numWeeks), end);
double[] total = new double[numWeeks];
for (Product product : products) {
List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
if (resourceGroups.size() == 0) {
continue;
}
DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
if (dataManager == null) {
continue;
}
for (int i = 0; i < accounts.size(); i++) {
List<Account> accountList = Lists.newArrayList(accounts.get(i));
TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null, null, resourceGroups);
Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region, AggregateType.none, false);
for (Tag tag : data.keySet()) {
for (int week = 0; week < numWeeks; week++) {
String key = accounts.get(i) + "|" + tag + "|" + week;
if (costs.containsKey(key))
costs.put(key, data.get(tag)[week] + costs.get(key));
else
costs.put(key, data.get(tag)[week]);
total[week] += data.get(tag)[week];
}
}
}
}
boolean firstLine = true;
DateTime currentWeekEnd = end;
for (int week = numWeeks - 1; week >= 0; week--) {
String weekStr;
if (week == numWeeks - 1)
weekStr = "Last week";
else
weekStr = (numWeeks - week - 1) + " weeks ago";
String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
body.append(String.format("<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>", background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5), formatter.print(currentWeekEnd).substring(5)));
for (int i = 0; i < accounts.size(); i++) {
Account account = accounts.get(i);
for (int j = 0; j < regions.size(); j++) {
Region region = regions.get(j);
String key = account + "|" + region + "|" + week;
double cost = costs.get(key) == null ? 0 : costs.get(key);
Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account), Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
body.append(getValueCell(cost, lastCost, link, firstLine));
}
}
link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions, currentWeekEnd.minusWeeks(1), currentWeekEnd);
body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
body.append("</tr>");
firstLine = false;
currentWeekEnd = currentWeekEnd.minusWeeks(1);
}
body.append("</table>");
numberFormatter.setMaximumFractionDigits(0);
numberFormatter.setMinimumFractionDigits(0);
if (!StringUtils.isEmpty(throughputMetrics))
body.append(throughputMetrics);
body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
String product = entry.getKey();
List<String> selected = entry.getValue();
if (selected == null || selected.size() == 0)
continue;
link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end);
body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>", getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
for (String name : selected) body.append(" ").append(name).append("<br>");
}
body.append("<hr><br>");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setFileName(file.getName());
DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
mimeBodyPart.setDataHandler(new DataHandler(ds));
mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
mimeBodyPart.setHeader("Content-Disposition", "inline");
mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
file.delete();
return mimeBodyPart;
}
use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.
the class DefaultSmtpAgent method getNotificationPart.
/*
* try to get the notification part of an multipart/report message
*/
private MimeBodyPart getNotificationPart(Message noteMessage) {
MimeBodyPart retVal = null;
try {
ByteArrayDataSource dataSource = new ByteArrayDataSource(noteMessage.getRawInputStream(), noteMessage.getContentType());
MimeMultipart dispMsg = new MimeMultipart(dataSource);
retVal = (MimeBodyPart) dispMsg.getBodyPart(1);
} catch (Exception e) {
}
return retVal;
}
use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.
the class DocumentRepositoryAbstract method provideAndRegisterDocumentSet.
/**
* Handle an incoming ProvideAndRegisterDocumentSetRequestType object and
* transform to XDM or relay to another XDR endponit.
*
* @param prdst
* The incoming ProvideAndRegisterDocumentSetRequestType object
* @return a RegistryResponseType object
* @throws Exception
*/
protected RegistryResponseType provideAndRegisterDocumentSet(ProvideAndRegisterDocumentSetRequestType prdst) throws Exception {
RegistryResponseType resp = null;
try {
getHeaderData();
@SuppressWarnings("unused") InitialContext ctx = new InitialContext();
DirectDocuments documents = xdsDirectDocumentsTransformer.transform(prdst);
List<String> forwards = new ArrayList<String>();
// Get endpoints (first check direct:to header, then go to intendedRecipients)
if (StringUtils.isNotBlank(directTo))
forwards = Arrays.asList((new URI(directTo).getSchemeSpecificPart()));
else {
forwards = ParserHL7.parseRecipients(documents);
}
messageId = UUID.randomUUID().toString();
// TODO patID and subsetId
String patId = "PATID TBD";
String subsetId = "SUBSETID";
getAuditMessageGenerator().provideAndRegisterAudit(messageId, remoteHost, endpoint, to, thisHost, patId, subsetId, pid);
// Send to SMTP endpoints
if (getResolver().hasSmtpEndpoints(forwards)) {
// Get a reply address (first check direct:from header, then go to authorPerson)
if (StringUtils.isNotBlank(directFrom))
replyEmail = (new URI(directFrom)).getSchemeSpecificPart();
else {
replyEmail = documents.getSubmissionSet().getAuthorPerson();
replyEmail = StringUtils.splitPreserveAllTokens(replyEmail, "^")[0];
replyEmail = StringUtils.contains(replyEmail, "@") ? replyEmail : "nhindirect@nhindirect.org";
}
LOGGER.info("SENDING EMAIL TO " + getResolver().getSmtpEndpoints(forwards) + " with message id " + messageId);
// Construct message wrapper
DirectMessage message = new DirectMessage(replyEmail, getResolver().getSmtpEndpoints(forwards));
message.setSubject("XD* Originated Message");
message.setBody("Please find the attached XDM file.");
message.setDirectDocuments(documents);
// Send mail
MailClient mailClient = getMailClient();
mailClient.mail(message, messageId, suffix);
}
// Send to XD endpoints
for (String reqEndpoint : getResolver().getXdEndpoints(forwards)) {
String endpointUrl = getResolver().resolve(reqEndpoint);
String to = StringUtils.remove(endpointUrl, "?wsdl");
Long threadId = new Long(Thread.currentThread().getId());
LOGGER.info("THREAD ID " + threadId);
ThreadData threadData = new ThreadData(threadId);
threadData.setTo(to);
List<Document> docs = prdst.getDocument();
// Make a copy of the original documents
List<Document> originalDocs = new ArrayList<Document>();
for (Document d : docs) originalDocs.add(d);
// Clear document list
docs.clear();
// Re-add documents
for (Document d : originalDocs) {
Document doc = new Document();
doc.setId(d.getId());
DataHandler dh = d.getValue();
ByteArrayOutputStream buffOS = new ByteArrayOutputStream();
dh.writeTo(buffOS);
byte[] buff = buffOS.toByteArray();
DataSource source = new ByteArrayDataSource(buff, documents.getDocument(d.getId()).getMetadata().getMimeType());
DataHandler dhnew = new DataHandler(source);
doc.setValue(dhnew);
docs.add(doc);
}
LOGGER.info(" SENDING TO ENDPOINT " + to);
DocumentRepositoryProxy proxy = new DocumentRepositoryProxy(endpointUrl, new DirectSOAPHandlerResolver());
RegistryResponseType rrt = proxy.provideAndRegisterDocumentSetB(prdst);
String test = rrt.getStatus();
if (test.indexOf("Failure") >= 0) {
String error = "";
try {
error = rrt.getRegistryErrorList().getRegistryError().get(0).getCodeContext();
} catch (Exception x) {
}
throw new Exception("Failure Returned from XDR forward:" + error);
}
getAuditMessageGenerator().provideAndRegisterAuditSource(messageId, remoteHost, endpoint, to, thisHost, patId, subsetId, pid);
}
resp = getRepositoryProvideResponse(messageId);
relatesTo = messageId;
action = "urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-bResponse";
to = endpoint;
setHeaderData();
} catch (Exception e) {
e.printStackTrace();
throw (e);
}
return resp;
}
use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.
the class DocumentRepositoryAbstract method provideAndRegisterDocumentSet.
/**
* Handle an incoming ProvideAndRegisterDocumentSetRequestType object and
* transform to XDM or relay to another XDR endponit.
*
* @param prdst
* The incoming ProvideAndRegisterDocumentSetRequestType object
* @return a RegistryResponseType object
* @throws Exception
*/
protected RegistryResponseType provideAndRegisterDocumentSet(ProvideAndRegisterDocumentSetRequestType prdst, SafeThreadData threadData) throws Exception {
RegistryResponseType resp = null;
try {
@SuppressWarnings("unused") InitialContext ctx = new InitialContext();
DirectDocuments documents = xdsDirectDocumentsTransformer.transform(prdst);
List<String> forwards = new ArrayList<String>();
// Get endpoints (first check direct:to header, then go to intendedRecipients)
if (StringUtils.isNotBlank(threadData.getDirectTo()))
forwards = Arrays.asList((new URI(threadData.getDirectTo()).getSchemeSpecificPart()));
else {
forwards = ParserHL7.parseDirectRecipients(documents);
}
// messageId = UUID.randomUUID().toString(); remove this , its is not righ,
//we should keep the message id of the original message for a lot of reasons vpl
// TODO patID and subsetId for atn
String patId = threadData.getMessageId();
String subsetId = threadData.getMessageId();
getAuditMessageGenerator().provideAndRegisterAudit(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
// Send to SMTP endpoints
if (getResolver().hasSmtpEndpoints(forwards)) {
String replyEmail;
// Get a reply address (first check direct:from header, then go to authorPerson)
if (StringUtils.isNotBlank(threadData.getDirectFrom()))
replyEmail = (new URI(threadData.getDirectFrom())).getSchemeSpecificPart();
else {
// replyEmail = documents.getSubmissionSet().getAuthorPerson();
replyEmail = documents.getSubmissionSet().getAuthorTelecommunication();
// replyEmail = StringUtils.splitPreserveAllTokens(replyEmail, "^")[0];
replyEmail = ParserHL7.parseXTN(replyEmail);
replyEmail = StringUtils.contains(replyEmail, "@") ? replyEmail : "nhindirect@nhindirect.org";
}
LOGGER.info("SENDING EMAIL TO " + getResolver().getSmtpEndpoints(forwards) + " with message id " + threadData.getMessageId());
// Construct message wrapper
DirectMessage message = new DirectMessage(replyEmail, getResolver().getSmtpEndpoints(forwards));
message.setSubject("XD* Originated Message");
message.setBody("Please find the attached XDM file.");
message.setDirectDocuments(documents);
// Send mail
MailClient mailClient = getMailClient();
String fileName = threadData.getMessageId().replaceAll("urn:uuid:", "");
mailClient.mail(message, fileName, threadData.getSuffix());
getAuditMessageGenerator().provideAndRegisterAuditSource(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
}
// Send to XD endpoints
for (String reqEndpoint : getResolver().getXdEndpoints(forwards)) {
String endpointUrl = getResolver().resolve(reqEndpoint);
String to = StringUtils.remove(endpointUrl, "?wsdl");
threadData.setTo(to);
threadData.setDirectTo(to);
threadData.save();
List<Document> docs = prdst.getDocument();
// Make a copy of the original documents
List<Document> originalDocs = new ArrayList<Document>();
for (Document d : docs) originalDocs.add(d);
// Clear document list
docs.clear();
// Re-add documents
for (Document d : originalDocs) {
Document doc = new Document();
doc.setId(d.getId());
DataHandler dh = d.getValue();
ByteArrayOutputStream buffOS = new ByteArrayOutputStream();
dh.writeTo(buffOS);
byte[] buff = buffOS.toByteArray();
DataSource source = new ByteArrayDataSource(buff, documents.getDocument(d.getId()).getMetadata().getMimeType());
DataHandler dhnew = new DataHandler(source);
doc.setValue(dhnew);
docs.add(doc);
}
LOGGER.info(" SENDING TO ENDPOINT " + to);
DocumentRepositoryProxy proxy = new DocumentRepositoryProxy(endpointUrl, new DirectSOAPHandlerResolver());
RegistryResponseType rrt = proxy.provideAndRegisterDocumentSetB(prdst);
String test = rrt.getStatus();
if (test.indexOf("Failure") >= 0) {
String error = "";
try {
error = rrt.getRegistryErrorList().getRegistryError().get(0).getCodeContext();
} catch (Exception x) {
}
throw new Exception("Failure Returned from XDR forward:" + error);
}
getAuditMessageGenerator().provideAndRegisterAuditSource(threadData.getMessageId(), threadData.getRemoteHost(), threadData.getRelatesTo(), threadData.getTo(), threadData.getThisHost(), patId, subsetId, threadData.getPid());
}
resp = getRepositoryProvideResponse(threadData.getMessageId());
String relatesTo = threadData.getRelatesTo();
threadData.setRelatesTo(threadData.getMessageId());
threadData.setAction("urn:ihe:iti:2007:ProvideAndRegisterDocumentSet-bResponse");
threadData.setTo(null);
threadData.save();
} catch (Exception e) {
e.printStackTrace();
throw (e);
}
return resp;
}
use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.
the class MDNStandard method getNotificationFieldsAsHeaders.
/**
* Parses the notification part fields of a MDN MimeMessage message. The message is expected to conform to the MDN specification
* as described in RFC3798.
* @return The notification part fields as a set of Internet headers.
*/
public static InternetHeaders getNotificationFieldsAsHeaders(MimeMessage message) {
if (message == null)
throw new IllegalArgumentException("Message can not be null");
MimeMultipart mm = null;
try {
ByteArrayDataSource dataSource = new ByteArrayDataSource(message.getRawInputStream(), message.getContentType());
mm = new MimeMultipart(dataSource);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse notification fields.", e);
}
return getNotificationFieldsAsHeaders(mm);
}
Aggregations