Search in sources :

Example 31 with DataSource

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("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;").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;
}
Also used : DataHandler(javax.activation.DataHandler) DateTime(org.joda.time.DateTime) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) FileInputStream(java.io.FileInputStream) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) Interval(org.joda.time.Interval)

Example 32 with DataSource

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);
}
Also used : Resource(org.springframework.core.io.Resource) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource)

Example 33 with 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);
}
Also used : URLDataSource(javax.activation.URLDataSource) DataHandler(javax.activation.DataHandler) JAXBElement(javax.xml.bind.JAXBElement) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource)

Example 34 with DataSource

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;
}
Also used : DSDispatcher(org.jvnet.ws.wadl.util.DSDispatcher) UriBuilder(org.jvnet.ws.wadl.util.UriBuilder) DataSource(javax.activation.DataSource)

Example 35 with DataSource

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;
}
Also used : DirectMessage(org.nhindirect.xd.common.DirectMessage) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document) URI(java.net.URI) InitialContext(javax.naming.InitialContext) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) DirectDocuments(org.nhindirect.xd.common.DirectDocuments) MailClient(org.nhind.xdm.MailClient) SmtpMailClient(org.nhind.xdm.impl.SmtpMailClient) DirectSOAPHandlerResolver(org.nhindirect.xd.soap.DirectSOAPHandlerResolver) ThreadData(org.nhindirect.xd.soap.ThreadData) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) RegistryResponseType(oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType) DocumentRepositoryProxy(org.nhindirect.xd.proxy.DocumentRepositoryProxy)

Aggregations

DataSource (javax.activation.DataSource)53 DataHandler (javax.activation.DataHandler)31 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)16 InputStream (java.io.InputStream)12 MimeMultipart (javax.mail.internet.MimeMultipart)11 OMFactory (org.apache.axiom.om.OMFactory)11 RandomDataSource (org.apache.axiom.testutils.activation.RandomDataSource)11 MimeBodyPart (javax.mail.internet.MimeBodyPart)10 IOException (java.io.IOException)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 FileDataSource (javax.activation.FileDataSource)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 OMElement (org.apache.axiom.om.OMElement)7 File (java.io.File)6 Reader (java.io.Reader)5 QName (javax.xml.namespace.QName)5 MimeHandlerException (com.zimbra.cs.mime.MimeHandlerException)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 URI (java.net.URI)4 Multipart (javax.mail.Multipart)4