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.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

public static MimeMessage createReport(final MailDefinition mailDefinition, final Session session,
        final DataRow parameters) throws ReportProcessingException, ContentIOException, MessagingException {
    final MasterReport bodyReport = mailDefinition.getBodyReport();
    final String[] paramNames = parameters.getColumnNames();
    final ReportParameterValues parameterValues = bodyReport.getParameterValues();
    for (int i = 0; i < paramNames.length; i++) {
        final String paramName = paramNames[i];
        if (isParameterDefined(bodyReport, paramName)) {
            parameterValues.put(paramName, parameters.get(paramName));
        }/*w  ww.j  av  a 2  s.co m*/
    }

    final ReportProcessTaskRegistry registry = ReportProcessTaskRegistry.getInstance();
    final String bodyType = mailDefinition.getBodyType();
    final ReportProcessTask processTask = registry.createProcessTask(bodyType);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ReportProcessTaskUtil.configureBodyStream(processTask, bout, "report", null);
    processTask.setReport(bodyReport);
    if (processTask instanceof MultiStreamReportProcessTask) {
        final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) processTask;
        mtask.setBulkLocation(mtask.getBodyContentLocation());
        mtask.setBulkNameGenerator(new DefaultNameGenerator(mtask.getBodyContentLocation(), "data"));
        mtask.setUrlRewriter(new MailURLRewriter());
    }
    processTask.run();
    if (processTask.isTaskSuccessful() == false) {
        if (processTask.isTaskAborted()) {
            logger.info("EMail Task received interrupt.");
            return null;
        } else {
            logger.info("EMail Task failed:", processTask.getError());
            throw new ReportProcessingException("EMail Task failed", processTask.getError());
        }
    }

    final EmailRepository repository = new EmailRepository(session);
    final MimeBodyPart messageBodyPart = repository.getBodypart();
    final ByteArrayDataSource dataSource = new ByteArrayDataSource(bout.toByteArray(),
            processTask.getReportMimeType());
    messageBodyPart.setDataHandler(new DataHandler(dataSource));

    final int attachmentsSize = mailDefinition.getAttachmentCount();
    for (int i = 0; i < attachmentsSize; i++) {
        final MasterReport report = mailDefinition.getAttachmentReport(i);
        final String type = mailDefinition.getAttachmentType(i);
        final ContentLocation location = repository.getRoot();
        final ContentLocation bulkLocation = location.createLocation("attachment-" + i);

        final ReportProcessTask attachmentProcessTask = registry.createProcessTask(type);
        attachmentProcessTask.setBodyContentLocation(bulkLocation);
        attachmentProcessTask.setBodyNameGenerator(new DefaultNameGenerator(bulkLocation, "report"));
        attachmentProcessTask.setReport(report);
        if (attachmentProcessTask instanceof MultiStreamReportProcessTask) {
            final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) attachmentProcessTask;
            mtask.setBulkLocation(bulkLocation);
            mtask.setBulkNameGenerator(new DefaultNameGenerator(bulkLocation, "data"));
            mtask.setUrlRewriter(new MailURLRewriter());
        }
        attachmentProcessTask.run();

        if (attachmentProcessTask.isTaskSuccessful() == false) {
            if (attachmentProcessTask.isTaskAborted()) {
                logger.info("EMail Task received interrupt.");
            } else {
                logger.info("EMail Task failed:", attachmentProcessTask.getError());
                throw new ReportProcessingException("EMail Task failed", attachmentProcessTask.getError());
            }
        }
    }

    return repository.getEmail();
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * GZipping a string.//from w  w  w .j  a va2 s . c o m
 * 
 * @param data the content to be gzipped.
 * @param filename the name for the file.
 * @return a ByteArrayDataSource.
 */
protected ByteArrayDataSource compressFile(File fileName) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gz = new GZIPOutputStream(out);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fileName));
    byte[] dataBuffer = new byte[512];
    while ((bufferedInputStream.read(dataBuffer)) != -1) {
        gz.write(dataBuffer);
    }
    gz.close();
    bufferedInputStream.close();
    ByteArrayDataSource dataSrc = new ByteArrayDataSource(out.toByteArray(), "application/x-gzip");
    return dataSrc;
}

From source file:com.aurel.track.util.emailHandling.MailSender.java

/**
 * /*from www .ja va 2 s .com*/
 * @param smtpMailSettings
 * @param internetAddressFrom
 * @param internetAddressesTo
 * @param subject
 * @param messageBody
 * @param isPlain
 * @param attachments
 * @param internetAddressesCC
 * @param internetAddressesBCC
 * @param internetAddressesReplayTo
 */
private void init(SMTPMailSettings smtpMailSettings, InternetAddress internetAddressFrom,
        InternetAddress[] internetAddressesTo, String subject, String messageBody, boolean isPlain,
        List<LabelValueBean> attachments, InternetAddress[] internetAddressesCC,
        InternetAddress[] internetAddressesBCC, InternetAddress[] internetAddressesReplayTo) {
    this.smtpMailSettings = smtpMailSettings;
    try {
        if (isPlain) {
            email = new SimpleEmail();
            if (attachments != null && attachments.size() > 0) {
                email = new MultiPartEmail();
            }
        } else {
            email = new HtmlEmail();
        }
        if (LOGGER.isTraceEnabled()) {
            email.setDebug(true);
        }
        email.setHostName(smtpMailSettings.getHost());
        email.setSmtpPort(smtpMailSettings.getPort());
        email.setCharset(smtpMailSettings.getMailEncoding() != null ? smtpMailSettings.getMailEncoding()
                : DEFAULTENCODINGT);
        if (timeout != null) {
            email.setSocketConnectionTimeout(timeout);
            email.setSocketTimeout(timeout);
        }
        if (smtpMailSettings.isReqAuth()) {
            email = setAuthMode(email);
        }
        email = setSecurityMode(email);

        for (int i = 0; i < internetAddressesTo.length; ++i) {
            email.addTo(internetAddressesTo[i].getAddress(), internetAddressesTo[i].getPersonal());
        }
        if (internetAddressesCC != null) {
            for (int i = 0; i < internetAddressesCC.length; ++i) {
                email.addCc(internetAddressesCC[i].getAddress(), internetAddressesCC[i].getPersonal());
            }
        }
        if (internetAddressesBCC != null) {
            for (int i = 0; i < internetAddressesBCC.length; ++i) {
                email.addBcc(internetAddressesBCC[i].getAddress(), internetAddressesBCC[i].getPersonal());
            }
        }
        if (internetAddressesReplayTo != null) {
            for (int i = 0; i < internetAddressesReplayTo.length; ++i) {
                email.addReplyTo(internetAddressesReplayTo[i].getAddress(),
                        internetAddressesReplayTo[i].getPersonal());
            }
        }
        email.setFrom(internetAddressFrom.getAddress(), internetAddressFrom.getPersonal());
        email.setSubject(subject);
        String cid = null;
        if (isPlain) {
            email.setMsg(messageBody);
        } else {
            if (messageBody.contains("cid:$$CID$$")) {
                URL imageURL = null;
                InputStream in = null;
                in = MailSender.class.getClassLoader().getResourceAsStream("tracklogo.gif");

                if (in != null) {
                    imageURL = new URL(ApplicationBean.getInstance().getServletContext().getResource("/")
                            + "logoAction.action?type=m");
                    DataSource ds = new ByteArrayDataSource(in, "image/" + "gif");
                    cid = ((HtmlEmail) email).embed(ds, "Genji");
                } else {
                    String theResource = "/WEB-INF/classes/resources/MailTemplates/tracklogo.gif";
                    imageURL = ApplicationBean.getInstance().getServletContext().getResource(theResource);
                    cid = ((HtmlEmail) email).embed(imageURL, "Genji");
                }
                messageBody = messageBody.replaceFirst("\\$\\$CID\\$\\$", cid);
            }
            Set<String> attachSet = new HashSet<String>();
            messageBody = MailImageBL.replaceInlineImages(messageBody, attachSet);
            if (!attachSet.isEmpty()) {
                Iterator<String> it = attachSet.iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    StringTokenizer st = new StringTokenizer(key, "_");
                    String workItemIDStr = st.nextToken();
                    String attachmentKeyStr = st.nextToken();
                    TAttachmentBean attachmentBean = null;
                    try {
                        attachmentBean = AttachBL.loadAttachment(Integer.valueOf(attachmentKeyStr),
                                Integer.valueOf(workItemIDStr), true);
                    } catch (Exception ex) {
                    }
                    if (attachmentBean != null) {
                        String fileName = attachmentBean.getFullFileNameOnDisk();
                        File file = new File(fileName);
                        InputStream is = new FileInputStream(file);
                        DataSource ds = new ByteArrayDataSource(is, "image/" + "gif");
                        cid = ((HtmlEmail) email).embed(ds, key);
                        messageBody = messageBody.replaceAll("cid:" + key, "cid:" + cid);
                    }
                }
            }
            ((HtmlEmail) email).setHtmlMsg(messageBody);
        }
        if (attachments != null && !attachments.isEmpty()) {
            includeAttachments(attachments);
        }
    } catch (Exception e) {
        LOGGER.error("Something went wrong trying to assemble an e-mail: " + e.getMessage());
    }

}

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test//  w w  w.j ava2s .com
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

From source file:ch.dbs.actions.reports.ILVReport.java

/**
 * Send an email with attached PDF as ILL order (ILV-Bestellung).
 *//*from  w w  w  .jav a  2s  .c om*/
public ActionForward sendIlvMail(final ActionMapping mp, final ActionForm fm, final HttpServletRequest rq,
        final HttpServletResponse rp) {

    final Auth auth = new Auth();
    // make sure the user is logged in
    if (!auth.isLogin(rq)) {
        return mp.findForward(Result.ERROR_TIMEOUT.getValue());
    }
    // check access rights
    if (!auth.isBibliothekar(rq) && !auth.isAdmin(rq)) {
        return mp.findForward(Result.ERROR_MISSING_RIGHTS.getValue());
    }
    // if activated on system level, access will be restricted to paid only
    if (auth.isPaidOnly(rq)) {
        return mp.findForward(Result.ERROR_PAID_ONLY.getValue());
    }

    String forward = Result.FAILURE.getValue();

    final IlvReportForm ilvf = (IlvReportForm) fm;
    final UserInfo ui = (UserInfo) rq.getSession().getAttribute("userinfo");
    final Check check = new Check();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {

        // validate email: failing mails would be returned to the system email and not
        // to the library generating the invalid email!
        if (check.isEmail(ilvf.getTo())) {

            // prepare attachment
            DataSource aAttachment = null;

            // create PDF report using the appropriate ILL form number
            runReport(ilvf, ui, baos);

            aAttachment = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");

            // prepare email
            final InternetAddress[] to = new InternetAddress[2];
            to[0] = new InternetAddress(ilvf.getTo());
            to[1] = new InternetAddress(ui.getKonto().getDbsmail());

            // Create and send email
            final MHelper mh = new MHelper(to, ilvf.getSubject(), composeMailBody(ui, ilvf), aAttachment,
                    composeFilename(ilvf, ui));
            mh.setReplyTo(ui.getKonto().getDbsmail());
            mh.send();

            forward = Result.SUCCESS.getValue();
            final String content = "ilvmail.confirmation";
            final String link = "listkontobestellungen.do?method=overview";
            final ch.dbs.form.Message mes = new ch.dbs.form.Message(content, link);
            rq.setAttribute("message", mes);
            rq.setAttribute("IlvReportForm", ilvf);

        } else {
            final ErrorMessage em = new ErrorMessage("error.email", "listkontobestellungen.do?method=overview");
            rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
        }
    } catch (final JRException e1) {
        final ErrorMessage em = new ErrorMessage("error.createilvreport",
                "listkontobestellungen.do?method=overview");
        rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
    } catch (final Exception e) {
        final ErrorMessage em = new ErrorMessage("error.sendmail", e.getMessage(),
                "listkontobestellungen.do?method=overview");
        rq.setAttribute(Result.ERRORMESSAGE.getValue(), em);
    } finally {
        try {
            baos.close();
        } catch (final IOException e) {
            LOG.error(e.toString());
        }
    }

    return mp.findForward(forward);
}

From source file:pt.ist.fenixedu.integration.task.exportData.parking.ExportCarParkUsers.java

private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray)
        throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients",
            FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);

    final Sender sender = Bennu.getInstance().getSystemSender();

    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualizao");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    Multipart multipart = new MimeMultipart();

    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);/*  w ww.  ja v  a 2s  .co m*/

    Transport.send(message);
}

From source file:br.ufg.reqweb.components.MailBean.java

private void processEmailToStaff(Map<String, List<Map<String, ?>>> messageMap, String reportPath,
        String reportTitle) {/*from   w ww  .  ja v  a2 s  .c o  m*/
    for (Entry message : messageMap.entrySet()) {
        JRMapCollectionDataSource dataSource;
        List<TipoRequerimentoEnum> tipoRequerimentoList;
        List<RequerimentoStatusEnum> status;
        Map reportParameters = new HashMap();
        tipoRequerimentoList = Arrays.asList(TipoRequerimentoEnum.values());
        status = Arrays.asList(new RequerimentoStatusEnum[] { RequerimentoStatusEnum.ABERTO,
                RequerimentoStatusEnum.EM_ANDAMENTO });
        for (RequerimentoStatusEnum statusEnum : RequerimentoStatusEnum.values()) {
            reportParameters.put(statusEnum.name(),
                    LocaleBean.getDefaultMessageBundle().getString(statusEnum.getStatus()));
        }
        System.out.println("path: " + reportPath);
        dataSource = new JRMapCollectionDataSource((List<Map<String, ?>>) message.getValue());
        reportParameters.put("TITULO", reportTitle);
        reportParameters.put("MATRICULA", LocaleBean.getDefaultMessageBundle().getString("usuarioMatricula"));
        reportParameters.put("NOME", LocaleBean.getDefaultMessageBundle().getString("discente"));
        reportParameters.put("DOCENTE", LocaleBean.getDefaultMessageBundle().getString("docente"));
        reportParameters.put("DISCIPLINA", LocaleBean.getDefaultMessageBundle().getString("disciplina"));
        reportParameters.put("TURMA", LocaleBean.getDefaultMessageBundle().getString("turma"));
        reportParameters.put("DATA_PROVA", LocaleBean.getDefaultMessageBundle().getString("dataProvaA"));
        reportParameters.put("DATA_REQUERIMENTO",
                LocaleBean.getDefaultMessageBundle().getString("dataCriacao"));
        reportParameters.put("CURSO", LocaleBean.getDefaultMessageBundle().getString("curso"));
        reportParameters.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento"));
        reportParameters.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status"));
        reportParameters.put("TOTAL", LocaleBean.getDefaultMessageBundle().getString("total"));
        for (TipoRequerimentoEnum tipoRequerimento : tipoRequerimentoList) {
            reportParameters.put(tipoRequerimento.name(), tipoRequerimento.getTipoLocale());
        }
        JasperPrint jrp;
        try {
            jrp = JasperFillManager.fillReport(context.getRealPath(reportPath), reportParameters, dataSource);
            InputStream inputStream = new ByteArrayInputStream(JasperExportManager.exportReportToPdf(jrp));
            MultiPartEmail email = new MultiPartEmail();
            DataSource ds = new ByteArrayDataSource(inputStream, "application/pdf");
            email.attach(ds, "reqweb.pdf", LocaleBean.getDefaultMessageBundle().getString("relatorioDiario"));
            email.setHostName(configDao.getValue("mail.mailHost"));
            email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort")));

            String mailSender = configDao.getValue("mail.mailSender");
            String user = configDao.getValue("mail.mailUser");
            String password = configDao.getValue("mail.mailPassword");
            boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL"));

            email.setAuthenticator(new DefaultAuthenticator(user, password));
            email.setSSLOnConnect(useSSL);
            email.setFrom(mailSender);
            email.addTo(message.getKey().toString());
            email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail"));
            String messageBody = String.format("%s\n\n%s",
                    LocaleBean.getDefaultMessageBundle().getString("subjectMail"),
                    LocaleBean.getDefaultMessageBundle().getString("messageMail"));
            email.setMsg(messageBody);
            email.send();
        } catch (IOException | NullPointerException | EmailException | JRException e) {
            System.out.println("erro ao enviar email");
            System.out.println(e);
        }
    }
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {//ww w . ja va2 s .c o m
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:voldemort.coordinator.CoordinatorRestAPITest.java

private TestVersionedValue doGet(String key, Map<String, Object> options) {
    HttpURLConnection conn = null;
    String response = null;//  w  ww.ja v a  2s.c  o m
    TestVersionedValue responseObj = null;
    int expectedResponseCode = 200;
    try {

        // Create the right URL and Http connection
        String base64Key = new String(Base64.encodeBase64(key.getBytes()));
        URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key);
        conn = (HttpURLConnection) url.openConnection();

        // Set the right headers
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000");
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                Long.toString(System.currentTimeMillis()));

        // options
        if (options != null) {
            if (options.get("timeout") != null && options.get("timeout") instanceof String) {
                conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS,
                        (String) options.get("timeout"));
            }
            if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) {
                expectedResponseCode = (Integer) options.get("responseCode");
            }
        }

        // Check for the right response code
        if (conn.getResponseCode() != expectedResponseCode) {
            System.err.println("Illegal response during GET : " + conn.getResponseMessage());
            fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode());
        }

        if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) {
            return null;
        }

        // Buffer the result into a string
        ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        assertEquals("The number of body parts expected is not 1", 1, mp.getCount());

        MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0);
        VectorClock vc = RestUtils
                .deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]);
        response = (String) part.getContent();

        responseObj = new TestVersionedValue(response, vc);

    } catch (Exception e) {
        e.printStackTrace();
        fail("Error in sending the REST request");
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return responseObj;
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateMessageWithAttachment(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Vera Oliphant <oli@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.setText("Good as gold");
    MimeMultipart multi = new ZMimeMultipart("mixed");
    ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
    cdisp.setParameter("filename", "fun.txt");

    ZMimeBodyPart bp = new ZMimeBodyPart();
    // MimeBodyPart.setDataHandler() invalidates Content-Type and CTE if there is any, so make sure
    // it gets called before setting Content-Type and CTE headers.
    try {//from ww  w . j  a v a  2s .  c  o m
        bp.setDataHandler(new DataHandler(new ByteArrayDataSource("Feeling attached.", "text/plain")));
    } catch (IOException e) {
        throw new MessagingException("could not generate mime part content", e);
    }
    bp.addHeader("Content-Disposition", cdisp.toString());
    bp.addHeader("Content-Type", "text/plain");
    bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
    multi.addBodyPart(bp);

    mm.setContent(multi);
    mm.saveChanges();

    return new ParsedMessage(mm, false);
}