List of usage examples for javax.mail.internet MimeBodyPart getDataHandler
@Override public DataHandler getDataHandler() throws MessagingException
From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java
public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException { log.trace("unmarshal(InputStream)"); try {/* ww w .j a v a2 s . c om*/ stream = SharedDeferredStream.toSharedInputStream(stream); MimeMessage mimeMessage = new MimeMessage(session, stream); Object msgContent = mimeMessage.getContent(); if (!(msgContent instanceof MimeMultipart)) { throw new IllegalMessageStructureException( "Expected a multipart mime message, got " + msgContent.getClass()); } MimeMultipart multipart = (MimeMultipart) msgContent; if (multipart.getCount() < 2) { throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts"); } ShsMessage shsMessage = new ShsMessage(); BodyPart labelPart = multipart.getBodyPart(0); if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) { throw new IllegalMessageStructureException( "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType()); } ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent()); shsMessage.setLabel(label); Content content = label.getContent(); if (content == null) { throw new IllegalMessageStructureException("Label contains no content elements"); } // this reads only as many mime body parts as there are content/data elements in the label int i = 1; for (Object o : content.getDataOrCompound()) { MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i); DataHandler dh = dp.getDataHandler(); DataPart dataPart = new DataPart(); dataPart.setDataHandler(new DataHandler( new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType()))); dataPart.setContentType(dh.getContentType()); String encoding = dp.getEncoding(); if (encoding != null) { dataPart.setTransferEncoding(encoding); } dataPart.setFileName(dp.getFileName()); if (o instanceof Data) { Data data = (Data) o; dataPart.setDataPartType(data.getDatapartType()); } else if (o instanceof Compound) { continue; } shsMessage.addDataPart(dataPart); i++; } return shsMessage; } catch (Exception e) { if (e instanceof IllegalMessageStructureException) { throw (IllegalMessageStructureException) e; } throw new IllegalMessageStructureException(e); } }