Java Examples for javax.activation.DataSource

The following java examples will help you to understand the usage of javax.activation.DataSource. These source code samples are taken from different open source projects.

Example 1
Project: padaf-master  File: PdfA1bValidator.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.awl.edoc.pdfa.validation.PdfAValidator#validate(javax.activation.DataSource
	 * )
	 */
public synchronized ValidationResult validate(DataSource source) throws ValidationException {
    DocumentHandler handler = createDocumentHandler(source);
    try {
        // syntax (javacc) validation
        try {
            PDFParser parser = new PDFParser(source.getInputStream());
            parser.PDF();
            handler.setParser(parser);
        } catch (IOException e) {
            throw new ValidationException("Failed to parse datasource due to : " + e.getMessage(), e);
        } catch (ParseException e) {
            return createErrorResult(e);
        }
        // if here is reached, validate with helpers
        // init PDF Box document
        PDDocument document = null;
        try {
            document = PDDocument.load(handler.getSource().getInputStream());
            handler.setDocument(document);
        } catch (IOException e) {
            throw new ValidationException("PDFBox failed to parse datasource", e);
        }
        // init PDF Extractor
        try {
            SimpleCharStream scs = new SimpleCharStream(source.getInputStream());
            ExtractorTokenManager extractor = new ExtractorTokenManager(scs);
            extractor.parse();
            handler.setPdfExtractor(extractor);
        } catch (IOException e) {
            throw new ValidationException("PDF ExtractorTokenMng failed to parse datasource", e);
        }
        // call all helpers
        ArrayList<ValidationError> allErrors = new ArrayList<ValidationError>();
        // Execute priority helpers.
        for (AbstractValidationHelper helper : priorHelpers) {
            runValidation(handler, helper, allErrors);
        }
        // Execute other helpers.
        for (AbstractValidationHelper helper : standHelpers) {
            runValidation(handler, helper, allErrors);
        }
        // check result
        ValidationResult valRes = null;
        if (allErrors.size() == 0) {
            valRes = new ValidationResult(true);
        } else {
            // there are some errors
            valRes = new ValidationResult(allErrors);
        }
        // addition of the some objects to avoid a second file parsing  
        valRes.setPdf(document);
        valRes.setXmpMetaData(handler.getMetadata());
        return valRes;
    } catch (ValidationException e) {
        handler.close();
        throw e;
    }
}
Example 2
Project: with-aes-master  File: PdfA1bValidator.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * net.awl.edoc.pdfa.validation.PdfAValidator#validate(javax.activation.DataSource
	 * )
	 */
public synchronized ValidationResult validate(DataSource source) throws ValidationException {
    DocumentHandler handler = createDocumentHandler(source);
    try {
        ArrayList<ValidationError> allErrors = new ArrayList<ValidationError>();
        // syntax (javacc) validation
        try {
            PDFParser parser = new PDFParser(source.getInputStream());
            handler.setParser(parser);
            parser.PDF();
        } catch (IOException e) {
            throw new ValidationException("Failed to parse datasource due to : " + e.getMessage(), e);
        } catch (ParseException e) {
            allErrors.addAll(createErrorResult(e).getErrorsList());
        }
        // if here is reached, validate with helpers
        // init PDF Box document
        PDDocument document = null;
        try {
            document = PDDocument.load(handler.getSource().getInputStream());
            handler.setDocument(document);
        } catch (IOException e) {
            throw new ValidationException("PDFBox failed to parse datasource", e);
        }
        // init PDF Extractor
        try {
            SimpleCharStream scs = new SimpleCharStream(source.getInputStream());
            ExtractorTokenManager extractor = new ExtractorTokenManager(scs);
            extractor.parse();
            handler.setPdfExtractor(extractor);
        } catch (IOException e) {
            throw new ValidationException("PDF ExtractorTokenMng failed to parse datasource", e);
        }
        // Execute priority helpers.
        for (AbstractValidationHelper helper : priorHelpers) {
            runValidation(handler, helper, allErrors);
        }
        // Execute other helpers.
        for (AbstractValidationHelper helper : standHelpers) {
            runValidation(handler, helper, allErrors);
        }
        // check result
        ValidationResult valRes = null;
        if (allErrors.size() == 0) {
            valRes = new ValidationResult(true);
        } else {
            // there are some errors
            valRes = new ValidationResult(allErrors);
        }
        // addition of the some objects to avoid a second file parsing  
        valRes.setPdf(document);
        valRes.setXmpMetaData(handler.getMetadata());
        return valRes;
    } catch (ValidationException e) {
        handler.close();
        throw e;
    }
}
Example 3
Project: subetha-master  File: DetachmentContentHandler.java View source code
/*
	 * (non-Javadoc)
	 * @see javax.activation.DataContentHandler#getContent(javax.activation.DataSource)
	 */
public Object getContent(DataSource ds) throws IOException {
    // Extract the String id
    InputStreamReader reader = new InputStreamReader(ds.getInputStream(), "ASCII");
    StringBuilder builder = new StringBuilder();
    int ch;
    while ((ch = reader.read()) >= 0) builder.append((char) ch);
    // Return it as a Long
    return Long.valueOf(builder.toString());
}
Example 4
Project: VaadinUtils-master  File: JasperEmailBuilder.java View source code
public void send(boolean debug) throws EmailException {
    Preconditions.checkNotNull(fromAddress);
    Preconditions.checkNotNull(tos.size() > 0);
    Preconditions.checkNotNull(subject);
    Preconditions.checkNotNull(this.htmlBody != null || this.renderedReportBody != null, "You must specify a body.");
    ImageHtmlEmail email = new ImageHtmlEmail();
    if (this.renderedReportBody != null)
        email.setDataSourceResolver(new JasperDataSourceResolver(renderedReportBody));
    email.setDebug(debug);
    email.setHostName(settings.getSmtpFQDN());
    email.setSmtpPort(settings.getSmtpPort());
    if (settings.isAuthRequired())
        email.setAuthentication(settings.getUsername(), settings.getPassword());
    if (settings.getUseSSL()) {
        email.setSslSmtpPort(settings.getSmtpPort().toString());
        email.setSSLOnConnect(true);
        email.setSSLCheckServerIdentity(false);
    }
    email.setFrom(fromAddress);
    email.setBounceAddress(settings.getBounceEmailAddress());
    email.setSubject(subject);
    for (String to : this.tos) email.addTo(to);
    for (String cc : this.ccs) email.addCc(cc);
    for (String bcc : this.bccs) email.addBcc(bcc);
    if (StringUtils.isNotEmpty(this.htmlBody))
        email.setHtmlMsg(this.htmlBody);
    else
        email.setHtmlMsg("The body of this email was left blank");
    if (this.renderedReportBody != null)
        email.setHtmlMsg(this.renderedReportBody.getBodyAsHtml());
    email.setTextMsg(this.textBody);
    for (DataSource attachment : this.attachments) email.attach(attachment, attachment.getName(), attachment.getName());
    email.send();
}
Example 5
Project: cyrille-leclerc-master  File: MailApiTest.java View source code
public void testSendMailWithAttachment() throws UnsupportedEncodingException, MessagingException {
    Properties properties = new Properties();
    Session session = Session.getDefaultInstance(properties, null);
    session.setDebug(true);
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setText("This is my text");
    mimeMessage.setSubject("the subject");
    mimeMessage.setSender(new InternetAddress("cleclerc@pobox.com", "Cyrille Le Clerc"));
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("c.leclerc@fr.vuitton.com"));
    Multipart multipart = new MimeMultipart();
    mimeMessage.setContent(multipart);
    BodyPart bodyPart = new MimeBodyPart();
    multipart.addBodyPart(bodyPart);
    bodyPart.setText("this is the text");
    URL url = getClass().getResource("deliveryOrder.pdf");
    DataSource dataSource = new FileDataSource(url.getFile());
    BodyPart bodyPart2 = new MimeBodyPart();
    multipart.addBodyPart(bodyPart2);
    bodyPart2.setDataHandler(new DataHandler(dataSource));
    bodyPart2.setFileName("deliveryOrder.pdf");
    Transport transport = session.getTransport("smtp");
    transport.connect("smtp.vuitton.lvmh", null, null);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
Example 6
Project: elmis-master  File: ReportingRateNotificationController.java View source code
@RequestMapping(value = "/send/report", method = POST, headers = BaseController.ACCEPT_JSON)
public ResponseEntity<OpenLmisResponse> sendWithReportAttachment(@RequestBody MessageCollection messageParams, HttpServletRequest request) {
    Integer userId = loggedInUserId(request).intValue();
    /** extract message inputs from the payload **/
    String reportKey = messageParams.getReportKey();
    List<MessageDto> messages = messageParams.getMessages();
    String subject = messageParams.getSubject();
    String outputOption = messageParams.getOutputOption();
    Map<String, String[]> reportFilterParams = messageParams.getReportParams();
    /** Export report and process email attachment **/
    ByteArrayOutputStream byteArrayOutputStream = reportManager.exportReportBytesStream(userId, reportKey, reportFilterParams, outputOption);
    byte[] bytes = byteArrayOutputStream.toByteArray();
    DataSource attachmentDataSource;
    String fileName;
    switch(outputOption.toUpperCase()) {
        case XLS:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_VND_MS_EXCEL);
            fileName = REPORT_XLS;
            break;
        case HTML:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_HTML);
            fileName = REPORT_HTML;
            break;
        default:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_PDF);
            fileName = REPORT_PDF;
            break;
    }
    for (MessageDto dto : messages) {
        emailService.sendMimeMessage(dto.getContact(), subject, dto.getMessage(), fileName, attachmentDataSource);
    }
    return OpenLmisResponse.success("Success");
}
Example 7
Project: Resteasy-master  File: NoContentStreamingCloseTest.java View source code
/**
     * @tpTestDetails Empty DataSource test.
     * @tpSince RESTEasy 3.0.16
     */
@Test
public void testEmptyDataSource() throws Exception {
    NoContentStreamingCloseTestInputStream testInputStream = new NoContentStreamingCloseTestInputStream(new byte[0]);
    ResteasyClient client = //
    new ResteasyClientBuilder().register(//
    new NoContentStreamingCloseTestFilter(NoContentStreamingCloseTestResponse.buildStreamingResponse(testInputStream, 0))).build();
    DataSource in = //
    client.target(//
    "http://localhost/uri_is_ignored").request().get(//
    DataSource.class);
    Assert.assertNotNull("DataSource should not be null", in);
    InputStream is = in.getInputStream();
    Assert.assertEquals(RESPONSE_ERROR_MSG, 0, IOUtils.toByteArray(is).length);
    is.close();
    Assert.assertTrue(CLOSE_ERROR_MSG, testInputStream.isClosed());
    client.close();
}
Example 8
Project: robe-master  File: MailItemTest.java View source code
@Test
public void constructorAndToStringAndHash() throws Exception {
    MailItem item1 = new MailItem("title", "body", (DataSource) null, "sender", "receiver");
    MailItem item2 = new MailItem("title", "body", (DataSource) null, "sender", Arrays.asList("receiver"));
    item1.setId("1");
    item2.setId("1");
    assertEquals(item1, item2);
    MailItem item3 = new MailItem("title", "body", (List<DataSource>) null, "sender", "receiver");
    MailItem item4 = new MailItem("title", "body", (List<DataSource>) null, "sender", Arrays.asList("receiver"));
    item3.setId("1");
    item4.setId("1");
    assertEquals(item3, item4);
    assertEquals(item1.toString(), item2.toString());
    assertEquals(item1.hashCode(), item2.hashCode());
}
Example 9
Project: cxf-master  File: DataSourceProviderTest.java View source code
public static MimeMultipart readAttachmentParts(String contentType, InputStream bais) throws MessagingException, IOException {
    DataSource source = new ByteArrayDataSource(bais, contentType);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage mm = new MimeMessage(session);
    mm.setContent(mpart);
    mm.addHeaderLine("Content-Type:" + contentType);
    return (MimeMultipart) mm.getContent();
}
Example 10
Project: jentrata-msh-master  File: AS2MessageReceiverService.java View source code
public void serviceRequested(WebServicesRequest request, WebServicesResponse response) throws SOAPRequestException, DAOException {
    Element[] bodies = request.getBodies();
    String messageId = getText(bodies, "messageId");
    if (messageId == null) {
        throw new SOAPFaultException(SOAPFaultException.SOAP_FAULT_CLIENT, "Missing request information");
    }
    AS2Processor.core.log.info("Message Receiver received download request - Message ID: " + messageId);
    SOAPResponse soapResponse = (SOAPResponse) response.getTarget();
    SOAPMessage soapResponseMessage = soapResponse.getMessage();
    MessageDAO messageDao = (MessageDAO) AS2Processor.core.dao.createDAO(MessageDAO.class);
    MessageDVO messageDvo = (MessageDVO) messageDao.createDVO();
    messageDvo.setMessageId(messageId);
    messageDvo.setMessageBox(MessageDVO.MSGBOX_IN);
    messageDvo.setAs2From("%");
    messageDvo.setAs2To("%");
    messageDvo.setPrincipalId("%");
    messageDvo.setStatus(MessageDVO.STATUS_PROCESSED);
    List messagesList = messageDao.findMessagesByHistory(messageDvo, 1, 0);
    Iterator messagesIterator = messagesList.iterator();
    while (messagesIterator.hasNext()) {
        MessageDVO targetMessageDvo = (MessageDVO) messagesIterator.next();
        PayloadRepository repository = AS2Processor.getIncomingPayloadRepository();
        Iterator payloadCachesIterator = repository.getPayloadCaches().iterator();
        while (payloadCachesIterator.hasNext()) {
            PayloadCache cache = (PayloadCache) payloadCachesIterator.next();
            String cacheMessageID = cache.getMessageID();
            if (cacheMessageID.equals(targetMessageDvo.getMessageId())) {
                try {
                    FileInputStream fis = new FileInputStream(cache.getCache());
                    DataSource ds = null;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    if (getParameters().getProperty("is_compress").equals("true")) {
                        DeflaterOutputStream dos = new DeflaterOutputStream(baos);
                        IOHandler.pipe(fis, dos);
                        dos.finish();
                        ds = new ByteArrayDataSource(baos.toByteArray(), "application/deflate");
                    } else {
                        IOHandler.pipe(fis, baos);
                        ds = new ByteArrayDataSource(baos.toByteArray(), cache.getContentType());
                    }
                    DataHandler dh = new DataHandler(ds);
                    AttachmentPart attachmentPart = soapResponseMessage.createAttachmentPart();
                    attachmentPart.setContentId(messageId);
                    attachmentPart.setDataHandler(dh);
                    soapResponseMessage.addAttachmentPart(attachmentPart);
                    MessageDAO dao = (MessageDAO) AS2Processor.core.dao.createDAO(MessageDAO.class);
                    targetMessageDvo.setStatus(MessageDVO.STATUS_DELIVERED);
                    dao.persist(targetMessageDvo);
                } catch (Exception e) {
                    AS2Processor.core.log.error("Error in collecting message", e);
                }
            }
        }
    }
    generateReply(response, soapResponseMessage.countAttachments() > 0);
}
Example 11
Project: maven-h2o-master  File: AS2MessageReceiverService.java View source code
public void serviceRequested(WebServicesRequest request, WebServicesResponse response) throws SOAPRequestException, DAOException {
    Element[] bodies = request.getBodies();
    String messageId = getText(bodies, "messageId");
    if (messageId == null) {
        throw new SOAPFaultException(SOAPFaultException.SOAP_FAULT_CLIENT, "Missing request information");
    }
    AS2Processor.core.log.info("Message Receiver received download request - Message ID: " + messageId);
    SOAPResponse soapResponse = (SOAPResponse) response.getTarget();
    SOAPMessage soapResponseMessage = soapResponse.getMessage();
    MessageDAO messageDao = (MessageDAO) AS2Processor.core.dao.createDAO(MessageDAO.class);
    MessageDVO messageDvo = (MessageDVO) messageDao.createDVO();
    messageDvo.setMessageId(messageId);
    messageDvo.setMessageBox(MessageDVO.MSGBOX_IN);
    messageDvo.setAs2From("%");
    messageDvo.setAs2To("%");
    messageDvo.setPrincipalId("%");
    messageDvo.setStatus(MessageDVO.STATUS_PROCESSED);
    List messagesList = messageDao.findMessagesByHistory(messageDvo, 1, 0);
    Iterator messagesIterator = messagesList.iterator();
    while (messagesIterator.hasNext()) {
        MessageDVO targetMessageDvo = (MessageDVO) messagesIterator.next();
        PayloadRepository repository = AS2Processor.getIncomingPayloadRepository();
        Iterator payloadCachesIterator = repository.getPayloadCaches().iterator();
        while (payloadCachesIterator.hasNext()) {
            PayloadCache cache = (PayloadCache) payloadCachesIterator.next();
            String cacheMessageID = cache.getMessageID();
            if (cacheMessageID.equals(targetMessageDvo.getMessageId())) {
                try {
                    FileInputStream fis = new FileInputStream(cache.getCache());
                    DataSource ds = null;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    if (getParameters().getProperty("is_compress").equals("true")) {
                        DeflaterOutputStream dos = new DeflaterOutputStream(baos);
                        IOHandler.pipe(fis, dos);
                        dos.finish();
                        ds = new ByteArrayDataSource(baos.toByteArray(), "application/deflate");
                    } else {
                        IOHandler.pipe(fis, baos);
                        ds = new ByteArrayDataSource(baos.toByteArray(), cache.getContentType());
                    }
                    DataHandler dh = new DataHandler(ds);
                    AttachmentPart attachmentPart = soapResponseMessage.createAttachmentPart();
                    attachmentPart.setContentId(messageId);
                    attachmentPart.setDataHandler(dh);
                    soapResponseMessage.addAttachmentPart(attachmentPart);
                    MessageDAO dao = (MessageDAO) AS2Processor.core.dao.createDAO(MessageDAO.class);
                    targetMessageDvo.setStatus(MessageDVO.STATUS_DELIVERED);
                    dao.persist(targetMessageDvo);
                } catch (Exception e) {
                    AS2Processor.core.log.error("Error in collecting message", e);
                }
            }
        }
    }
    generateReply(response, soapResponseMessage.countAttachments() > 0);
}
Example 12
Project: jruby-cxf-master  File: DataSourceType.java View source code
@Override
protected byte[] getBytes(Object object) {
    DataSource dataSource = (DataSource) object;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        InputStream stream = dataSource.getInputStream();
        IOUtils.copy(stream, baos);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
Example 13
Project: shopizer-v1.1.5-master  File: SimpleSmtpMailModule.java View source code
public void send(final String email, final String subject, final Map entries) throws Exception {
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email));
    InternetAddress inetAddress = new InternetAddress();
    inetAddress.setPersonal(super.getFromEmail());
    inetAddress.setAddress(super.getFromAddress());
    mimeMessage.setFrom(inetAddress);
    mimeMessage.setSubject(subject);
    Multipart mp = new MimeMultipart("alternative");
    // Create a "text" Multipart message
    BodyPart textPart = new MimeBodyPart();
    Template textTemplate = super.getConfiguration().getTemplate(super.getFreemarkerTemplate());
    final StringWriter textWriter = new StringWriter();
    try {
        textTemplate.process(entries, textWriter);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate text mail", e);
    }
    textPart.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {

        public InputStream getInputStream() throws IOException {
            return new StringBufferInputStream(textWriter.toString());
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Read-only data");
        }

        public String getContentType() {
            return "text/plain";
        }

        public String getName() {
            return "main";
        }
    }));
    mp.addBodyPart(textPart);
    // Create a "HTML" Multipart message
    Multipart htmlContent = new MimeMultipart("related");
    BodyPart htmlPage = new MimeBodyPart();
    Template htmlTemplate = super.getConfiguration().getTemplate(super.getFreemarkerTemplate());
    final StringWriter htmlWriter = new StringWriter();
    try {
        htmlTemplate.process(entries, htmlWriter);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate HTML mail", e);
    }
    htmlPage.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {

        public InputStream getInputStream() throws IOException {
            return new StringBufferInputStream(htmlWriter.toString());
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Read-only data");
        }

        public String getContentType() {
            return "text/html";
        }

        public String getName() {
            return "main";
        }
    }));
    htmlContent.addBodyPart(htmlPage);
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlContent);
    mp.addBodyPart(htmlPart);
    mimeMessage.setContent(mp);
    throw new Exception("Not Implemented, needs to connect to an implementation");
// simple http server sends emails on port 25, no configuration required
// https://aspirin.dev.java.net/ (2 jars are required dnsjava and
// aspirin)
// org.masukomi.aspirin.core.MailQue.queMail(mimeMessage);
}
Example 14
Project: wso2-axis2-transports-master  File: BinaryBuilder.java View source code
public OMElement processDocument(DataSource dataSource, String contentType, MessageContext msgContext) throws AxisFault {
    QName wrapperQName = BaseConstants.DEFAULT_BINARY_WRAPPER;
    if (msgContext.getAxisService() != null) {
        Parameter wrapperParam = msgContext.getAxisService().getParameter(BaseConstants.WRAPPER_PARAM);
        if (wrapperParam != null) {
            wrapperQName = BaseUtils.getQNameFromString(wrapperParam.getValue());
        }
    }
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMElement wrapper = factory.createOMElement(wrapperQName, null);
    DataHandler dataHandler = new DataHandler(dataSource);
    wrapper.addChild(factory.createOMText(dataHandler, true));
    msgContext.setDoingMTOM(true);
    return wrapper;
}
Example 15
Project: axis2-java-master  File: PlainTextBuilder.java View source code
public OMElement processDocument(DataSource dataSource, String contentType, MessageContext msgContext) throws AxisFault {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    Charset cs = Charset.forName(BuilderUtil.getCharSetEncoding(contentType));
    QName wrapperQName = getWrapperQName(msgContext);
    return factory.createOMElement(new WrappedTextNodeOMDataSourceFromDataSource(wrapperQName, dataSource, cs), wrapperQName);
}
Example 16
Project: camel-webinar-master  File: Client.java View source code
public static void main(String args[]) throws Exception {
    VertragsService_Service vertragsServiceService = new VertragsService_Service();
    VertragsService vertragsService = vertragsServiceService.getVertragsServiceSOAP();
    BindingProvider provider = (BindingProvider) vertragsService;
    Map<String, Object> requestContext = provider.getRequestContext();
    requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8040/services/VertragsService");
    SOAPBinding binding = (SOAPBinding) provider.getBinding();
    binding.setMTOMEnabled(true);
    List<DataHandler> anlagen = new ArrayList<DataHandler>();
    DataSource ds = new FileDataSource(new File("PDFUserGuide.pdf"));
    DataHandler anlage = new DataHandler(ds);
    anlagen.add(anlage);
    vertragsService.anlegen("1", new Date(), anlagen);
    System.exit(0);
}
Example 17
Project: geronimo-master  File: AbstractHandler.java View source code
public void testGetContent() throws Exception {
    final byte[] bytes = "Hello World".getBytes();
    DataSource ds = new DataSource() {

        public InputStream getInputStream() {
            return new ByteArrayInputStream(bytes);
        }

        public OutputStream getOutputStream() {
            throw new UnsupportedOperationException();
        }

        public String getContentType() {
            throw new UnsupportedOperationException();
        }

        public String getName() {
            throw new UnsupportedOperationException();
        }
    };
    Object o = dch.getContent(ds);
    assertEquals("Hello World", o);
}
Example 18
Project: lemon-master  File: UserAvatarService.java View source code
public DataSource viewAvatarById(Long accountId, int width, String tenantId) throws Exception {
    if (accountId == null) {
        logger.info("accountId cannot be null");
        return null;
    }
    String key = "accountId:" + accountId + ":" + width;
    String userId = Long.toString(accountId);
    DataSource dataSource = this.avatarCache.getDataSource(userId, width);
    if (dataSource != null) {
        return dataSource;
    }
    AccountInfo accountInfo = accountInfoManager.get(accountId);
    dataSource = this.viewAvatarByAccountInfo(accountInfo, width, tenantId);
    this.avatarCache.updateDataSource(userId, width, dataSource);
    return dataSource;
}
Example 19
Project: pdfbox-master  File: AbstractTestAction.java View source code
/**
     * Read a simple PDF/A to create a valid Context
     * 
     * @return
     * @throws Exception
     */
protected PreflightContext createContext() throws Exception {
    DataSource ds = new FileDataSource("src/test/resources/pdfa-with-annotations-square.pdf");
    PDDocument doc = PDDocument.load(ds.getInputStream());
    PreflightDocument preflightDocument = new PreflightDocument(doc.getDocument(), Format.PDF_A1B);
    PreflightContext ctx = new PreflightContext(ds);
    ctx.setDocument(preflightDocument);
    preflightDocument.setContext(ctx);
    return ctx;
}
Example 20
Project: quickstarts-master  File: InternalEchoServiceBean.java View source code
@Override
public String echoImage(String fileName) {
    String newFileName = "external-switchyard.png";
    DataSource image = message.getAttachment(fileName);
    // Something is wrong in Camel it throws StackOverFlow error.
    // message.removeAttachment(fileName);
    message.addAttachment(newFileName, image);
    newFileName = _echoService.echoImage(newFileName);
    return newFileName;
}
Example 21
Project: springlab-master  File: LargeImageWebServiceImpl.java View source code
/**
	 * @see LargeImageWebService#getImage()
	 */
public LargeImageResult getImage() {
    try {
        //采用applicationContext获�Web应用中的文件.
        File image = applicationContext.getResource("/img/logo.jpg").getFile();
        //采用activation的DataHandler实现Streaming传输.
        DataSource dataSource = new FileDataSource(image);
        DataHandler dataHandler = new DataHandler(dataSource);
        LargeImageResult result = new LargeImageResult();
        result.setImageData(dataHandler);
        return result;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return WSResult.buildResult(LargeImageResult.class, WSResult.IMAGE_ERROR, "Image reading error.");
    }
}
Example 22
Project: grisu-connectors-master  File: CXFServiceInterfaceCreator.java View source code
public ServiceInterface create(String serviceInterfaceUrl, String username, String password, String myproxyServer, int myproxyPort) {
    final JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    final AegisDatabinding aDB = new AegisDatabinding();
    final AegisContext acontext = new AegisContext();
    final HashSet<java.lang.Class<?>> classes = new HashSet<java.lang.Class<?>>();
    classes.add(DocumentImpl.class);
    acontext.setRootClasses(classes);
    final HashMap<Class<?>, String> classMap = new HashMap<Class<?>, String>();
    classMap.put(DocumentImpl.class, "org.w3c.dom.Document");
    /*
		 * acontext.setBeanImplementationMap(classMap);
		 * acontext.setReadXsiTypes(true); acontext.setWriteXsiTypes(true);
		 */
    acontext.setMtomEnabled(true);
    /**
		 * System.out.println(acontext.getTypeMapping().getType(FileDataSource.
		 * class)); acontext.getTypeMapping().register(FileDataSource.class,
		 * XMLSchemaQNames.XSD_BASE64, new DataSourceType(false, null));
		 **/
    aDB.setAegisContext(acontext);
    factory.setServiceClass(CXFServiceInterface.class);
    factory.setAddress(serviceInterfaceUrl);
    factory.getServiceFactory().setDataBinding(aDB);
    factory.setServiceName(new QName("http://serviceInterfaces.control.grisu.vpac.org/", "grisu"));
    /* factory.setWsdlLocation(serviceInterfaceUrl +"?wsdl"); */
    factory.getInInterceptors().add(new LoggingInInterceptor());
    factory.getOutInterceptors().add(new LoggingOutInterceptor());
    factory.getOutInterceptors().add(new ClientAuthInterceptor(username, password, myproxyServer, myproxyPort));
    final ServiceInterface service = (ServiceInterface) factory.create();
    final Client client = ClientProxy.getClient(service);
    client.getEndpoint().put("mtom-enabled", "true");
    /**
		 * org.apache.cxf.aegis.type.basic.BeanType:
		 * [class=javax.activation.FileDataSource,
		 * QName={http://activation.javax}FileDataSource,
		 * info=org.apache.cxf.aegis.type.java5.AnnotatedTypeInfo@171b4ca]
		 * org.apache.cxf.aegis.type.mtom.DataSourceType[class=javax.activation.
		 * DataSource, QName={http://www.w3.org/2001/XMLSchema}base64Binary]
		 * org.
		 * apache.cxf.aegis.type.mtom.DataHandlerType[class=javax.activation.
		 * DataHandler, QName={http://www.w3.org/2001/XMLSchema}base64Binary]
		 **/
    System.out.println(acontext.getTypeMapping().getType(FileDataSource.class));
    System.out.println(acontext.getTypeMapping().getTypeCreator().createType(DataSource.class));
    System.out.println(acontext.getTypeMapping().getTypeCreator().createType(DataHandler.class));
    /*
		 * Service s = aDB.getService();
		 * 
		 * s.put("org.w3c.dom.Document.implementation",
		 * "org.apache.xerces.dom.DocumentImpl");
		 */
    return service;
}
Example 23
Project: shopizer-master  File: HtmlEmailSenderImpl.java View source code
public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException {
    JavaMailSenderImpl impl = (JavaMailSenderImpl) mailSender;
    // if email configuration is present in Database, use the same
    if (emailConfig != null) {
        impl.setProtocol(emailConfig.getProtocol());
        impl.setHost(emailConfig.getHost());
        impl.setPort(Integer.parseInt(emailConfig.getPort()));
        impl.setUsername(emailConfig.getUsername());
        impl.setPassword(emailConfig.getPassword());
        Properties prop = new Properties();
        prop.put("mail.smtp.auth", emailConfig.isSmtpAuth());
        prop.put("mail.smtp.starttls.enable", emailConfig.isStarttls());
        impl.setJavaMailProperties(prop);
    }
    mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    InternetAddress inetAddress = new InternetAddress();
    inetAddress.setPersonal(eml);
    inetAddress.setAddress(from);
    mimeMessage.setFrom(inetAddress);
    mimeMessage.setSubject(subject);
    Multipart mp = new MimeMultipart("alternative");
    // Create a "text" Multipart message
    BodyPart textPart = new MimeBodyPart();
    freemarkerMailConfiguration.setClassForTemplateLoading(HtmlEmailSenderImpl.class, "/");
    Template textTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
    final StringWriter textWriter = new StringWriter();
    try {
        textTemplate.process(templateTokens, textWriter);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate text mail", e);
    }
    textPart.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {

        public InputStream getInputStream() throws IOException {
            //		.toString());
            return new ByteArrayInputStream(textWriter.toString().getBytes(CHARSET));
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Read-only data");
        }

        public String getContentType() {
            return "text/plain";
        }

        public String getName() {
            return "main";
        }
    }));
    mp.addBodyPart(textPart);
    // Create a "HTML" Multipart message
    Multipart htmlContent = new MimeMultipart("related");
    BodyPart htmlPage = new MimeBodyPart();
    freemarkerMailConfiguration.setClassForTemplateLoading(HtmlEmailSenderImpl.class, "/");
    Template htmlTemplate = freemarkerMailConfiguration.getTemplate(new StringBuilder(TEMPLATE_PATH).append("").append("/").append(tmpl).toString());
    final StringWriter htmlWriter = new StringWriter();
    try {
        htmlTemplate.process(templateTokens, htmlWriter);
    } catch (TemplateException e) {
        throw new MailPreparationException("Can't generate HTML mail", e);
    }
    htmlPage.setDataHandler(new javax.activation.DataHandler(new javax.activation.DataSource() {

        public InputStream getInputStream() throws IOException {
            //		.toString());
            return new ByteArrayInputStream(textWriter.toString().getBytes(CHARSET));
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Read-only data");
        }

        public String getContentType() {
            return "text/html";
        }

        public String getName() {
            return "main";
        }
    }));
    htmlContent.addBodyPart(htmlPage);
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlContent);
    mp.addBodyPart(htmlPart);
    mimeMessage.setContent(mp);
// if(attachment!=null) {
// MimeMessageHelper messageHelper = new
// MimeMessageHelper(mimeMessage, true);
// messageHelper.addAttachment(attachmentFileName, attachment);
// }
}
Example 24
Project: ABMS-master  File: MailSender.java View source code
public static void sendMail(String subject, String to, String message, String file) throws AddressException, MessagingException {
    PropertiesReader propertiesReader = new PropertiesReader();
    String username = propertiesReader.readProperty("mail.properties", "email");
    String password = propertiesReader.readProperty("mail.properties", "password");
    // Step1
    Properties mailServerProperties = System.getProperties();
    mailServerProperties.put("mail.smtp.port", "587");
    mailServerProperties.put("mail.smtp.auth", "true");
    mailServerProperties.put("mail.smtp.starttls.enable", "true");
    // Step2
    Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
    MimeMessage generateMailMessage = new MimeMessage(getMailSession);
    generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    generateMailMessage.setSubject(subject);
    String emailBody = message;
    // generateMailMessage.setContent(emailBody, "text/html");
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(emailBody, "text/html");
    // Create multiPart Message
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // Part two is attachement
    if (file != null) {
        BodyPart attachBodyPart = new MimeBodyPart();
        String filename = file;
        DataSource source = new FileDataSource(filename);
        attachBodyPart.setDataHandler(new DataHandler(source));
        String fileN = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
        attachBodyPart.setFileName(fileN);
        multipart.addBodyPart(attachBodyPart);
    }
    generateMailMessage.setContent(multipart);
    // Step3
    Transport transport = getMailSession.getTransport("smtp");
    // Enter your correct gmail UserID and Password
    // if you have 2FA enabled then provide App Specific Password
    transport.connect("smtp.gmail.com", username, password);
    transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
    transport.close();
}
Example 25
Project: camel-master  File: MimeMessageConsumeTest.java View source code
/**
     * Lets encode a multipart mime message
     */
protected void populateMimeMessageBody(MimeMessage message) throws MessagingException {
    MimeBodyPart plainPart = new MimeBodyPart();
    plainPart.setText(body);
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText("<html><body>" + body + "</body></html>");
    Multipart alt = new MimeMultipart("alternative");
    alt.addBodyPart(plainPart);
    alt.addBodyPart(htmlPart);
    Multipart mixed = new MimeMultipart("mixed");
    MimeBodyPart wrap = new MimeBodyPart();
    wrap.setContent(alt);
    mixed.addBodyPart(wrap);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    DataSource ds;
    try {
        File f = new File(getClass().getResource("/log4j2.properties").toURI());
        ds = new FileDataSource(f);
    } catch (URISyntaxException ex) {
        ds = new URLDataSource(getClass().getResource("/log4j2.properties"));
    }
    DataHandler dh = new DataHandler(ds);
    BodyPart attachmentBodyPart;
    // Create another body part
    attachmentBodyPart = new MimeBodyPart();
    // Set the data handler to the attachment
    attachmentBodyPart.setDataHandler(dh);
    // Set the filename
    attachmentBodyPart.setFileName(dh.getName());
    // Set Disposition
    attachmentBodyPart.setDisposition(Part.ATTACHMENT);
    mixed.addBodyPart(plainPart);
    mixed.addBodyPart(htmlPart);
    // Add attachmentBodyPart to multipart
    mixed.addBodyPart(attachmentBodyPart);
    message.setContent(mixed);
}
Example 26
Project: carbon-registry-master  File: GetTextContentUtil.java View source code
/**
     * return the byte content of the wsdl/wadl/xsd/xml source as a DataHandler
     *
     * @param fetchURL source URL
     * @return handler    byte DataHandler of the wsdl content
     * @throws RegistryException
     */
public static DataHandler getByteContent(String fetchURL) throws RegistryException {
    StringBuilder sb = new StringBuilder();
    DataHandler handler = null;
    BufferedReader in = null;
    if (fetchURL.matches(URL_SOURCE_REGEX)) {
        try {
            URL sourceURL = new URL(fetchURL);
            in = new BufferedReader(new InputStreamReader(sourceURL.openConnection().getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            DataSource ds = new ByteArrayDataSource(encodeString(sb.toString()), DECODE_TYPE);
            handler = new DataHandler(ds);
        } catch (IOException e) {
            String msg = "Wrong or unavailable source URL " + fetchURL + ".";
            throw new RegistryException(msg, e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    String msg = "Error occurred while trying to close the BufferedReader";
                    log.warn(msg, e);
                }
            }
        }
    } else {
        String msg = "Invalid source URL format " + fetchURL + ".";
        log.error(msg);
        throw new RegistryException(msg);
    }
    return handler;
}
Example 27
Project: jaulp.core-master  File: ByteArrayDataSourceTest.java View source code
@Test
public void testByteArrayDataSource() throws IOException {
    final String expected = "Sample Data";
    final DataSource dataSource = new ByteArrayDataSource(expected.getBytes(), Mimetypes.TEXT_PLAIN.getMimetype());
    final DataHandler dataHandler = new DataHandler(dataSource);
    final String rawString = getString(dataHandler);
    final String actual = new String(Base64.decodeBase64(rawString));
    assertEquals("Not expected content", expected, actual);
}
Example 28
Project: java-mime-multipart-mixed-master  File: MultipartMixed.java View source code
public void process(final byte[] data) {
    try {
        process(new MimeMultipart(new DataSource() {

            @Override
            public OutputStream getOutputStream() throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public String getName() {
                throw new UnsupportedOperationException();
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(data);
            }

            @Override
            public String getContentType() {
                return MULTIPART_MIXED.getBaseType();
            }
        }));
    } catch (final MessagingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
Example 29
Project: OWL-S-Restful-master  File: WADLRequestImpl.java View source code
public Object request(String uri, String method, WADLParameter inputParam, HashMap<String, Object> headerParams, String expectedMediaType) {
    try {
        URL u;
        u = new URL(uri);
        URLConnection c = u.openConnection();
        InputStream in = null;
        if (c instanceof HttpURLConnection) {
            HttpURLConnection h = (HttpURLConnection) c;
            h.setRequestMethod(method);
            if (expectedMediaType != null) {
                setAccept(h, expectedMediaType);
            }
            if (headerParams != null) {
                for (String key : headerParams.keySet()) {
                    h.setRequestProperty(key, headerParams.get(key).toString());
                }
            }
            if (inputParam != null && (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT"))) {
                h.setChunkedStreamingMode(-1);
                h.setRequestProperty("Content-Type", inputParam.getMediaType());
                h.setDoOutput(true);
                h.connect();
                OutputStream out = h.getOutputStream();
                byte buffer[] = new byte[4096];
                int bytes;
                DataHandler dh = new DataHandler(inputParam.getValue(), inputParam.getMediaType());
                DataSource input = dh.getDataSource();
                InputStream inputStream = input.getInputStream();
                while ((bytes = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, bytes);
                }
                out.close();
            } else {
                h.connect();
            }
            this.mediaType = h.getContentType();
            this.status = h.getResponseCode();
            if (this.status < 400) {
                in = h.getInputStream();
            } else {
                in = h.getErrorStream();
            }
            StringBuffer outSB = new StringBuffer();
            byte outBytes[] = new byte[4096];
            int bytes;
            while ((bytes = in.read(outBytes)) != -1) {
                outSB.append(new String(outBytes, 0, bytes));
            }
            this.representation = outSB.toString();
            return this.representation;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return null;
}
Example 30
Project: pdf-image-compare-master  File: PdfDocumentComparatorTest.java View source code
/**
     * We compare a document with itself.
     */
@Test
public void testIdenticalPdfDocuments() throws Exception {
    DataSource referenceDataSource = new FileDataSource(new File(testDocumentDir, "open-office-01.pdf"));
    DataSource documentDataSource = new FileDataSource(new File(testDocumentDir, "open-office-01.pdf"));
    PdfDocumentComparatorResult pdfDocumentComparatorResult = new PdfDocumentComparator().compareDocuments(referenceDataSource, documentDataSource);
    System.out.println(pdfDocumentComparatorResult);
    new PdfDocumentComparatorResultWriter().writeToDirectory(testResultDir, "testIdenticalPdfDocuments", pdfDocumentComparatorResult);
    assertNotNull(pdfDocumentComparatorResult);
    assertEquals(1, pdfDocumentComparatorResult.getReferenceNrOfPages());
    assertEquals(1, pdfDocumentComparatorResult.getDocumentNrOfPages());
    assertEquals(1, pdfDocumentComparatorResult.getImageDifferResultList().size());
    assertTrue(pdfDocumentComparatorResult.isIdentical());
    assertEquals("open-office-01.pdf", pdfDocumentComparatorResult.getReferenceName());
    assertEquals("open-office-01.pdf", pdfDocumentComparatorResult.getDocumentName());
    assertTrue(pdfDocumentComparatorResult.toString().length() > 16);
}
Example 31
Project: tesb-rt-se-master  File: MailSender.java View source code
private Multipart createMultipart(String message, URL attachment) throws MessagingException {
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(message);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource source = new URLDataSource(attachment);
    messageBodyPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(messageBodyPart);
    return multipart;
}
Example 32
Project: theone4ever_git-master  File: AttachmentTest.java View source code
//END SNIPPET: setup    
/**
     * Create a webservice client using wsdl url
     *
     * @throws Exception
     */
//START SNIPPET: webservice
public void testAttachmentViaWsInterface() throws Exception {
    Service service = Service.create(new URL("http://127.0.0.1:4204/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService"));
    assertNotNull(service);
    AttachmentWs ws = service.getPort(AttachmentWs.class);
    // retrieve the SOAPBinding
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();
    binding.setMTOMEnabled(true);
    String request = "tsztelak@gmail.com";
    // Byte array
    String response = ws.stringFromBytes(request.getBytes());
    assertEquals(request, response);
    // Data Source
    DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8");
    // not yet supported !
    //        response = ws.stringFromDataSource(source);
    //        assertEquals(request, response);
    // Data Handler
    response = ws.stringFromDataHandler(new DataHandler(source));
    assertEquals(request, response);
}
Example 33
Project: tomee-master  File: AttachmentTest.java View source code
//END SNIPPET: setup    
/**
     * Create a webservice client using wsdl url
     *
     * @throws Exception
     */
//START SNIPPET: webservice
public void testAttachmentViaWsInterface() throws Exception {
    Service service = Service.create(new URL("http://localhost:" + port + "/webservice-attachments/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService"));
    assertNotNull(service);
    AttachmentWs ws = service.getPort(AttachmentWs.class);
    // retrieve the SOAPBinding
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();
    binding.setMTOMEnabled(true);
    String request = "tsztelak@gmail.com";
    // Byte array
    String response = ws.stringFromBytes(request.getBytes());
    assertEquals(request, response);
    // Data Source
    DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8");
    // not yet supported !
    //        response = ws.stringFromDataSource(source);
    //        assertEquals(request, response);
    // Data Handler
    response = ws.stringFromDataHandler(new DataHandler(source));
    assertEquals(request, response);
}
Example 34
Project: apache_ant-master  File: MimeMailer.java View source code
/**
     * Send the email.
     *
     * @throws BuildException if the email can't be sent.
     */
@Override
public void send() {
    try {
        final Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", String.valueOf(port));
        // Aside, the JDK is clearly unaware of the Scottish
        // 'session', which involves excessive quantities of
        // alcohol :-)
        Session sesh;
        Authenticator auth = null;
        if (SSL) {
            try {
                final Provider p = Class.forName("com.sun.net.ssl.internal.ssl.Provider").asSubclass(Provider.class).newInstance();
                Security.addProvider(p);
            } catch (final Exception e) {
                throw new BuildException("could not instantiate ssl security provider, check that you have JSSE in your classpath");
            }
            // SMTP provider
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.smtps.host", host);
            if (isPortExplicitlySpecified()) {
                props.put("mail.smtps.port", String.valueOf(port));
                props.put("mail.smtp.socketFactory.port", String.valueOf(port));
            }
        }
        if (user != null || password != null) {
            props.put("mail.smtp.auth", "true");
            auth = new SimpleAuthenticator(user, password);
        }
        if (isStartTLSEnabled()) {
            props.put("mail.smtp.starttls.enable", "true");
        }
        sesh = Session.getInstance(props, auth);
        //create the message
        final MimeMessage msg = new MimeMessage(sesh);
        final MimeMultipart attachments = new MimeMultipart();
        //set the sender
        if (from.getName() == null) {
            msg.setFrom(new InternetAddress(from.getAddress()));
        } else {
            msg.setFrom(new InternetAddress(from.getAddress(), from.getName()));
        }
        // set the reply to addresses
        msg.setReplyTo(internetAddresses(replyToList));
        msg.setRecipients(Message.RecipientType.TO, internetAddresses(toList));
        msg.setRecipients(Message.RecipientType.CC, internetAddresses(ccList));
        msg.setRecipients(Message.RecipientType.BCC, internetAddresses(bccList));
        // Choosing character set of the mail message
        // First: looking it from MimeType
        String charset = parseCharSetFromMimeType(message.getMimeType());
        if (charset != null) {
            // Assign/reassign message charset from MimeType
            message.setCharset(charset);
        } else {
            // Next: looking if charset having explicit definition
            charset = message.getCharset();
            if (charset == null) {
                // Using default
                charset = DEFAULT_CHARSET;
                message.setCharset(charset);
            }
        }
        // Using javax.activation.DataSource paradigm
        final StringDataSource sds = new StringDataSource();
        sds.setContentType(message.getMimeType());
        sds.setCharset(charset);
        if (subject != null) {
            msg.setSubject(subject, charset);
        }
        msg.addHeader("Date", getDate());
        if (headers != null) {
            for (Header h : headers) {
                msg.addHeader(h.getName(), h.getValue());
            }
        }
        final PrintStream out = new PrintStream(sds.getOutputStream());
        message.print(out);
        out.close();
        final MimeBodyPart textbody = new MimeBodyPart();
        textbody.setDataHandler(new DataHandler(sds));
        attachments.addBodyPart(textbody);
        for (File file : files) {
            MimeBodyPart body = new MimeBodyPart();
            if (!file.exists() || !file.canRead()) {
                throw new BuildException("File \"%s\" does not exist or is not readable.", file.getAbsolutePath());
            }
            final FileDataSource fileData = new FileDataSource(file);
            final DataHandler fileDataHandler = new DataHandler(fileData);
            body.setDataHandler(fileDataHandler);
            body.setFileName(file.getName());
            attachments.addBodyPart(body);
        }
        msg.setContent(attachments);
        try {
            // Send the message using SMTP, or SMTPS if the host uses SSL
            final Transport transport = sesh.getTransport(SSL ? "smtps" : "smtp");
            transport.connect(host, user, password);
            transport.sendMessage(msg, msg.getAllRecipients());
        } catch (final SendFailedException sfe) {
            if (!shouldIgnoreInvalidRecipients()) {
                throw new BuildException(GENERIC_ERROR, sfe);
            }
            if (sfe.getValidSentAddresses() == null || sfe.getValidSentAddresses().length == 0) {
                throw new BuildException("Couldn't reach any recipient", sfe);
            }
            Address[] invalid = sfe.getInvalidAddresses();
            if (invalid == null) {
                invalid = new Address[0];
            }
            for (int i = 0; i < invalid.length; i++) {
                didntReach(invalid[i], "invalid", sfe);
            }
            Address[] validUnsent = sfe.getValidUnsentAddresses();
            if (validUnsent == null) {
                validUnsent = new Address[0];
            }
            for (int i = 0; i < validUnsent.length; i++) {
                didntReach(validUnsent[i], "valid", sfe);
            }
        }
    } catch (MessagingExceptionIOException |  e) {
        throw new BuildException(GENERIC_ERROR, e);
    }
}
Example 35
Project: blynk-server-master  File: GMailClient.java View source code
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    StringBuilder sb = new StringBuilder();
    for (QrHolder qrHolder : attachmentData) {
        sb.append(qrHolder.token).append(",").append(qrHolder.deviceId).append(",").append(qrHolder.dashId).append("\n");
    }
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(sb.toString(), "text/csv");
    attachmentsPart.setDataHandler(new DataHandler(source));
    attachmentsPart.setFileName("tokens.csv");
    multipart.addBodyPart(attachmentsPart);
}
Example 36
Project: classlib6-master  File: XMLProviderArgumentBuilder.java View source code
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) {
    if (model.mode == Service.Mode.PAYLOAD) {
        return new PayloadSource();
    } else {
        if (model.datatype == Source.class)
            return new PayloadSource();
        if (model.datatype == DataSource.class)
            return new DataSourceParameter(binding);
        throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass, model.datatype));
    }
}
Example 37
Project: CZ3003_Backend-master  File: emailSender.java View source code
public static void sendEmail(String from, String recipients, String subject, String messageText, int priority) throws MessagingException {
    Message message = new MimeMessage(objSession);
    message.setFrom(new InternetAddress(from));
    //Need to test the line below for multiple recipients:
    //InternetAddress[] toAddresses={new InternetAddress(strRecipient)};
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
    message.setSubject(subject);
    message.setText(messageText);
    if (messageText.endsWith(".pdf")) {
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        messageBodyPart = new MimeBodyPart();
        String file = "path of file to be attached";
        String fileName = "report.pdf";
        DataSource source = new FileDataSource(messageText);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileName);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
    }
    Transport.send(message);
}
Example 38
Project: datacollection-master  File: GMailSender.java View source code
public void addAttachment(File file, String subject) throws Exception {
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(file);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(file.getName());
    _multipart.addBodyPart(messageBodyPart);
    BodyPart messageBodyPart2 = new MimeBodyPart();
    messageBodyPart2.setText(subject);
    _multipart.addBodyPart(messageBodyPart2);
}
Example 39
Project: droolsjbpm-master  File: AbstractFormDispatcher.java View source code
protected DataHandler processTemplate(final String name, InputStream src, Map<String, Object> renderContext) {
    DataHandler merged = null;
    try {
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(name, new InputStreamReader(src), cfg);
        final ByteArrayOutputStream bout = new ByteArrayOutputStream();
        Writer out = new OutputStreamWriter(bout);
        temp.process(renderContext, out);
        out.flush();
        merged = new DataHandler(new DataSource() {

            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(bout.toByteArray());
            }

            public OutputStream getOutputStream() throws IOException {
                return bout;
            }

            public String getContentType() {
                return "*/*";
            }

            public String getName() {
                return name + "_DataSource";
            }
        });
    } catch (Exception e) {
        throw new RuntimeException("Failed to process form template", e);
    }
    return merged;
}
Example 40
Project: dsql-master  File: SendEmailAction.java View source code
@Override
protected void replace(String tag, String mimeType, String ext, byte[] bytes, Writer writer) throws IOException {
    try {
        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName(tag + "." + ext);
        DataSource src = new ByteArrayDataSource(bytes, mimeType);
        attachment.setDataHandler(new DataHandler(src));
        String cid = tag + "." + ext;
        attachment.setHeader("Content-ID", "<" + cid + ">");
        multiPart.addBodyPart(attachment);
        if (mimeType.startsWith("image")) {
            writer.write("<div><br></div><div><img src=\"cid:" + cid + "\"><br></div>");
        } else {
            writer.write("<div><br></div><div><a href=\"cid:" + cid + "\"><br></div>");
        }
    } catch (MessagingException ex) {
        throw new IOException(ex);
    }
}
Example 41
Project: easy-mail-master  File: HtmlProcessorTest.java View source code
@Test
public void testExceptionHandling() {
    boolean hasHtmlTransformationExceptionBeenCaught = false;
    try {
        HtmlProcessor.process(new HtmlContentProvider() {

            @Override
            public String getHtmlMessageContent() {
                throw new RuntimeException();
            }

            @Override
            public DataSource getImageDataSource(final String relativeUrl) {
                return null;
            }

            @Override
            public URL getBaseURL() {
                return null;
            }
        });
        fail("Should have thrown an excpetion");
    } catch (HtmlTransformationException e) {
        hasHtmlTransformationExceptionBeenCaught = true;
    } catch (Exception e) {
        fail("Caught the Wrong Exception:" + e.getClass().toString());
    }
    assertTrue("Failed to catch HtmlTransformationException.", hasHtmlTransformationExceptionBeenCaught);
}
Example 42
Project: Elasticsearch2Excel-plugin-master  File: MailAPI.java View source code
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();
    }
}
Example 43
Project: everrest-master  File: DataSourceEntityProvider.java View source code
/**
     * Create DataSource instance dependent entity size. If entity has size less
     * then <tt>MAX_BUFFER_SIZE</tt> then {@link ByteArrayDataSource} will be
     * created otherwise {@link MimeFileDataSource} will be created.
     *
     * @param entityStream
     *         the {@link InputStream} of the HTTP entity
     * @param mimeType
     *         media type of data, HTTP header 'Content-type'
     * @return See {@link DataSource}
     * @throws IOException
     *         if any i/o errors occurs
     */
private DataSource createDataSource(InputStream entityStream, String mimeType) throws IOException {
    boolean overflow = false;
    byte[] buffer = new byte[8192];
    ApplicationContext context = ApplicationContext.getCurrent();
    int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize);
    int bytesNum;
    while (!overflow && ((bytesNum = entityStream.read(buffer)) != -1)) {
        bos.write(buffer, 0, bytesNum);
        if (bos.size() > bufferSize) {
            overflow = true;
        }
    }
    if (overflow) {
        File file = FileCollector.getInstance().createFile();
        try (OutputStream fos = new FileOutputStream(file)) {
            bos.writeTo(fos);
            while ((bytesNum = entityStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesNum);
            }
        }
        return new MimeFileDataSource(file, mimeType);
    }
    return new ByteArrayDataSource(bos.toByteArray(), mimeType);
}
Example 44
Project: FB2OnlineConverter-master  File: BookSender.java View source code
public void run() {
    File fileAttachment = book;
    try {
        //                Authenticator auth = new SMTPAuthenticator(fromAddress, fromPassword);
        //                Session session = Session.getInstance(properties, auth);
        Session session = Session.getInstance(mailSessionProperties);
        NoIdMimeMessage message = new NoIdMimeMessage(session);
        message.setMessageId("book." + bookId);
        message.addFrom(new Address[] { new InternetAddress(fromAddress, fromName) });
        message.addRecipients(Message.RecipientType.TO, new Address[] { new InternetAddress(targetAddress) });
        message.setSubject("Requested book" + fileAttachment.getName());
        Multipart multipart = new MimeMultipart();
        // create the message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        //fill message
        messageBodyPart.setText("book " + fileAttachment.getName());
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        // @todo content type
        DataSource source = new FileDataSource(fileAttachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(fileAttachment.getName());
        multipart.addBodyPart(messageBodyPart);
        // Put parts in message
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        logger.error("Can't send mail to user for document " + bookId, e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        logger.error("Can't send mail to user for document " + bookId, e);
        throw new RuntimeException(e.getMessage(), e);
    }
}
Example 45
Project: geronimo-specs-master  File: TextHandler.java View source code
/**
     * Method getContent
     *
     * @param datasource
     * @return
     * @throws IOException
     */
public Object getContent(final DataSource datasource) throws IOException {
    final InputStream is = datasource.getInputStream();
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    int count;
    final byte[] buffer = new byte[1000];
    try {
        while ((count = is.read(buffer, 0, buffer.length)) > 0) {
            os.write(buffer, 0, count);
        }
    } finally {
        is.close();
    }
    try {
        return os.toString(getCharSet(datasource.getContentType()));
    } catch (final ParseException e) {
        throw new UnsupportedEncodingException(e.getMessage());
    }
}
Example 46
Project: ikvm-openjdk-master  File: XMLProviderArgumentBuilder.java View source code
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) {
    if (model.mode == Service.Mode.PAYLOAD) {
        return new PayloadSource();
    } else {
        if (model.datatype == Source.class)
            return new PayloadSource();
        if (model.datatype == DataSource.class)
            return new DataSourceParameter(binding);
        throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass, model.datatype));
    }
}
Example 47
Project: javablog-master  File: SendWithImg.java View source code
public static void main(String[] args) {
    //邮件�数
    Properties prop = new Properties();
    // 指定å??è®®
    prop.put("mail.transport.protocol", "smtp");
    // 主机   stmp.qq.com
    prop.put("mail.smtp.host", "smtp.qq.com");
    // 端�
    prop.put("mail.smtp.port", 25);
    // 用户密�认�
    prop.put("mail.smtp.auth", "true");
    // 调试模�
    prop.put("mail.debug", "true");
    //设置密�和账户,和��人必须一致;
    Authenticator authenticator = new EmailAuthenticator("374126165@qq.com", "wang126165");
    //1.创建一个邮件会�
    Session session = Session.getDefaultInstance(prop, authenticator);
    //2.创建邮件体对象
    MimeMessage message = new MimeMessage(session);
    //3.设置�数:标题,�件人,收件人,时间,内容
    try {
        //3.1标题
        message.setSubject("带图片邮件", "utf-8");
        //3.2��时间
        message.setSentDate(new Date());
        //3.3�件人
        message.setFrom(new InternetAddress("374126165@qq.com"));
        //3.4接收人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("491629346@qq.com"));
        /***************设置邮件内容: 多功能用户邮件 (related)*******************/
        //4.1构建一个多功能邮件快
        MimeMultipart related = new MimeMultipart("related");
        // 4.2 构建多功能邮件�内容 = 左侧文本 + �侧图片资�
        MimeBodyPart content = new MimeBodyPart();
        MimeBodyPart resource = new MimeBodyPart();
        //设置具体内容
        //图片路径
        String filePath = SendWithImg.class.getResource("1.png").getPath();
        DataSource ds = new FileDataSource(new File(filePath));
        DataHandler handler = new DataHandler(ds);
        resource.setDataHandler(handler);
        //设置资æº?å??称,给外键引用
        resource.setContentID("mark");
        //设置具体文本
        content.setContent("<img src='cid:mark'/>  我的公�Ptool", "text/html;charset=UTF-8");
        //将内容加入
        related.addBodyPart(content);
        related.addBodyPart(resource);
        //把��快添加到邮件中
        message.setContent(related);
        //��
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
Example 48
Project: jaxws-master  File: TestApp.java View source code
private DataHandler getDataHandler(final String file) throws Exception {
    return new DataHandler(new DataSource() {

        public String getContentType() {
            return "text/html";
        }

        public InputStream getInputStream() {
            return getClass().getClassLoader().getResourceAsStream(file);
        }

        public String getName() {
            return null;
        }

        public OutputStream getOutputStream() {
            throw new UnsupportedOperationException();
        }
    });
}
Example 49
Project: jtheque-core-master  File: MailUtils.java View source code
/**
     * Attach files to the message.
     *
     * @param email The email to get the files from.
     * @param mp    The multi part message.
     *
     * @throws MessagingException Throw if an error occurs during the attaching files process.
     */
private static void attachFiles(Email email, Multipart mp) throws MessagingException {
    for (File f : email.getAttachedFiles()) {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(f);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(source.getName());
        mp.addBodyPart(messageBodyPart);
    }
}
Example 50
Project: ManagedRuntimeInitiative-master  File: XMLProviderArgumentBuilder.java View source code
static XMLProviderArgumentBuilder create(ProviderEndpointModel model) {
    if (model.mode == Service.Mode.PAYLOAD) {
        return new PayloadSource();
    } else {
        if (model.datatype == Source.class)
            return new PayloadSource();
        if (model.datatype == DataSource.class)
            return new DataSourceParameter();
        throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass, model.datatype));
    }
}
Example 51
Project: MyPublicRepo-master  File: InboundAttachmentDataHandler.java View source code
@Override
protected void finalize() throws Throwable {
    DataSource ds = m_delegate.getDataSource();
    if (!(ds instanceof CachedFileDataSource)) {
        return;
    }
    CachedFileDataSource cfds = (CachedFileDataSource) ds;
    File file = cfds.getFile();
    try {
        file.delete();
    } catch (Throwable t) {
        file = null;
    }
}
Example 52
Project: OA-master  File: MessageParser.java View source code
private static void parse(Message message) {
    try {
        MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
        // 获��件人地�
        String from = parser.getFrom();
        // 获�抄�人地�
        List<Address> cc = parser.getCc();
        // 获�收件人地�
        List<Address> to = parser.getTo();
        // 获�回�邮件时的收件人
        String replyTo = parser.getReplyTo();
        // 获�邮件主题
        String subject = parser.getSubject();
        // 获�Html内容
        String htmlContent = parser.getHtmlContent();
        // 获�纯文本邮件内容(注:有些邮件�支�html)
        String plainContent = parser.getPlainContent();
        System.out.println(subject);
        // 获�附件,并写入�盘
        List<DataSource> attachments = parser.getAttachmentList();
        for (DataSource ds : attachments) {
            BufferedOutputStream outStream = null;
            BufferedInputStream ins = null;
            try {
                String fileName = folder + File.separator + ds.getName();
                outStream = new BufferedOutputStream(new FileOutputStream(fileName));
                ins = new BufferedInputStream(ds.getInputStream());
                byte[] data = new byte[2048];
                int length = -1;
                while ((length = ins.read(data)) != -1) {
                    outStream.write(data, 0, length);
                }
                outStream.flush();
                System.out.println("附件:" + fileName);
            } finally {
                if (ins != null) {
                    ins.close();
                }
                if (outStream != null) {
                    outStream.close();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 53
Project: ODE-X-master  File: XMLDataContentHandler.java View source code
@Override
public Object getTransferData(DataFlavor flavor, DataSource dataSource) throws UnsupportedFlavorException, IOException {
    if (XMLStreamReader.class.equals(flavor.getRepresentationClass())) {
        try {
            return XMLInputFactory.newInstance().createXMLStreamReader(dataSource.getInputStream());
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else if (Document.class.equals(flavor.getRepresentationClass())) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder parser = factory.newDocumentBuilder();
            return parser.parse(dataSource.getInputStream());
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else if (StreamSource.class.equals(flavor.getRepresentationClass())) {
        try {
            return new StreamSource(dataSource.getInputStream());
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
    throw new IOException(String.format("Unsupported dataflavor %s", flavor));
}
Example 54
Project: openjdk-master  File: XMLProviderArgumentBuilder.java View source code
static XMLProviderArgumentBuilder createBuilder(ProviderEndpointModel model, WSBinding binding) {
    if (model.mode == Service.Mode.PAYLOAD) {
        return new PayloadSource();
    } else {
        if (model.datatype == Source.class)
            return new PayloadSource();
        if (model.datatype == DataSource.class)
            return new DataSourceParameter(binding);
        throw new WebServiceException(ServerMessages.PROVIDER_INVALID_PARAMETER_TYPE(model.implClass, model.datatype));
    }
}
Example 55
Project: openxds-master  File: ProvideAndRegisterDocumentSetTest.java View source code
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;
}
Example 56
Project: PerformanceRegressionTest-master  File: SampleMail.java View source code
public static void mail(String attachement) throws Exception {
    InputStream in = null;
    final Properties props = new Properties();
    try {
        in = new FileInputStream("mail.properties");
        props.load(in);
    } finally {
        if (in != null) {
            in.close();
        }
    }
    Authenticator auth = new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.getProperty("mail.username"), props.getProperty("mail.password"));
        }
    };
    Session session = Session.getDefaultInstance(props, auth);
    MimeMessage message = new MimeMessage(session);
    message.setSubject("Performance regression test failed: " + DateFormat.getInstance().format(new Date()));
    Address address = new InternetAddress("perftest@neotechnology.com", "Performance Tester");
    message.setFrom(address);
    for (Address add : MailToList.getAddresses()) {
        message.addRecipient(RecipientType.BCC, add);
    }
    // Create the message part
    BodyPart messageBodyPart = new MimeBodyPart();
    // Fill the message
    messageBodyPart.setText("Test Failed");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    // Part two is attachment
    File f = new File(attachement);
    // for ( String filename : f.list( new FilenameFilter()
    // {
    //
    // @Override
    // public boolean accept( File dir, String name )
    // {
    // return name.endsWith( "gz" );
    // }
    //
    // } ) )
    DataSource source = new FileDataSource(f);
    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(f.getName());
    multipart.addBodyPart(messageBodyPart);
    // Put parts in message
    message.setContent(multipart);
    Transport.send(message);
}
Example 57
Project: Plain-of-JARs-master  File: mailsender.java View source code
public static void main(String[] args) {
    String path2 = ".";
    File[] myarray;
    String version = "1.0.0";
    String program = "MailSender";
    System.out.println(program + " " + version);
    String username = "";
    String from = "";
    String host = "";
    String port = "";
    String password = "";
    String email_addresses = "";
    String email_subject = "";
    String email_text = "";
    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream("config.properties"));
        username = prop.getProperty("username");
        from = prop.getProperty("from");
        host = prop.getProperty("host");
        port = prop.getProperty("port");
        password = prop.getProperty("password");
        email_addresses = prop.getProperty("email_addresses");
        email_subject = prop.getProperty("email_subject");
        email_text = prop.getProperty("email_text");
        path2 = prop.getProperty("directory");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    final String username_final = username;
    final String password_final = password;
    File directory = new File(path2);
    Properties props = new Properties();
    props.put("mail.smtp.auth", true);
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    myarray = directory.listFiles(new FileFilter() {

        public boolean accept(File dir) {
            return dir.toString().endsWith(".zip") && dir.isFile();
        }
    });
    System.out.println("Found " + myarray.length + " file(s)");
    for (int j = 0; j < myarray.length; j++) {
        int file_number = j + 1;
        System.out.print("\rProcessing file " + file_number + " of " + myarray.length);
        File path = myarray[j];
        String path_current = path.toString();
        File file_file = new File(path_current);
        String file = path_current;
        String filename = path.getName();
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username_final, password_final);
            }
        });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email_addresses));
            message.setSubject(email_subject);
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(email_text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            //System.out.println("Sending");
            Transport.send(message);
        //System.out.println("Done");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    System.out.println("");
    System.out.println("Done");
}
Example 58
Project: platform2-master  File: SendMail.java View source code
public static void send(String from, String to, String cc, String bcc, String host, String subject, String text, File attachedFile) throws MessagingException {
    // Start a session
    java.util.Properties properties = System.getProperties();
    Session session = Session.getInstance(properties, null);
    // Construct a message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    to = to.replace(';', ',');
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    //this Address[] ccAddressess = InternetAddress.parse(cc); or similar
    if ((cc != null) && !("".equals(cc))) {
        cc = cc.replace(';', ',');
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
    }
    if ((bcc != null) && !("".equals(bcc))) {
        bcc = bcc.replace(';', ',');
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc));
    }
    /** @todo tryggvi laga */
    /*
			message.setSubject(parseCharacters(subject));
		
			message.setText(parseCharacters(text));
		
		*/
    message.setSubject((subject));
    if (attachedFile == null) {
        message.setText((text));
    } else {
        BodyPart body = new MimeBodyPart();
        body.setText(text);
        BodyPart attachment = new MimeBodyPart();
        DataSource attachmentSource = new FileDataSource(attachedFile);
        DataHandler attachmentHandler = new DataHandler(attachmentSource);
        attachment.setDataHandler(attachmentHandler);
        attachment.setFileName(attachedFile.getName());
        attachment.setDescription("Attached file");
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(body);
        System.out.println("Adding attachment " + attachment);
        multipart.addBodyPart(attachment);
        message.setContent(multipart);
    }
    //Connect to the transport
    Transport transport = session.getTransport("smtp");
    transport.connect(host, "", "");
    //Send the message and close the connection
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}
Example 59
Project: RAVA-Voting-master  File: MailService.java View source code
public static void sendMessageWithFile(String recipient, String subject, String message, String filename) throws MessagingException {
    if (mailService == null) {
        mailService = new MailService();
    }
    MimeMessage mimeMessage = new MimeMessage(mailSession);
    mimeMessage.setFrom(new InternetAddress(FROM));
    mimeMessage.setSender(new InternetAddress(FROM));
    mimeMessage.setSubject(subject);
    //mimeMessage.setContent(message, "text/plain");
    BodyPart body = new MimeBodyPart();
    body.setText(message);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);
    body = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    body.setDataHandler(new DataHandler(source));
    body.setFileName(filename.substring(filename.lastIndexOf('\\') + 1));
    multipart.addBodyPart(body);
    mimeMessage.setContent(multipart);
    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    Transport transport = mailSession.getTransport("smtps");
    transport.connect(HOST, PORT, USER, PASSWORD);
    transport.addTransportListener(new MyTransportListener());
    transport.sendMessage(mimeMessage, mimeMessage.getRecipients(Message.RecipientType.TO));
    transport.close();
}
Example 60
Project: RemoteDesktopSharing-master  File: EMail.java View source code
public static boolean sendMail(String subject, String content, String attached_files) {
    Properties properties = System.getProperties();
    properties.put("mail.smtps.host", SERVER);
    properties.put("mail.smtps.auth", "true");
    Session session = Session.getInstance(properties);
    if (DEBUG) {
        session.setDebug(true);
    }
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(SettingsConstatnts.MAIL_SERVER));
        if (SettingsConstatnts.MAIL_SEND_TO != null) {
            msg.addRecipients(Message.RecipientType.TO, SettingsConstatnts.MAIL_SEND_TO);
        }
        msg.setContent(content, "text/html");
        msg.setSubject(subject);
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Fill the message
        messageBodyPart.setText(content);
        // Create a Multipart
        Multipart multipart = new MimeMultipart();
        // Add part one
        multipart.addBodyPart(messageBodyPart);
        for (StringTokenizer tokenizer = new StringTokenizer(attached_files, ","); tokenizer.hasMoreTokens(); ) {
            String filepath = tokenizer.nextToken().trim();
            String filename = filepath.substring(filepath.lastIndexOf('\\'));
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filepath);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);
            multipart.addBodyPart(messageBodyPart);
        }
        msg.setContent(multipart);
        msg.saveChanges();
        Transport tr = session.getTransport("smtps");
        tr.connect(SERVER, SettingsConstatnts.MAIL_SERVER, SettingsConstatnts.MAIL_SERVER_PSWD);
        tr.sendMessage(msg, msg.getAllRecipients());
        tr.close();
        System.out.println("sending success");
        return true;
    } catch (AuthenticationFailedException e) {
        System.out.println(e.getMessage());
        return false;
    } catch (SendFailedException e) {
        System.out.println(e.getMessage());
        return false;
    } catch (MessagingException e) {
        System.out.println(e.getMessage());
        return false;
    }
}
Example 61
Project: simple-java-mail-master  File: EqualsHelper.java View source code
private static boolean isEqualDataSource(final DataSource resource1, final DataSource resource2) {
    if (resource1.getName() != null ? !resource1.getName().equals(resource2.getName()) : resource2.getName() != null) {
        return false;
    }
    return resource1.getContentType() != null ? resource1.getContentType().equals(resource2.getContentType()) : resource2.getContentType() == null;
}
Example 62
Project: turmeric-runtime-master  File: InboundAttachmentDataHandler.java View source code
@Override
protected void finalize() throws Throwable {
    DataSource ds = m_delegate.getDataSource();
    if (!(ds instanceof CachedFileDataSource)) {
        return;
    }
    CachedFileDataSource cfds = (CachedFileDataSource) ds;
    File file = cfds.getFile();
    try {
        file.delete();
    } catch (Throwable t) {
        file = null;
    }
}
Example 63
Project: wildfly-master  File: JaxrsMultipartProviderTestCase.java View source code
@Test
public void testJaxRsWithNoApplication() throws Exception {
    String result = performCall("myjaxrs/form");
    DataSource mimeData = new ByteArrayDataSource(result.getBytes(), "multipart/related");
    MimeMultipart mime = new MimeMultipart(mimeData);
    String string = (String) mime.getBodyPart(0).getContent();
    Assert.assertEquals("Hello", string);
    string = (String) mime.getBodyPart(1).getContent();
    Assert.assertEquals("World", string);
}
Example 64
Project: Wink-master  File: DSResource.java View source code
@POST
public Response post(DataSource dataSource) {
    Response resp = null;
    try {
        InputStream inputStream = dataSource.getInputStream();
        byte[] inputBytes = new byte[inputStream.available()];
        int next = inputStream.read();
        int i = 0;
        while (next != -1) {
            if (i == inputBytes.length) {
                inputBytes = ArrayUtils.copyOf(inputBytes, 2 * i);
            }
            inputBytes[i] = (byte) next;
            next = inputStream.read();
            i++;
        }
        TestDataSource entity = new TestDataSource(inputBytes, dataSource.getName(), dataSource.getContentType());
        ResponseBuilder rb = Response.ok();
        rb.entity(entity);
        resp = rb.build();
    } catch (Exception e) {
        ResponseBuilder rb = Response.serverError();
        resp = rb.build();
    }
    return resp;
}
Example 65
Project: wonder-master  File: ERMailDataAttachment.java View source code
@Override
protected BodyPart getBodyPart() throws MessagingException {
    MimeBodyPart bp = new MimeBodyPart();
    if (getDataHandler() == null) {
        DataSource ds = new ByteArrayDataSource((byte[]) content(), _mimeType);
        bp.setDataHandler(new DataHandler(ds));
    } else {
        bp.setDataHandler(getDataHandler());
        if (_mimeType != null) {
            bp.setHeader("Content-type", _mimeType);
        }
    }
    if (contentID() != null) {
        bp.setHeader("Content-ID", contentID());
    }
    bp.setFileName(fileName());
    return bp;
}
Example 66
Project: doqui-index-master  File: ServiceImpl.java View source code
public Attachment downloadMethod(String uid, String usr, String pwd, String repo) throws SystemException {
    logger.debug("[ServiceImpl:downloadMethod] BEGIN");
    start();
    //String sourcePathDL = getPropsValue("sourcePathDL");
    Attachment myFile = new Attachment();
    //myFile.fileType = fileType;
    try {
        ResourceBundle resources = ResourceBundle.getBundle("mtom");
        Properties prop = new Properties();
        prop.put("java.naming.factory.initial", resources.getString("CONTEXT"));
        prop.put("java.naming.provider.url", resources.getString("URL_TO_CONNECT"));
        Context ctx = new InitialContext(prop);
        EcmEngineManagement management_bean = ((EcmEngineManagementHome) ctx.lookup(resources.getString("JNDI_NAME_MANAGEMENT"))).create();
        EcmEngineSearch search_bean = ((EcmEngineSearchHome) ctx.lookup(resources.getString("JNDI_NAME_SEARCH"))).create();
        OperationContext context = new OperationContext();
        context.setUsername(usr);
        context.setPassword(pwd);
        context.setRepository(repo);
        context.setFruitore(usr);
        context.setNomeFisico(usr);
        ResultContent rc = management_bean.getContentMetadata(new Node(uid), context);
        String pn = rc.getPrefixedName();
        Path absolutePath = search_bean.getAbsolutePath(new Node(uid), context);
        File sourceFile = new File(absolutePath.getPath());
        myFile.fileSize = sourceFile.length();
        myFile.fileName = pn.substring(pn.indexOf(":") + 1, pn.lastIndexOf("."));
        myFile.fileType = pn.substring(pn.lastIndexOf(".") + 1);
        javax.activation.DataSource source = new FileDataSource(sourceFile);
        myFile.attachmentDataHandler = new DataHandler(source);
        if (logger.isInfoEnabled()) {
            logger.info("[ServiceImpl:downloadMethod] Download di " + myFile.fileName + "." + myFile.fileType + " iniziato.");
        }
        dumpElapsed("downloadMethod", "UID: " + uid + " - FILENAME: " + myFile.fileName + "." + myFile.fileType + " - FILESIZE: " + myFile.fileSize + " - FILEPATH: " + absolutePath.getPath(), "Download iniziato.");
    } catch (Exception e) {
        e.printStackTrace();
        throw new SystemException("Errore durante la lettura del file sul server", e);
    } finally {
        stop();
        logger.debug("[ServiceImpl:downloadMethod] END");
    }
    /*File sourceFile = new File(sourcePathDL + fileName + "." + fileType);
		if (!sourceFile.canRead()) {
			throw new SystemException("Il file da scaricare " + fileName + "." + fileType + " non esiste.");
		} else {
			myFile.fileSize = sourceFile.length();
			javax.activation.DataSource source = new FileDataSource(sourceFile);
			myFile.attachmentDataHandler = new DataHandler(source);
			return myFile;
		}*/
    return myFile;
}
Example 67
Project: milton-master  File: StandardMessageFactoryImpl.java View source code
private void addAttachmentToMime(MimeMultipart multipart, Attachment att) throws MessagingException {
    System.out.println("StandardMessageFactoryImpl - addAttachmentToMime2 - " + att.getContentId());
    MimeBodyPart bp = new MimeBodyPart();
    DataSource fds = new AttachmentReadingDataSource(att);
    bp.setDataHandler(new DataHandler(fds));
    bp.setHeader("Content-ID", att.getContentId());
    bp.setDisposition(att.getDisposition());
    bp.setFileName(att.getName());
    multipart.addBodyPart(bp);
}
Example 68
Project: milton2-master  File: StandardMessageFactoryImpl.java View source code
private void addAttachmentToMime(MimeMultipart multipart, Attachment att) throws MessagingException {
    System.out.println("StandardMessageFactoryImpl - addAttachmentToMime2 - " + att.getContentId());
    MimeBodyPart bp = new MimeBodyPart();
    DataSource fds = new AttachmentReadingDataSource(att);
    bp.setDataHandler(new DataHandler(fds));
    bp.setHeader("Content-ID", att.getContentId());
    bp.setDisposition(att.getDisposition());
    bp.setFileName(att.getName());
    multipart.addBodyPart(bp);
}
Example 69
Project: spring-framework-2.5.x-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from a
	 * <code>javax.activation.DataSource</code>.
	 * <p>Note that the InputStream returned by the DataSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * <code>getInputStream()</code> multiple times.
	 * <p><b>NOTE:</b> Invoke <code>addInline</code> <i>after</i> {@link #setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param dataSource the <code>javax.activation.DataSource</code> to take
	 * the content from, determining the InputStream and the content type
	 * @throws MessagingException in case of errors
	 * @see #addInline(String, java.io.File)
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
    Assert.notNull(contentId, "Content ID must not be null");
    Assert.notNull(dataSource, "DataSource must not be null");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
    // We're using setHeader here to remain compatible with JavaMail 1.2,
    // rather than JavaMail 1.3's setContentID.
    mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
    mimeBodyPart.setDataHandler(new DataHandler(dataSource));
    getMimeMultipart().addBodyPart(mimeBodyPart);
}
Example 70
Project: spring-framework-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from a
	 * {@code javax.activation.DataSource}.
	 * <p>Note that the InputStream returned by the DataSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * {@code getInputStream()} multiple times.
	 * <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@link #setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param dataSource the {@code javax.activation.DataSource} to take
	 * the content from, determining the InputStream and the content type
	 * @throws MessagingException in case of errors
	 * @see #addInline(String, java.io.File)
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
    Assert.notNull(contentId, "Content ID must not be null");
    Assert.notNull(dataSource, "DataSource must not be null");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
    // We're using setHeader here to remain compatible with JavaMail 1.2,
    // rather than JavaMail 1.3's setContentID.
    mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
    mimeBodyPart.setDataHandler(new DataHandler(dataSource));
    getMimeMultipart().addBodyPart(mimeBodyPart);
}
Example 71
Project: activityinfo-master  File: SmtpMailSender.java View source code
@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", "activityinfo@configure-me.com"), 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 (MessagingExceptionUnsupportedEncodingException |  e) {
        throw new RuntimeException(e);
    }
}
Example 72
Project: albert-master  File: JavaMailWithAttachment.java View source code
/**
     * ��邮件
     * 
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUser
     *            收件人地�
     * @param attachment
     *            附件
     */
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
    try {
        // �件人
        InternetAddress from = new InternetAddress(sender_username);
        message.setFrom(from);
        // 收件人
        InternetAddress to = new InternetAddress(receiveUser);
        message.setRecipient(Message.RecipientType.TO, to);
        // 邮件主题
        message.setSubject(subject);
        // �multipart对象中添加邮件的�个部分内容,包括文本内容和附件
        Multipart multipart = new MimeMultipart();
        // 添加邮件正文
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);
        // 添加附件的内容
        if (attachment != null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            // 网上æµ?传的解决文件å??ä¹±ç ?的方法,其实用MimeUtility.encodeWordå°±å?¯ä»¥å¾ˆæ–¹ä¾¿çš„æ?žå®š
            // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?你的中文附件标题å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ?
            //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");
            //MimeUtility.encodeWordå?¯ä»¥é?¿å…?文件å??ä¹±ç ?
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }
        // 将multipart对象放到message中
        message.setContent(multipart);
        // �存邮件
        message.saveChanges();
        transport = session.getTransport("smtp");
        // smtp验è¯?,就是你用æ?¥å?‘邮件的邮箱用户å??密ç ?
        //            transport.connect(mailHost, sender_username, sender_password);
        transport.connect(host, port, sender_username, sender_password);
        // ��
        transport.sendMessage(message, message.getAllRecipients());
        System.out.println("send success!");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 73
Project: aq2o-master  File: SendMail.java View source code
public void sendMail(String[] recipients, String subject, String htmlBody) throws Exception {
    Properties props = new Properties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", host);
    props.setProperty("mail.port", "" + port);
    props.setProperty("mail.user", user);
    props.setProperty("mail.password", password);
    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);
    Transport transport = mailSession.getTransport();
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(subject);
    message.setFrom(new InternetAddress(from));
    message.setSentDate(new Date());
    for (String recipient : recipients) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
    }
    //
    // This HTML mail have to 2 part, the BODY and the embedded image
    //
    MimeMultipart multipart = new MimeMultipart("related");
    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    // String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
    messageBodyPart.setContent(htmlBody, "text/html");
    // add it
    multipart.addBodyPart(messageBodyPart);
    // second part (the image)
    /*
		 * messageBodyPart = new MimeBodyPart(); DataSource fds = new
		 * FileDataSource("C:\\images\\jht.gif");
		 * messageBodyPart.setDataHandler(new DataHandler(fds));
		 * messageBodyPart.setHeader("Content-ID", "<image>");
		 * 
		 * // add it multipart.addBodyPart(messageBodyPart);
		 */
    // put everything together
    message.setContent(multipart);
    transport.connect();
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}
Example 74
Project: capedwarf-blue-master  File: MessageConverter.java View source code
private MimeBodyPart createAttachmentBodyPart(MailService.Attachment attachment) throws MessagingException {
    if (hasInvalidAttachmentFileType(attachment.getFileName())) {
        throw new IllegalArgumentException(String.format("Invalid attachment file type: %s", attachment));
    }
    DataSource source = new ByteArrayDataSource(attachment.getData(), "application/octet-stream");
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(source));
    bodyPart.setFileName(attachment.getFileName());
    return bodyPart;
}
Example 75
Project: carbon-business-process-master  File: BPMNUploadExecutor.java View source code
@Override
public boolean execute(HttpServletRequest request, HttpServletResponse response) throws CarbonException, IOException {
    String errMsg;
    response.setContentType("text/html; charset=utf-8");
    PrintWriter out = response.getWriter();
    String webContext = (String) request.getAttribute(CarbonConstants.WEB_CONTEXT);
    String serverURL = (String) request.getAttribute(CarbonConstants.SERVER_URL);
    String cookie = (String) request.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);
    Map<String, ArrayList<FileItemData>> fileItemsMap = getFileItemsMap();
    if (fileItemsMap == null || fileItemsMap.isEmpty()) {
        String msg = "File uploading failed.";
        log.error(msg);
        out.write("<textarea>" + "(function(){i18n.fileUplodedFailed();})();" + "</textarea>");
        return true;
    }
    BPMNUploaderClient uploaderClient = new BPMNUploaderClient(configurationContext, serverURL + "BPMNUploaderService", cookie);
    File uploadedTempFile;
    try {
        for (FileItemData fileData : fileItemsMap.get("bpmnFileName")) {
            String fileName = getFileName(fileData.getFileItem().getName());
            //Check filename for \ charactors. This cannot be handled at the lower stages.
            if (fileName.matches("(.*[\\\\].*[/].*|.*[/].*[\\\\].*)")) {
                log.error("BPMN Package Validation Failure: one or more of the following illegal characters are in " + "the package.\n ~!@#$;%^*()+={}[]| \\<>");
                throw new Exception("BPMN Package Validation Failure: one or more of the following illegal characters " + "are in the package. ~!@#$;%^*()+={}[]| \\<>");
            }
            //Check file extension.
            checkServiceFileExtensionValidity(fileName, ALLOWED_FILE_EXTENSIONS);
            if (fileName.lastIndexOf('\\') != -1) {
                int indexOfColon = fileName.lastIndexOf('\\') + 1;
                fileName = fileName.substring(indexOfColon, fileName.length());
            }
            if (fileData.getFileItem().getFieldName().equals("bpmnFileName")) {
                uploadedTempFile = new File(CarbonUtils.getTmpDir(), fileName);
                fileData.getFileItem().write(uploadedTempFile);
                DataSource dataSource = new FileDataSource(uploadedTempFile);
                uploaderClient.addUploadedFileItem(new DataHandler(dataSource), fileName, "bar");
            }
        }
        uploaderClient.uploadFileItems();
        String msg = "Your BPMN package has been uploaded successfully. Please refresh this page in a" + " while to see the status of the new process.";
        CarbonUIMessage.sendCarbonUIMessage(msg, CarbonUIMessage.INFO, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
        return true;
    } catch (Exception e) {
        errMsg = "File upload failed :" + e.getMessage();
        log.error(errMsg, e);
        CarbonUIMessage.sendCarbonUIMessage(errMsg, CarbonUIMessage.ERROR, request, response, getContextRoot(request) + "/" + webContext + "/bpmn/process_list_view.jsp");
    }
    return false;
}
Example 76
Project: cbtest-master  File: S3FileSystemBucketAdapter.java View source code
@Override
public DataHandler loadObjectRange(String mountedRoot, String bucket, String fileName, long startPos, long endPos) {
    File file = new File(getBucketFolderDir(mountedRoot, bucket) + File.separatorChar + fileName);
    try {
        DataSource ds = new FileRangeDataSource(file, startPos, endPos);
        return new DataHandler(ds);
    } catch (MalformedURLException e) {
        throw new FileNotExistException("Unable to open underlying object file");
    } catch (IOException e) {
        throw new FileNotExistException("Unable to open underlying object file");
    }
}
Example 77
Project: constellio-master  File: EmailServices.java View source code
public Message createMessage(String from, String subject, String body, List<MessageAttachment> attachments) throws MessagingException, IOException {
    Message message = new MimeMessage(Session.getInstance(System.getProperties()));
    if (StringUtils.isNotBlank(from)) {
        message.setFrom(new InternetAddress(from));
    }
    if (subject != null) {
        message.setSubject(subject);
    }
    MimeBodyPart content = new MimeBodyPart();
    if (body != null) {
        content.setText(body);
    } else {
        content.setText("");
    }
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(content);
    // add attachments
    if (attachments != null && !attachments.isEmpty()) {
        for (MessageAttachment messageAttachment : attachments) {
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(messageAttachment.getInputStream(), messageAttachment.getMimeType());
            attachment.setDataHandler(new DataHandler(source));
            attachment.setFileName(messageAttachment.getAttachmentName());
            multipart.addBodyPart(attachment);
        }
    }
    message.setContent(multipart);
    return message;
}
Example 78
Project: dk-master  File: MailNotifyServiceImpl.java View source code
protected void sendContext(MimeMessage msg, NotifyDo message) throws MessagingException {
    // �multipart对象中添加邮件的�个部分内容,包括文本内容和附件
    Multipart multipart = new MimeMultipart();
    // 设置邮件的文本内容
    BodyPart contentPart = new MimeBodyPart();
    contentPart.setText(message.MESSAGE_CONTEXT);
    multipart.addBodyPart(contentPart);
    // 添加附件
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(message.getFilePath());
    // 添加附件的内容
    messageBodyPart.setDataHandler(new DataHandler(source));
    // 添加附件的标题
    // 这里很é‡?è¦?,通过下é?¢çš„Base64ç¼–ç ?的转æ?¢å?¯ä»¥ä¿?è¯?你的中文附件标题å??在å?‘é€?æ—¶ä¸?会å?˜æˆ?ä¹±ç ?
    sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
    messageBodyPart.setFileName("=?UTF-8?B?" + enc.encode((message.getFileName() + ".xls").getBytes()) + "?=");
    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);
    msg.saveChanges();
}
Example 79
Project: EmmageePlus-master  File: MailSender.java View source code
/**
	 * 以文本格���邮件
	 * 
	 * @param sender
	 * @param encryptPassword
	 * @param smtp
	 * @param subject
	 * @param content
	 * @param file
	 * @param maillists
	 * @return
	 */
public static boolean sendTextMail(String sender, String encryptPassword, String smtp, String subject, String content, String file, String[] maillists) {
    if (maillists == null || maillists.length == 0 || ("".equals(maillists[0].trim()))) {
        return false;
    } else {
        // Get system properties
        Properties props = new Properties();
        // Setup mail server
        props.put("mail.smtp.host", smtp);
        props.put("mail.smtp.port", PORT);
        // Get session
        // 如果需�密�验�,把这里的false改�true
        props.put("mail.smtp.auth", "true");
        // 判断是�需�身份认�
        CustomizedAuthenticator authenticator = null;
        if (true) {
            // 如果需�身份认�,则创建一个密�验�器
            authenticator = new CustomizedAuthenticator(sender, encryptPassword);
        }
        // 根�邮件会�属性和密�验�器构造一个��邮件的session
        Session sendMailSession = Session.getInstance(props, authenticator);
        try {
            // 根�session创建一个邮件消�
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件��者地�
            Address from = new InternetAddress(sender);
            // 设置邮件消�的��者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地�,并设置到邮件消�中
            Address[] tos = null;
            tos = new InternetAddress[maillists.length];
            for (int i = 0; i < maillists.length; i++) {
                tos[i] = new InternetAddress(maillists[i]);
            }
            // Message.RecipientType.TO属性表示接收者的类型为TO
            mailMessage.setRecipients(Message.RecipientType.TO, tos);
            // 设置邮件消�的主题
            mailMessage.setSubject(subject);
            // 设置邮件消���的时间
            mailMessage.setSentDate(new Date());
            BodyPart bodyPart = new MimeBodyPart();
            bodyPart.setText(content);
            MimeBodyPart attachPart = new MimeBodyPart();
            DataSource source = new FileDataSource(file);
            attachPart.setDataHandler(new DataHandler(source));
            attachPart.setFileName(file);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodyPart);
            multipart.addBodyPart(attachPart);
            mailMessage.setContent(multipart);
            MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
            mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
            mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
            mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
            mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
            mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
            CommandMap.setDefaultCommandMap(mc);
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }
    return false;
}
Example 80
Project: entando-components-master  File: AttachmentAction.java View source code
private void addNewBodyPart(Multipart multiPart) throws ApsSystemException {
    try {
        String bodyPartFileName = this._filename;
        String bodypartFolder = this.getMultipartFolder(multiPart);
        String fileName = bodypartFolder + File.separator + bodyPartFileName;
        InputStream inputStream = new FileInputStream(this._file);
        FileHelper.saveFile(fileName, inputStream);
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(bodyPartFileName);
        messageBodyPart.setDisposition(Part.ATTACHMENT);
        multiPart.addBodyPart(messageBodyPart);
    } catch (Throwable t) {
        throw new ApsSystemException("Errore in preparazione attachments in reply", t);
    }
}
Example 81
Project: entando-plugins-parent-master  File: AttachmentAction.java View source code
private void addNewBodyPart(Multipart multiPart) throws ApsSystemException {
    try {
        String bodyPartFileName = this._filename;
        String bodypartFolder = this.getMultipartFolder(multiPart);
        String fileName = bodypartFolder + File.separator + bodyPartFileName;
        InputStream inputStream = new FileInputStream(this._file);
        FileHelper.saveFile(fileName, inputStream);
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(bodyPartFileName);
        messageBodyPart.setDisposition(Part.ATTACHMENT);
        multiPart.addBodyPart(messageBodyPart);
    } catch (Throwable t) {
        throw new ApsSystemException("Errore in preparazione attachments in reply", t);
    }
}
Example 82
Project: etk-component-master  File: DataSourceEntityProvider.java View source code
/**
   * Create DataSource instance dependent entity size. If entity has size less
   * then <tt>MAX_BUFFER_SIZE</tt> then {@link ByteArrayDataSource} will be
   * created otherwise {@link MimeFileDataSource} will be created.
   * 
   * @param entityStream the {@link InputStream} of the HTTP entity
   * @param mimeType media type of data, HTTP header 'Content-type'
   * @return See {@link DataSource}
   * @throws IOException if any i/o errors occurs
   */
private static DataSource createDataSource(InputStream entityStream, String mimeType) throws IOException {
    boolean overflow = false;
    byte[] buffer = new byte[8192];
    ApplicationContext context = ApplicationContextImpl.getCurrent();
    int bufferSize = (Integer) context.getAttributes().get(RequestHandler.WS_RS_BUFFER_SIZE);
    ByteArrayOutputStream bout = new ByteArrayOutputStream(bufferSize);
    int bytes = -1;
    while ((bytes = entityStream.read(buffer)) != -1) {
        bout.write(buffer, 0, bytes);
        if (bout.size() > bufferSize) {
            overflow = true;
            break;
        }
    }
    if (!overflow)
        // small data , use bytes
        return new ByteArrayDataSource(bout.toByteArray(), mimeType);
    // large data, use file
    final File file = File.createTempFile("datasource", "tmp");
    OutputStream fout = new FileOutputStream(file);
    // copy data from byte array in file
    bout.writeTo(fout);
    while ((bytes = entityStream.read(buffer)) != -1) fout.write(buffer, 0, bytes);
    fout.close();
    return new MimeFileDataSource(file, mimeType);
}
Example 83
Project: gedcomx-java-master  File: FamilySearchMemories.java View source code
@Override
public SourceDescriptionState addArtifact(SourceDescription description, DataSource artifact, StateTransitionOption... options) {
    if (description != null) {
        ArtifactMetadata artifactMetadata = description.findExtensionOfType(ArtifactMetadata.class);
        if (artifactMetadata != null) {
            ArtifactType type = artifactMetadata.getKnownType();
            if (type != null) {
                ArrayList<StateTransitionOption> newOptions = new ArrayList<StateTransitionOption>(Arrays.asList(options));
                newOptions.add(artifactType(type));
                options = newOptions.toArray(new StateTransitionOption[newOptions.size()]);
            }
        }
    }
    return super.addArtifact(description, artifact, options);
}
Example 84
Project: HR-WebServices-Examples-Java-master  File: SWAClient.java View source code
public static void transferFile(File file, String destinationFile) throws Exception {
    Options options = new Options();
    options.setTo(targetEPR);
    options.setProperty(Constants.Configuration.ENABLE_SWA, Constants.VALUE_TRUE);
    options.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
    // Increase the time out when sending large attachments
    options.setTimeOutInMilliSeconds(10000);
    options.setTo(targetEPR);
    options.setAction("urn:uploadFile");
    // assume the use runs this sample at
    // <axis2home>/samples/soapwithattachments/ dir
    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("../../repository", null);
    ServiceClient sender = new ServiceClient(configContext, null);
    sender.setOptions(options);
    OperationClient mepClient = sender.createClient(ServiceClient.ANON_OUT_IN_OP);
    MessageContext mc = new MessageContext();
    FileDataSource fileDataSource = new FileDataSource(file);
    // Create a dataHandler using the fileDataSource. Any implementation of
    // javax.activation.DataSource interface can fit here.
    DataHandler dataHandler = new DataHandler(fileDataSource);
    String attachmentID = mc.addAttachment(dataHandler);
    SOAPFactory fac = OMAbstractFactory.getSOAP11Factory();
    SOAPEnvelope env = fac.getDefaultEnvelope();
    OMNamespace omNs = fac.createOMNamespace("http://service.soapwithattachments.sample", "swa");
    OMElement uploadFile = fac.createOMElement("uploadFile", omNs);
    OMElement nameEle = fac.createOMElement("name", omNs);
    nameEle.setText(destinationFile);
    OMElement idEle = fac.createOMElement("attchmentID", omNs);
    idEle.setText(attachmentID);
    uploadFile.addChild(nameEle);
    uploadFile.addChild(idEle);
    env.getBody().addChild(uploadFile);
    mc.setEnvelope(env);
    mepClient.addMessageContext(mc);
    mepClient.execute(true);
    MessageContext response = mepClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
    SOAPBody body = response.getEnvelope().getBody();
    OMElement element = body.getFirstElement().getFirstChildWithName(new QName("http://service.soapwithattachments.sample", "return"));
    System.out.println(element.getText());
}
Example 85
Project: j-road-master  File: AttachmentEchoEndpoint.java View source code
@Override
protected AttachmentEchoResponse invokeBean(AttachmentEchoRequest requestBean) throws IOException {
    // Creation of a response object -- must correspond to
    // response type defined in XML Schema definition.
    AttachmentEchoResponse response = new AttachmentEchoResponse();
    // Create a temporary object to store our data
    byte[] data = null;
    // Logging
    log.info("Received attachment, type: " + requestBean.getNest().getAttachment().getContentType() + ", size: " + requestBean.getNest().getAttachment().getInputStream().available());
    // Using a Spring helper class we read an InputStream to a byte array.
    // In real situations you probably want to pass the InputStream around.
    data = FileCopyUtils.copyToByteArray(requestBean.getNest().getAttachment().getInputStream());
    /*
     * JAXB generates DataHandler type setters for attachments, so you need to find a way to get your data into a
     * DataHandler. The easiest way to accomplish this, is to create a DataSource. A DataSource used here only needs to
     * provide an InputStream and a content type. A simple DataSource, which takes a byte array and content-type in
     * string form is included. Usually you would use something like FileDataSource, UrlDataSource or you can easily
     * implement your own. All a DataSource basically does in this context is give an InputStream and a content type for
     * that InputStream. An alternative way is to define a DataContentHandler and pass an object+content type when
     * creating a DataHandler. This way you will have to implement a DataContentHandler and DataContentHandlerFactory,
     * however.
     */
    DataSource ds = new ByteArrayDataSource(requestBean.getNest().getAttachment().getContentType(), data);
    // Now we can easily construct a DataHandler and pass it to JAXB.
    // Converting it to an attachment is handled by the library.
    DataHandler dh = new DataHandler(ds);
    AttachmentEchoNest nest = new AttachmentEchoNest();
    nest.setAttachment(dh);
    response.setNest(nest);
    // Finally, we return the response object.
    return response;
}
Example 86
Project: javamail_android-master  File: image_gif.java View source code
public Object getContent(DataSource ds) throws IOException {
    InputStream is = ds.getInputStream();
    int pos = 0;
    int count;
    byte buf[] = new byte[1024];
    while ((count = is.read(buf, pos, buf.length - pos)) != -1) {
        pos += count;
        if (pos >= buf.length) {
            int size = buf.length;
            if (size < 256 * 1024)
                size += size;
            else
                size += 256 * 1024;
            byte tbuf[] = new byte[size];
            System.arraycopy(buf, 0, tbuf, 0, pos);
            buf = tbuf;
        }
    }
    return BitmapFactory.decodeByteArray(buf, 0, pos);
}
Example 87
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: UIAttachment.java View source code
@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);
    }
}
Example 88
Project: jbossws-cxf-master  File: JBWS2259TestCase.java View source code
@Test
@RunAsClient
public void testCall() throws Exception {
    URL wsdlURL = new URL(baseURL + "?wsdl");
    QName serviceName = new QName("http://ws.jboss.org/jbws2259", "EndpointService");
    Service service = Service.create(wsdlURL, serviceName);
    Endpoint port = service.getPort(Endpoint.class);
    BindingProvider bindingProvider = (BindingProvider) port;
    SOAPBinding soapBinding = (SOAPBinding) bindingProvider.getBinding();
    soapBinding.setMTOMEnabled(true);
    File sharkFile = getResourceFile("jaxws/jbws2259/attach.jpeg");
    DataSource ds = new FileDataSource(sharkFile);
    DataHandler handler = new DataHandler(ds);
    String expectedContentType = "image/jpeg";
    Photo p = new Photo();
    p.setCaption("JBWS2259 Smile :-)");
    p.setExpectedContentType(expectedContentType);
    p.setImage(handler);
    Photo reponse = port.echo(p);
    DataHandler dhResponse = reponse.getImage();
    String contentType = dhResponse.getContentType();
    assertEquals("content-type", expectedContentType, contentType);
}
Example 89
Project: jolie-dbus-master  File: SMTPService.java View source code
@RequestResponse
public void sendMail(Value request) throws FaultException {
    /*
		 * Host & Authentication
		 */
    Authenticator authenticator = null;
    Properties props = new Properties();
    props.put("mail.smtp.host", request.getFirstChild("host").strValue());
    if (request.hasChildren("authenticate")) {
        Value auth = request.getFirstChild("authenticate");
        props.put("mail.smtp.auth", "true");
        authenticator = new SimpleAuthenticator(auth.getFirstChild("username").strValue(), auth.getFirstChild("password").strValue());
    }
    Session session = Session.getDefaultInstance(props, authenticator);
    Message msg = new MimeMessage(session);
    try {
        /*
			 * Recipents (To, Cc, Bcc)
			 */
        msg.setFrom(new InternetAddress(request.getFirstChild("from").strValue()));
        for (Value v : request.getChildren("to")) {
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(v.strValue()));
        }
        for (Value v : request.getChildren("cc")) {
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(v.strValue()));
        }
        for (Value v : request.getChildren("bcc")) {
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(v.strValue()));
        }
        /*
			 * Subject
			 */
        msg.setSubject(request.getFirstChild("subject").strValue());
        /*
			 * Content
			 */
        final String contentText = request.getFirstChild("content").strValue();
        String type = "text/plain";
        if (request.hasChildren("contentType")) {
            type = request.getFirstChild("contentType").strValue();
        }
        final String contentType = type;
        DataHandler dh = new DataHandler(new DataSource() {

            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(contentText.getBytes());
            }

            public OutputStream getOutputStream() throws IOException {
                throw new IOException("Operation not supported");
            }

            public String getContentType() {
                return contentType;
            }

            public String getName() {
                return "mail content";
            }
        });
        msg.setDataHandler(dh);
        /*
			 * Reply To
			 */
        ValueVector replyTo = request.getChildren("replyTo");
        int nAddr = replyTo.size();
        Address[] replyAddr = new Address[nAddr];
        for (int i = 0; i < nAddr; i++) {
            replyAddr[i] = new InternetAddress(replyTo.get(i).strValue());
        }
        msg.setReplyTo(replyAddr);
        /*
			 * Send
			 */
        Transport.send(msg);
    } catch (MessagingException e) {
        throw new FaultException("SMTPFault", e);
    }
}
Example 90
Project: KolabDroid-master  File: message_rfc822.java View source code
/**
     * Return the content.
     */
public Object getContent(DataSource ds) throws IOException {
    // create a new MimeMessage
    try {
        Session session;
        if (ds instanceof MessageAware) {
            MessageContext mc = ((MessageAware) ds).getMessageContext();
            session = mc.getSession();
        } else {
            // Hopefully a rare case.  Also hopefully the application
            // has created a default Session that can just be returned
            // here.  If not, the one we create here is better than
            // nothing, but overall not a really good answer.
            session = Session.getDefaultInstance(new Properties(), null);
        }
        return new MimeMessage(session, ds.getInputStream());
    } catch (MessagingException me) {
        throw new IOException("Exception creating MimeMessage in " + "message/rfc822 DataContentHandler: " + me.toString());
    }
}
Example 91
Project: kspl-selenium-helper-master  File: EmailUtil.java View source code
public void sendEmail(String toEmail, String fileAttachment) {
    if (this.pfm == null)
        return;
    this.setTo(toEmail);
    this.setFileAttachment(fileAttachment);
    Properties props = new Properties();
    //props.put("mail.smtp.auth", "true");
    //props.put("mail.smtp.starttls.enable", this.isEnableSSL());
    //props.put("mail.smtp.host", this.getHost());
    //props.put("mail.smtp.port", this.port);
    session = Session.getInstance(props, new javax.mail.Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(getFrom(), getPassword());
        }
    });
    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(getFrom()));
        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(this.getTo()));
        // Set Subject: header field
        message.setSubject("Report");
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();
        // Now set the actual message
        messageBodyPart.setText("Kindly find the attached detaild report with this email.");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();
        // Set text message part
        multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = this.getFileAttachment();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        // Send the complete message parts
        message.setContent(multipart);
        // Send message
        send(message);
        log.write("Sent message successfully....");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
Example 92
Project: Labos3eSup-master  File: Smtp.java View source code
public void addPartFichier(String path) {
    if (messageMultipart == null) {
        messageMultipart = new MimeMultipart();
        multipart = true;
    }
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    DataSource dataSource = new FileDataSource(path);
    try {
        mimeBodyPart.setDataHandler(new DataHandler(dataSource));
        mimeBodyPart.setFileName(path);
        messageMultipart.addBodyPart(mimeBodyPart);
    } catch (MessagingException ex) {
        Logger.getLogger(Smtp.class.getName()).log(Level.SEVERE, null, ex);
        correct = false;
    }
}
Example 93
Project: mailssenger-master  File: MailSender.java View source code
/*
	 * for attachment
	 */
public void addAttachment(String filename) throws Exception {
    System.out.println("::addAttachment::  filename is " + filename);
    filename = filename.replace("file://", "");
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    _multipart.addBodyPart(messageBodyPart);
}
Example 94
Project: mediation-master  File: BuilderMediator.java View source code
public boolean mediate(MessageContext msgCtx) {
    SynapseLog synLog = getLog(msgCtx);
    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Build mediator : start");
    }
    SOAPEnvelope envelope = msgCtx.getEnvelope();
    org.apache.axis2.context.MessageContext messageContext = ((Axis2MessageContext) msgCtx).getAxis2MessageContext();
    OMElement contentEle = envelope.getBody().getFirstChildWithName(RelayConstants.BINARY_CONTENT_QNAME);
    if (contentEle != null) {
        OMNode node = contentEle.getFirstOMChild();
        if (node != null && (node instanceof OMText)) {
            OMText binaryDataNode = (OMText) node;
            DataHandler dh = (DataHandler) binaryDataNode.getDataHandler();
            if (dh == null) {
                if (synLog.isTraceOrDebugEnabled()) {
                    synLog.auditWarn("Message has the Binary content element. " + "But doesn't have binary content embedded within it");
                }
                return true;
            }
            DataSource dataSource = dh.getDataSource();
            //Ask the data source to stream, if it has not already cached the request
            if (dataSource instanceof StreamingOnRequestDataSource) {
                ((StreamingOnRequestDataSource) dataSource).setLastUse(true);
            }
            InputStream in = null;
            try {
                in = dh.getInputStream();
            } catch (IOException e) {
                handleException("Error retrieving InputStream from data handler", e, msgCtx);
            }
            String contentType = (String) messageContext.getProperty(Constants.Configuration.CONTENT_TYPE);
            OMElement element = null;
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Trying to build a message with content type :" + contentType);
            }
            try {
                if (specifiedBuilder != null) {
                    // if a builder class is specified, it gets the preference
                    element = specifiedBuilder.processDocument(in, contentType, messageContext);
                } else {
                    // otherwise, use the builder associated with this contentType
                    element = messageBuilder.getDocument(contentType, messageContext, in);
                }
            } catch (Exception e) {
                synLog.auditWarn("Error building message with content type :" + contentType);
            }
            if (element != null) {
                try {
                    messageContext.setEnvelope(TransportUtils.createSOAPEnvelope(element));
                    if (specifiedFormatter != null) {
                        messageContext.setProperty(MessageBuilder.FORCED_RELAY_FORMATTER, specifiedFormatter);
                    } else {
                        // set the formatter map to the message context
                        messageContext.setProperty(MessageBuilder.RELAY_FORMATTERS_MAP, messageBuilder.getFormatters());
                    }
                } catch (AxisFault axisFault) {
                    handleException("Failed to set the built SOAP " + "Envelope to the message context", axisFault, msgCtx);
                }
            } else {
                synLog.auditWarn("Error occurred while trying to build the message, " + "trying to send the message through");
            }
            //now we have undone thing done  by Relay
            if (synLog.isTraceOrDebugEnabled()) {
                synLog.traceOrDebug("Build mediator : end");
            }
        } else {
            if (synLog.isTraceOrDebugEnabled()) {
                //if is not wrapped binary content, there is nothing to be done
                synLog.traceOrDebug("not wrapped binary content, there is nothing to be done");
            }
        }
    } else if (envelope.getBody().getFirstElement() == null) {
        // set the formatter map to the message context
        messageContext.setProperty(MessageBuilder.RELAY_FORMATTERS_MAP, messageBuilder.getFormatters());
    }
    return true;
}
Example 95
Project: opensearchserver-master  File: EmlParser.java View source code
@Override
protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang) throws IOException, SearchLibException {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);
    try {
        MimeMessage mimeMessage = new MimeMessage(session, streamLimiter.getNewInputStream());
        MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();
        ParserResultItem result = getNewParserResultItem();
        String from = mimeMessageParser.getFrom();
        if (from != null)
            result.addField(ParserFieldEnum.email_display_from, from.toString());
        for (Address address : mimeMessageParser.getTo()) result.addField(ParserFieldEnum.email_display_to, address.toString());
        for (Address address : mimeMessageParser.getCc()) result.addField(ParserFieldEnum.email_display_cc, address.toString());
        for (Address address : mimeMessageParser.getBcc()) result.addField(ParserFieldEnum.email_display_bcc, address.toString());
        result.addField(ParserFieldEnum.subject, mimeMessageParser.getSubject());
        result.addField(ParserFieldEnum.htmlSource, mimeMessageParser.getHtmlContent());
        result.addField(ParserFieldEnum.content, mimeMessageParser.getPlainContent());
        result.addField(ParserFieldEnum.email_sent_date, mimeMessage.getSentDate());
        result.addField(ParserFieldEnum.email_received_date, mimeMessage.getReceivedDate());
        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            result.addField(ParserFieldEnum.email_attachment_name, dataSource.getName());
            result.addField(ParserFieldEnum.email_attachment_type, dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(getSourceDocument(), dataSource.getName(), dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults) result.addField(ParserFieldEnum.email_attachment_content, parserResult);
        }
        if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
            result.langDetection(10000, ParserFieldEnum.content);
        else
            result.langDetection(10000, ParserFieldEnum.htmlSource);
    } catch (Exception e) {
        throw new IOException(e);
    }
}
Example 96
Project: pgpsigner-master  File: MailCommand.java View source code
@Override
public void executeInteractiveCommand(final String[] args) {
    SecretKey secretKey = getContext().getSignKey();
    String senderMail = secretKey.getMailAddress();
    String senderName = secretKey.getName();
    if (StringUtils.isEmpty(senderMail)) {
        System.out.println("Could not extract sender mail from sign key.");
        return;
    }
    for (final PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) {
        if (key.isSigned() && !key.isMailed()) {
            try {
                String recipient = getContext().isSimulation() ? senderMail : key.getMailAddress();
                if (StringUtils.isEmpty(recipient)) {
                    System.out.println("No mail address for key " + key.getKeyId() + ", skipping.");
                    continue;
                }
                System.out.println("Sending Key " + key.getKeyId() + " to " + recipient);
                MultiPartEmail mail = new MultiPartEmail();
                mail.setHostName(getContext().getMailServerHost());
                mail.setSmtpPort(getContext().getMailServerPort());
                mail.setFrom(senderMail, senderName);
                mail.addTo(recipient);
                if (!getContext().isSimulation()) {
                    mail.addBcc(senderMail);
                }
                mail.setSubject("Your signed PGP key - " + key.getKeyId());
                mail.setMsg("This is your signed PGP key " + key.getKeyId() + " from the " + getContext().getSignEvent() + " key signing event.");
                final String name = key.getKeyId() + ".asc";
                mail.attach(new DataSource() {

                    public String getContentType() {
                        return "application/pgp-keys";
                    }

                    public InputStream getInputStream() throws IOException {
                        return new ByteArrayInputStream(key.getArmor());
                    }

                    public String getName() {
                        return name;
                    }

                    public OutputStream getOutputStream() throws IOException {
                        throw new UnsupportedOperationException();
                    }
                }, name, "Signed Key " + key.getKeyId());
                mail.send();
                key.setMailed(true);
            } catch (EmailException ee) {
                System.out.println("Could not send mail for Key " + key.getKeyId());
            }
        }
    }
}
Example 97
Project: PortlandStateJava-master  File: SendAndReceiveMultipartWithGreenmailIT.java View source code
private MimeBodyPart createZipAttachment(File zipFile) throws MessagingException {
    // Now attach the Zip file
    DataSource ds = new FileDataSource(zipFile) {

        @Override
        public String getContentType() {
            return "application/zip";
        }
    };
    DataHandler dh = new DataHandler(ds);
    MimeBodyPart filePart = new MimeBodyPart();
    String zipFileTitle = "ZipFile.zip";
    filePart.setDataHandler(dh);
    filePart.setFileName(zipFileTitle);
    filePart.setDescription("Zip File");
    return filePart;
}
Example 98
Project: rest-client-tools-master  File: DataSourceProvider.java View source code
/**
    * @param in
    * @param mediaType
    * @return
    * @throws java.io.IOException
    */
public static DataSource readDataSource(final InputStream in, final MediaType mediaType) throws IOException {
    byte[] memoryBuffer = new byte[4096];
    int readCount = in.read(memoryBuffer, 0, memoryBuffer.length);
    File tempFile = null;
    if (in.available() > 0) {
        tempFile = File.createTempFile("resteasy-provider-datasource", null);
        FileOutputStream fos = new FileOutputStream(tempFile);
        try {
            ProviderHelper.writeTo(in, fos);
        } finally {
            fos.close();
        }
    }
    if (readCount == -1)
        readCount = 0;
    return new SequencedDataSource(memoryBuffer, 0, readCount, tempFile, mediaType.toString());
}
Example 99
Project: restlet-framework-java-master  File: MultipartProvider.java View source code
/**
     * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType,
     *      MultivaluedMap, InputStream)
     */
public Multipart readFrom(Class<Multipart> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpResponseHeaders, InputStream entityStream) throws IOException {
    final String contentType = "multipart/form-data";
    final DataSource ds = new ByteArrayDataSource(entityStream, contentType);
    try {
        return new MimeMultipart(ds);
    } catch (MessagingException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        final IOException ioExc = new IOException("Could not deserialize the data to a Multipart");
        ioExc.initCause(e);
        throw ioExc;
    }
}
Example 100
Project: seam-2.2-master  File: UIAttachment.java View source code
@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);
    }
}
Example 101
Project: seam-revisited-master  File: UIAttachment.java View source code
@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);
    }
}