Java javax.mail.util.ByteArrayDataSource 代码实例

・36 分钟阅读

以下是展示如何使用javax.mail.util.ByteArrayDataSource的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public void attachWB(XSSFWorkbook wb, String fileName) {
        messageBodyPart = new MimeBodyPart();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataSource ds = null;
        try {
                wb.write(baos);
                byte[] bytes = baos.toByteArray();
                ds = new ByteArrayDataSource(bytes, "application/excel");
                DataHandler dh = new DataHandler(ds);
                messageBodyPart.setDataHandler(dh);
                messageBodyPart.setFileName(fileName + ".xlsx");
                multipart.addBodyPart(messageBodyPart);
                message.setContent(multipart);
        } catch (IOException e) {
                e.printStackTrace();
        } catch (MessagingException e) {
                e.printStackTrace();
        }
}
 

实例 2


public Object getReadControlObject() {
    Employee emp = new Employee(123);
    byte[] bytes = new byte[] { 0, 1, 2, 3};
    emp.setPhoto(bytes);
    ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "application/octet-stream");
    DataHandler dh = new DataHandler(ds);
    emp.setData(dh);
    return emp;
}
 

实例 3


/**
 * For backward compatibility: assumes format METS_EXT1_0.uri
 *
 * @deprecated use ingestAndCommit(apia, apim, in, ingestFormat, logMessage)
 *             instead.
 */
@Deprecated
public static String ingestAndCommit(FedoraAPIAMTOM apia,
                                     FedoraAPIMMTOM apim,
                                     InputStream in,
                                     String logMessage)
        throws RemoteException, IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    StreamUtility.pipeStream(in, out, 4096);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(out.toByteArray(),
    "text/xml"));
    String pid = apim.ingest(handler, METS_EXT1_0.uri, logMessage);
    return pid;
}
 

实例 4


@Override @LogException
public void send(Message message) {
    try {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(message.getSubject(), Charsets.UTF_8.name());
        mimeMessage.addRecipients(RecipientType.TO, toArray(message.getTo()));
        mimeMessage.addRecipients(RecipientType.BCC, toArray(message.getBcc()));
        mimeMessage.setFrom(new InternetAddress(configuration.getProperty("smtp.from",
                "[email protected]"), configuration.getProperty("smtp.from.name", "ActivityInfo")));
        if (message.getReplyTo() != null) {
            mimeMessage.setReplyTo(new Address[]{message.getReplyTo()});
        }
        String body;
        if (message.hasHtmlBody()) {
            body = message.getHtmlBody();
            mimeMessage.setDataHandler(new DataHandler(new HTMLDataSource(body)));
        } else {
            body = message.getTextBody();
            mimeMessage.setText(body, Charsets.UTF_8.name());
        }
        LOGGER.finest("message to " + message.getTo() + ":n" + body);
        if (!message.getAttachments().isEmpty()) {
            Multipart multipart = new MimeMultipart();
            for (MessageAttachment attachment : message.getAttachments()) {
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(attachment.getFilename());
                DataSource src = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
                part.setDataHandler(new DataHandler(src));
                multipart.addBodyPart(part);
            }
            mimeMessage.setContent(multipart);
        }
        mimeMessage.saveChanges();
        Transport.send(mimeMessage);
    } catch (MessagingException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 

实例 5


private static MimeBodyPart createXmlAttachment(Student student) {
  byte[] xmlBytes = getXmlBytes(student);
  DataSource ds = new ByteArrayDataSource(xmlBytes, "text/xml");
  DataHandler dh = new DataHandler(ds);
  MimeBodyPart filePart = new MimeBodyPart();
  try {
    String xmlFileTitle = student.getId() + ".xml";
    filePart.setDataHandler(dh);
    filePart.setFileName(xmlFileTitle);
    filePart.setDescription("XML file for " + student.getFullName());
  } catch (MessagingException ex) {
    err.println("** Exception with file part: " + ex);
    System.exit(1);
  }
  return filePart;
}
 

实例 6


public MimeMultipart readFrom(
        Class<MimeMultipart> type, 
        Type genericType, 
        Annotation annotations[],
        MediaType mediaType, 
        MultivaluedMap<String, String> httpHeaders, 
        InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
 

实例 7


public MimeMultipart readFrom(
        Class<MimeMultipart> type, 
        Type genericType, 
        Annotation annotations[],
        MediaType mediaType, 
        MultivaluedMap<String, String> httpHeaders, 
        InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
 

实例 8


public MimeMultipart readFrom(
        Class<MimeMultipart> type, 
        Type genericType, 
        Annotation annotations[],
        MediaType mediaType, 
        MultivaluedMap<String, String> httpHeaders, 
        InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
 

实例 9


/**
 * Adds an embedded image (attachment type) to the email message and generates the necessary {@link DataSource} with the given byte
 * data. Then delegates to {@link #addEmbeddedImage(String, DataSource)}. At this point the datasource is actually a
 * {@link ByteArrayDataSource}.
 *
 * @param name The name of the image as being referred to from the message content body (eg. '&lt;cid:signature&gt;').
 * @param data The byte data of the image to be embedded.
 * @param mimetype The content type of the given data (eg. "image/gif" or "image/jpeg").
 * @see ByteArrayDataSource
 * @see #addEmbeddedImage(String, DataSource)
 */
public void addEmbeddedImage(final String name, final byte[] data, final String mimetype) {
        final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, mimetype);
        dataSource.setName(name);
        addEmbeddedImage(name, dataSource);
}
 

实例 10


protected OMElement addOneDocument(OMElement request, String document, String documentId, boolean includeWhitespace) throws IOException {
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007" , null);
        OMElement docElem = fac.createOMElement("Document", ns);
        docElem.addAttribute("id", documentId, null);
       // A string, turn it into an StreamSource
    DataSource ds = new ByteArrayDataSource(document, "text/xml"); 
        DataHandler handler = new DataHandler(ds);
       OMText binaryData = fac.createOMText(handler, true);
       if (includeWhitespace)
       {
        /** The whitespace */
        docElem.addChild(fac.createOMText("n"));
       }
       docElem.addChild(binaryData);
       Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest");
       OMElement submitObjectsRequest = null;
       for (;iter.hasNext();) {
        submitObjectsRequest = (OMElement)iter.next();
        if (submitObjectsRequest != null)
                break;
       }
       submitObjectsRequest.insertSiblingAfter(docElem);
       return request;
}
 

实例 11


/**
 * This function convert the base64String encoded image to actual Image and store it in specified directory path
 * @param base64String text encoded Image ,path Path to store the Image,This process repeats for every received message
 * @throwsI OException
 */
public static void WriteImageFromBase64(String base64String, String path) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(base64String);
        bytearr = new ByteArrayDataSource(buf, "image/jpeg");
        InputStream in = bytearr.getInputStream();
        File file = new File(path);
        byte buf1[] = new byte[1024];
        int len;
        FileOutputStream fos = new FileOutputStream(file);
        while((len = in.read(buf)) > 0)
                fos.write(buf, 0, len);
        fos.close();
        in.close();
}
 

实例 12


/**Verifies the signature of the passed signed part*/
public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType, X509Certificate certificate) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    String signatureTransferEncoding = null;
    MimeMultipart checkPart = (MimeMultipart) signedPart.getContent();
    //it is sure that it is a signed part: set the type to multipart if the
    //parser has problems parsing it. Don't know why sometimes a parsing fails for
    //MimeBodyPart. This check looks if the parser is able to find more than one subpart
    if (checkPart.getCount() == 1) {
        MimeMultipart multipart = new MimeMultipart(
                new ByteArrayDataSource(data, contentType));
        MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null));
        possibleSignedMessage.setContent(multipart, multipart.getContentType());
        possibleSignedMessage.saveChanges();
        //overwrite the formerly found signed part
        signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage);
    }
    //get the content encoding of the signature
    MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent();
    //body part 1 is always the signature
    String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding");
    if (encodingHeader != null) {
        signatureTransferEncoding = encodingHeader[0];
    }
    return (helper.verify(signedPart, signatureTransferEncoding, certificate));
}
 

实例 13


/**
 * @param notification
 * @param sender
 * @param summary
 * @param messageText
 * @param to
 * @return
 * @throws NotificationException
 */
public static Hashtable sendEmail(Device device, Notification notification,
                NotificationSender sender, String summary, String messageText,
                String to) throws NotificationException {
        // Get system properties
        Properties props = System.getProperties();
        if (props == null)
                props = new Properties();
        String[] smtpServers = BrokerFactory.getConfigurationBroker()
                        .getStringValues("smtp.server");
        if ((smtpServers == null) || (smtpServers.length <= 0)) {
                smtpServers = new String[1];
                smtpServers[0] = "localhost";
        }
        int smtpServerNum = 0;
        boolean succeeded = false;
        int errorNum = 0;
        String error = "";
        String id = "unknown_" + System.currentTimeMillis();
        while ((smtpServerNum < smtpServers.length) && (!succeeded)) {
                try {
                        String smtpServer = smtpServers[smtpServerNum];
                        BrokerFactory.getLoggingBroker().logDebug(
                                        "Trying SMTP Server num " + smtpServerNum + ": "
                                                        + smtpServer + ".");
                        smtpServerNum++;
                        // Setup mail server
                        props.put("mail.smtp.host", smtpServer);
                        // Set the "from" address to the bounce address
                        if (BrokerFactory.getConfigurationBroker().getBooleanValue(
                                        "email.bounce.enable", true)) {
                                props.put("mail.smtp.from", notification.getUuid()
                                                + "_"
                                                + device.getUuid()
                                                + BrokerFactory.getConfigurationBroker()
                                                                .getStringValue("email.bounce.suffix",
                                                                                "-bounce") + "@"
                                                + getDomainPartOfFrom());
                                BrokerFactory.getLoggingBroker().logDebug(
                                                "Bounce address is " + props.get("mail.smtp.from"));
                        }
                        // Get session
                        Session session = Session.getDefaultInstance(props, null);
                        session.getProperties().setProperty("mail.smtp.host",
                                        smtpServer);
                        // Define message
                        MimeMessage message = new MimeMessage(session);
                        InternetAddress returnAddress = getReturnEmailAddress(device,
                                        notification);
                        BrokerFactory.getLoggingBroker().logDebug(
                                        "SMTP from address=" + returnAddress);
                        message.setFrom(returnAddress);
                        message.addRecipient(Message.RecipientType.TO,
                                        new InternetAddress(to));
                        // String[] parts = splitMessage(messageText,
                        // device.getMaxCharactersSize(), device.getMaxMessages());
                        String[] parts = splitMessage(messageText, 10240, device
                                        .getMaxMessages());
                        for (int partNum = 0; partNum < parts.length; partNum++) {
                                if (parts.length < 2) {
                                        message.setSubject(summary);
                                } else {
                                        message.setSubject((partNum + 1) + ": " + summary);
                                }
                                message.setText(parts[partNum]);
                                if (BrokerFactory.getConfigurationBroker().getBooleanValue(
                                                "email.attachments.attach", false)) {
                                        NotificationMessage[] attachments = notification
                                                        .getMessages();
                                        Multipart attachmentParts = new MimeMultipart();
                                        MimeBodyPart attachmentPart = new MimeBodyPart();
                                        attachmentPart.setText(parts[partNum]);
                                        attachmentParts.addBodyPart(attachmentPart);
                                        for (int i = 1; i < attachments.length; i++) {
                                                NotificationMessage attachment = attachments[i];
                                                if (!attachment.getContentType().equals(NotificationMessage.NOTIFICATION_CONTENT_TYPE)) {
                                                        attachmentPart = new MimeBodyPart();
                                                        DataSource source = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
                                                        attachmentPart.setDataHandler(new DataHandler(source));
                                                        attachmentPart.setFileName(attachment.getFilename());
                                                        attachmentParts.addBodyPart(attachmentPart);
                                                }
                                        }
                                        message.setContent(attachmentParts);
                                }
                                // Send message
                                BrokerFactory.getLoggingBroker().logInfo(
                                                "Sending SMTP Email:n" + message.toString());
                                // Check for STMP authentication
                                // If we don't find it, just use the Transport's static
                                // methods
                                // If we do, use the more complicated method that allows
                                // authn
                                String smtpUsername = BrokerFactory
                                                .getConfigurationBroker().getStringValue(
                                                                "smtp.username", null);
                                String smtpPassword = BrokerFactory
                                                .getConfigurationBroker().getStringValue(
                                                                "smtp.password", null);
                                if ((smtpUsername == null) || (smtpPassword == null)) {
                                        Transport.send(message);
                                } else {
                                        Transport tr = session.getTransport("smtp");
                                        tr.connect(smtpServer, smtpUsername, smtpPassword);
                                        message.saveChanges(); // don't forget this
                                        tr.sendMessage(message, message.getAllRecipients());
                                        tr.close();
                                }
                        }
                        id = message.getMessageID();
                        succeeded = true;
                } catch (AddressException e) {
                        e.printStackTrace();
                        error = e.getMessage();
                        errorNum = NotificationException.FAILED;
                        notification.getSender().handleBounce(device);
                        BrokerFactory.getLoggingBroker().logError(e);
                } catch (MessagingException e) {
                        e.printStackTrace();
                        error = e.getMessage();
                        errorNum = NotificationException.TEMPORARILY_FAILED;
                        BrokerFactory.getLoggingBroker().logError(e);
                }
        }
        if (!succeeded) {
                throw new NotificationException(errorNum, error);
        }
        Hashtable params = new Hashtable();
        params.put("tracking number", id);
        return params;
}
 

实例 14


public static void send(MailMessage message, Session session) throws InvalidMailAddressException, MailDispatcherException {
        final MimeMessage mimeMessage = new MimeMessage(session);
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        final Multipart multipart = new MimeMultipart();
        Iterator<String> iterator = null;
        boolean hasAdress = false;
        List<String> incorrectAddresses = new ArrayList<String>();
        try {
           // From
           if (StringHelper.isEmpty(message.getFromAddress())) {
                // skip the send
                throw InvalidMailAddressException.emptyFromMailAddressException();
           }
           try {
                mimeMessage.setFrom(new InternetAddress(message.getFromAddress(), true));
           } catch (final AddressException ade) {
                // skip the send
                throw InvalidMailAddressException.invalidMailAddressException(message.getFromAddress());
           }
           mimeMessage.setSubject(message.getSubject(), message.getBodyCharSet());
           // mime type and charset
           messageBodyPart.setContent(message.getBody(), message.getBodyContentType() + "; charset=" + message.getBodyCharSet());
           // priority
           mimeMessage.addHeaderLine("X-Priority: " + String.valueOf(message.getPriority()));
           // first part of the message as multipart
           multipart.addBodyPart(messageBodyPart);
           // To Addresses
           if (message.getToAddresses() != null) {
                for (iterator = message.getToAddresses().iterator(); iterator.hasNext();) {
                   String mail = iterator.next();
                   try {
                        mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, true));
                        hasAdress = true;
                   } catch (final Throwable ae) {
                        incorrectAddresses.add(mail);
                   }
                }
           }
           // CC Addresses
           if (message.getCcAddresses() != null) {
                for (iterator = message.getCcAddresses().iterator(); iterator.hasNext();) {
                   String mail = iterator.next();
                   try {
                        mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(mail, true));
                        hasAdress = true;
                   } catch (final Throwable ae) {
                        incorrectAddresses.add(mail);
                   }
                }
           }
           // BCC Addresses
           if (message.getBccAddresses() != null) {
                for (iterator = message.getBccAddresses().iterator(); iterator.hasNext();) {
                   String mail = iterator.next();
                   try {
                        mimeMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail, true));
                        hasAdress = true;
                   } catch (final Throwable ae) {
                        incorrectAddresses.add(mail);
                   }
                }
           }
           // Attachments
           if (hasAdress && message.getAttachmentNames() != null) {
                for (final String attachName : message.getAttachmentNames()) {
                   try {
                        final MailAttachment mailAttach = message.getAttachment(attachName);
                        StringBuilder contentType = new StringBuilder();
                        if (mailAttach.getContentType() != null) {
                           contentType.append(mailAttach.getContentType());
                        }
                        if (mailAttach.getContentCharset() != null) {
                           if (contentType.length() > 0) {
                                contentType.append("; ");
                           }
                           contentType.append("charset=").append(mailAttach.getContentCharset());
                        }
                        messageBodyPart = new MimeBodyPart();
                        messageBodyPart.setFileName(attachName);
                        messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(mailAttach.getInputStream(), contentType.length() > 0 ? contentType
                                .toString() : null)));
                        multipart.addBodyPart(messageBodyPart);
                   } catch (IOException ioe) {
                        // skip the send
                        throw MailDispatcherException.ioReadMailAttachmentException(attachName, ioe);
                   }
                }
           }
           // add content to the envelope
           mimeMessage.setContent(multipart);
        } catch (MessagingException me) {
           // technical error while building the mail message
           throw new MailDispatcherException("mail.service.message.build.error", me);
        }
        // send the message
        if (hasAdress == true) {
           try {
                long currentTimeMillis = System.currentTimeMillis();
                LOGGER.debug("mail sending starting at {}", new Date().toString());
                Transport.send(mimeMessage);
                LOGGER.debug("mail sending ended in an elapsed time of {} ms", System.currentTimeMillis() - currentTimeMillis);
           } catch (MessagingException me) {
                // error while sending the mail message
                throw new MailDispatcherException("mail.service.message.send.error", me);
           }
        }
        // no valid address & no incorrect address
        if (!hasAdress && incorrectAddresses.isEmpty()) {
           throw InvalidMailAddressException.emptyToMailAddressException();
        }
        // valid address & incorrect address
        else if (!incorrectAddresses.isEmpty()) { throw InvalidMailAddressException.invalidMailAddressException(incorrectAddresses
                .toArray(new String[incorrectAddresses.size()])); }
   }
 

实例 15


@Override
public void encodeEnd(FacesContext context) throws IOException
{
   DataSource ds = null;
   try
   {
      if (getValue() instanceof URL)
      {
         URL url = (URL) getValue();
         ds = new URLDataSource(url);
      }
      else if (getValue() instanceof File)
      {
         File file = (File) getValue();
         ds = new FileDataSource(file);
      }
      else if (getValue() instanceof String)
      {
         String string = (String) getValue();
         ds = new URLDataSource( FacesResources.getResource( string, context.getExternalContext() ) );
      }
      else if (getValue() instanceof InputStream)
      {
         InputStream is = (InputStream) getValue();
         ds = new ByteArrayDataSource(is, getContentType());
      }
      else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData"))
      {
         Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
         Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
         Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
         Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
         ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
      }
      else if (getValue() != null && getValue().getClass().isArray())
      {
         if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE))
         {
            byte[] b = (byte[]) getValue();
            ds = new ByteArrayDataSource(b, getContentType());
         }
      }
      if (ds != null)
      {
          // Check the DataSource is available
          try
          {
              ds.getInputStream();
          }
          catch (Exception e) 
          {
              if (value != null)
              {
                  throw new NullPointerException("Error accessing " + value);
              }
              else
              {
                  throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
              }
         }
         MimeBodyPart attachment = new MimeBodyPart();
         // Need to manually set the contentid
         String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
         if(disposition.equals("inline"))
         {
            attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
         }
         attachment.setDataHandler(new DataHandler(ds));
         attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
         attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
         findMessage().getAttachments().add(attachment);
         if (getStatus() != null)
         {
            AttachmentStatus attachmentStatus = new AttachmentStatus();
            if(disposition.equals("inline"))
            {
               attachmentStatus.setContentId(contentId);
            }
            Contexts.getEventContext().set(getStatus(), attachmentStatus);
         }
      }
   }
   catch (MessagingException e)
   {
      throw new FacesException(e.getMessage(), e);
   }
}
 
讨论
淘淘あ西西 profile image