List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(String data, String type) throws IOException
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private void addEncryptedPDF(MimeMessage message, byte[] pdf) throws MessagingException { /*//from ww w .j av a2 s. co m * Find the existing PDF. The expect that the message is a multipart/mixed. */ if (!message.isMimeType("multipart/mixed")) { throw new MessagingException("Content-type should have been multipart/mixed."); } Multipart mp; try { mp = (Multipart) message.getContent(); } catch (IOException e) { throw new MessagingException("Error getting message content.", e); } BodyPart pdfPart = null; /* * Fallback in case the template does not contain a DjigzoHeader.MARKER */ BodyPart fallbackPart = null; for (int i = 0; i < mp.getCount(); i++) { BodyPart part = mp.getBodyPart(i); if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) { pdfPart = part; break; } /* * Fallback scanning for application/pdf in case the template does not contain a DjigzoHeader.MARKER */ if (part.isMimeType("application/pdf")) { fallbackPart = part; } } if (pdfPart == null) { if (fallbackPart != null) { getLogger().info("Marker not found. Using ocet-stream instead."); /* * Use the octet-stream part */ pdfPart = fallbackPart; } else { throw new MessagingException("Unable to find the attachment part in the template."); } } pdfPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pdf, "application/pdf"))); }
From source file:fr.gouv.culture.thesaurus.util.MailUtil.java
/** * Ajoute une pice jointe l'email courant. * //from w ww .j a v a2s. c om * @param data * le flux d'entre des donnes de la pice jointe * @param contentType * le type de contenu * @param fileName * le nom du fichier * @param description * la description * @throws IOException * Erreur de lecture des donnes binaires. */ public void addAttachment(InputStream data, String contentType, String fileName, String description) throws IOException { attachments.add(new AttachmentBean(new ByteArrayDataSource(data, contentType), fileName, description)); }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @param msg// w w w . j a v a 2s. c om * @throws MessagingException * @throws IOException */ public void createForwardMessage(Message msg) throws MessagingException, IOException { init(); setSubject("Fwd: " + msg.getSubject()); setHtmlMessage(MessageUtils.isHtmlMessage(msg)); List<MimePart> attachments = MessageUtils.attachmentsFromPart(msg); if (attachments != null) { for (MimePart part : attachments) { DataSource source = part.getDataHandler().getDataSource(); ByteArrayDataSource newSource = new ByteArrayDataSource(source.getInputStream(), source.getContentType()); if (StringUtils.isEmpty(source.getName())) { newSource.setName(this.applicationContext.getMessage("message.unknown.attachment", null, SessionManager.get().getLocale())); } else { newSource.setName(source.getName()); } addComposeAttachment(newSource); } } Preferences prefs = SessionManager.get().getPreferences(); MessageTextUtil.messageTextFromPart(msg, this, true, MessageTextMode.REPLY, prefs, 0); }
From source file:voldemort.restclient.R2Store.java
private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) { Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>(); try {/*from ww w. j av a 2s. c om*/ // Build the multipart object byte[] bytes = new byte[entity.length()]; entity.copyBytes(bytes, 0); // Get the outer multipart object ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed"); MimeMultipart mp = new MimeMultipart(ds); for (int i = 0; i < mp.getCount(); i++) { // Get an individual part. This contains all the versioned // values for a particular key referenced by content-location MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i); // Get the key String contentLocation = part.getHeader("Content-Location")[0]; String base64Key = contentLocation.split("/")[2]; ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key)); if (logger.isDebugEnabled()) { logger.debug("Content-Location : " + contentLocation); logger.debug("Base 64 key : " + base64Key); } // Create an array list for holding all the (versioned values) List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>(); // Get the nested Multi-part object. This contains one part for // each unique versioned value. ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(), "multipart/mixed"); MimeMultipart valueParts = new MimeMultipart(nestedDS); for (int valueId = 0; valueId < valueParts.getCount(); valueId++) { MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId); String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]; int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]); if (logger.isDebugEnabled()) { logger.debug("Received serialized Vector Clock : " + serializedVC); } VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class); // get the value bytes InputStream input = valuePart.getInputStream(); byte[] bodyPartBytes = new byte[contentLength]; input.read(bodyPartBytes); VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp()); valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock)); } results.put(key, valueResultList); } } catch (MessagingException e) { throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonParseException e) { throw new VoldemortException( "JSON parsing exception while trying to parse GET response " + e.getMessage(), e); } catch (JsonMappingException e) { throw new VoldemortException( "JSON mapping exception while trying to parse GET response " + e.getMessage(), e); } catch (IOException e) { throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e); } return results; }
From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Compresses the payload using the ZLIB algorithm *///w ww. j a va2 s . c o m private MimeBodyPart compressPayload(Partner receiver, byte[] data, String contentType) throws SMIMEException, MessagingException { MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); bodyPart.addHeader("Content-Type", contentType); if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { bodyPart.addHeader("Content-Transfer-Encoding", "base64"); } else { bodyPart.addHeader("Content-Transfer-Encoding", "binary"); } SMIMECompressedGenerator generator = new SMIMECompressedGenerator(); if (receiver.getContentTransferEncoding() == AS2Message.CONTENT_TRANSFER_ENCODING_BASE64) { generator.setContentTransferEncoding("base64"); } else { generator.setContentTransferEncoding("binary"); } return (generator.generate(bodyPart, SMIMECompressedGenerator.ZLIB)); }
From source file:org.openhealthtools.openxds.integrationtests.XdsTest.java
protected OMElement addOneDocument(OMElement request, String document, String documentId) 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); docElem.addChild(binaryData);/*from ww w . j a v a 2 s. c om*/ Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest"); OMElement submitObjectsRequest = null; for (; iter.hasNext();) { submitObjectsRequest = (OMElement) iter.next(); if (submitObjectsRequest != null) break; } submitObjectsRequest.insertSiblingAfter(docElem); return request; }
From source file:com.mirth.connect.connectors.http.HttpReceiver.java
private HttpRequestMessage createRequestMessage(Request request, boolean ignorePayload) throws IOException, MessagingException { HttpRequestMessage requestMessage = new HttpRequestMessage(); requestMessage.setMethod(request.getMethod()); requestMessage.setHeaders(HttpMessageConverter.convertFieldEnumerationToMap(request)); requestMessage.setParameters(extractParameters(request)); ContentType contentType;//from w w w . j av a 2 s. c o m try { contentType = ContentType.parse(request.getContentType()); } catch (RuntimeException e) { contentType = ContentType.TEXT_PLAIN; } requestMessage.setContentType(contentType); requestMessage.setRemoteAddress(StringUtils.trimToEmpty(request.getRemoteAddr())); requestMessage.setQueryString(StringUtils.trimToEmpty(request.getQueryString())); requestMessage.setRequestUrl(StringUtils.trimToEmpty(getRequestURL(request))); requestMessage.setContextPath(StringUtils.trimToEmpty(new URL(requestMessage.getRequestUrl()).getPath())); if (!ignorePayload) { InputStream requestInputStream = request.getInputStream(); // If a security handler already consumed the entity, get it from the request attribute instead try { byte[] entity = (byte[]) request.getAttribute(EntityProvider.ATTRIBUTE_NAME); if (entity != null) { requestInputStream = new ByteArrayInputStream(entity); } } catch (Exception e) { } // If the request is GZIP encoded, uncompress the content List<String> contentEncodingList = requestMessage.getCaseInsensitiveHeaders() .get(HTTP.CONTENT_ENCODING); if (CollectionUtils.isNotEmpty(contentEncodingList)) { for (String contentEncoding : contentEncodingList) { if (contentEncoding != null && (contentEncoding.equalsIgnoreCase("gzip") || contentEncoding.equalsIgnoreCase("x-gzip"))) { requestInputStream = new GZIPInputStream(requestInputStream); break; } } } /* * First parse out the body of the HTTP request. Depending on the connector settings, * this could end up being a string encoded with the request charset, a byte array * representing the raw request payload, or a MimeMultipart object. */ // Only parse multipart if XML Body is selected and Parse Multipart is enabled if (connectorProperties.isXmlBody() && connectorProperties.isParseMultipart() && ServletFileUpload.isMultipartContent(request)) { requestMessage.setContent( new MimeMultipart(new ByteArrayDataSource(requestInputStream, contentType.toString()))); } else if (isBinaryContentType(contentType)) { requestMessage.setContent(IOUtils.toByteArray(requestInputStream)); } else { requestMessage.setContent(IOUtils.toString(requestInputStream, HttpMessageConverter.getDefaultHttpCharset(request.getCharacterEncoding()))); } } return requestMessage; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Writes a passed payload part to the passed message object. *//*from w w w .j av a2 s.c o m*/ public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception { List<Part> attachmentList = new ArrayList<Part>(); AS2Info info = message.getAS2Info(); if (!info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); if (payloadPart.isMimeType("multipart/*")) { //check if it is a CEM if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) { messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM); if (this.logger != null) { this.logger.log(Level.FINE, this.rb.getResourceString("found.cem", new Object[] { messageInfo.getMessageId(), message }), info); } } ByteArrayOutputStream mem = new ByteArrayOutputStream(); payloadPart.writeTo(mem); mem.flush(); mem.close(); MimeMultipart multipart = new MimeMultipart( new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType())); //add all attachments to the message for (int i = 0; i < multipart.getCount(); i++) { //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) { attachmentList.add(multipart.getBodyPart(i)); } } } else { attachmentList.add(payloadPart); } } else { //its a MDN, write whole part attachmentList.add(payloadPart); } //write the parts for (Part attachmentPart : attachmentList) { ByteArrayOutputStream payloadOut = new ByteArrayOutputStream(); InputStream payloadIn = attachmentPart.getInputStream(); this.copyStreams(payloadIn, payloadOut); payloadOut.flush(); payloadOut.close(); byte[] data = payloadOut.toByteArray(); AS2Payload as2Payload = new AS2Payload(); as2Payload.setData(data); String[] contentIdHeader = attachmentPart.getHeader("content-id"); if (contentIdHeader != null && contentIdHeader.length > 0) { as2Payload.setContentId(contentIdHeader[0]); } String[] contentTypeHeader = attachmentPart.getHeader("content-type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { as2Payload.setContentType(contentTypeHeader[0]); } try { as2Payload.setOriginalFilename(payloadPart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } if (as2Payload.getOriginalFilename() == null) { String filenameheader = header.getProperty("content-disposition"); if (filenameheader != null) { //test part for convinience: extract file name MimeBodyPart filenamePart = new MimeBodyPart(); filenamePart.setHeader("content-disposition", filenameheader); try { as2Payload.setOriginalFilename(filenamePart.getFileName()); } catch (MessagingException e) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error", new Object[] { info.getMessageId(), e.getMessage(), }), info); } } } } message.addPayload(as2Payload); } }
From source file:be.e_contract.dssp.client.DigitalSignatureServiceClient.java
private String addAttachment(String mimetype, byte[] data) { String contentId = UUID.randomUUID().toString(); LOG.debug("adding attachment: " + contentId); DataSource dataSource = new ByteArrayDataSource(data, mimetype); DataHandler dataHandler = new DataHandler(dataSource); BindingProvider bindingProvider = (BindingProvider) this.dssPort; Map<String, Object> requestContext = bindingProvider.getRequestContext(); Map<String, DataHandler> outputMessageAttachments = new HashMap<String, DataHandler>(); requestContext.put(MessageContext.OUTBOUND_MESSAGE_ATTACHMENTS, outputMessageAttachments); outputMessageAttachments.put(contentId, dataHandler); return contentId; }
From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerWriter.java
private GenericArtifact[] createProjectTrackerAttachment(GenericArtifact ga) { String targetArtifactId = ga.getDepParentTargetArtifactId(); String artifactId = ptHelper.getArtifactIdFromFullyQualifiedArtifactId(targetArtifactId); TrackerWebServicesClient twsclient = null; GenericArtifact parentArtifact = null; byte[] data = null; String attachmentMimeType = null; String attachmentName = null; DataSource dataSource = null; File attachmentFile = null;/*from w w w .j a va 2 s. c o m*/ String repositoryId = ga.getTargetRepositoryId(); try { twsclient = this.getConnection(ga); ClientArtifactListXMLHelper currentArtifactHelper = twsclient.getArtifactById(artifactId); ClientArtifact currentArtifact = currentArtifactHelper.getAllArtifacts().get(0); String retrievedArtifactId = currentArtifact.getArtifactID(); if (!artifactId.equals(retrievedArtifactId)) { log.warn("Artifact seems to have moved, old id: " + artifactId + ", new id: " + retrievedArtifactId + ", so do not ship it ..."); return new GenericArtifact[] { ga }; } String retrievedProject = currentArtifact.getProject(); if (retrievedProject != null) { String projectName = null; if (repositoryId != null) { String[] splitProjectName = repositoryId.split(":"); if (splitProjectName != null) { if (splitProjectName.length >= 1) { projectName = splitProjectName[0]; } else { throw new IllegalArgumentException("Repository id " + repositoryId + " is not valid." + " Could not extract project name from repository id"); } } } if (projectName != null) { if (!retrievedProject.equals(projectName)) { log.warn("PT Artifact with id " + artifactId + " has moved from project " + projectName + " to artifact with id " + retrievedArtifactId + " in project " + retrievedProject + ", so do not ship it ..."); return new GenericArtifact[] { ga }; } } } String attachmentType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_TYPE, ga); String sourceAttachmentId = ga.getSourceArtifactId(); String parentSourceArtifactId = ga.getDepParentSourceArtifactId(); if (attachmentType.equals(AttachmentMetaData.AttachmentType.LINK.toString())) { String url = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_SOURCE_URL, ga); url = "<html><body><a href=\"" + url + "\">" + url + "</a></body></html>"; data = url.getBytes(); attachmentMimeType = AttachmentMetaData.TEXT_HTML; attachmentName = "Link-attachment-" + parentSourceArtifactId + "-" + sourceAttachmentId + ".html"; ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType); baDS.setName(attachmentName); dataSource = baDS; } else { String attachmentDataFileName = GenericArtifactHelper .getStringGAField(AttachmentMetaData.ATTACHMENT_DATA_FILE, ga); attachmentMimeType = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_MIME_TYPE, ga); attachmentName = GenericArtifactHelper.getStringGAField(AttachmentMetaData.ATTACHMENT_NAME, ga); if (StringUtils.isEmpty(attachmentDataFileName)) { data = ga.getRawAttachmentData(); ByteArrayDataSource baDS = new ByteArrayDataSource(data, attachmentMimeType); baDS.setName(attachmentName); dataSource = baDS; } else { File attachmentDataFile = new File(attachmentDataFileName); String tempDir = System.getProperty("java.io.tmpdir"); attachmentFile = new File(tempDir, attachmentName); if (attachmentDataFile.exists()) { boolean renamingSuccessful = attachmentDataFile.renameTo(attachmentFile); if (renamingSuccessful) { dataSource = new FileDataSource(attachmentFile); } else { dataSource = new FileDataSource(attachmentDataFile); } } else { String message = "Attachment data file " + attachmentDataFileName + " does not exist."; FileNotFoundException e = new FileNotFoundException(message); log.error(message, e); throw new CCFRuntimeException(message, e); } } } String attachmentDescription = null; attachmentDescription = GenericArtifactHelper .getStringGAField(AttachmentMetaData.ATTACHMENT_DESCRIPTION, ga); if (StringUtils.isEmpty(attachmentDescription)) { attachmentDescription = "Attachment added by Connector"; } long attachmentId = -1; attachmentId = twsclient.postAttachment(artifactId, attachmentDescription, dataSource); currentArtifactHelper = twsclient.getArtifactById(artifactId); currentArtifact = currentArtifactHelper.getAllArtifacts().get(0); String modifiedOn = currentArtifact.getAttributeValue(ProjectTrackerReader.TRACKER_NAMESPACE, ProjectTrackerReader.MODIFIED_ON_FIELD); long modifiedOnMilliSeconds = Long.parseLong(modifiedOn); Date lastModifiedDate = new Date(modifiedOnMilliSeconds); ga.setTargetArtifactId(Long.toString(attachmentId)); ga.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate)); ga.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds)); ga.setDepParentTargetRepositoryId(ga.getTargetRepositoryId()); ga.setDepParentTargetRepositoryKind(ga.getTargetRepositoryKind()); log.info("Attachment with id " + attachmentId + " is created for the PT artifact " + artifactId + " with the attachment " + sourceAttachmentId + " from artifact " + parentSourceArtifactId); parentArtifact = new GenericArtifact(); // make sure that we do not update the synchronization status record // for replayed attachments parentArtifact.setTransactionId(ga.getTransactionId()); parentArtifact.setArtifactType(GenericArtifact.ArtifactTypeValue.PLAINARTIFACT); parentArtifact.setArtifactAction(GenericArtifact.ArtifactActionValue.UPDATE); parentArtifact.setArtifactMode(GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); parentArtifact.setConflictResolutionPriority(ga.getConflictResolutionPriority()); parentArtifact.setSourceArtifactId(ga.getDepParentSourceArtifactId()); parentArtifact.setSourceArtifactLastModifiedDate(ga.getSourceArtifactLastModifiedDate()); parentArtifact.setSourceArtifactVersion(ga.getSourceArtifactVersion()); parentArtifact.setSourceRepositoryId(ga.getSourceRepositoryId()); parentArtifact.setSourceSystemId(ga.getSourceSystemId()); parentArtifact.setSourceSystemKind(ga.getSourceSystemKind()); parentArtifact.setSourceRepositoryKind(ga.getSourceRepositoryKind()); parentArtifact.setSourceSystemTimezone(ga.getSourceSystemTimezone()); parentArtifact.setTargetArtifactId(targetArtifactId); parentArtifact.setTargetArtifactLastModifiedDate(DateUtil.format(lastModifiedDate)); parentArtifact.setTargetArtifactVersion(Long.toString(modifiedOnMilliSeconds)); parentArtifact.setTargetRepositoryId(ga.getTargetRepositoryId()); parentArtifact.setTargetRepositoryKind(ga.getTargetRepositoryKind()); parentArtifact.setTargetSystemId(ga.getTargetSystemId()); parentArtifact.setTargetSystemKind(ga.getTargetSystemKind()); parentArtifact.setTargetSystemTimezone(ga.getTargetSystemTimezone()); } catch (WSException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (RemoteException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (ServiceException e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } catch (Exception e) { String message = "Exception while creating PT artifact attachment"; log.error(message, e); throw new CCFRuntimeException(message, e); } finally { if (attachmentFile != null) { boolean fileDeleted = attachmentFile.delete(); if (!fileDeleted) { log.warn("The temporary attachment file" + attachmentFile.getAbsolutePath() + " could not be deleted"); } } if (twsclient != null) { this.releaseConnection(twsclient); } } return new GenericArtifact[] { ga, parentArtifact }; }