Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:org.kuali.kra.s2s.service.impl.KRAS2SServiceImpl.java

/**
 * This method is used to submit forms to Grants.gov. It generates forms for
 * a given {@link ProposalDevelopmentDocument}, validates and then submits
 * the forms//from  w  ww . j  a  va  2  s. c  o m
 * 
 * @param pdDoc
 *            Proposal Development Document.
 * @return true if submitted false otherwise.
 * @throws S2SException
 * @see org.kuali.kra.s2s.service.S2SService#submitApplication(org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument)
 */
public boolean submitApplication(ProposalDevelopmentDocument pdDoc) throws S2SException {
    boolean submissionStatus = false;
    Forms forms = Forms.Factory.newInstance();
    List<AttachmentData> attList = new ArrayList<AttachmentData>();
    if (generateAndValidateForms(forms, attList, pdDoc)) {
        GrantApplicationDocument grantApplicationDocument = getGrantApplicationDocument(pdDoc, forms);

        Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
        List<S2sAppAttachments> s2sAppAttachmentList = new ArrayList<S2sAppAttachments>();
        DataHandler attachmentFile;
        for (AttachmentData attachmentData : attList) {
            attachmentFile = new DataHandler(
                    new ByteArrayDataSource(attachmentData.getContent(), attachmentData.getContentType()));

            attachments.put(attachmentData.getContentId(), attachmentFile);
            S2sAppAttachments appAttachments = new S2sAppAttachments();
            appAttachments.setContentId(attachmentData.getContentId());
            appAttachments.setProposalNumber(pdDoc.getDevelopmentProposal().getProposalNumber());
            s2sAppAttachmentList.add(appAttachments);
        }
        S2sAppSubmission appSubmission = new S2sAppSubmission();
        appSubmission.setStatus(S2SConstants.GRANTS_GOV_STATUS_MESSAGE);
        appSubmission.setComments(S2SConstants.GRANTS_GOV_COMMENTS_MESSAGE);
        SubmitApplicationResponse response = null;

        String applicationXmlText = grantApplicationDocument
                .xmlText(s2SFormGeneratorService.getXmlOptionsPrefixes());
        String applicationXml = s2SUtilService.removeTimezoneFactor(applicationXmlText);
        response = grantsGovConnectorService.submitApplication(applicationXml, attachments,
                pdDoc.getDevelopmentProposal().getProposalNumber());
        appSubmission.setStatus(S2SConstants.GRANTS_GOV_SUBMISSION_MESSAGE);
        saveSubmissionDetails(pdDoc, appSubmission, response, applicationXml, s2sAppAttachmentList);
        submissionStatus = true;
    }
    return submissionStatus;
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java

public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) {
    logger.debug("IN");
    MimeBodyPart messageBodyPart = null;
    try {//from w w w  .  jav  a2  s .  co m

        String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : "";

        byte[] buffer = new byte[4096]; // Create a buffer for copying
        int bytesRead;

        // the zip
        String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH);

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipOutputStream out = new ZipOutputStream(bout);

        logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip");

        //files to zip
        String[] entries = tempFolder.list();

        for (int i = 0; i < entries.length; i++) {
            //File f = new File(tempFolder, entries[i]);
            File f = new File(tempFolder + File.separator + entries[i]);
            if (f.isDirectory())
                continue;//Ignore directory
            logger.debug("insert file: " + f.getName());
            FileInputStream in = new FileInputStream(f); // Stream to read file
            ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry
            out.putNextEntry(entry); // Store entry
            while ((bytesRead = in.read(buffer)) != -1)
                out.write(buffer, 0, bytesRead);
            in.close();
        }
        out.close();

        messageBodyPart = new MimeBodyPart();
        DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip");
        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip");

    } catch (Exception e) {
        logger.error("Error while creating the zip", e);
        return null;
    }

    logger.debug("OUT");

    return messageBodyPart;
}

From source file:org.apromore.service.impl.ProcessServiceImpl.java

/**
 * @see org.apromore.service.ProcessService#exportProcess(String, Integer, String, Version, String, String, boolean, java.util.Set)
 * {@inheritDoc}//www .j  a v a 2s . c  om
 */
@Override
public ExportFormatResultType exportProcess(final String name, final Integer processId, final String branch,
        final Version version, final String format, final String annName, final boolean withAnn,
        Set<RequestParameterType<?>> canoniserProperties) throws ExportFormatException {
    try {
        // Debug tracing of the authenticated principal
        org.springframework.security.core.Authentication auth = org.springframework.security.core.context.SecurityContextHolder
                .getContext().getAuthentication();
        if (auth != null) {
            LOGGER.info("Authentication principal=" + auth.getPrincipal() + " details=" + auth.getDetails()
                    + " thread=" + Thread.currentThread());
        } else {
            LOGGER.info("Authentication is null");
        }

        ExportFormatResultType exportResult = new ExportFormatResultType();

        // Work out if we are looking at the original format or native format for this model.
        if (isRequestForNativeFormat(processId, branch, version, format)) {
            exportResult.setNative(new DataHandler(new ByteArrayDataSource(
                    nativeRepo.getNative(processId, branch, version.toString(), format).getContent(),
                    "text/xml")));
        } else if (isRequestForAnnotationsOnly(format)) {
            exportResult
                    .setNative(
                            new DataHandler(new ByteArrayDataSource(
                                    annotationRepo.getAnnotation(processId, branch, version.toString(),
                                            AnnotationHelper.getAnnotationName(annName)).getContent(),
                                    "text/xml")));
        } else {
            CanonicalProcessType cpt = getProcessModelVersion(processId, name, branch, version, false);
            Process process;
            if (format.equals(Constants.CANONICAL)) {
                exportResult.setNative(new DataHandler(
                        new ByteArrayDataSource(canoniserSrv.CPFtoString(cpt), Constants.XML_MIMETYPE)));
            } else {
                DecanonisedProcess dp;
                AnnotationsType anf = null;
                process = processRepo.findOne(processId);
                if (withAnn) {
                    Annotation ann = annotationRepo.getAnnotation(processId, branch, version.toString(),
                            annName);
                    if (ann != null) {
                        String annotation = ann.getContent();
                        if (annotation != null && !annotation.equals("")) {
                            ByteArrayDataSource dataSource = new ByteArrayDataSource(annotation,
                                    Constants.XML_MIMETYPE);
                            anf = ANFSchema.unmarshalAnnotationFormat(dataSource.getInputStream(), false)
                                    .getValue();
                        }
                    }

                    if (ann != null && !process.getNativeType().getNatType()
                            .equalsIgnoreCase(ann.getNatve().getNativeType().getNatType())) {
                        anf = annotationSrv.preProcess(ann.getNatve().getNativeType().getNatType(), format, cpt,
                                anf);
                    } else {
                        anf = annotationSrv.preProcess(process.getNativeType().getNatType(), format, cpt, anf);
                    }
                } else if (annName == null) {
                    anf = annotationSrv.preProcess(null, format, cpt, null);
                }

                dp = canoniserSrv.deCanonise(format, cpt, anf, canoniserProperties);

                exportResult.setMessage(PluginHelper.convertFromPluginMessages(dp.getMessages()));
                exportResult.setNative(
                        new DataHandler(new ByteArrayDataSource(dp.getNativeFormat(), Constants.XML_MIMETYPE)));
            }
        }

        return exportResult;
    } catch (Exception e) {
        LOGGER.error("Failed to export process model {} to format {}", name, format);
        LOGGER.error("Original exception was: ", e);
        throw new ExportFormatException(e);
    }
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;//ww  w . ja v  a2 s  . com
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:se.vgregion.usdservice.USDServiceImpl.java

private DataHandler createDataHandler(Attachment attachment) {
    DataSource source;/*from w  ww .  j a v a2  s .  c om*/
    try {
        source = new ByteArrayDataSource(attachment.getData(), "application/octet-stream");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return new DataHandler(source);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//from   w  w w.j a  v a  2  s.  c  o m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server//  ww  w  .j  a va2 s . c  om
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject)
        throws MessagingException, IOException {
    MimeMessage message = prepareMimeMessage(subject);
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(//from  www.  j  ava 2  s  .  c o  m
            new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8")));
    scriptPart.setDisposition(MimeBodyPart.ATTACHMENT);
    // setting a DataHandler with no mailcap definition is not
    // supported by the specs. Javamail activation still work,
    // but Geronimo activation translate it to text/plain.
    // Let's manually force the header.
    scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8");
    scriptPart.setFileName(SCRIPT_NAME);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    return message;
}

From source file:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * Ajoute une pice jointe  l'email courant.
 * /*from  ww w .ja  va2 s. c o  m*/
 * @param data
 *            les donnes binaires de la pice jointe
 * @param contentType
 *            le type de contenu
 * @param fileName
 *            le nom du fichier
 * @param description
 *            la description
 * @throws IOException
 *             Erreur de lecture des donnes binaires.
 */
public void addAttachment(byte[] data, String contentType, String fileName, String description)
        throws IOException {
    attachments.add(new AttachmentBean(new ByteArrayDataSource(data, contentType), fileName, description));
}