List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource
public ByteArrayDataSource(String data, String type) throws IOException
From source file:de.extra.extraClientLight.helper.BuildExtraTransport.java
/** * Stellt den Body mit Nutzdaten zusammen * //w w w.ja v a 2s.c o m * @param nutzdaten * Nutzdatenobjekt als Stream * @return TransportRequestBodyType * @throws IOException */ private static TransportRequestBodyType buildBody(InputStream nutzdaten) throws IOException { TransportRequestBodyType requestBody = new TransportRequestBodyType(); DataType data = new DataType(); Base64CharSequenceType payload = new Base64CharSequenceType(); DataSource ds = new ByteArrayDataSource(IOUtils.toByteArray(nutzdaten), "application"); DataHandler dataHandler = new DataHandler(ds); payload.setValue(dataHandler); data.setBase64CharSequence(payload); requestBody.setData(data); return requestBody; }
From source file:stg.pr.engine.mailer.SmallEmailAttachment.java
public DataSource getDataSource() { return new ByteArrayDataSource(bytes, contentType); }
From source file:cz.zcu.kiv.eegdatabase.webservices.semantic.SemanticServiceImpl.java
/** * Generates an ontology document from POJO objects. * This method transforms the Jena's output using Owl-Api. * * @param syntaxType - syntax (rdf,owl,ttl) * @return/*from w w w . j ava 2 s .co m*/ * @throws WebServiceException * @throws IOException * @throws OWLOntologyStorageException * @throws OWLOntologyCreationException */ public DataHandler getOntologyOwlApi(String syntaxType) throws SOAPException { InputStream is = null; byte[] bytes = null; ByteArrayDataSource owl = null; ByteArrayOutputStream os = new ByteArrayOutputStream(); try { int i; is = simpleSemanticFactory.getOntologyOwlApi(syntaxType); while ((i = is.read()) > -1) { os.write(i); } } catch (OWLOntologyCreationException e) { log.error(e); throw new SOAPException(e); } catch (OWLOntologyStorageException e) { log.error(e); throw new SOAPException(e); } catch (IOException e) { log.error(e); throw new SOAPException(e); } owl = new ByteArrayDataSource(os.toByteArray(), "fileBinaryStream"); return new DataHandler(owl); }
From source file:org.apache.axis2.transport.http.MultipartFormDataFormatterTest.java
public void testTransportHeadersOfFileAttachments() throws Exception { String FILE_NAME = "binaryFile.xml"; String FIELD_NAME = "fileData"; String CONTENT_TYPE_VALUE = "text/xml"; String MEDIATE_ELEMENT = "mediate"; String FILE_KEY = "fileAttachment"; String CONTENT_DISPOSITION = "Content-Disposition"; String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; String CONTENT_TYPE = "Content-Type"; String FORM_DATA_ELEMENT = "form-data"; String NAME_ELEMENT = "name"; String FILE_NAME_ELEMENT = "filename"; String CONTENT_TRANSFER_ENCODING_VALUE = "binary"; MultipartFormDataFormatter formatter = new MultipartFormDataFormatter(); File binaryAttachment = getTestResourceFile(FILE_NAME); MessageContext mc = new MessageContext(); DiskFileItem diskFileItem = null;//from w ww .ja va2 s .c o m InputStream input = null; try { if (binaryAttachment.exists() && !binaryAttachment.isDirectory()) { diskFileItem = (DiskFileItem) new DiskFileItemFactory().createItem(FIELD_NAME, CONTENT_TYPE_VALUE, true, binaryAttachment.getName()); input = new FileInputStream(binaryAttachment); OutputStream os = diskFileItem.getOutputStream(); int ret = input.read(); while (ret != -1) { os.write(ret); ret = input.read(); } os.flush(); } } finally { input.close(); } DataSource dataSource = new DiskFileDataSource(diskFileItem); DataHandler dataHandler = new DataHandler(dataSource); SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory(); SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope(); SOAPBody body = soapEnvelope.getBody(); OMElement bodyFirstChild = soapFactory.createOMElement(new QName(MEDIATE_ELEMENT), body); OMText binaryNode = soapFactory.createOMText(dataHandler, true); soapFactory.createOMElement(FILE_KEY, null, bodyFirstChild).addChild(binaryNode); mc.setEnvelope(soapEnvelope); OMOutputFormat format = new OMOutputFormat(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); formatter.writeTo(mc, format, baos, true); MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType())); BodyPart bp = mp.getBodyPart(0); String contentDispositionValue = FORM_DATA_ELEMENT + "; " + NAME_ELEMENT + "=\"" + FILE_KEY + "\"; " + FILE_NAME_ELEMENT + "=\"" + binaryAttachment.getName() + "\""; String contentTypeValue = bp.getHeader(CONTENT_TYPE)[0].split(";")[0]; assertEquals(contentDispositionValue, bp.getHeader(CONTENT_DISPOSITION)[0]); assertEquals(CONTENT_TYPE_VALUE, contentTypeValue); assertEquals(CONTENT_TRANSFER_ENCODING_VALUE, bp.getHeader(CONTENT_TRANSFER_ENCODING)[0]); }
From source file:ee.cyber.licensing.service.MailService.java
public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId) throws MessagingException, IOException, SQLException { License license = licenseRepository.findById(licenseId); List<Contact> contacts = contactRepository.findAll(license.getCustomer()); List<String> receivers = getReceivers(mailbody, contacts); logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }//www . j ava 2s.c o m }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "License dude")); //mailMessage.setReplyTo(InternetAddress.parse(email, false)); mailMessage.setSubject(mailbody.getSubject()); //String emailBody = body + "<br><br> Regards, <br>Cybernetica team"; mailMessage.setSentDate(new Date()); for (String receiver : receivers) { mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); } if (fileId != 0) { MailAttachment file = fileRepository.findById(fileId); if (file != null) { String fileName = file.getFileName(); byte[] fileData = file.getData_b(); if (fileName != null) { // Create a multipart message for attachment Multipart multipart = new MimeMultipart(); // Body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(mailbody.getBody(), "text/html"); multipart.addBodyPart(messageBodyPart); //Attachment part messageBodyPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); mailMessage.setContent(multipart); } } } else { mailMessage.setContent(mailbody.getBody(), "text/html"); } logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.MultimediaWSDaoTestBase.java
@Test public void createSessionMultimediaTest() throws Exception { InputStream is = new ByteArrayInputStream("TEST2".getBytes()); ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg"); DataHandler dataHandler = new DataHandler(rawData); BlackboardMultimediaResponse createSessionMultimedia = dao.createSessionMultimedia(session.getSessionId(), user.getEmail(), "test.mpeg", "aliens", dataHandler); multimedias.add(createSessionMultimedia.getMultimediaId()); List<BlackboardMultimediaResponse> repositoryMultimedias = dao .getSessionMultimedias(session.getSessionId()); assertNotNull(repositoryMultimedias); assertTrue(repositoryMultimedias.size() == 1); }
From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java
/** * Create a MimeBodyPart.//from w ww . jav a2s . c om * * @param item * @return * @throws MessagingException * @throws IOException */ private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException { final String fileName = FilenameUtils.getName(item.getName()); final String contentType = item.getContentType(); final InputStream stream = item.openStream(); ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType); source.setName(fileName); return source; }
From source file:net.maritimecloud.identityregistry.utils.EmailUtil.java
public void sendBugReport(BugReport report) throws MailException, MessagingException { MimeMessage message = this.mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(bugReportEmail);//from w w w. j a v a 2s . c o m helper.setFrom(from); helper.setSubject(report.getSubject()); helper.setText(report.getDescription()); if (report.getAttachments() != null) { for (BugReportAttachment attachment : report.getAttachments()) { // Decode base64 encoded data byte[] data = Base64.getDecoder().decode(attachment.getData()); ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachment.getMimetype()); helper.addAttachment(attachment.getName(), dataSource); } } this.mailSender.send(message); }
From source file:mitm.djigzo.web.pages.dlp.patterns.PatternsImport.java
public void onSuccess() { try {/*from w w w. j ava 2 s . c o m*/ if (file == null) { throw new IllegalStateException("file is null"); } SizeLimitedInputStream limit = new SizeLimitedInputStream(file.getStream(), MAX_XML_SIZE, true /* exception */); DataSource source = new ByteArrayDataSource(limit, file.getContentType()); DataHandler dataHandler = new DataHandler(source); BinaryDTO xml = new BinaryDTO(dataHandler); policyPatternManagerWS.importFromXML(xml, skipExisting); importSuccess = true; } catch (Exception e) { logger.error("Error importing patterns", e); importError = true; importErrorMessage = e.getMessage(); } }
From source file:org.sigmah.server.mail.MailSenderImpl.java
@Override public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException { final String user = email.getAuthenticationUserName(); final String password = email.getAuthenticationPassword(); final Properties properties = new Properties(); properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL); properties.setProperty(MAIL_SMTP_HOST, email.getHostName()); properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort())); final StringBuilder toBuilder = new StringBuilder(); for (final String to : email.getToAddresses()) { if (toBuilder.length() > 0) { toBuilder.append(','); }//from www. j a v a2s . com toBuilder.append(to); } final StringBuilder ccBuilder = new StringBuilder(); if (email.getCcAddresses().length > 0) { for (final String cc : email.getCcAddresses()) { if (ccBuilder.length() > 0) { ccBuilder.append(','); } ccBuilder.append(cc); } } final Session session = javax.mail.Session.getInstance(properties); try { final DataSource attachment = new ByteArrayDataSource(fileStream, FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType()); final Transport transport = session.getTransport(); if (password != null) { transport.connect(user, password); } else { transport.connect(); } final MimeMessage message = new MimeMessage(session); // Configures the headers. message.setFrom(new InternetAddress(email.getFromAddress(), false)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false)); if (email.getCcAddresses().length > 0) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false)); } message.setSubject(email.getSubject(), email.getEncoding()); // Html body part. final MimeMultipart textMultipart = new MimeMultipart("alternative"); final MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\""); textMultipart.addBodyPart(htmlBodyPart); final MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(textMultipart); // Attachment body part. final MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setFileName(fileName); attachmentPart.setDescription(fileName); // Mail multipart content. final MimeMultipart contentMultipart = new MimeMultipart("related"); contentMultipart.addBodyPart(textBodyPart); contentMultipart.addBodyPart(attachmentPart); message.setContent(contentMultipart); message.saveChanges(); // Sends the mail. transport.sendMessage(message, message.getAllRecipients()); } catch (UnsupportedEncodingException ex) { throw new EmailException( "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex); } catch (IOException ex) { throw new EmailException("An error occured while reading the attachment of an email.", ex); } catch (MessagingException ex) { throw new EmailException("An error occured while sending an email.", ex); } }