use of javax.activation.DataSource 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.activation.DataSource in project spring-framework by spring-projects.
the class MimeMessageHelper method addAttachment.
/**
* Add an attachment to the MimeMessage, taking the content from an
* {@code org.springframework.core.io.InputStreamResource}.
* <p>Note that the InputStream returned by the InputStreamSource
* implementation needs to be a <i>fresh one on each call</i>, as
* JavaMail will invoke {@code getInputStream()} multiple times.
* @param attachmentFilename the name of the attachment as it will
* appear in the mail
* @param inputStreamSource the resource to take the content from
* (all of Spring's Resource implementations can be passed in here)
* @param contentType the content type to use for the element
* @throws MessagingException in case of errors
* @see #addAttachment(String, java.io.File)
* @see #addAttachment(String, javax.activation.DataSource)
* @see org.springframework.core.io.Resource
*/
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
}
DataSource dataSource = createDataSource(inputStreamSource, contentType, attachmentFilename);
addAttachment(attachmentFilename, dataSource);
}
use of javax.activation.DataSource in project spring-framework by spring-projects.
the class StandardClasses method standardClassDataHandler.
public JAXBElement<DataHandler> standardClassDataHandler() {
DataSource dataSource = new URLDataSource(getClass().getResource("spring-ws.png"));
DataHandler dataHandler = new DataHandler(dataSource);
return new JAXBElement<>(NAME, DataHandler.class, dataHandler);
}
use of javax.activation.DataSource in project intellij-community by JetBrains.
the class Endpoint method getArtifactInfoByUri.
public static DataSource getArtifactInfoByUri(String uri) throws IOException, MalformedURLException {
DSDispatcher _dsDispatcher = new DSDispatcher();
UriBuilder _uriBuilder = new UriBuilder();
_uriBuilder.addPathSegment(uri);
String _url = _uriBuilder.buildUri(Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap());
DataSource _retVal = _dsDispatcher.doGET(_url, Collections.<String, Object>emptyMap(), "application/vnd.org.jfrog.artifactory.search.ArtifactSearchResult+json");
return _retVal;
}
use of javax.activation.DataSource 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;
}
Aggregations