Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.// w ww . j a v  a 2s  . c  o  m
 * 
 * @throws Exception
 */
@Test
public void testScenario() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId);
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

@Test
public void deCanoniseWithAnnotationsSuccessEPML() throws Exception {
    String name = "EPML 2.0";
    InputStream cpf = new ByteArrayDataSource(CanonicalWithAnnotationModel.CANONICAL_XML, "text/xml")
            .getInputStream();/*from ww w.jav a 2s. c o  m*/
    DataSource anf = new ByteArrayDataSource(CanonicalWithAnnotationModel.ANNOTATION_XML, "text/xml");

    Set<Canoniser> availableCanonisers = cSrv.listByNativeType(name);
    Iterator<Canoniser> iter = availableCanonisers.iterator();
    assertTrue(iter.hasNext());
    Canoniser c = iter.next();
    assertNotNull(c);
    assertEquals(name, c.getNativeType());
    assertEquals(0, c.getMandatoryParameters().size());
    assertEquals(1, c.getOptionalParameters().size());

    Set<ParameterType<?>> optionalProperties = c.getOptionalParameters();
    assertEquals(1, optionalProperties.size());

    DecanonisedProcess dp = cSrv.deCanonise(name, getTypeFromXML(cpf), getANFTypeFromXML(anf),
            epmlCanoniserRequest);

    MatcherAssert.assertThat(dp.getNativeFormat(), Matchers.notNullValue());
    MatcherAssert.assertThat(dp.getMessages(), Matchers.notNullValue());
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public MimeMessageHelper addAttachment(String name, String type, byte[] content) throws MessagingException {

    BodyPart attachmentPart = new MimeBodyPart();
    ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(content, type);

    attachmentPart.setDataHandler(new DataHandler(byteArrayDataSource));
    attachmentPart.setFileName(name);/*w w w  . ja  v a  2s. c  o m*/

    attachmentPart.setDisposition(Part.ATTACHMENT);
    attachments.add(attachmentPart);
    return this;
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Using Content-Type " + contentType + " for MimeMessage: " + part);
    }//from   w  w w.j a  v  a2  s .c  o  m

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}

From source file:mitm.common.mail.MailUtils.java

/**
 * Converts any 8bit encoded parts to 7bit. Returns true if a part (or all parts) were converted from
 * 8bit to 7bit./*from   ww w. j  a  va  2s . c  o m*/
 * 
 * @param part
 * @throws MessagingException
 */
public static boolean convertTo7Bit(MimePart part) throws MessagingException, IOException {
    boolean converted = false;

    if (part.isMimeType("multipart/*")) {
        Multipart parts = (Multipart) part.getContent();

        int count = parts.getCount();

        for (int i = 0; i < count; i++) {
            boolean partConverted = convertTo7Bit((MimePart) parts.getBodyPart(i));

            if (partConverted) {
                converted = true;
            }
        }
    } else if ("8bit".equalsIgnoreCase(part.getEncoding())) {
        String encoding = part.isMimeType("text/*") ? "quoted-printable" : "base64";

        /*
         * We need to use a ByteArrayDataSource to make sure it will always be encoded
         */
        part.setDataHandler(
                new DataHandler(new ByteArrayDataSource(part.getInputStream(), part.getContentType())));

        part.setHeader("Content-Transfer-Encoding", encoding);
        part.addHeader("X-MIME-Autoconverted", "from 8bit to " + encoding + " by Djigzo");

        converted = true;
    }

    return converted;
}

From source file:org.simplejavamail.internal.util.MimeMessageParser.java

/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource/*from w  ww .  ja va  2 s .c  o m*/
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part) throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}

From source file:org.pentaho.platform.scheduler2.email.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {/*from  w w w  . j  a va  2s  .co m*/
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (attachment == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }

        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

        if (body != null) {
            MimeBodyPart bodyMessagePart = new MimeBodyPart();
            bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
            multipart.addBodyPart(bodyMessagePart);
        }

        // attach the file to the message
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
        multipart.addBodyPart(attachmentBodyPart);

        // add the Multipart to the message
        msg.setContent(multipart);

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachement(final NodeRef nodeRef, MimeMultipart content, final Boolean convert)
        throws MessagingException {

    MappedByteBuffer buf;/*w ww.ja va  2s. co m*/
    byte[] array = new byte[0];
    ContentReader reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
    String fileName = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);
    String type = reader.getMimetype().split("/")[0];
    if (!type.equalsIgnoreCase("image") && !reader.getMimetype().equalsIgnoreCase(MimetypeMap.MIMETYPE_PDF)
            && convert) {
        ContentWriter writer = contentService.getTempWriter();
        writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
        String srcMimeType = reader.getMimetype();
        //String srcMimeType = ((ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT)).getMimetype();
        //String srcMimeType = this.getMimeTypeForFileName(fileName);
        ContentTransformer transformer = contentService.getTransformer(srcMimeType, MimetypeMap.MIMETYPE_PDF);
        if (transformer != null) {
            try {
                transformer.transform(reader, writer);
                reader = writer.getReader();
                fileName = fileName.substring(0, fileName.lastIndexOf('.'));
                fileName += ".pdf";
            } catch (ContentIOException ex) {
                logger.warn("could not transform content");
                logger.warn(ex);
                //need to refresh reader as the transformer failing closes the reader
                reader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
            }
        }
    }
    try {
        buf = reader.getFileChannel().map(FileChannel.MapMode.READ_ONLY, 0, reader.getSize());
        if (reader.getSize() <= Integer.MAX_VALUE) {
            array = new byte[(int) reader.getSize()];
            buf.get(array);
        }
    } catch (IOException ex) {
        logger.error("There was an error reading file into memory.");
        logger.error(ex);
        array = new byte[0];
    }

    ByteArrayDataSource ds = new ByteArrayDataSource(array, reader.getMimetype());
    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setFileName(fileName);
    attachment.setDataHandler(new DataHandler(ds));
    content.addBodyPart(attachment);
}

From source file:mitm.application.djigzo.ws.impl.MailRepositoryWSImpl.java

@Override
@StartTransaction/* www .java  2 s  . c o m*/
public BinaryDTO getMimeMessage(String id) throws WebServiceCheckedException {
    try {
        MimeMessage message = getItemInternal(id).getMimeMessage();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        MailUtils.writeMessage(message, bos);

        DataSource source = new ByteArrayDataSource(bos.toByteArray(), MimeTypes.OCTET_STREAM);
        DataHandler dataHandler = new DataHandler(source);

        return new BinaryDTO(dataHandler);
    } catch (MessagingException e) {
        throw new WebServiceCheckedException("Error while getting MimeMessage", e);
    } catch (IOException e) {
        throw new WebServiceCheckedException("Error while getting MimeMessage", e);
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
        throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Using Content-Type " + contentType + " for BodyPart: " + part);
    }/*w  ww  .j a  va  2 s.  c  o m*/

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}